A Script to Print ModelState Errors and Field Names

This will write to the Output Window all the errors that are being thrown from the ModelState of an asp.net MVC Razor app.

var errors = ModelState.Where(m => m.Value.Errors.Count() > 0);
foreach (var kvp in errors)
{
    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1}", kvp.Key, kvp.Value.Errors[0].ErrorMessage));
}

The script above is helpful if/when you receive ModelState errors in your MVC Controller for no easily discernible reason. In other words, the output of the script above will print which Model fields are causing the ModelState.IsValid to return false.

LINQ Equivalent to SQL “IN” Operator

This is an example of how you can use the LINQ “Contains” in a similar way to how you use the SQL “IN” operator.

The code example below will use an XDocument object as our data that we would like to query. The XDocument contains a set of books where each book as a unique ID. 

We are going to use the .Contains extension to filter out the books that have an ID of 1, 3, and 5.


void Main()
{
	XDocument doc = GetBooks();
	
	Console.WriteLine(string.Format("Show all books\r\n{0}", doc));
	
	// A string array that will be used to as our Book ID filter. 
	// You can think of this array as the arguments that are used in the SQL "IN" operator
	string[] bookIds = new string[] {"1","3","5"};
	
	// Get books out of the xml object that have an ID of 1, 3, or 5
	var books = from b in doc.Descendants("Book")
				where bookIds.Contains(b.Element("ID").Value)
				select b;
			
	Console.WriteLine("\r\nShow the filtered books");
	foreach(var b in books)
		Console.WriteLine(b);
}

XDocument GetBooks()
{ 
  // Manually create an XML document that contain books
	XDocument doc = new XDocument(
		new XElement("Books",
			new XElement("Book",
				new XElement("Title", "Don Quixote"),
				new XElement("ID", 1),
				new XElement("Author", "Miguel de Cervantes")
				),
			new XElement("Book",
				new XElement("Title", "A Tale of Two Cities"),
				new XElement("ID", 2),
				new XElement("Author", "Charles Dickens")
				),
			new XElement("Book",
				new XElement("Title", "The Little Prince"),
				new XElement("ID", 3),
				new XElement("Author", "Antoine de Saint-Exupéry")
				),
			new XElement("Book",
				new XElement("Title", "The Da Vinci Code"),
				new XElement("ID", 4),
				new XElement("Author", "Dan Brown")
				),
			new XElement("Book",
				new XElement("Title", "The Catcher in the Rye"),
				new XElement("ID", 5),
				new XElement("Author", "J.D. Salinger")
				)));
				
		return doc;
}

This is the output of the code above…

Show all books
<Books>
  <Book>
    <Title>Don Quixote</Title>
    <ID>1</ID>
    <Author>Miguel de Cervantes</Author>
  </Book>
  <Book>
    <Title>A Tale of Two Cities</Title>
    <ID>2</ID>
    <Author>Charles Dickens</Author>
  </Book>
  <Book>
    <Title>The Little Prince</Title>
    <ID>3</ID>
    <Author>Antoine de Saint-Exupéry</Author>
  </Book>
  <Book>
    <Title>The Da Vinci Code</Title>
    <ID>4</ID>
    <Author>Dan Brown</Author>
  </Book>
  <Book>
    <Title>The Catcher in the Rye</Title>
    <ID>5</ID>
    <Author>J.D. Salinger</Author>
  </Book>
</Books>

Show the filtered books

<Book>
  <Title>Don Quixote</Title>
  <ID>1</ID>
  <Author>Miguel de Cervantes</Author>
</Book>
<Book>
  <Title>The Little Prince</Title>
  <ID>3</ID>
  <Author>Antoine de Saint-Exupéry</Author>
</Book>
<Book>
  <Title>The Catcher in the Rye</Title>
  <ID>5</ID>
  <Author>J.D. Salinger</Author>
</Book>

Quick-And-Dirty Example On ASP.NET MVC Client Side Validation

This post will walk you through a very simple example on how you can implement Client-Side Validation using the unobtrusive validation support library for jQueryand jQuery Validate, and ASP.NET MVC using Visual Studio 2010.

Step 1: Using Visual Studio 2010, create a new “ASP.NET MVC 4 Web Application”. Give a name for the new Project – In this example I named it “ClientSideValidation”


Step 2: Select an “Empty” template for the Project


Step 3: Add a New Folder to the Project and name it “Resources”. Once done, create sub-folders (under Resources) and name them CSS, Javascript, and Resx.


Step 4: Add a new Style Sheet (.css file) to the “CSS” directory that you just created and name it “ValidationStyles.css”


Step 5: Copy/Paste these styles to your newly created “ValidationStyles.css” file (These styles will be used by the jQuery pack that does the client-side validation)

/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error
{
    color: #f00;
}

.field-validation-valid
{
    display: none;
}

.input-validation-error
{
    border: 1px solid #f00;
    background-color: #fee;
}

.validation-summary-errors
{
    border: 1px solid red;
    padding: 5px;
    margin: 2px;
    background-color: #FFE6E8;
    font-size: .9em;
    color: #f00;
}

