Showing posts with label Show all posts
Showing posts with label Show all posts

January 30, 2015

I have a website that I configured to use https using IIS and have setup the links to point to the https version of the site. However, IIS does not automatically redirect the http version of the site to https and instead display error messages on the screen. This is bad as other sites had linked to the http version of prior to setting up https.

January 8, 2015

In this post, I will show how to read a single file from a password protected zip file and then display it on a web browser. This scenario might be more required in a windows application but since the focus is to read from the zip file than to display it on the web browser, I will go ahead with browser.

To read from the zip file, I am using a NuGet package - SharpZipLib. This library can ne used to read a password protected zip file. If you are not familiar on how to add or manage NuGet packages, then check the NuGet Docs. After the package is added, I will use the ICSharpCode.SharpZipLib.Zip to read the zip file.

December 30, 2014

Load XML in a GridView using Asp.Net

Xml files can be loaded into a GridView control in To load xml files, it can be usually binded to the GridView by creating the xml data source and then setting the data source property of the GridView. However, if xml files contains nodes, then it does not work and instead produces error -

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

To bind the xml file with nodes, it's easier to create a dataset and then to bind it to the gridview from code behind. Here is an example of how that would work.

Sample Xml File
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Customers>
  3.   <Customer>
  4.     <Id>C1</Id>
  5.     <Name>John</Name>
  6.     <DateOfBirth>9 Jan 1960</DateOfBirth>
  7.     <Phone>99999999</Phone>
  8.     <Address>Canberra</Address>
  9.   </Customer>
  10.   <Customer>
  11.     <Id>C2</Id>
  12.     <Name>Smith</Name>
  13.     <DateOfBirth>10 August 1980</DateOfBirth>
  14.     <Phone>88888888</Phone>
  15.     <Address>Sydney</Address>
  16.   </Customer>
  17.   <Customer>
  18.     <Id>C3</Id>
  19.     <Name>Peter</Name>
  20.     <DateOfBirth>12 June 1978</DateOfBirth>
  21.     <Phone>77777777</Phone>
  22.     <Address>Melbourne</Address>
  23.   </Customer>
  24. </Customers>


aspx page
  1.     <div>
  2.     <asp:GridView ID="GridView1" runat="server">
  3.     </asp:GridView>
  4. </div>


Code to bind xml to gridview
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     if (!IsPostBack)
  4.     {
  5.         DataSet ds = new DataSet();
  6.         ds.ReadXml(MapPath("~/App_Data/data.xml"));
  7.         GridView1.DataSource = ds;
  8.         GridView1.DataBind();
  9.     }
  10. }

December 17, 2014

Properties of uploaded image provide option to upload files like images using FileUpload control but how can we find out certain properties of the image like file size and dimensions. In this post, I will show how to find those properties.

First, in the design view, I got a FileUpload control and a Button. The image will be uploaded when the button is clicked.

  1. <div>
  2.     <asp:FileUpload ID="fu1" runat="server" />
  3.     <asp:Button ID="b1" runat="server" Text="Save" OnClick="b1_Click" />
  4. </div>

In the code-behind, I am using System.Drawing.Image to get image dimension and ContentLength property to get the file size as shown below.

  1. protected void b1_Click(object sender, EventArgs e)
  2. {
  3.     System.Drawing.Image img = System.Drawing.Image.FromStream(fu1.PostedFile.InputStream);
  4.     double height = img.Height;
  5.     double width = img.Width;
  7.     double filesize = fu1.PostedFile.ContentLength / 1024;
  9.     //do something with the values
  10. }

August 20, 2014

Form Data is not valid

I have this web forms application through which users can log on and view a number of records from a database and then make modification as needed. However, as the number of records have increased for users; for some users with a large number of records, the site is failing with the message "form data is not valid".

Since the issue is happening only for large accounts, I was somewhat certain that it's related to the number of form elements that can be posted back to the server. Microsoft introduced an upper limit to the number of the form elements that can be posted back to the server - So, to fix the issue, I added a new app setting in web.config file called "aspnet:MaxHttpCollectionKeys" and set its value to a number - 5000. And that's it - the site started working fine again.

Just to be clear though, I think this is a temporary fix and the application should be modified anyway as sooner or later that new limit might be reached as well.

July 18, 2014

I deployed an application but when I ran the application, it failed with the message "Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified." . I re-checked the web.config file and it had the following line under assembly section

July 16, 2014

Browser Back Button Working After Logout

Here is a scenario in an application where the user logs out which takes them back to the login page but when the user hits the back button, he/she can view the previous page. During the log out event, Session is cleared and caching is disabled but the previous page is still shown. So, how can we work around this?

The browser history is an option to go back to previously visited pages (both forward & backward). The browser caches psges visited and the history buttons - backward and forward can be considered as a pointer that is linked to the page previously visited by the user.

So, to fix the issue, we need to make sure the pages don't get cached. Since the pages are behind authentication - it makes perfect sense not to cache the pages at all. We can implement the caching or not caching in the following ways in

Option 1 - Code behind
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  4.     Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
  5.     Response.Cache.SetNoStore();
  6. }


