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;
  6.  
  7.     Console.Write("username: ");
  8.     username = Console.ReadLine();
  9.  
  10.     Console.Write("password: ");
  11.  
  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);
  30.  
  31.     //Console.WriteLine(username + " : " + password);
  32.     Console.WriteLine("");
  33.     
  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.

Serialize
  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; }
  8.  
  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.     }
  14.  
  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.     }
  24.  
  25.     public override int GetHashCode()
  26.     {
  27.         unchecked
  28.         {
  29.             int hash = 23;
  30.  
  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. }
  40.  
  41. public class Company
  42. {
  43.     public List<Employee> ListOfEmployees { get; set; }
  44.  
  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. }
  54.  
  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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  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 asp.net application but when I ran the application, it failed with the message "Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=10.0.0.0, 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 asp.net.

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

Reference: Shahed Kazi at AspNetify.com