.validation-summary-valid
{
    display: none;
}

Step 6: Go to http://www.jquery.com and download the latest jQuery pack and save the pack to your “\Resources\Javascript” directory (at the time of this post, the latest jQuery pack is version 1.8.2 and the name of the pack is “jquery-1.8.2.min.js“).


Step 7: In Windows Explorer, navigate to “C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\jQuery.Validation.1.8.1\Content\Scripts\”, then copy/paste the jQuery pack named “jquery.validate.min.js” to the “\Resources\Javascript” directory in your Project.


Step 8: In Windows Explorer, navigate to “C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.jQuery.Unobtrusive.Validation.2.0.20505.0\Content\Scripts”, then copy/paste the “jquery.validate.unobtrusive.min.js” file to your \Resources\Javascript directory in your Project.


Step 9: Add a new Resource file to your \Resources\Resx directory named “ValidationStrings.resx“. Then add the following Name and Values to your .resx file:

Name Value
StringLengthRange The string must be between {2} and {1} characters
NumberRange The number range must be between {1} and {2}
StringMaximumLength The string must not be more than {1} characters


Step 10: Add a new class to the “Models” directoryName the class as “Person” and copy/paste the code below to your Person class:

public class Person
    {
        [Required]
        [StringLength(80,ErrorMessageResourceType=typeof(ValidationStrings),ErrorMessageResourceName="StringLengthRange",MinimumLength=6)]
        public string EmailAddress { get; set; }

        [Range(0,100,ErrorMessageResourceType=typeof(ValidationStrings),ErrorMessageResourceName="NumberRange")]
        public int FavoriteNumber { get; set; }

        [StringLength(15,ErrorMessageResourceType=typeof(ValidationStrings),ErrorMessageResourceName="StringMaximumLength")]
        public string FirstName { get; set; }
    }



Step 11: Build the Project by hitting “F6” or going to “Build > Build Solution”


Step 12: Add a new Controller to your “Controllers” directory and name it “homeController”


Step 13: In the “homeController” class, right-click inside of the “Index()” method, then select “Add View…”

Step 14: In the “Add View” window, select the checkbox for “Create a strongly-typed view”, then select the “Person” model that is located in the dropdown box. If you don’t see the Person model, you need run a Build (F6).


Step 15: Add the following Razor scripts to your Index.cshtml page:

@model ClientSideValidation.Models.Person
<html>
<head>
    <title>Clientside Validation Example</title>
    <link href="/Resources/CSS/ValidationStyles.css" rel="stylesheet" type="text/css" />
    <script src="/Resources/Javascript/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="/Resources/Javascript/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/Resources/Javascript/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
</head>
<body>
    <h2>
        Clientside Validation</h2>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <br />

        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName)
        @Html.ValidationMessageFor(m => m.FirstName)
        <br />

        @Html.LabelFor(m => m.EmailAddress)
        @Html.TextBoxFor(m => m.EmailAddress)
        @Html.ValidationMessageFor(m => m.EmailAddress)
        <br />

        @Html.LabelFor(m => m.FavoriteNumber)
        @Html.TextBoxFor(m => m.FavoriteNumber)
        @Html.ValidationMessageFor(m => m.FavoriteNumber)
        <br />

        <input type="submit" />
    }
</body>
</html>


Step 16: Ready to go! Run (F5) the MVC project and test out the client-side validation.


Step 17: Do yourself a favor and check out the rendered HTML (View Source). You’ll notice the auto-generated “data-val” (spoken as “data dash val”) attributes that are located within the HTML elements. These attributes are used by the “jquery.validate.unobtrusive.min.js” jQuery pack.

Here’s what the rendered HTML looks like:


<html>
<head>
    <title>Clientside Validation Example</title>
    <link href="/Resources/CSS/ValidationStyles.css" rel="stylesheet" type="text/css" />
    <script src="/Resources/Javascript/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="/Resources/Javascript/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/Resources/Javascript/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
</head>
<body>
    <h2>Clientside Validation</h2>
<form action="/" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">

<ul><li style="display:none"></li></ul></div>

<br />

<label for="FirstName">FirstName</label>

<input data-val="true"
	data-val-length="The string must not be more than 15 characters"
	data-val-length-max="15"
	id="FirstName" name="FirstName" type="text" value="" />

	<span class="field-validation-valid"
	data-valmsg-for="FirstName"
	data-valmsg-replace="true"></span>

	<br />

<label for="EmailAddress">EmailAddress</label>

<input data-val="true"
	data-val-length="The string must be between 6 and 80 characters"
	data-val-length-max="80"
	data-val-length-min="6"
	data-val-required="The EmailAddress field is required."
	id="EmailAddress" name="EmailAddress" type="text" value="" />

	<span class="field-validation-valid"
	data-valmsg-for="EmailAddress"
	data-valmsg-replace="true"></span>

	<br />

<label for="FavoriteNumber">FavoriteNumber</label>