Option 2 - Works on any page
  1. <head runat="server">
  2.     <title></title>
  3.     <meta http-equiv="Cache-Control" content="no-cache" />
  4.     <meta http-equiv="Pragma" content="no-cache" />
  5.     <meta http-equiv="Expires" content="0" />
  6. </head>


In the above code, you can paste the code in the master page for the authenticated pages or alternatively, if there is no fixed master page for authenticated pages - then, it needs to be places on all all required pages.

July 10, 2014

List of Cultures in Asp.Net

Ever wondered the list of cultures and languages available in Here's how you can get the whole list.

May 29, 2014

In the previous post, I showed how to save an image to a database. In this post, I will show how to retrieve an image and display it in an page. Note that the image is saved in bytes format rather than as a file and displaying it in an Image control requires more work. Therefore, in this post, I have used the html img element to display the image.

May 26, 2014

Save Image to Sql Server

Sql server allows for the "Image" data type that can be used to save images in databases. In this post, I will show how to save an image to the database. In a nutshell, I will use a File Upload control to upload the image and use entity framework to save the image.

May 7, 2014

In, Response.Redirect, PostBackUrl and Server.Transfer are similar but all of these are somewhat different. In this post, I will go through the differences of these three approaches.


This will cause the browser to load the specified page. The page may or may not be part of the existing application. This will result in a http get and the new page will not have access to any data on the current page. This can be triggered by any control that performs postback or even on Page_Load event.

Response.Redirect can be set in the following way.

  1. protected void b1_Click(object sender, EventArgs e)
  2. {
  3.     Response.Redirect("some page");
  4. }



PostBackUrl property can only be set on an button control. The UseSubmitBehavior property needs to be set to true. This will result in a http post and the new page can retrieve current page's data using Request.Form and Page.PreviousPage. The user will notice the change in the once the button is clicked. PostBackUrl can contain pages from current application or any other pages as well.

PostBackUrl is set in the following way.

  1. <asp:Button ID="b1" runat="server" Text="postback" PostBackUrl="~/PostBack2.aspx" UseSubmitBehavior="true" />


To retrieve data,

protected void Page_Load(object sender, EventArgs e)
    l1.Text = Request.Form["t1"];
    l1.Text += ((TextBox)this.PreviousPage.FindControl("t1")).Text;


Server.Transfer performs a http post and data can be obtained similar to PostBackUrl, that is, using both Request.Form and Page.PreviousPage. Server.Transfer can only transfer to a page in the current application. Also the url does not change in the browser. Like Response.Redirect, this can be triggered by any control that performs postback or even on Page_Load event.

Server.Transfer can be used in the following way.

protected void b2_Click(object sender, EventArgs e)

To retrieve data,

protected void Page_Load(object sender, EventArgs e)
    l1.Text = Request.Form["t1"];
    l1.Text += ((TextBox)this.PreviousPage.FindControl("t1")).Text;

May 6, 2014

jQuery not working within Update Panel

I wrote this jQuery validation for a site and it all worked in my test page but for some reason it stopped working in the real page. Since the real page is a currently live, I started creating and testing the validation on the dummy page first. After some debugging for finding the issue, I realised that the jQuery is not running within the actual page since the controls and html elements are within the Update Panel.

May 1, 2014

Most (if not all) web sites will have a default start page for example, default.aspx, index.aspx, home.aspx, etc. The default start page kicks in when someone goes to a url that does not refer to the page (no file extension) but possibly to a folder - for example, or . Without the default page, the user will be shown or not shown the directory listing page depending on the IIS configuration. For security reasons, it's better not to show end users the directory listing page. I once saw an application with directory listing that was showing the log folder and files.

April 29, 2014

Data attributes are a cool way to store extra data for html elements. Previously, when we needed to store additional data for an html element we would store it hidden elements whereas now with data attributes, we can store it within the html element itself as shown below.

  1. <li data-test="test">data</li>


Since data attributes are standard html attributes, we can use it within as well. Here's an example on how we can load country / capital data within a ListView control, store the capital information as data attribute and then display the capital when the user hovers over the country using jQuery.

April 22, 2014

In this post, I will show how to upload multiple files at once using the File Upload control and jQuery's uploadify plugin. Download the Uploadify plugin if you have not already done so. Copy the uploadify.css, uploadify.min.js and uploadify.swf to your project in appropriate folders. For example, I have copied the javascript file to scripts folder and so on. Using javascript, I will specify the file types that can be uploaded using the "fileExt" parameter. Also, I have assigned paths to the swf and a handler. The handler is the file that will handle the request unlike the usual way of performing file uploads within the code behind file. Here's the source code for the page.

  1. <!DOCTYPE html>
  3. <html xmlns="">
  4. <head runat="server">
  5.     <title></title>
  6.     <script src="scripts/jquery.min.js"></script>
  7.     <script src="scripts/jquery.uploadify.min.js"></script>
  8.     <link href="css/uploadify.css" />
  9.     <script type="text/javascript">
  10.         $(function () {
  11.             $("#<%=FU1.ClientID %>").uploadify({
  12.                 'swf': 'scripts/uploadify.swf',
  13.                 'uploader': '/Handler/FileHandler.ashx',
  14.                 'cancelImg': 'cancel.png',
  15.                 'buttonText': 'Choose Files to Upload',
  16.                 'fileDesc': 'Image Files',
  17.                 'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
  18.                 'multi': true,
  19.                 'auto': true
  20.             });
  21.         })
  22. </script>
  23. </head>
  24. <body>
  25.     <form id="form1" runat="server">
  26.     <div>
  27.     <asp:FileUpload ID="FU1" runat="server" />
  28.     </div>
  29.     </form>
  30. </body>
  31. </html>

