Immediate Window in VB.NET

If you’re in debugging a VB.NET execution in the Immediate Window, to view the value you use the question mark:

? strpassword

Otherwise you’ll get :

Property access must assign to the property or use its value.

Error Logging in ASP.NET MVC with ELMAH

Error logging in ASP.NET MVC is extremely easy with ELMAH (Error Logging Modules and Handlers). I suggest you get it from NuGet:

Once you have it installed, it can instantly start recording errors, even Yellow Screens of Deaths. Here’s a list of errors from Elmah:

So what happens, is after you set it up via NuGet, you can get started viewing issues (if there are any) via elmah.axd. So in my case:

http://localhost:56598/elmah.axd

Now, if you’re using Chrome, and you view this page, Chrome will try to request for favicon.ico, which is not delivered from this web page. So, you have to write a filter in your web.config to ignore the .ico file:

     .
     .
     .
  <elmah>    
    <errorFilter>
      <test>
        <regex binding="Context.Request.ServerVariables['URL']" pattern="/favicon\.ico(\z|\?)" />     
      </test>
    </errorFilter>    
  </elmah>
 
</configuration>

Or if you want to completely ignore 404 errors:

     .
     .
     .
  <elmah>    
    <errorFilter>
      <test>
        <equal binding="HttpStatusCode" value="404" type="Int32" />     
      </test>
    </errorFilter>    
  </elmah>
</configuration>

By default, ELMAH stores error details in memory, so every time the app pool gets restarted, it gets flushed. To dump the data to SQL Server instead, update your web.config:

  <elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ElmahConnectionString"/>
  </elmah>
</configuration>

The Elmah connection string is pretty straightforward:

<connectionStrings>
  <add name="ElmahConnectionString " connectionString="Initial Catalog=my_database;data source=.\SQLEXPRESS;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Then you go to the Elmah project page and run the SQL Server script via SSMS – MAKE SURE YOU RUN ‘USE ‘ first!

http://code.google.com/p/elmah/downloads/list

It then creates a table:

Model Binding and Validation ASP.NET MVC Sample Project

I wanted to share this sample project I put together that demonstrates model-binding and validation of several form components, including complex ones such as dropdowns, checkboxes, and radio buttons. There are several aspects to think about when submitting a form:

  1. HTML form value has to map to the correct C# property/object via Model Binding.
  2. Value submitted has to be properly validated based on Attributes or logic in controller.
  3. If the form has invalid data, the form has to refresh itself and be populated with all the values the user previous attempted to submit.
  4. The appropriate error messages have to be displayed next. The error messages can be part of the set of attributes above the property or handled via ViewBag/ViewData object.

The following example has all that. It also uses a ViewModel (BankAccount.cs) to piece together the main Business Domain Models (e.g. Person).

Download the Sample Project

Here’s our classes in the project:

Model Binding to a Dropdown

Sample #1: Binding to a List<string>

There’s a few ways to model bind a collection to a dropdown using the DropDown HTML helpers in ASP.NET MVC. Let’s first look at a simple scenario, where we have a dropdown and we want to bind to a List of states.

For this example, we’re going to construct a class called Globalization that has the list of states. (I use an this object to hold look-up data sets.)

  public class Globalization
  {
    public List<string> States
    {
      get
      {
        return new List<string>() 
        {
          "NY", "NJ", "IL", "TX", "FL"
        };
      }
    }

Now let’s create our model:

public class Person
{
  [Required(ErrorMessage="Please choose a state!")]
  public string State { get; set; }
}

And follow up with our Controller:

  public class HomeController : Controller
  {
    Globalization global = new Globalization();
 
    public ActionResult Index()
    {
      return View();
    }
    Globalization global = new Globalization();
 
    public ActionResult Index()
    {
      return View();
    }
 
    [HttpPost]
    public ActionResult Index(Person ba, FormCollection form)
    {      
      // Let's check if the state form field exists in the Global State list...
      if (global.States.Exists(s => s == form["State"] ? true : false))
      {
        // Clear the errors from the state property of the modelstate
        ModelState["State"].Errors.Clear();
      }      
 
      // Let's put it in the ViewBag so we can retain the user's form state when 
      // the page is refreshed and the forms are repopulated with what the user
      // previously put in.       
      ViewBag.selectedState = form["State"];
 
      if (ModelState.IsValid)
      {
        // Run further server-side business logic from private methods.
        // DoFurtherStuff();
        return (RedirectToAction("Success"));
      }
 
      return View(ba);
    }
 
    public ActionResult Success()
    {
      return View("Success");
    }
  }

Now let’s do the View:

@model MvcApplication10.Models.Person
@using MvcApplication10.Models;
@{
  ViewBag.Title = "BankAccount";
  Html.EnableClientValidation(false);
  Html.EnableUnobtrusiveJavaScript(false);
}
 
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "mvcform" }))
{    
  <fieldset>
    <legend>BankAccount</legend>
 
    <div class="editor-field">      
      @{ 
        SelectList slStates = new SelectList(new Globalization().States, ViewBag.selectedState); 
      }
      @Html.DropDownList("State", slStates.OrderBy( x => x.Text ), "")
      @Html.ValidationMessageFor(model => model.State)
    </div>
 
    <p>
      <input type="submit" value="Create" />
    </p>
  </fieldset>
}
<div>
  @Html.ActionLink("Back to List", "Index")
