April 30, 2014

I had this strange issue earlier today where I could not log into windows azure portal. The error message was irritating and yet funny and the site kept saying "you cannot login to the windows azure as you have logged out from somewhere else" and then "clock OK to log out". However, when log out button is clicked it takes some time and then eventually it comes back with the message that it cannot sign me out of windows azure portal.

April 29, 2014

Send Email using Gmail and C#

Many of us use gmail for emails and it is possible to send emails using code and gmail as host. In this post, I will show how to send emails using gmail and C#. It is actually really easy to send emails via gmail. We just need to

I was working on a Sql server database and since there were few issues, I copied the backup of the database to run some queries. Since I don't use it often and the database is huge, I saved the mdf file in an external hard drive but then I notice that every now then when I open Sql Server  Management Studio, the database fails to open with the message "Recovery Pending".

To solve this issue, I can simply reload the database from the backup but then I will need access to the backup file every time. Alternatively, I can write a few queries to solve this issue.

To start with, I will set the database to Emergency state and change it to a Single User mode.

  1. USE master
  2. GO
  4. --run 1
  6. GO
  8. GO


Next, check if the database has errors using CHECKDB command.

  1. --run 2

This is the step where you need to decide what to do with the errors that you have received. Depending on your scenario, you can repair the database with or without any data loss.

  1. --run 3
  2. --no data loss
  5. --potential data loss


Finally, change the database mode to multi user mode.

  1. --run 4
  3. GO


Your database should be running again now.

Convert between XDocument and XmlDocument

In one of the applications I was working, I noticed that as we have developed the application we have used both System.Xml and System.Xml.Linq namespaces. Now this can happen for a number of reasons including that as the application got developed, the new namespaces were used but the old code has not been refactored and it's not a priority as well as the latest .NET framework supports it. However, sometimes we might need to convert files from old to new version and vice versa. In my situation, I had to convert XDocument to XmlDocument and vice versa. To cater for this requirement I wrote a class with static methods that perform the conversion taking advantage of the XmlNodeReader and XmlReader classes.

Here's the sample code of the class.

XDoc to XmlDoc
  1. public class XmlConversion
  2. {
  3.     public static XmlDocument ToXmlDocument(XDocument xdoc)
  4.     {
  5.         var xmlDocument = new XmlDocument();
  6.         using (var reader = xdoc.CreateReader())
  7.         {
  8.             xmlDocument.Load(reader);
  9.         }
  10.         return xmlDocument;
  11.     }
  13.     public static XDocument ToXDocument(XmlDocument xmlDoc)
  14.     {
  15.         using (var reader = new XmlNodeReader(xmlDoc))
  16.         {
  17.             reader.MoveToContent();
  18.             return XDocument.Load(reader);
  19.         }
  20.     }
  21. }

Few days back I ran into a issue where my website failed with the message that

  1. {System.Data.SqlClient.SqlException (0x80131904): Could not allocate space for object 'dbo.Table1'.'PK_TableID' in database 'TestDB' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.
  2. Uncommittable transaction is detected at the end of the batch. The transaction is rolled back.


Initially I thought the database was out space but then it sounded strange as I was not expecting the database to run out of space. After checking the database space I noticed that it only had a few MBs of data remaining for the primary while the log file had a huge data capacity. To fix the issue, update the max size of the database so it can save the data. Also, make sure the server has sufficient space to cater for the increased space.

However, sooner or later you are going to run out of space and therefore it's a good idea to increase the max size to unlimited but you need to make sure the server can cater for it.

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 asp.net 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 24, 2014

I am trying to debug a code where a web service was being consumed by both .NET and Java application. I was in a scenario where I had to generate the raw request and response xml file and share it with the java developer. Usually, we can simply call the objects / methods in .net and so how can we view the raw request and response files when calling the web services. To work on this scenario, we can take advantage of System.Web.Services.Protocols.SoapExtension in .NET and create our own class by implementing the SoapExtension class.

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. }

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.

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.

Reference: Shahed Kazi at AspNetify.com