The Handler basically gets the files uploaded and the saves it to a specified folder. In this instance, I am saving it to the UserFiles folder within the application. Make sure you have already created the folder with the correct permissions (read / write attributes). Here's the source code for the handler.

File Upload Handler
  1. public class FileHandler : IHttpHandler
  2. {
  4.     public void ProcessRequest(HttpContext context)
  5.     {
  6.         context.Response.ContentType = "text/plain";
  7.         HttpPostedFile uploadFiles = context.Request.Files["Filedata"];
  8.         string pathToSave = HttpContext.Current.Server.MapPath("~/UserFiles/") + uploadFiles.FileName;
  9.         uploadFiles.SaveAs(pathToSave);
  10.     }
  12.     public bool IsReusable
  13.     {
  14.         get
  15.         {
  16.             return false;
  17.         }
  18.     }
  19. }

April 16, 2014

Bind Enum to DropDownList in Asp.Net

Enum in C# is a quick way to store constants. We can also assign value like int or chars to the constants. In other words, we can have a basic key - value sort of scenario with enums. Okay, so, how can I use a enum and bind it to a dropdownlist in

To analyse what we need to do, we basically need to pull the names and the values from the enum and say a particular key has a particular value. Enums do not have a way to export the data to a list but it can export the list of names and list of values separately. The lists produced are in the same order and so we can say list[value] belongs to list[key].

April 4, 2014

In a web page, a lot of content and different types of files are transferred from the server to the client - for example, dynamic content from / mvc, and static content like images, css and javascripts. All these types of files add to performance hit. To avoid some of these problems we can cache the static content to the client browser. So, in this post, I will talk about how to add expire header to the static files.

April 1, 2014

Ok, this one is interesting and not something that I prefer doing but on one the tasks that I was working on - I had to call a method on an aspx page from a user control within the page. It's not good practice to call page's methods from user controls as the user control should not have to know the page where it can be used. So, how can we do it.

March 31, 2014

Different ways to combine urls

In, there are different way to combine urls with the easiest way to simply add multiple strings and the better way to use classes and methods already from In this post, I will show different way to add multiple url parts to form a valid url.

In there are few classes with urls can be constructed like the Uri class. However, I actually prefer the use of UriBuilder class as it provides more options to specify the parameters like host, query string, anchor links, port number and so on. This is much easier class to work with than to build urls with other classes. So, below is the source code for two ways to build urls - one with concatenating strings and another with UriBuilder class.

String vs UriBuilder
  1. using System;
  2. using System.Text;
  4. namespace WebApplication1
  5. {
  6.     public partial class UrlParts : System.Web.UI.Page
  7.     {
  8.         private bool isSecure = false;
  9.         private string host = "";
  10.         private int? port = 8080;
  11.         private string path = "mvc";
  12.         private string query = "s=entity|framework";
  13.         private string hash = "ef";
  15.         //http: //|framework#ef
  17.         protected void Page_Load(object sender, EventArgs e)
  18.         {
  19.             Response.Write("from string: " + UrlsByStrings());
  20.             Response.Write("<br>from url builder: " + UrlsByUriClass());
  21.         }
  23.         private string UrlsByStrings()
  24.         {
  25.             StringBuilder sb = new StringBuilder();
  27.             if (isSecure)
  28.                 sb.Append("https://");
  29.             else
  30.                 sb.Append("http://");
  32.             sb.Append(host);
  34.             if (port.HasValue)
  35.                 sb.Append(":" + port.Value.ToString());
  38.             if (path != null)
  39.                 sb.Append("/" + path);
  42.             if (query != null)
  43.                 sb.Append("?" + query);
  45.             if (hash != null)
  46.                 sb.Append("#" + hash);
  48.             return sb.ToString();
  49.         }
  52.         private string UrlsByUriClass()
  53.         {
  54.             UriBuilder ub = new UriBuilder();
  55.             ub.Scheme = isSecure ? "https" : "http";
  56.             ub.Host = host;
  58.             ub.Port = port.HasValue ? port.Value : -1;
  59.             ub.Path = path == null ? string.Empty : path;
  60.             ub.Query = query == null ? string.Empty : query;
  61.             ub.Fragment = hash == null ? string.Empty : hash;
  63.             return ub.ToString();
  64.         }
  65.     }
  66. }

March 30, 2014

I can do lot of cool things with but sometimes I don't like the idea of postbacks, specially when working on large pages. Imagine a page with a number of controls and every postback will send the controls data back and and forth and recreate the controls. So, how can I write and call methods on code-behind from aspx pages without using postbacks.

Reference: Shahed Kazi at