</div>

So with this app, if we don’t pick a value from the dropdown, we get an error:

Now, let’s look at the HTML code generated:

<select id="State" name="State">
  <option value=""></option>
  <option>FL</option>
  <option>IL</option>
  <option>NJ</option>
  <option>NY</option>
  <option>TX</option>
</select>

Notice that the option elements don’t have explicit values, so they’ll be set to the text inside the option elements. So that’s equivalent to:

<select id="State" name="State">
  <option value=""></option>
  <option value="FL">FL</option>
  <option value="IL">IL</option>
  <option value="NJ">NJ</option>
  <option value="NY">NY</option>
  <option value="TX">TX</option>
</select>

We leave the first one blank so the user has to select a value. So what if we want to bind the dropdown to a key/value pair collection like Dictionary? Like this for example:

<select id="State" name="State">
  <option value="4523">FL</option>
  <option value="6345">IL</option>
</select>

To do the above, refer to the next section…

Sample #2: Binding to a List<SelectListItem>

Now let’s visualize a different scenerio:

Where the HTML generated is:

<select class="input-validation-error" id="CategoryModel_StatusID" name="CategoryModel.StatusID">
  <option selected="selected" value=""></option>
  <option value="1">Approval Code</option>
  <option value="2">More Info Requested</option>
  <option value="3">Rejected</option>
  <option value="4">Deleted</option>
  <option value="5">Approved</option>
</select>

and we have to populate it with the data from the db (Status table):

Where the schema is:

