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.

I build an application using Visual Studio and Sql Server and built the model using Entity Framework but when I deployed the application, I keep getting an error. To give bit more information, I set up the database using Sql Server 2012 and applied the compatibility level to Sql Server 2005 as the database server only had Sql Server 2005. Ya, I know it's an old server but it's not a priority to the business to update that server.

So, after running the application against the production database, I realised that the error is happening from the database server and not from the web server. Basically, it's failing to a add a record when the table has a datetime column and it's failing with the message "The version of SQL Server in use does not support datatype 'datetime2'". I was a bit confused as I thought I have applied the compatibility settings correctly.

To further test, I reloaded the data model from the Sql Server 2005 database but the error was still there.

Now, to fix the issue, I opened the edmx file in an xml editor and within <edmx:StorageModels> element there is "ProviderManifestToken" attribute in "Schema" element. The value for "ProviderManifestToken" was set to 2008. Bingo. I changed that value to 2005 and recompiled the application which fixed the issue.

This is probably a bug in Entity Framework as it not picking up the right database and instead applying a default lowest value.

To apply the compatibility level, right click the database name in SQL Server Management Studio, and click on Properties, navigate to Options and then set compatibility level.


Models in an MVC application are just classes and therefore it is easy to add data annotations in the class itself. When MVC generates the views, the different field names and validation messages and datatypes are automatically generated. For example, the following can be a data model in an application.

The above LoginModel is copied from the auto generated template in an MVC application. Note that the data annotations like "Required", "DataType" are applied. However, if the model is generated from Entity Framework, these data annotations will not appear and how would we add the necessary data annotations.

So, to add annotations to an Entity model, we can take advantage of the System.ComponentModel.DataAnnotations.MetadataTypeAttribute class that allows to specify the metadata class to use with the data model class. So, we need to create a new class specify the metadata attribute which will link the data model class to another class which will contain all the data annotations for the necessary fields.

Here is an example of how this would work.

public partial class Account
    //empty class just to apply class level attribute
    //imagine this as data annotations for Account
    //is in AccountMetaData class

public class AccountMetaData
    //same property name & type as in the Entity model
    [Display(Name = "Date of Birth of date")]
    public DateTime DateOfBirth;

    [MinLength(6, ErrorMessage = "Too short")]
    public string AnnountName;

I am working on an older product and updating it to use the latest version of .NET and Entity Framework. Now that I have created the Entity Framework model using database first approach, I am finding issues like "EntityType 'EntityName' has no key defined". Basically, what this means is that the table in the database does not have a primary key defined. To fix the issue, the database needs to be updated and a primary key needs to be defined.

I have downloaded a visual studio solution from a source control repository like github or tfs but now the project is not building. It's giving an error message - referenced component 'EntityFramework' could not be found.

In this scenario, the issue is that Entity Framework has been added as a NuGet package and the package has not been restored. It's not necessary to store packages in source control as these can be downloaded and installed on the fly. So, to enable automatic restore of packages, click on Tools > NuGet Package Manager > Package Manager Settings . A prompt will appear where "Allow NuGet to download missing packages" and "Automatically check for missing packages during build in visual studio" needs to be ticked.

July 25, 2014

Select Top 1 or Top n basically returns the first n rows of data based on the sql query. Select Top 1 1 or Top n s will return the first n rows with data s depending on the sql query.

I generated two scripts using Database project in Visual studio - one for updating the database and another for rollback if deployment fails. When I ran the update script, the database updated fine but I ran the rollback script - it failed with the message "Rows were detected. The schema update is terminating because data loss might occur". The issue is somewhat obvious; I have added new fields in a table and if I rollback, meaning if drop those fields then any data in those fields will be lost. So, how can we create script so we can run it. Since the script is needed for rollback, it might be necessary to run it.

July 22, 2014

I am building a console application that checks for username and password before proceeding. However, by default, the characters typed in console will appear which is not good as I don't want to display the password the user types in. So, how can I hide or mask the password.

In this code snippet, I will show how we could mask the password. In short, I will read through the characters entered for password and mask it using empty characters. Backspace will still work as expected. If the user hits the Enter key, it will move on for the next prompt.

  1. static void Main(string[] args)
  2. {
  3.     string username = string.Empty;
  4.     string password = string.Empty;
  5.     ConsoleKeyInfo key;
  7.     Console.Write("username: ");
  8.     username = Console.ReadLine();
  10.     Console.Write("password: ");
  12.     do
  13.     {
  14.         key = Console.ReadKey(true);
  15.         if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
  16.         {
  17.             password += key.KeyChar;
  18.             Console.Write(string.Empty);
  19.         }
  20.         else
  21.         {
  22.             if (key.Key == ConsoleKey.Backspace && password.Length > 0)
  23.             {
  24.                 password = password.Substring(0, (password.Length - 1));
  25.                 Console.Write("\b \b");
  26.             }
  27.         }
  28.     }
  29.     while (key.Key != ConsoleKey.Enter);
  31.     //Console.WriteLine(username + " : " + password);
  32.     Console.WriteLine("");
  34.     //Console.WriteLine("Is Authenticated: " + (AuthenticateUser(username, password)).ToString());
  35.     Console.ReadLine();
  36. }

