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="http://www.w3.org/1999/xhtml">
  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. }
Blogger Tricks

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 asp.net.

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 15, 2014

I was trying to kill all spid that points my database but I kept getting the error message "Cannot Use Kill to kill your own Process". The error message was a bit strange as I have done this a number of times without any issues. So, basically this is what I tried.

April 14, 2014

Sql - Count by XML Attribute

I have a Sql table with a XML column and I want to do a count of rows of data grouped by an attribute value of the XML column. We might need these kind of queries when the XML attribute refer to a type of data. For example, I might have country code as AU and US that refers to two different countries where the data came from. Ok, so, how can I do that?

First, we have a sql table with an XML column to hold the data. I will use the same table as in my previous post on how to query csv from XML column. Here is a copy of the example data that I have.


To query this table, I will perform the usual sql select operation on the column and get the attribute values and then perform sql count operation from an outer sql query. Here's the script on how I did it.

Sql Script
  1. SELECT src.typeid as [TypeId],
  2.     count(src.typeid) as [Count]
  3. FROM
  4.   (
  5.     SELECT [Tag].value('(/a/@data)[1]', 'nvarchar(50)') as name
  6.         ,[Tag].value('(/a/@type)[1]', 'int') as typeid
  7.     FROM [Employee].[dbo].[Table_2]
  8.   ) src
  10.   group by src.typeid

April 11, 2014

Query Comma Separated Values in Sql

Here is a situation where I will need to select and compare values from a table in sql server which stores data in a comma separated list. Well selecting data is not a problem but we want to run a query and compare the values within the list. In my scenario, the list contains numbers only but the solution will work for both numbers and strings. One solution will be to compare using LIKE and then check if the number exist but this won't necessarily be correct as ,2, and ,22, and 12, might all return the same result and the list does not contain commas at the start or at the end.

April 10, 2014

HTML5 Data Attributes and Javascript

We have an html page or an asp.net page with html elements and I want to store some data for the html elements on the client side. Prior to html5, we might be storing the data using hidden fields or query string but it's not really a clean approach and would require some javascript and matching the element and hidden field ids before it works.

To support the above use case html elements now has a new attribute "data-" and we can specify any name after the "data-". For example, we can have a data attribute like below.

April 7, 2014

I have this scenario where I need to insert xml data to a xml column in Sql Server that already has an empty string in it. The xml column I have allows null and I need to update both null and and empty xml to a default value. When I started writing the script finding the null value was really easy - I could write something like this.

  1. SELECT xmldata
  2. from Table_1
  3. where XmlData IS NULL

But finding the xml column with empty string was difficult. First of all, I could not write the following

  1. SELECT xmldata
  2. from Table_1
  3. where XmlData = ''


as it returned error

Msg 402, Level 16, State 1, Line 2
The data types xml and varchar are incompatible in the equal to operator.

So, to solve the issue, I used the inbuilt function DataLength() on the xml column and compared if the value is 5 or not. Data length for empty string is 5. Based on this comparison, I updated the xml column.

  1. SELECT xmldata
  2. from Table_1
  3. where DATALENGTH(XmlData) = 5

I had this situation where I had a XML column in a table within a Sql Server database which allowed NULL and I had to change this to must have values. Changing this is trivial when it is a new database with some test data but in my situation, I had to modify an existing database and therefore - the quickest way to change was to add the default xml to all fields that had NULL and then to apply a default value for this column. However, when I add the default value via Sql Server Management Studio, it complained - "Error validating the default for column - column name".

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 asp.net / 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.

AppPool Recycling and Performance

In IIS, there is a setting to set the recycling conditions for Application Pools (AppPool). So, what is an AppPool? When a website is run within IIS, it runs within a single worker process (w3wp.exe). Running a single worker process puts a high load on the process. Instead, IIS allows to run multiple worker processes using AppPools. A single AppPool can run one or multiple web applications.

Now, AppPool has a recycle option which basically restarts the process. When the process recycles, the new process is started simultaneously so that no HTTP requests are missed. However, the process kills the data in the memory that the applications stores including cache data, sessions and static variables. Now this is both good and bad. It's good because any outages caused by memory leaks issue will not occur but it's bad there will be a performance hit once the process starts.


To make the above situation worse, the default settings in IIS recycles the AppPool every 1740 minutes that is 29 hours. That is, with default setting, it will recycle today at midnight, tomorrow at 5am, day after tomorrow at 10am and so on. To minimise the performance issue, we should reset the setting to a fixed time when the usage on the server is low. The performance issue will still be there but it will impact a lot less number of people this way.

Reference: Shahed Kazi at AspNetify.com