CREATE TABLE [dbo].[Status](
	[StatusID] [tinyint] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NOT NULL
 CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED 
(
	[StatusID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

So we write the C# code a little different for this scenario. I’ve found that for this, it’s helpful to use the helper @Html.DropDownListFor(), which accepts an IEnumerable, which you’ll have to construct.

First let’s create our Model class:

public class Category
{		
    [Required(ErrorMessage = "Status is required.")]
    public Byte StatusID { get; set; }
}

For convenience, let’s also create a ViewModel class that uses Category. We’re also using Dapper here, which makes db connection a snap. Check out the tutorial for more details.

  /// <summary>
  /// We create his class so we can map data from Dapper.
  /// </summary>
  public class StateSelectListItem
  {
    public string Name { get; set; }
    public byte StatusID { get; set; }
  }
 
  /// <summary>
  /// This is the ViewModel for the Category Create Form
  /// </summary>
  public class CategoryViewModel
  {
    public Category CategoryModel { get; set; }
 
    public List<SelectListItem> ListStatusCodes
    {
      get
      {
        // We're putting an empty SelectListItem so that the first item in the drop down
        // is blank. 
        List<SelectListItem> selectList = new List<SelectListItem>() { new SelectListItem() { Text = "", Value = "", Selected = false } };
 
        using (SqlConnection conn = new SqlConnection("Data Source=NARUTO;Initial Catalog=GalaxyM33;Integrated Security=True"))
        {
          conn.Open();
 
          // Let's map the results (using Dapper) to the list of StateSelectListItem
          IEnumerable listStatus = conn.Query<StateSelectListItem>("select StatusID, Name From [Status]");
 
          // We're adding SelectList objects to the List...
          foreach (StateSelectListItem item in listStatus)
          {
            selectList.Add(new SelectListItem() { Text = item.Name, Value = item.StatusID.ToString() });
          }
 
          conn.Close();
        }
        return selectList;
      }
    }
  }

Here’s the controller:

    public ActionResult Create()
    {
      CategoryViewModel viewModel = new CategoryViewModel();    
      return View(viewModel);
    }
 
    [HttpPost]
    public ActionResult Create(CategoryViewModel viewModel)
    {      
      return View(viewModel);
    }

Now for the View:

@model ViewModels.CategoryViewModel
@{
  ViewBag.Title = "Create";
  Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
  @Html.ValidationSummary(true)
  <fieldset>
    <legend>Category</legend>
    <div class="editor-field">      
      @Html.DropDownListFor(m => m.CategoryModel.StatusID, Model.ListStatusCodes)
      @Html.ValidationMessageFor(model => model.CategoryModel.StatusID)
    </div>       
    <p>
      <input type="submit" value="Create" />
    </p>
  </fieldset>
}
<div>
  @Html.ActionLink("Back to List", "Index")
</div>

That should do it.

Download Sample 1

Dapper – A C# Micro ORM Library Makes Data Access a Snap – Part 1

I’ve recently gotten a chance to try out Dapper – a micro ORM library by Sam Saffron, which originally spawned from StackOverflow’s codeset. If you’re looking for an extremely light-weight library to access your SQL Server, I highly recommend it. It focuses more on convention than configuration. It also does not have the overhead that EntityFramework or NHibernate have, and it emphasizes speed and ease-of-use.

Dapper is a collection of Extension Methods that enhance the Connection object (or rather extends the IDbConnection interface). It also embraces the use of inline SQL in your code, which is useful when retrieving sets that are less trivial. With its buddy, Dapper-Extensions by Thad Smith, it makes DB interaction even easier.

Both of these libraries can be downloaded from NuGet, and you’ll need them to run the following code.

There’s really just one thing that I found irritating about the Dapper project: the documentation. While there is documentation found at its Google Code home page, I find it very lacking.

Anywhoot, to get started first we need to create our table. Once we have that and add some data, we’ll use the Dapper to extract the data and map to objects.

----------------------------------------
-- Customer Schema
----------------------------------------
CREATE TABLE [dbo].[Customer](
[CustomerID] [uniqueidentifier] NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Age] [int] NULL,
[IsAllowed] [bit] NULL,
[DateRegistered] [datetime] NULL,
[AdditionalDetails] [nvarchar](max) NULL,
CONSTRAINT [PK_Customer_1] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
 
ALTER TABLE [dbo].[Customer] ADD  CONSTRAINT [DF_Customer_CustomerID]  DEFAULT (newid()) FOR [CustomerID]
GO
 
----------------------------------------
-- Data
----------------------------------------
INSERT INTO [dbo].[Customer]([CustomerID], [FirstName], [LastName], [Age], [IsAllowed], [DateRegistered], [AdditionalDetails])
  SELECT N'5458dff8-cea2-4bdb-9431-1dea56f109f8', N'Bruce', N'Wayne', 31, 1, '20080604 08:13:44.000', N'I am Batman' UNION ALL
  SELECT N'1767bc57-af03-4b17-891f-2aa9af244180', N'Peter', N'Parker', 25, 1, '20120103 12:22:28.000', N'I am Spider-Man' UNION ALL
  SELECT N'dc2bf42d-045b-4189-bd6b-8bf1bf120291', N'Eddie', N'Brock', 34, 0, '20040123 02:45:41.000', N'We are Venom'

OK, so this is what we have so far:

Because Dapper focuses more on convention over configuration, it’s important to note that when you create your class:

  • The name of your class must match the name of the table, otherwise an exception is thrown.
  • All column names must match all class property names, otherwise an exception is thrown.
  • If a column is not used (in NOT written out in the SELECT statement) and the class property exists, it will set to NULL or assign a default value – more on this later.

Now that we’re aware of these points, let’s see the code to get started:

using System;
using Dapper;
using System.Data.SqlClient;
 
class Customer
{
  public Guid CustomerID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
  public bool IsAllowed { get; set; }
  public DateTime DateRegistered { get; set; }
  public string AdditionalDetails { get; set; }
}
 
class Program
{
  private static void Main()
  {
 
    using (SqlConnection conn = new SqlConnection("Data Source=NARUTO;Initial Catalog=TESTDATABASE;Integrated Security=True"))
    {
      conn.Open();
 
      // Put dapper code here.
 
      conn.Close();
    }
 
    Console.ReadLine();
  }
}

OK, so there’s nothing out of the ordinary here. We’re creating the class we want to map our data to, creating a Connection object, opening, closing, and then disposing (via using). Now let’s suck up some data within our Main() method:

private static void Main()
{
  using (SqlConnection conn = new SqlConnection("Data Source=NARUTO;Initial Catalog=TESTDATABASE;Integrated Security=True"))
  {
    conn.Open();
 
    IEnumerable customers = conn.Query("SELECT * FROM Customer");
 
    foreach (Customer c in customers)
    {
      Console.WriteLine("CustomerID: " + c.CustomerID);
      Console.WriteLine("FirstName: " + c.FirstName);
      Console.WriteLine("LastName: " + c.LastName);
      Console.WriteLine("Age: " + c.Age);
      Console.WriteLine("IsAllowed: " + c.IsAllowed);
      Console.WriteLine("DateRegistered: " + c.DateRegistered);
      Console.WriteLine("AdditionalDetails: " + c.AdditionalDetails);
      Console.WriteLine("-----------------------------------------------");
    }
 
    conn.Close();
  }
 
  Console.ReadLine();
}

As we see, the Query extension method pulls in the data based on the select statements. The Query method returns a strongly-typed list of Customer. You should see the following:

Now what if we want to get the number of records in the table? Well, because Query returns an IEnumerable, we cannot use the Count property. To do so, we convert to a List:

List<Customers> customers = (List<Customers>)conn.Query("SELECT * FROM Customer");
Console.WriteLine(customers.Count);

That should give us the count. To see how the data types were mapped, we can take a look at the Dapper source code, SqlMapper.cs inside the static method SqlMapper(). For reference, you can take a peek at these two sources to understand SQL Server/CLR/.NET framework data types:

http://stackoverflow.com/questions/425389/c-sharp-equivalent-of-sql-server-2005-datatypes

http://msdn.microsoft.com/en-us/library/ms131092.aspx

For our example though, we saw that the data types were mapped:

Mismatches and Nulls

In the query that we ran, we were making the assumption that all columns in the db match all the properties in the class. What if we have a mismatch? What if we have this?

IEnumerable customers = conn.Query("SELECT LastName FROM Customer");

Notice that we’re only retrieving the LastName, while we have other properties in our Customer class. Well, this is what you would see:

So from the above, we notice that Dapper will handle Nulls by:

  • Setting strings as Nulls
  • Setting a Guid to 00000000-0000-0000-0000-000000000000
  • Setting an int to 0
  • Setting bool to false
  • Setting a DateTime to 1/1/0001 12:00:00 AM

Which will all happen when Dapper cannot find a class property to map to from the column value. Also, if you column name that DOES NOT match a property, it will throw a SqlException of “Invalid Column Name”.

Parameterization

What if we want to pass a parameter into our SQL? Let’s pass a parameter:

IEnumerable customers = conn.Query("SELECT * FROM Customer WHERE AGE &gt; @Age", new { Age = 30 } );

Notice that I’m passing in an anonymous object. I could also have done:

Customer someCustomer = new Customer {
Age = 33,
FirstName = "Clark Kent"
};
 
IEnumerable customers = conn.Query("SELECT * FROM Customer WHERE AGE &gt; @Age", someCustomer );

Which yields:

The property in someCustomer (FirstName = “Clark Kent”) is silently ignored because it’s not used in the SELECT statement.

When the above is run, SQL Server Profiler shows that the following is run:

exec sp_executesql N'SELECT * FROM Customer WHERE AGE &gt; @Age',N'@Age int',@Age=33

So we know it’s parameterized.

To call a stored procedure and map it to objects, we do, assuming we have the following sproc:

CREATE PROCEDURE GetCustomers
(
@IsAllowed BIT
)
AS
BEGIN
 
SELECT * FROM Customer
WHERE IsAllowed = @IsAllowed
 
END

We do:

// The second @ token does not have to be named "@IsAllowed" and can be named anything as
// long as the C# property in the anonymous object is named the same thing.
IEnumerable customers = conn.Query("GetCustomers @IsAllowed = @IsAllowed", new { IsAllowed = 33 } );

Also accepted:

IEnumerable customers = conn.Query("GetCustomers @IsAllowed = @Allow", new { Allow = 33 } );

Or you can be more explicit by specifying the command type (StoredProcedure):

IEnumerable customers = conn.Query("GetCustomers", new { IsAllowed = 33 }, commandType: CommandType.StoredProcedure );

Or writing it a more secure way:

DynamicParameters parameters = new DynamicParameters();
parameters.Add("@IsAllowed", 'f', dbType:DbType.Int32);
 
IEnumerable customers = conn.Query("GetCustomers", parameters, commandType: CommandType.StoredProcedure );

To insert data, we do as follows:

Customer customer = new Customer{
  FirstName = "Mazinger",
  LastName = "Z",
  Age = 40,
  IsAllowed = true,
  DateRegistered = DateTime.Now,
  AdditionalDetails = "Metallic defender"
};
 
conn.Execute(@"INSERT INTO Customer
                                  ( FirstName ,
                                  LastName ,
                                  Age ,
                                  IsAllowed ,
                                  DateRegistered ,
                                  AdditionalDetails
 
                   )
                   VALUES  ( @FirstName ,
                                 @LastName ,
                                 @Age ,
                                 @IsAllowed ,
                                 @DateRegistered ,
                                 @AdditionalDetails
                               )"
                 , customer);

This ends part 1 of the tutorial. I will post the 2nd part soon.

MongoDB Console Tip: Better Display of Object on Console

Quick tip. This is just a neat way to better display the JSON from the console. For example, if I did this in one of my dbs:

db.client.find()

I would get:

{ "_id" : ObjectId("4da45b3cf980ed161462c2ef"), "ContactEmergencyDetails" : { "awesome" :
[ 1111, 2222, 3333 ], "cool" : "awesome", "dan" : [ 4.5, 5.322 ] }, "firstname" : null, "lastname" : null }

But if I changed it to this (converting it to Array):

db.client.find().toArray()

It formats it better:

[
  {
    "_id" : ObjectId("4da45b3cf980ed161462c2ef"),
    "ContactEmergencyDetails" : {
      "awesome" : [
                    1111,
                    2222,
                    3333
                ],
        "cool" : "awesome",
        "dan" : [
                  4.5,
                  5.322
                ]
  },
  "firstname" : null,
  "lastname" : null
  }
]

Event Delegation/Propagation (Bubbling) via jQuery

I was going through the book JavaScript Programmer’s Reference by Alexei White and noticed two diagrams that explain the event delegation and event propagation:

So rather than binding an event handler to each tr or td, you bind only to the table element, and capture the event (via bubbling), detect the element that fired it, and then fire the event handler. This is more efficient than binding to each and every tr or td – instead you rely on the action bubbling up to one element.

Let’s demonstrate this using jQuery:

<html>
<head>
<script language="JavaScript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
 
<script type="text/javascript">
$(document).ready( function() {
 
 // http://api.jquery.com/event.target/
 // http://docs.jquery.com/Events_%28Guide%29
 
 $("#datatable").click( function(event) {    
   // Detect the element that fired off the event
   if ( event.target.nodeName == "TD" )
   {
     alert( "you clicked on a td element" );
   }
 });
});
 
</script>
 
 
</head>
 
<body>
 
<table id="datatable" border="1">
 <tr>    
   <th>Header 1a</th>
   <th>Header 1b</th>
   <th>Header 1c</th>
   <th>Header 1d</th>
   <th>Header 1e</th>
 </tr>
 
 <tr id="row1">
   <td id="aaa">Data 1a</td>
   <td>Data 1b</td>
   <td>Data 1c</td>
   <td>Data 1d</td>
   <td>Data 1e</td>
 </td>
 
 <tr id="row2">
   <td>Data 1a</td>
   <td>Data 1b</td>
   <td>Data 1c</td>
   <td>Data 1d</td>
   <td>Data 1e</td>
 </td>
 
 <tr id="row3">
   <td>Data 1a</td>
   <td>Data 1b</td>
   <td>Data 1c</td>
   <td>Data 1d</td>
   <td>Data 1e</td>
 </td>
 
 <tr id="row4">
   <td>Data 1a</td>
   <td>Data 1b</td>
   <td>Data 1c</td>
   <td>Data 1d</td>
   <td>Data 1e</td>
 </td>
 
</table>
</body>
</html>

Model Binding Checkboxes to a List

Model binding things other than textboxes could be tricky in ASP.NET MVC. To correctly model bind, one has to follow a specific naming/value conventions in the HTML.

Let’s say we have a model object called People, and we have a List of states people have lived in.

  public class People
  {
    public List<string> StatesLiveIn { get; set; }
  }

And in our View we have as follows:

@model TestBinder.Models.People
 
foreach (string state in new List<string>() { "NY","NJ","FL","IL","TX" })
{     
  @state <input  type="checkbox" value="@state" name="StatesLiveIn" /><br />      
}

Out controller simple looks like this:

    public ActionResult Index()
    {
      return View();
    }
 
    [HttpPost]
    public ActionResult Index(People p)
    {
      return View(p);
    }

If we put a trace point at the return line, and inspect after the user has submitted only NY and TX…

…we’ll see that it was correctly bound…

Companies Who Use ASP.NET

During a job hunt, I compiled a list of companies that use ASP.NET. Most of them, without a surprise, are big corporate ones. Also, not all of them use ASP.NET exclusively for their entire site/business. Many of these sites have subsites for their many divisions, so a mix of technologies are used.

I’m going to keep updating as I find more.

Microsoft Amazon