July 18, 2014

Serialize Object to Xml

In this example, I will show how to serialize an object in xml. In this post, I will use an Employee object, create a List of Employees and then serialize the object to xml. Serialization can data from objects needs to be saved in the filesystem or other storage and then used later for retrieval. Here is the code on how this can be achieved.

  1. public class Employee
  2. {
  3.     public string FirstName { get; set; }
  4.     public string LastName { get; set; }
  5.     public DateTime DateOfBirth { get; set; }
  6.     public DateTime DateJoined { get; set; }
  7.     public bool IsRetired { get; set; }
  9.     public override string ToString()
  10.     {
  11.         return "First Name: " + FirstName + "\nLastName: " + LastName + "\nDate of Birth: " + DateOfBirth
  12.             + "\nDate Joined: " + DateJoined + "\nIs Retired? " + IsRetired;
  13.     }
  15.     public override bool Equals(object obj)
  16.     {
  17.         Employee em = (Employee)obj;
  18.         return this.FirstName == em.FirstName
  19.             && this.LastName == em.LastName
  20.             && this.DateOfBirth == em.DateOfBirth
  21.             && this.DateJoined == em.DateJoined
  22.             && this.IsRetired == em.IsRetired;
  23.     }
  25.     public override int GetHashCode()
  26.     {
  27.         unchecked
  28.         {
  29.             int hash = 23;
  31.             hash = FirstName == null ? hash * 11 : hash * 17 + FirstName.GetHashCode();
  32.             hash = LastName == null ? hash * 19 : hash * 17 + LastName.GetHashCode();
  33.             hash = DateOfBirth == null ? hash * 13 : hash * 17 + DateOfBirth.GetHashCode();
  34.             hash = DateJoined == null ? hash * 7 : hash * 17 + DateJoined.GetHashCode();
  35.             hash = IsRetired == null ? hash * 7 : hash * 17 + IsRetired.GetHashCode();
  36.             return hash;
  37.         }
  38.     }  
  39. }
  41. public class Company
  42. {
  43.     public List<Employee> ListOfEmployees { get; set; }
  45.     public Company()
  46.     {
  47.         List<Employee> list = new List<Employee>();
  48.         list.Add(new Employee() { FirstName = "John", LastName = "Smith", DateJoined = new DateTime(2007, 10, 12), DateOfBirth = new DateTime(1960, 2, 8), IsRetired = false });
  49.         list.Add(new Employee() { FirstName = "Jake", LastName = "Troy", DateJoined = new DateTime(2010, 1, 13), DateOfBirth = new DateTime(1980, 2, 18), IsRetired = true });
  50.         list.Add(new Employee() { FirstName = "Shawn", LastName = "Clark", DateJoined = new DateTime(2008, 12, 15), DateOfBirth = new DateTime(1990, 12, 8), IsRetired = false });
  51.         ListOfEmployees = list;
  52.     }
  53. }
  55. public class TestSerialize
  56. {
  57.     public string Serialize()
  58.     {
  59.         XmlSerializer xSer = new XmlSerializer(typeof(Company));
  60.         var req = new Company();
  61.         StringWriter sw = new StringWriter();
  62.         XmlWriter writer = XmlWriter.Create(sw);
  63.         xSer.Serialize(writer, req);
  64.         return sw.ToString();
  65.     }
  66. }


Once the code is run, the xml produced looks like below.