<input data-val="true"
	data-val-number="The field FavoriteNumber must be a number."
	data-val-range="The number range must be between 0 and 100"
	data-val-range-max="100"
	data-val-range-min="0"
	data-val-required="The FavoriteNumber field is required."
	id="FavoriteNumber" name="FavoriteNumber" type="text" value="" />

	<span class="field-validation-valid"
	data-valmsg-for="FavoriteNumber"
	data-valmsg-replace="true"></span>

		<br />
        <input type="submit" />
</form>
</body>
</html>

Config File Connection String Syntax for SQL Express Databases

When creating an application that uses a SQL Express database, you may choose to use a database that exists locally within your application (i.e. the SQL Express database resides in the App_Data directory of your application) or you may prefer to use a database that has been registered with the SQLExpress Server (i.e. you have attached the database to your SQLExpress Server from within Microsoft SQL Server Management Studio – aka SSMS).

Depending on where your database exists, you must use the correct Connection String for your application to make a successful connection to your database. Typically (and preferably), I like to place my Connection String information in the App.Config or Web.Config file. Here is the correct Connection String XML tag syntax for the two different database locations that were previously mentioned.

<configuration>
<connectionStrings>
    <!-- This is an example of a connection string for a SQL Express database that lives in the application's App_Data directory -->
    <add name="LocalConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;User Instance=True" />

    <!-- This is an example of a connection string for a SQL Express database that lives in the SQL Express Server's list of registered (or attached) databases. Attaching a database to the SQL Server is typically done via SQL Server Management Studio (SSMS) -->
    <add name="ServerConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DATABASE1;Integrated Security=True" />
</connectionStrings>
</configuration>

C# Code Examples of using the different Connection Strings

public class DAL
    {
        public static List&lt;UserModel&gt; GetUsers()
        {
            List<UserModel>; users = new List<UserModel>();
            
            // This example uses the connection string that points to the database that resides in the local App_Data directory of this application
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalConnection"].ToString()))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM [User]", conn);
                conn.Open();
                SqlDataReader sdr = cmd.ExecuteReader();

                while (sdr.Read())
                {
                    UserModel user = new UserModel();
                    user.EmailAddress = sdr["Email"].ToString();
                    user.Password = sdr["Password"].ToString();
                    user.UserId = (int)sdr["UserId"];
                    user.Username = sdr["Username"].ToString();
                    users.Add(user);
                }
            }

            return users;
        }
    }

Could not load file or assembly or one of its dependencies.

Here is a fix for an error that I received in Visual Studio 2010

The error reads:

Could not load file or assembly ‘file:/// [path to assembly]’ or one of its dependencies. An attempt was made to load a program with an incorrect format. Line 465, position 5.

To fix the problem, I did this:

  1. Double-click the error (which was located in the VS2010 Error List Window)
  2. After double-clicking the error, the cursor will be placed in an XML closing tag called </data>. From the closing </data> tag, scroll to the opening <data> tag. The <data> tag contents looked like this:
    <data name="imageList.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>
            AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
  3. Manually make a change to a part of the string exactly as follows: Change the end of the string from
    j00LjAuMC4w to j0yLjAuMC4w

    Note that the only change is swapping out the second zero with a ‘y’

  4. Rebuild the Visual Studio Solution

Notice! The stream data that you edited was derived from an ImageList that exists in your assembly. So, each and every time you make a change to the ImageList or open the Windows Form  (that contains the ImageList) in Designer Mode, you will need to do the above procedure.

This problem occurs when your development machine is running a 64bit OS (I was running Windows Server 2008 RS 64bit). Apparently, what’s happening is Visual Studio is serializing ImageLists with a reference to .NET 4.0 instead of .NET 2. This information is specifically defined at the “j00” section of the serialized data. Changing the data to “j0y” informs ResGen.exe that the ImageList targets .NET 2.

Named and Optional Arguments

Compared to how much there is to know about the C# language, I’m the first to admit that I know very little. However, sometimes when I stumble across a C# spec that I’ve never known prior, I inadvertently blurt out “how did I NOT already know that?!” … just a few minutes ago, I committed the blurt!

I didn’t know (’til now) that Visual C# 2010 introduced named and optional arguments.

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter’s name rather than with the parameter’s position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named and optional parameters, when used together, enable you to supply arguments for only a few parameters from a list of optional parameters. [ref]

class NamedExample
{
    static void Main(string[] args)
    {
        // The method can be called in the normal way, by using positional arguments.
        Console.WriteLine(CalculateBMI(123, 64));

        // Named arguments can be supplied for the parameters in either order.
        Console.WriteLine(CalculateBMI(weight: 123, height: 64));
        Console.WriteLine(CalculateBMI(height: 64, weight: 123));

        // Positional arguments cannot follow named arguments.
        // The following statement causes a compiler error.
        //Console.WriteLine(CalculateBMI(weight: 123, 64));

        // Named arguments can follow positional arguments.
        Console.WriteLine(CalculateBMI(123, height: 64));
    }

    static int CalculateBMI(int weight, int height)
    {
        return (weight * 703) / (height * height);
    }
}

Personally, I don’t think this new addition to the C#2010 spec isn’t something that I will use that much (if at all), but still – It’s certainly worth knowing that it’s there.