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.

Install Xamarin in Visual Studio 2013

I recently installed Visual Studio 2013 and noticed that when I attempt to create a new Xamarin Android project, the Android template is missing from the “New Project” window.

The cause of the problem is that Xamarin hasn’t yet (as of the date of this writing) included a VS2013 installer. To work around this problem, I followed Daniel Hilgarth’s instructions as follows…

  1. Install Xamarin in Visual Studio 2012
  2. Copy the files from c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Xamarin\ to c:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Xamarin\
  3. Copy the folders Android and ios from inside c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplates\CSharp\ to c:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ProjectTemplates\CSharp\
  4. Copy the folders Xamarin.Android and ios from c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\ to c:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplates\CSharp\
  5. Execute the following command from a command prompt with elevation: "c:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" /setup /nosetupvstemplates

That’s it. You should now have a fully functional Xamarin setup in VS 2013!

Thank you, Daniel!

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>

Team Foundation Server Error TF31002

This post will discuss a solution for the Team Foundation Server that reads:

Microsoft Visual Studio

TF31002: Unable to connect to this Team Foundation Server:
https://libra:12303/tfs.
Team Foundation Server Url: https://libra:12303/tfs

Possible reasons for failure include:
– The name, port number, or protocol for the Team Foundation Server is incorrect.
– The Team Foundation Server is offline
– The password has expired or incorrect.

Technical information (for administrator):
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

tf31002error

I received this error when I tried to Add my TFS Server to my Visual Studio 2010 Team Explorer.

The key piece of information that is mentioned in the error message is:

Technical information (for administrator):
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

This key piece of information informs us that we need to create an SSL Certificate on the TFS server (in my case, the TFS server is on my machine named “Libra”).

Here’s a procedure for creating an SSL cert on the server and installing it on the client.

  1. Log into the server and go to the IIS Manager, then double-click the Server Certificates icon.
    iismanager-01
  2. Located in the “Actions” side-bar, click the “Create Self-Signed Certificate…” link.
  3. Follow the on-screen instructions, then click “OK”.
    createssl1
  4. Right-click on the SSL certificate, then select “Export…”.
    exportssl
  5. Export the SSL Certificate to your Desktop and specify a password. After you export the SSL Certificate, move the certificate to the Desktop of the computer that is running Visual Studio.
  6. From the computer that is running Visual Studio, right-click the SSL Certifcate then select “Install PFX”.
    installpfx
  7. Follow the on-screen instructions using the default settings where applicable. However, when you get to the step of the Certificate Import Wizard that allows you to specify which store to save the certificate in, choose the “Trusted Root Certification Authorities” store.
    trustedrootcertificationauthorities
  8. Finish up the Certificate Import Wizard and you’re done.

Now that you have created and installed an SSL Certificate, you can add the TFS Server to your list of TFS Servers in your Visual Studio Team Explorer.

Windows Update Error Code 80243004

The Problem

In an attempt to update my Windows Server 2008 R2 server with Microsoft Visual Studio Team Foundation Server 2010 Service Pack 1 I received the error code:

Some updates were not installed
Failed: 1 update
Error(s) found:
Code 80243004 Windows Update encountered an unknown error.

The Fix

  1. Open the Taskbar Properties (Right-click the Taskbar, then select Properties)
    WindowsUpdate-Error-80243004
  2. From within the Taskbar tab, click the “Customize…” button
    WindowsTaskbarProperties
  3. The “Notification Area Icons” window will open. In this window, change the state of the “Always show all icons and notifications on the taskbar” checkbox. In other words, if your checkbox is already selected, then deselect it – likewise, if your checkbox is NOT already selected, then select it. I know this sounds like a weird fix, but I’ve witnessed this fix with my own eyes.
    AlwaysShowAllIconsAndNotificationsOnTheTaskbar
  4. Click the “OK” button
  5. In Windows Update, try to install the update(s) again.
    WindowsUpdate-Error-80243004-Fixed

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;
        }
    }