Resultant xml
  1. <?xml version="1.0" encoding="utf-16"?>
  2. <Company xmlns:xsi="" xmlns:xsd="">
  3.   <ListOfEmployees>
  4.     <Employee>
  5.       <FirstName>John</FirstName>
  6.       <LastName>Smith</LastName>
  7.       <DateOfBirth>1960-02-08T00:00:00</DateOfBirth>
  8.       <DateJoined>2007-10-12T00:00:00</DateJoined>
  9.       <IsRetired>false</IsRetired>
  10.     </Employee>
  11.     <Employee>
  12.       <FirstName>Jake</FirstName>
  13.       <LastName>Troy</LastName>
  14.       <DateOfBirth>1980-02-18T00:00:00</DateOfBirth>
  15.       <DateJoined>2010-01-13T00:00:00</DateJoined>
  16.       <IsRetired>true</IsRetired>
  17.     </Employee>
  18.     <Employee>
  19.       <FirstName>Shawn</FirstName>
  20.       <LastName>Clark</LastName>
  21.       <DateOfBirth>1990-12-08T00:00:00</DateOfBirth>
  22.       <DateJoined>2008-12-15T00:00:00</DateJoined>
  23.       <IsRetired>false</IsRetired>
  24.     </Employee>
  25.   </ListOfEmployees>
  26. </Company>

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

jQuery Validation and jQuery Unobtrusive Validation are validation frameworks for validating data in web pages. The main difference between the two is that jQuery Validation requires javascript codes to be entered in the page whereas jQuery Unobtrusive Validation requires the validation related data to be available in the data- attributes for the html elements. So, with the first option, the html elements will contain javascripts in it whereas with the later, the code will be lot cleaner.

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.

I run an instance of Sql Server in my local machine but noticed that my laptop is running very low in memory. So, I stopped the Sql Server by right clicking on the "Sql Server" name in Sql Server Management Studio and clicked Stop. A few prompts appeared that I had to click to stop the Sql Server.

July 11, 2014

I have set up a website using Windows Azure and have created a sql database on azure but when I run the site, I get the error message "There is already an open DataReader associated with this Command". In my previous post, I showed how to resolve this issue with Entity Framework; however, even after setting the connection string correctly, that is adding 'MultipleActiveResultSets=True' did not fix the issue.

So, after few trials and errors, I figured that the connection string needs to be modified from within the website configuration in Azure portal as well. So,

  • Login to Azure portal,
  • Navigate to the website from the left hand panel,
  • Click on configure from the top menu,
  • Scroll to "Connection String" section towards the bottom of the screen,
  • Click to edit and add MultipleActiveResultSets=True;

That should be it. The issue should be resolved now. Enjoy.

July 10, 2014

While retrieving data from a Sql Server database using Entity Framework, I have sometimes received the error "There is already an open DataReader associated with this Command which must be closed first.". Entity Framework handles database connections properly, so what exactly is this issue?

Ater diving into it, I figured that the MultipleActiveResultSets attribute is set to false in the connection string which should be turned to true as there are multiple data retrieval commands running against a single database connection and maybe a select statement is running while another select statement is already executing.

Changing the MultipleActiveResultSets attribute to true fixed the issue. Here is a sample connection string.

  1. <add name="DemoEntities" connectionString="metadata=res://*/DemoLogic.DemoModel.DemoModel.csdl|res://*/DemoLogic.DemoModel.DemoModel.ssdl|res://*/DemoLogic.DemoModel.DemoModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Demo;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient"/>

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.

July 7, 2014

I am using Entity Framework to insert data to a database and I am getting the exception below.

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at MethodName(Int32 id, ...) in c:\Users\project\filename.cs:line 33}

June 5, 2014

I have this table that has a reference to itself and to use entity framework and query the table in an application. Creating associations to is not usual but can help in certain scenarios, for example, if you have a table containing Employee details and you want to manage Manager relation in the same table. In the post, I will use the above example and have EmployeeId and ManagerId in the same table and set the proper associations.

I cloned a project from source control repository and then opened it Visual Studio and straight way got a message that I cannot switch branches because of ResolveAssemblyReference.cache . So, what exactly is  ResolveAssemblyReference.cache?

I did searches in internet and most answers were not to worry about it. MSDN claims that this and other files like - ResolveAssemblyReferences, ResolveCOMReferences, GetFrameworkPaths, and CopyRunEnvironmentFiles - are needed for the design time in Visual Studio to work properly and intellisense may fail, however, there is no issues in building the project if these files are missing.

After thinking about it, I figured that the initial project is created using Visual Studio 2013 whereas I was loading the project in Visual Studio 2012 which is why the file generated was different from the one downloaded.

May 30, 2014

I am trying to add a database diagram for the tables in Sql Server Management Studio and it's failing with the message "Database diagram support objects cannot be installed because this database does not have a valid owner". This is a bit weird as I thought the owner is already set.

Get System Information using C#

In this post, I will quickly show how to get system related information like machine name, user name, domain name, or how long ago the system started, etc. Most of these information can be retrieved from System.Environment class and I will take advantage of this class to display this data.

Below is an example of how most of these information can be obtained from the System.Environment class.

