Archive for the ‘.net’ Category
HTML5 Support In Visual Studio 2010
I was trying to play around with HTML5 assuming that VS 2010 had shipped with HTML5 support but to my dismay it was not the case. Bummer! So I did a bit of homework and came up with an easy workaround. If you try googling for html5 visual studio 2010, the first link that you will see is HTML 5 Intellisense for Visual Studio 2010 and 2008. But unfortunately, the patch provided over there doesn’t seem to work. (DO I HAVE TO DO EVERYTHING!!)
So here’s how I got it to work.
- Download this archive and extract the contents to your desktop.
- Copy/Move html_5.xsd to D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\schemas\html. The path may vary depending on where you installed VS 2010 or Visual Web Developer 2010.
- From the extracted contents, run the appropriate registry file. In my case, it was VS-2010-x64.reg
- Now fire up Visual Studio 2010 (or VWD) and navigate to Tools > Options > Text Editor HTML > Validation. On the right panel, select HTML 5 as the Target.
- Now restart VS 2010 and you should be able to code valid HTML5. Enjoy!
ASP.NET SlidingMessage Control
The SlidingMessage server control is the ASP.NET version of the excellent jQuery SlidingMessage plugin by Henrik Joreteg. The control is very easy to use with minimal setup – all you have to do is drag and drop the control into your page and voila! you’re ready to go. The binary includes all the necessary javascript inlcuding jquery so you don’t even have to include them separately in your page.
Here’s how you invoke the sliding message, assuming SlidingMessage1 is the ID of the control:
SlidingMessage1.Text = "Congratulations. This works!";
SlidingMessage1.BackColor = System.Drawing.ColorTranslator.FromHtml("#0DFF00");
SlidingMessage1.IncludeJquery = false; //It’s included by default
SlidingMessage1.Show();
And as usual the whole thing is open source so knock yourself out! The source code and a demo is hosted at http://code.google.com/p/slidingmessage/
Happy Programming!
Discovering MSBuild – Part One
Background
This series is all about me trying to learn the dark art of MSBuild. Ever since I started developing .NET applications, I was aware of the existence of this strange tool but I could never harness its true potential. So lets begin our adventure!
Introduction
An MSBuild file typically known as an MSBuild Project File contains instructions on how to build your application step by step – neat stuff! This innovative tool from Microsoft helps you to take control over every aspect of the build process thereby helping you to automate the build and deployment process.
Overview
An MSBuild project file is basically an XML file. This XML document is defined by two XSD documents Microsoft.Build.CommonTypes.xsd and Microsoft.Buid.Core.xsd. Both these files are located in the %WINDIR%\Microsoft.NET\Framework\vXXXX\MSBuild folder. The basic structure of an MSBuild project file looks like this:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> </Project>
This structure is comprised of Properties, Items, Targets. Confused? You should be.
Put it simply, items are the files that are going to be built and properties are the build parameters ex. Configuration or OutputPath.
Project Properties
Properties are nothing but Key-Value pairs and apparently there two different types of Properties – Static, Dynamic. What I know about static properties is that they must be contained within a PropertyGroup element which is declared directly under the project element. A project element may contain multiple PropertyGroup elements.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ApplicationName>MyDemoApp</ApplicationName>
<WhyAmICrazy>I Have No Idea</WhyAmICrazy>
</PropertyGroup>
</Project>
In the above example, ApplicationName is the key and MyDemoApp is the value(DUH!!). Can values contain spaces? I have no idea – so lets find out. Paste the above code in notepad and save it with a *.proj extension, fire up the Visual Studio Command Prompt, and execute the script.
Oppsss! Look’s like we are missing something called Targets? Not to worry, let’s dig deeper.
Tasks & Targets
Targets are the work horses of the MSBuild file so without them the file would be literally useless. Properties are utilized within these targets. A task is the smallest unit of work and a target is a sequential set of tasks. The MSBuild tool ships with a predefined set of tasks like Copy, Csc(wow haven’t used this baby in a while!), Move, Exec, etc. Tasks are invoked using parameters which are just XML attributes with values. The attributes may vary from task to task. For our example we will try out the Message task.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ApplicationName>MyDemoApp</ApplicationName>
<WhyAmICrazy>I Have No Idea</WhyAmICrazy>
</PropertyGroup>
<Target Name="HelloWorld">
<Message Text="This is my first MSBuild Application" />
</Target>
</Project>
To build this project the command should be of the format
msbuild FILE_NAME /t:TARGET_NAME
For our example the command would look like
msbuild Sample1.proj /t:HelloWorld
You will see that the build succeeds without any errors! We may have won the battle but not the war
A more complicated example for you adrenaline junkies out there:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ApplicationName>MyDemoApp</ApplicationName>
<WhyAmICrazy>I Have No Idea</WhyAmICrazy>
</PropertyGroup>
<Target Name="HelloWorld">
<Message Text="This is my first MSBuild Application and $(WhyAmICrazy) why I love .NET" />
</Target>
</Project>
Until the next episode..
Using Jquery Grid with ASP.NET MVC
This excellent article from Phil Haack shows you how you can use the excellent JGrid plugin with ASP.NET MVC.
Thanks Phil!
http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
ASP.NET Maintenance Mode Module
Web developers at times need to put their web applications in an offline mode so as to prevent visitors from accessing the site while they are updating it. The classic way to do this would be to upload an app_offline.html file to the root of the web application. The limitation of this technique is that even the developer cannot visit the site! A developer might need to ensure if everything is working fine and at the same time prevent other users from accessing the web site.
So I created an HTTP module that helps overcome this issue. Just place a few lines in your web.config file and you are ready to go!
The following are the main features of this module:
1. Turn on/off the maintenance mode using a setting in the web.config file.
2. Specify the path to the landing page that will be shown to visitors.
3. Specify path to the login page if available.
4. Specify the allowed user roles.
5. Specify the allowed users.
Since the module is in its primary stage, please report any issues that you may find.
Resources
Programmatically extract body of a web page
The technique used in this article can be used to display the contents of an HTML page inside your ASP.NET pages instead of using IFRAMES.
System.Net.WebRequest req = System.Net.WebRequest.Create(Request.QueryString["url"]);
System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
System.IO.Stream respStream = resp.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(respStream);
string responseFromServer = sr.ReadToEnd();
System.Text.RegularExpressions.Regex bodyRegex = new System.Text.RegularExpressions.Regex(@"(]*>[\u0000-\uFFFF]+?)");
System.Text.RegularExpressions.Match bodyMatch = bodyRegex.Match(responseFromServer);
Literal1.Text = bodyMatch.Result("$0");
sr.Close();
respStream.Close();
resp.Close();
Thanks to ClayCo at the ASP.NET Forums for his help. Here is the link to the original thread http://forums.asp.net/t/1023144.aspx
Generating Tree-like UI structures
In many of my projects I have had to generate non-binary trees using information from the database and then display them in a “tree-like” structure as shown below.
My algorithm is very simple and it makes use of Dan Vanderboom’s excellent Generic Tree Collection but frankly I’m not satisfied with certain aspects of my algorithm. The main issue – the data can never be retrieved in the same order as shown above from the database.
Now that we have a collection ready, we can generate the tree structure
Finally, I add the items to my drop-down control by calling
GenerateDropDownList(rootCategory, 0);
Let’s have a look at the function
I know I could have used LINQ but many of my projects are running in .NET 2.0 so I had to go old-school! I’m looking forward to your valuable comments as to how YOU would do this and why your solution is more efficient than mine.
Happy Programming!
The Controls collection cannot be modified because the control contains code blocks
I’m pretty much sure many of you have encountered this error if you have been using Code blocks inside your ASP.NET master pages for example,
1: <img src='<%= Page.ResolveUrl("~/image/top-mnu-agents.jpg") %>' alt="Agents" name="agents"
2: width="109" height="42" border="0" id="agents" /></a>
Let’s say you want to use code blocks inside your JavaScript code, for example
1: function PreloadImages()
2: {
3: /*MM_preloadImages('<%= Page.ResolveUrl("~/image/top-mnu-property.jpg") %>',
4: '<%= Page.ResolveUrl("~/image/top-mnu-agents.jpg") %>',
5: '<%= Page.ResolveUrl("~/image/top-mnu-company.jpg") %>',
6: '<%= Page.ResolveUrl("~/image/top-mnu-contact.jpg") %>');*/
7: }
Is this going to work? Make a guess! No, its not! Bump! Even though the code block is inside a comment block! How’s that! If you are curious why, ask the guys at Microsoft
The workaround to this problem is Data Biding Expressions. Milan Negovan has discussed this in greater detail in this article.
Happy Programming!
Resizing Images In ASP.NET
I’m sure there are plenty of similar topics out there but this is my two cents. Lets say you have the following code in your ASP.NET page:
1 Upload a File: <asp:FileUpload ID="pictureUpload" runat="server" /><br />
2 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnCommand="handle_ButtonClick" CommandName="Upload" />
Let’s look at the event handler code that uploads the image to the server and resizes it.
1 protected void handle_ButtonClick(object sender, CommandEventArgs e)
2 {
3 if (e.CommandName == "Upload")
4 {
5 if (pictureUpload.HasFile)
6 {
7 string FilePath = HttpContext.Current.Server.MapPath(PATH_FILESFOLDER) + pictureUpload.FileName;
8 pictureUpload.SaveAs(FilePath);
9 ResizeImageAndSave(FilePath, 90);
10 }
11 }
12 }
13
14 public void ResizeImageAndSave(string FilePath, int Width)
15 {
16 Bitmap loBMP = new Bitmap(FilePath);
17 ImageFormat loFormat = loBMP.RawFormat;
18
19 //*** If the image is smaller than a thumbnail just return it
20 if (loBMP.Width < Width) return;
21
22 decimal lnRatio = Convert.ToDecimal(Width) / loBMP.Width;
23 int lnNewWidth = Width;
24 int lnNewHeight = Convert.ToInt32(loBMP.Height * lnRatio);
25
26 Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
27 Graphics g = Graphics.FromImage(bmpOut);
28 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
29 g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
30 g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
31
32 //Dispose old BMP object
33 loBMP.Dispose();
34
35 bmpOut.Save(FilePath);
36 bmpOut.Dispose();
37 }
The code is pretty obvious – save the file to the specified path, resize the image, dispose the old image and finally save the new image.
Happy Programming!
Using FlexiGrid in your ASP.NET application
I’ve been exploring JQuery for quiet some time now and I’m already a huge fan! Not only is it light-weight but its extensible too – there are plugins for everything, just name it! Well, almost everything
Today I’m going to demonstrate how we can use the excellent FlexiGrid plugin in our ASP.NET applications.
Add the following code to the head section of the document in which you want to display the grid.
2
3 <script src="scripts/jquery.js" type="text/javascript"></script>
4
5 <script src="scripts/jquery.flexigrid.js" type="text/javascript"></script>
6
7 <script type="text/javascript">
8
9 $(document).ready(function(){
10
11 $("#flex1").flexigrid
12 (
13 {
14 url: ‘GetData.aspx’,
15 dataType: ‘xml’,
16 colModel : [
17 {display: 'ISO', name : 'iso', width : 40, sortable : true, align: 'center'},
18 {display: 'Name', name : 'name', width : 180, sortable : true, align: 'left'},
19 {display: 'Printable Name', name : 'printable_name', width : 120, sortable : true, align: 'left'},
20 {display: 'ISO3', name : 'iso3', width : 130, sortable : true, align: 'left'},
21 {display: 'Number Code', name : 'numcode', width : 80, sortable : true, align: 'right'}
22 ],
23
24 /*searchitems : [
25 {display: 'ISO', name : 'iso'},
26 {display: 'Name', name : 'name', isdefault: true}
27 ],*/
28 sortname: "iso",
29 sortorder: "asc",
30 usepager: true,
31 title: ‘Countries’,
32 useRp: true,
33 rp: 15,
34 showTableToggleBtn: true,
35 width: 700,
36 height: 400
37 }
38 );
39 });
40
41 </script>
The grid is going to get its data from an aspx file called "GetData.aspx". In the Page_Load(..) event of this page, generate the XML and send it back to the requesting page.
1 int page = int.Parse( Request.Form[ "page" ].ToString() );
2 int rp = int.Parse( Request.Form[ "rp" ].ToString() );
3 string sortname = Request.Form[ "sortname" ].ToString();
4 string sortorder = Request.Form[ "sortorder" ].ToString();
5
6 string sort = String.Format( "ORDER BY {0} {1}", sortname, sortorder );
7
8 if( page == null )
9 page = 1;
10
11 if( rp == null )
12 rp = 10;
13
14 int start = ( ( page – 1 ) * rp );
15
16 string limit = String.Format( "LIMIT {0}, {1}", start, rp );
17
18 Response.ClearHeaders();
19 Response.AppendHeader( "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" );
20 Response.AppendHeader( "Last-Modified", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() );
21 Response.AppendHeader( "Cache-Control", "no-cache, must-revalidate" );
22 Response.AppendHeader( "Pragma", "no-cache" );
23 Response.AppendHeader( "Content-type", "text/xml" );
24
25
26 // Generating XML Data
27
28 EnumerableRowCollection<DataRow> data = GetCountryDataTable(sort, limit);
29
30 XDocument xmlDoc = new XDocument(
31 new XDeclaration("1.0", "utf-8", "yes"),
32
33 new XElement("rows",
34 new XElement("page", page.ToString()),
35 new XElement("total", GetTotalRecords().ToString()),
36 data.Select(row => new XElement("row", new XAttribute("id", row["iso"].ToString()),
37 new XElement("cell", row["iso"].ToString()),
38 new XElement("cell", row["name"].ToString()),
39 new XElement("cell", row["printable_name"].ToString()),
40 new XElement("cell", row["iso3"].ToString()),
41 new XElement("cell", row["numcode"].ToString())
42 )
43 )
44 )
45 );
46
47 Response.Write(xmlDoc);
48 Response.End();
Here’s the function that returns the DataRow collection.
1 private EnumerableRowCollection<DataRow> GetCountryDataTable( string sort, string limit )
2 {
3 using( DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx( String.Format( "SELECT iso,name,printable_name,iso3,numcode FROM country {0} {1}", sort, limit ) ) )
4 {
5 return sqlCmd.GetDataTable().AsEnumerable();
6 }
7 }
Finally, I used LINQ to create the XML document but you can do it using Strings or any other method you prefer.The download below does not include the MySQL connector for .NET 2.0. You will have to download it and include it in your project and remember to make the necessary changes in the connection string.
Happy Programming!