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.

Advertisements

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.

How to remove items from an enumerable object that are equal to items of another enumerable object

Let’s say we have two integer arrays:

int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
int[] b = { 3, 4, 5, 8, 9, 10, 45 }

C# provides a handy extension method that we can call that will compare the two arrays and then return a new enumerable object that will only contain integers from “a” that are NOT in “b”.

Example:

void Main()
{
 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 int[] b = { 3, 4, 5, 8, 9, 10, 45 };

 // Remove items from "a" that are not in "b"
 var c = a.Except(b);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }

 Console.WriteLine("--------");

 // Remove items from "b" that are not in "a"
 c = b.Except(a);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }
}

As you can see in the code above, the handy extension method is called “Except”. The formal definition of this extension method is:

Enumerable.Except(Of TSource) Method (IEnumerable(Of TSource), IEnumerable(Of TSource))
Produces the set difference of two sequences by using the default equality comparer to compare values.

Namespace: System.Linq
Assembly: System.Core (in System.Core.dll)

How to check if string exists in a List<string>

If you need to determine whether or not a string exists within a List<string>, you may want to ignore the case of the strings while doing the compare.

Thanks to an extension method that hangs off of the List<T>.Contains() method, this is very easy to do.

Say you have a List<string> which contains email addresses and you want to check to see if a specific email address exists within the List<string>, your code may look like this:

List<string> emails = new List<string>() {“keean@domain.com”, “ty@domain.com”, “milo@domain.com” };

string target = “KEEAN@domain.com”;

if (emails.Contains(target, StringComparer.OrdinalIgnoreCase))

    Console.WriteLine(“{0} exists in the list.”, target);

else

    Console.WriteLine(“{0} does not exist in the list.”, target);

For more information on the StringComparer class, read this MS article.

If you use the StringComparer class, you will notice that there are three “IgnoreCase” properties:

  1. StringComparer.CurrentCultureIgnoreCase
  2. StringComparer.InvariantCultureIgnoreCase
  3. StringComparer.OrdinalIgnoreCase

These are enumerations that specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods. For more information, check out this article.