System Information using asp.n
  1. using System;
  3. namespace WebApplication3
  4. {
  5.     public partial class Info : System.Web.UI.Page
  6.     {
  7.         protected void Page_Load(object sender, EventArgs e)
  8.         {
  9.             GetSystemInfo();
  10.         }
  12.         private void GetSystemInfo()
  13.         {
  14.             string br = "<br/>";
  15.             Response.Write("Machine Name: " + Environment.MachineName + br);
  16.             Response.Write("OS Version: " + Environment.OSVersion + br);
  17.             Response.Write("System Directory: " + Environment.SystemDirectory + br);
  18.             Response.Write("Domain Name: " + Environment.UserDomainName + br);
  19.             Response.Write("User name: " + Environment.UserName + br);
  20.             Response.Write("CLR version: " + Environment.Version + br);
  21.               Response.Write("System Started: " + Environment.TickCount / (1000 * 60 * 60) + "hours ago"+ br);
  22.             Response.Write("No of processors: " + Environment.ProcessorCount + br);
  23.             Response.Write("Current Directory: " + Environment.CurrentDirectory + br);
  25.         }
  26.     }
  27. }

May 29, 2014

Tables in a database can many to many relationships. For example, an Order can contain multiple Items and an Item can be in multiple Orders. In this scenario, the tables are linked to each other using a link table that contains the OrderId and ItemId. Here is how the table structure looks like.

Table Structure
  1. USE [Employee]
  2. GO
  5. GO
  7. GO
  8. CREATE TABLE [dbo].[Item](
  9.     [ItemId] [int] IDENTITY(1,1) NOT NULL,
  10.     [ItemName] [nvarchar](50) NOT NULL,
  12. (
  13.     [ItemId] ASC
  15. ) ON [PRIMARY]
  17. GO
  18. /****** Object:  Table [dbo].[Order]    Script Date: 29/05/2014 7:04:15 PM ******/
  20. GO
  22. GO
  23. CREATE TABLE [dbo].[Order](
  24.     [OrderId] [int] IDENTITY(1,1) NOT NULL,
  25.     [OrderName] [nvarchar](50) NOT NULL,
  27. (
  28.     [OrderId] ASC
  30. ) ON [PRIMARY]
  32. GO
  33. /****** Object:  Table [dbo].[OrderItem]    Script Date: 29/05/2014 7:04:15 PM ******/
  35. GO
  37. GO
  38. CREATE TABLE [dbo].[OrderItem](
  39.     [OrderId] [int] NOT NULL,
  40.     [ItemId] [int] NOT NULL
  41. ) ON [PRIMARY]
  43. GO
  44.   ALTER TABLE [dbo].[OrderItem]  WITH CHECK ADDCONSTRAINT [FK_OrderItem_Item] FOREIGN KEY([ItemId])
  45. REFERENCES [dbo].[Item] ([ItemId])
  46. GO
  47. ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Item]
  48. GO
  49.   ALTER TABLE [dbo].[OrderItem]  WITH CHECK ADDCONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
  50. REFERENCES [dbo].[Order] ([OrderId])
  51. GO
  52. ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
  53. GO


To import these tables in Entity Framework model, I will create a new edmx file and drag and drop the tables into the designer view. You will notice that the link table does not appear in the designer view and the link is denoted by a line with multiple (*) sign at both ends.


Now the model can be queried in the usual way as we would query any other entity framework model. Here is an example on how to get Items by OrderId and to add Items and Orders in the database.

Query Model
  1. using System.Collections.Generic;
  2. using System.Linq;
  4. namespace WebApplication3.Helper
  5. {
  6.     public class ItemOrderBll
  7.     {
  8.         private List< Model.Item> GetItemsByOrderId(int orderId)
  9.         {
  10.             using(Model.EmployeeEntities en = new Model.EmployeeEntities())
  11.             {
  12.                 return (from c in en.Items
  13.                         from d in en.Orders
  14.                         where d.OrderId == orderId
  15.                         select c).ToList();
  16.             }
  17.         }
  19.         private void AddStuff()
  20.         {
  21.             using (Model.EmployeeEntities en = new Model.EmployeeEntities())
  22.             {
  23.                 Model.Item item1 = new Model.Item() { ItemName = "Item 1" };
  24.                 Model.Item item2 = new Model.Item() { ItemName = "Item 2" };
  26.                 Model.Order order1 = new Model.Order() { OrderName = "Order 1" };
  27.                 Model.Order order2 = new Model.Order() { OrderName = "Order 2" };
  29.                 order1.Items.Add(item1);
  30.                 item2.Orders.Add(order2);
  32.                 en.SaveChanges();
  33.             }
  34.         }
  35.     }
  36. }
Reference: Shahed Kazi at