Archive for the ‘Development’ Category.

How to query a SQL database in C# using TableAdapters

Visual Studio has some great features to help you access the database and create objects for your database. You could manually create a connection string and manually create objects that represent the data in your database described here: How to query a SQL database in C#?. This article can show you how Visual Studio can do this for you.

So how is it done? By adding a Data Source.

Imagine you have a simple database for authentication with these tables:

User
- Id INT AUTOINCREMENT
- UserName VARCHAR(100)
- Password VARCHAR(MAX)
- Salt VARCHAR(MAX)

Person
- Id INT AUTOINCREMENT
- FirstName VARCHAR(255)
- LastName VARCHAR(255)
- Birthdate DATETIME
- UserId int FK to User.Id

Now imagine that you want to query these tables and use the data in your application.

Step 1 – Create a Visual Studio Project

  1. In visual studio create a new C# Console Application project.
  2. Once you have the project created, click on Project | Add New Data Source.
  3. Select Database and click Next.
  4. Select DataSet and click Next.
  5. Click New Connection and follow the wizard to connect to your database.
  6. Make sure that Yes, save the connection as is checked and give your saved connection a name and click Next.
  7. Click the checkbox next to Tables and click Finish.

This adds the following files to your project (the names might be slightly different on yours):

  • AuthDataSet.xsd
  • AuthDataSet.Designer.cs
  • AuthDataSet.xsc
  • AuthDataSet.xss

This code will add table adapters to your project. This basically does a lot of work for you and can save you a lot of potential development time.

Step 2 – Query a SQL Database using the Table Adapter

Now you can get the data from either of your tables with one line of code:

using System;
using System.Data;
using TableAdapterExample.AuthDataSetTableAdapters;

namespace TableAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Query the database (select * from Person) into a DataTable
            AuthDataSet.PersonDataTable table = new PersonTableAdapter().GetData();

            // Print out the table as proof.
            PrintDataTable(table);
        }

        /// How to print a DataTable
        private static void PrintDataTable(AuthDataSet.PersonDataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn col in table.Columns)
                {
                    Console.Write(row[col].ToString().Trim() + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

Hope that helps you.

ASP.NET, JavaScript, and HTML Element ID attributes

Today I had to fix some legacy code. It is ASP.NET code and it has both ASP.NET elements and ASP.NET Controls. The plan was to replace a large portion of code behind with JavaScript. The ASP.NET code needed to be a UserControl that could appear twice on the same page. This created some problems:

  1. ASP.NET creates some html controls but changes the id and the name attributes. While it is possible to run the web page and see what the attributes will be changed to and then use those strings statically in JavaScript, the JavaScript could easily break with slight changes to the ASP.NET code. This is not scalable or maintainable.
  2. ASP.NET does NOT rename the the id or the name attributes for normal HTML tags. First, that is a consistency issue. Second it is an issue using the same control multiple times. Third, if you want to get the value of a form element, doing so uses the name attribute and so each form element needs a separate name.

So lets explain the is problem with a real world scenario.

Lets say you have the following requirements:

  1. Create a UserControl, called PersonControl, that accepts person’s basic info: First name, Last name, and Birthdate.
  2. The form also has a button and it should only be enabled if all three fields are populated.
  3. The Birthdate should use JQuery’s DateTimePicker.
  4. The First name and Last name should be ASP.NET text boxes.

Now imagine the site already exists and you have to add this requirement:

  1. A web page should exist that has multiple PersonControls showing: for example: Employee, Emergency Contact.

The problem with ASP.NET, JavaScript, and HTML Element ID attributes

So let’s build this project using a single control and static id and name attributes and see how it works. Later we will see what we need to do to get this working with multiple PersonControls.

  1. Open Visual Studio and create a new ASP.NET Empty Web Application.
  2. Add JQuery and JQuery-UI. Do this as follows:
    1. Right-click on the project and choose Manage NuGet Packages.
    2. In the Manage NuGet Packages window, on the left, click Online.
    3. On the right, in the search field, type JQuery.
    4. Install JQuery and JQuery UI.
  3. Create new Web Form called PersonForm.
  4. Add the following into your PersonForm.aspx file:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PersonForm.aspx.cs" Inherits="AspAndJavaScriptExample.PersonForm" %>
    
    <%@ Register Src="~/PersonControl.ascx" TagPrefix="uc1" TagName="PersonControl" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>ASP.NET, JavaScript, and HTML id Attributes</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <h2>Employee</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
            </div>
            <%--<div>
                <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
            </div>--%>
        </form>
    </body>
    </html>
    
  5. Create a new Web User Control called PersonControl.
  6. Add the following into your PersonControl.ascx file:
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PersonControl.ascx.cs" Inherits="AspAndJavaScriptExample.PersonControl" %>
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PersonControl.ascx.cs" Inherits="AspAndJavaScriptExample.PersonControl" %>
    <link href="Content/themes/base/minified/jquery.ui.datepicker.min.css" rel="stylesheet" />
    <script src="scripts/jquery-2.0.0.min.js"></script>
    <script src="scripts/jquery-ui-1.10.3.min.js"></script>
    <script src="scripts/ButtonManager.js"></script>
    <script>
        $(function () {
            $(".datepicker").datepicker();
        });
    </script>
    
    <div style="border: solid; padding: 2px">
        First name:
        <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
        Last name:
        <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br />
        Birthdate:
        <input type="text" name="BirthDate" id="BirthDate" class="datepicker" /><br />
        <asp:Button ID="SubmitPerson" runat="server" Text="Submit" OnClick="SubmitPerson_Click" />
    </div>
    
  7. Add the following button SubmitPerson_Click method into your PersonControl.ascx file:
            protected void SubmitPerson_Click(object sender, EventArgs e)
            {   // Put break point here            
                var firstName = FirstName.Text;
                var laststName = LastName.Text;
                var birthdate = Request.Form["Birthdate"];
            }
    
  8. Now add this ButtonManager.js file.
    jQuery(document).ready(function () { 
        $("#PersonControlEmployee_FirstName").bind("propertychange keyup input paste", setButtonState);
        $("#PersonControlEmployee_LastName").bind("propertychange keyup input paste", setButtonState);
        $("#BirthDate").change(setButtonState);
        setButtonState();
    });
    
    var setButtonState = function () {
        if (!areValuesPopulated())
            $("#PersonControlEmployee_SubmitPerson").attr("disabled", "disabled");
        else
            $("#PersonControlEmployee_SubmitPerson").removeAttr("disabled");
    }
    
    var areValuesPopulated = function () {
        return $("#PersonControlEmployee_FirstName").val() != ""
             && $("#PersonControlEmployee_LastName").val() != ""
             && $("#BirthDate").datepicker().val() != "";
    }
    
  9. Now run the project and look at the source code of the html. It looks as follows:
    
    
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>
    	ASP.NET, JavaScript, and HTML id Attributes
    </title></head>
    <body>
        <form method="post" action="PersonForm.aspx" id="form1">
    <div class="aspNetHidden">
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="nkizDAjcAtd96A9EOpli0xdG3n6zTXVaM/5t2fmcAI5+LPQ6OzzIV2wUpisxoUTMFxIKkUwKDY4Xk36/NouRsiE81gq5z3Ch/tz3DlxJW9g=" />
    </div>
    
    <div class="aspNetHidden">
    
    	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="XCB0fxwKvdqEXpUBaICUtf6EzkAvBeahq0bywZekyukCuzvGVagqOnVHUWFHF2Cycd2xkg/UhNh/B3qNqabkBI+Flj52GkM3p6SF5eL/M4SnnfwmFBjWVOaTZ+IlwMvkR1bGuMxomyeJJ5HaU1FXWSYDYHVtgM9tdsVi31EireM=" />
    </div>
            <div>
                <h2>Employee</h2>
                
    <link href="Content/themes/base/minified/jquery.ui.datepicker.min.css" rel="stylesheet" />
    <script src="scripts/jquery-2.0.0.min.js"></script>
    <script src="scripts/jquery-ui-1.10.3.min.js"></script>
    <script src="scripts/ButtonManager.js"></script>
    <script>
        $(function () {
            $(".datepicker").datepicker();
        });
    </script>
    
    <div style="border: solid; padding: 2px">
        First name:
        <input name="PersonControlEmployee$FirstName" type="text" id="PersonControlEmployee_FirstName" /><br />
        Last name:
        <input name="PersonControlEmployee$LastName" type="text" id="PersonControlEmployee_LastName" /><br />
        Birthdate:
        <input type="text" name="BirthDate" id="BirthDate" class="datepicker" /><br />
        <input type="submit" name="PersonControlEmployee$SubmitPerson" value="Submit" id="PersonControlEmployee_SubmitPerson" />
    </div>
    
            </div>
            
        </form>
    </body>
    </html>
    

Problems

  1. Notice the id and name attributes on the tags. The ASP.NET controls have been altered by ASP.NET with a prefix. This is not the problem. This is good. If the control is used multiple times, then this keeps the id and name attributes unique and they are supposed to be unique. However, the problem is, if the id is changed in this line . . .
    <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
    

    . . . then id and name attributes in the child control will change. Since we are using those values statically in the ManageButton.js, any such change also breaks in the javascript. Also, we aren’t using a master page, but if you decided to add a master page, that add an additional prefix, which would create different id and name attributes, again causing the javascript to break. In fact, any such nesting change will change the id and name attributes breaking the javascript.

  2. The control that is not an ASP.NET control, the JQuery datepicker control, did not have the same modifications made to the Birthdate. So this tag won’t work if the control is used multiple times.

Do you want to see the problem?

Update your form in PersonForm.aspx to include multiple controls.

    <form id="form1" runat="server">
        <div>
            <h2>Employee</h2>
            <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
        </div>
        <div>
            <h2>Emergency Contact</h2>
            <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
        </div>
    </form>

Now give it try. See the problems? Ok. So now you have a simulation of the problematic code that I faced today.

Solution to ASP.NET, JavaScript, and HTML Element ID attributes

So we are going to fix this in parts. We are going to use a variable in the ASP.NET control called ClientID, that is basically the prefix used.

  1. Fix html elements to use the same prefix as the ASP.NET controls
  2. Fix the javascript to receive the ClientID as a parameter
  3. Fix the datepicker attributes

    First, let’s fix the ASP.NET and HTML so that all the id and name attributes are consistently changed.

    Change the datepicker line and add some code so it will have the same prefix as ASP.NET created html controls.

    <input type="text" name="<%=ClientID%>$BirthDate" id="<%=ClientID%>_BirthDate" class="datepicker" /><br />
    

    Pass the prefix into the JavaScript

    1. In the PersonControl.ascx file, add a little snippet of JavaScript code to pass the ClientID into the JavaScript files.
      <script>
          $(function () {
              $(".datepicker").datepicker();
          });
          jQuery(document).ready(function () {
              startManagingButton("<%=ClientID%>");
          });
      </script>
      
    2. Now update your JavaScript file to use that ClientID as the prefix. Notice, this is used in the events. I created a simple buildId method that I use throughout now.
      var startManagingButton = function (inIdPrefix) {
          $(buildId(inIdPrefix, "_FirstName")).bind("propertychange keyup input paste", inIdPrefix, setButtonState);
          $(buildId(inIdPrefix, "_LastName")).bind("propertychange keyup input paste", inIdPrefix, setButtonState);
          $(buildId(inIdPrefix, "_BirthDate")).change(inIdPrefix, setButtonState);
          setButtonState(inIdPrefix);
      }
      
      var setButtonState = function (inIdPrefix) {
          if (inIdPrefix.data)
              inIdPrefix = inIdPrefix.data;
          
          if ($(buildId(inIdPrefix, "_FirstName")).val() == "" || $(buildId(inIdPrefix, "_LastName")).val() == "" || $(buildId(inIdPrefix, "_BirthDate")).val() == "")
              $(buildId(inIdPrefix, "_SubmitPerson")).attr("disabled", "disabled");
          else
              $(buildId(inIdPrefix, "_SubmitPerson")).removeAttr("disabled");
      };
      
      var buildId = function (inIdPrefix, idSuffix) {
          return "#" + inIdPrefix + idSuffix;
      };
      

      Now no matter how you update or move this web page, the Id values always work.

    Use the ClientID in ASP.NET SubmitPerson_Click method

    Update the code to look as follows:

        protected void SubmitPerson_Click(object sender, EventArgs e)
        {   // Put break point here            
            var firstName = FirstName.Text;
            var laststName = LastName.Text;
            var birthdate = Request.Form[ClientID + "$Birthdate"];
        }
    

    Using the PersonControl multiple times

    Now everything should be working and you should be able to include as many instances of your control in your web page as you want.

    Update your form in PersonForm.aspx to include many of these controls.

        <form id="form1" runat="server">
            <div>
                <h2>Employee</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
            </div>
            <div>
                <h2>Spouse</h2>
                <uc1:PersonControl runat="server" ID="PersonControlSpouse" />
            </div>
            <div>
                <h2>Emergency Contact</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
            </div>
        </form>
    

    Now give it try. All instances of the PersonControl are now working. The dynamic id and name attributes are not a problem as we are handling them; in fact, they are part of the ultimate solution to make the control reusable.

    Conclusion

    ASP.NET, JavaScript, and HTML Element ID attributes can all be used to work together to make a nice cohesive application.

    If you have a better solution, please post a comment and let me know.

    Downloads

    Here is the project in both states:

    AspAndJavaScriptExample-problematic.zip

    AspAndJavaScriptExample-working.zip

    Bugs

    Now the only bug I can find is on clicking submit the JQuery datepicker field is cleared. I’ll try to fix that and post the solution in another post.

How to create an excel spreadsheet with C#?

I needed to create an Excel spread sheet in C# and I didn’t want to reinvent the wheel.

I found this awesome project: https://closedxml.codeplex.com

I already had a DataTable that I wanted to export in ASP.NET to an Excel file and download. I created an extension method for the DataTable.

    public static class CloseXMLHelper
    {
        public static XLWorkbook ToExcel(this DataTable inDataTable)
        {
            var wb = new XLWorkbook();
            var dataTable = inDataTable;

            // Add a DataTable as a worksheet
            wb.Worksheets.Add(dataTable);
            return wb;
        }
    }

Then I just followed the documentation on the project for allowing a user to download the excel file. I already had the myDataTable variable in the below snippet. If you are wondering how to create a DataTable from a database, see this post: How to query a SQL database in C#?

    var httpResponse = Response;
    httpResponse.Clear();
    httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    httpResponse.AddHeader("content-disposition", "attachment;filename=\"HelloWorld.xlsx\"");

    // Flush the workbook to the Response.OutputStream
    using (var memoryStream = new MemoryStream())
    {
        dataset.Tables[0].ToExcel().SaveAs(memoryStream);
        memoryStream.WriteTo(httpResponse.OutputStream);
        memoryStream.Close();
    }

    httpResponse.End();

It doesn’t get much more simple than this.

An HTML5 3 column layout example in ASP.NET

A while back I posted about an html5 three column layout. Here is the same layout, only this post has built the web site using ASP.NET and it includes a Visual Studio project.

The _Layout.cshtml file looks like this:

@RenderPage("~/Layout/_Header.cshtml")
@RenderPage("~/Layout/_Nav.cshtml")
<div id="main">
   <article id="main-article">@RenderBody()</article>
    @RenderPage("~/Layout/_LeftAside.cshtml")
    @RenderPage("~/Layout/_RightAside.cshtml")
</div>
@RenderPage("~/Layout/_Footer.cshtml")

Then of course, the HTLM5 layout is in the header, asides, article, and footer. And even though the Article is placed before the asides, the asides can be either on the left or the right.

Download it here: HTLM5_ASPNET_ThreeColumnLayoutExample.zip

Using knockout.js and MVVM with RadioButtons

In the example below, radio buttons selection list is created by binding to a list in the view model. I show how to bind to both the selected radio button’s value and name. I also show how to disable a button unless the radio button is selected.

<!-- Step 1 - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="scripts/knockout-2.2.1.js"></script>
    
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
        $(document).ready(function(){

			<!-- Step 4 - Add a RadioButtonModel -->
            function RadioButtonModel(inText, inValue, inGroupName) {
                this.text = inText;
				this.value = inValue;
				this.name = inGroupName;
            }

			<!-- Step 5 - Create ViewModel -->
            function SurveyViewModel() {
                var self = this;
                
				<!-- Step 7 - Create an observable list -->
                this.list = ko.observableArray([
                    new RadioButtonModel("Good", 10, "Q1"),
                    new RadioButtonModel("Average", 5, "Q1"),
                    new RadioButtonModel("Poor", 1, "Q1")
                ]);
				
				<!-- Step 8 - Create a selected item -->
				this.selected = ko.observable(0);
				
				<!-- Step 9 - (Optional) Create a computed value to get the selected text -->
				this.selectedtext = ko.computed(function() {
					var text = "";
				    ko.utils.arrayForEach(this.list(), function(item) {
						var selectedItem = self.selected();
						if (selectedItem == item.value)
							text = item.text;
					});
					return text;
				}, this);
				
				
				<!-- Step 10 - Create a computed value to require a selection before submitting -->
			    this.canClick = ko.computed( function() {
                    return this.selectedtext() != "";
                }, this);
                
            }
            
            <!-- Step 10 - Create a computed value to require a selection before submitting -->    
            ko.applyBindings(new SurveyViewModel());
        });
    </script>
</head>
<body>
    <!-- Step 11 - Create a div containing the html for one radio button and bind to foreach: list -->
    <div data-bind="foreach: list">
        <input type="radio" data-bind="attr: {name: name}, value: value, checked: $root.selected" /><span data-bind="text: text"></span>
    </div>

    <!-- Step 12 - Add html elements to see other properties -->
    <p data-bind="text: selected"></p>
    <p data-bind="text: selectedtext"></p>
    
    <!-- Step 13 - Add a button and bind its enable state -->
    <button type="submit" id="btnSubmit" data-bind="enable: canClick">Submit</button>

</body>
</html>

Hope this helps you.

Using MVVM with HTML5 and JavaScript

The MVVM pattern is an excellent pattern for separating the UI or View and the Code or ViewModel and Model.

With Knockout.js the MVVM pattern can be used with HTML5.

Previously I wrote this post: Using jQuery to enable/disable a button based a text box

This same thing could be done using binding and the MVVM pattern, with jQuery and Knockout.js.

Here is a single file example of using knockout.js and with databinding.

<!-- Step 1a - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="scripts/knockout-2.2.1.js"></script>
    
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
        $(document).ready(function(){
        
            <!-- Step 4 - Create a ViewModel -->
            function BasicViewModel() {
            
                <!-- Note: In this case the model is just a string and a bool -->
                <!-- Step 5 - Create a text property to bind the text to -->
                this.text = ko.observable('');
                
                <!-- Step 6 - Create a bool property to bind the button enabled state to -->
                this.canClick = ko.computed(function() {
                    return this.text() != null && this.text() != '';  
                    }, this);
                }
          
            <!-- Step 7 -  Activates knockout.js bindings -->
          ko.applyBindings(new BasicViewModel());
        });
    </script>
</head>
<body>

    <!-- Step 8 - Create a HTML Elements with bindings -->
    <input data-bind="value: text, valueUpdate:'afterkeydown'" />
    <button type="button" id="btnEnter" data-bind="enable: canClick">Enter</button>
</body>
</html>

Anyone who knows MVVM will surely realize that while this example is all in a single file, it is likely that you will have a separate viewmodel javascript file in a production environment.

Sharing checked out source between Visual Studio instances on Virtual Machines using a network share

I have a lot of Virtual Machines and having to checkout a large code base from source control to each box is annoying and time consuming. There are a couple of branches that take almost an hour to get the latest code.

I am using Visual Studio and TFS. Visual Studio and TFS is installed on all my VMs. So I set out to have the VM host store the source and then all the Virtual Machines map a drive to the host.

At first this appeared to work just fine, but then I started to run into errors. I fixed the errors one at a time.

There were a few things I had to do to make this work and I thought I would share them:

System Changes

  1. Map the drive and make it persistent. That means the drive stays mapped after reboot.
  2. Add the mapped drive as a local intranet site in Internet Explorer’s Security settings.

Visual Studio Changes

  1. Make sure to always log into to TFS in Visual Studio with the same user account. There will be TFS problems if you use a different user account.
  2. Add the loadFromRemoteSources tag to the section of the devenv.exe.config file and set it to true:

    Note: I had to run Notepad++ as administrator to make this change.

    Visual Studio 2010:
    C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.configVisual Studio 2012
    C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe.config

  3. Add the loadFromRemoteSources tag to other .config files.
    Note: In order to debug a web service, I had to also add this tag to the  WcfSvcHost.exe.config.

    Visual Studio 2010:
    C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfSvcHost.exe.config

    Visual Studio 2012
    C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WcfSvcHost.exe.config

    In that IDE folder there were a 22 .config files in VS 2010 and 32 in VS 2012. I am not sure which ones will ever need this. There are two schools of thought: 1. Add the loadFromRemoteSources tag to all of the config files or 2. Add them only when you encounter and error. Since I am in a lab environment and everything is on one physical box (the host and the hosted VMs) I went ahead and added this to all the config files.

  4. Sometimes when running Visual Studio as administrator, the mapped drive appears off line. Simple click File | Open | File and browse to the network drive. You don’t have to actually open anything. Just click cancel. It seems as soon as you browse to the mapped drive, Visual Studio knows about it and everything works fine.This doesn’t seem to work as well in VS 2012 on Windows Server 2012.  You may even have to have the drive mapped twice. Once as the logged in user and once as the Administrator. To do this open two command prompts: 1. A regular command prompt. 2. A command prompt running as Administrator. Run the mapped drive command in both: (Yes, use the same drive letter in both on Windows 2013 or Windows 8)

    net use z: \\pcname.domain.tld\yourshare /PERSISTENT:YES

Be aware you’ll get more prompts

I noticed than when running executables orVBScripts or PowerShell scripts, that I was prompted. This is because your running them from a network share, which is completely fine as long as you trust the network share.

Conclusion

Having all your Virtual Machines share the same source repository is possible and saves a lot of time checking out code as you don’t have to do it an each Virtual Machine.

Doing this for multiple users did not work well as the we used TFS and the source seemed to be tied to the user.

I have not yet tried to share between VS 2010 and VS 2012. I hope that works…I’ll update when I know.

Creating a QUnit Test Project in Visual Studio 2010

You may want to Unit Test your JavaScript code and one library to do this with is QUnit.

QUnit is based on the idea of opening a web page to run your JavaScript tests. So here is how I create a new QUnit project in Visual Studio.

This article assumes that you have the following installed already:

  • Visual Studio 2010 or later
  • The NuGet Add-in for Visual Studio

Step 1 – Create a Visual Studio Project

  1. Open Visual Studio.
  2. Go to File | New | Project.
  3. Select ASP.NET Empty Web Application.
  4. Give the project a name:
    Note: For this walk-thru, I named mine QUnitExample
  5. Click OK.

Step 2 – Import QUnit

Method 1 – Using NuGet

This step requires internet access.

  1. Right-click on your Project and choose Manage NuGet Packages.
  2. Search for QUnit and locate QUnit for ASP.NET MVC.
  3. Click Install next to QUnit for ASP.NET MVC.
  4. Click Close.

You should now see a folder called Content with a QUnit.css file and a folder called Scripts with a QUnit.js file.

Note: The NuGet package had old files, so I had to update them manually following Method 2.

Method 2 – Just downloading the files

If the NuGet package is not up to date, you may want to download the files manually. Follow the steps above to get QUnit through NuGet and if it doesn’t work, download the latest files from the QUnit web site and replace the ones NuGet added to your project with the latest ones.

Step 3 – Create an HTML file to display test results

  1. Right-click on the project and Choose Add | New Item.
  2. Find and choose HTML Page.
  3. Give the page a name.
    Note: I named mine QUnitTestResults.htm.
  4. Open the QUnitTestResults.htm file for editing.
  5. I made the DOCTYPE tag simpler in line 1:
  6. Enter something in the Title: Line 4.
    Note: I called mine QUnit Test Results.
  7. Add a Link to the qunity.css file: Line 5.
  8. Add a script in the body that calls the qunit.js file: Line 8.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Test Results</title>
  <link rel="stylesheet" href="/Content/qunit.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="/Scripts/qunit.js"></script>
  <script src="/Scripts/tests.js"></script>
</body>
</html>

Step 4 – Create your first QUnit Test

  1. Right-click on the Project and choose Add | New Folder.
  2. Rename the folder to TestScripts.
    Note: I like to keep the test scripts separate from the other scripts.
  3. Right-click on the TestScripts folder and Choose Add | New Item.
  4. Find and choose JScript File.
  5. Give the JavaScript file a name.
    I named mine ExampleTests.js.
  6. Open the ExampleTests.js file for editing.
  7. Add a test method to the ExampleTests.js file.
test("hello test", function () {
    ok(1 == "1", "Passed!");
});

Note: This test is straight from the QUnit home page.

Step 5 – Add the Tests to your HTML file

  1. Open the QUnitTestResults.htm file for editing.
  2. Add a script in the body that calls the ExampleTests.js file: Line 9.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Test Results</title>
  <link rel="stylesheet" href="/Content/qunit.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="/Scripts/qunit.js"></script>
  <script src="/Scripts/tests.js"></script>
  <script src="/TestScripts/ExampleTests.js"></script>
</body>
</html>

Step 6 – Run the tests

  1. Right-click on the QUnitExample project and choose Set as StartUp Project.
  2. Right-click on QUnitTestResults.htm and choose Set As Start Page.
  3. Click Debug | Start Debugging.

Step 7 – Start testing your JavaScript files

Now you probably want to recreate this project in as an additional project to your production solution (if you haven’t done this already).

It is time to start testing your JavaScript file. If you add the script to your project as a link, then you don’t have to maintain two copies of it.

  1. Right-click on the Scripts folder and choose Add | Existing Item.
  2. Browse to the JavaScript file that you want to test and select it but don’t add it yet.
  3. Click the down arrow next to Add and choose Add as link.
  4. Right-click on the TestScripts folder and Choose Add | New Item.
  5. Find and choose JScript File.
    Note: My file is called MySample.js.
  6. Give the JavaScript file a name.
    Note: I named mine MySampleTests.js.
  7. Open the ExampleTests.js file for editing.
  8. Start adding tests.

Conclusion

This method allows for rudimentary testing of your JavaScript. However, it does not integrate with Visual Studio, or Code Coverage, or Gated Check-ins. So there is a lot more work that needs to be done.

Changing ol and li html tags to have “Steps” and Hanging indent.

Let’s say you want to have a list of items. However, you want the word “Step” before each number in the list. You may be tempted to not use the ol and li tags and just write the list.

Step 1 – Do something.
Step 2 – Do something else.

However, it will be obnoxious to type “Step” every time. The list doesn’t scale either. If the list gets long and you want to reorder the list, or even add a step, you have to change every number. Also, what if you want a hanging indent? How are you going to do that?

Well, just use these CSS classes.

ol.Steps {
  counter-reset: section;
  list-style-type: none;
  padding: 0;
  padding-left: 55px;
}

ol.Steps li {
  text-indent: -55px;
}

ol.Steps li:before {
  counter-increment: section;
  content: "Step " counter(section) " - "; // Change to ": " if you like
}

Here is some sample html:

<ol class="Steps">
  <li>The first thing to do.</li>
  <li>The second thing to do.</li>
  <li>The third thing to do. However, this step is really, really long. In fact, it is so long that the instructions to do this step wrap all the way into multiple lines.</li>
  <li>The fourth thing to do.</li>
</ol>

Here is how it looks:

  1. The first thing to do.
  2. The second thing to do.
  3. The third thing to do. However, this step is really, really long. In fact, it is so long that the instructions to do this step wrap all the way into multiple lines. No really. It has to go one multiple lines, even if the screen is really, really big.
  4. The fourth thing to do.

Get Active Directory User’s GUID and SID in C#? (Part 2)

Yesterday we learned how to Get the Current User’s Active Directory info. Today we will learn how to get a named user’s Active Directory info?

Get a named User’s Active Directory info?

The first steps are the same as yesterday.

Step 1 – Create a new Console Application project in Visual Studio.

Step 2 – Add a .NET reference to System.DirectoryServices.AccountManagement.

Step 3 – Populate the Main Method as shown below.

using System;
using System.DirectoryServices.AccountManagement;

namespace NamedUserAdInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "Rhyous";
            PrincipalContext context = new PrincipalContext(ContextType.Domain);
            UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
            Console.WriteLine("Name: " + user.Name);
            Console.WriteLine("User: " + user.UserPrincipalName);
            Console.WriteLine("GUID: " + user.Guid);
            Console.WriteLine(" SID: " + user.Sid);
        }
    }
}

The only difference between the current user and a named user is that there is a static value for the current user called UserPrincipal.Current whereas for a named user, you need the user name.

Writing a program that does both

OK, so lets make a program that takes a parameter and does both. Here it is.

using System;
using System.DirectoryServices.AccountManagement;

namespace GetAdUserInfo
{
    class Program
    {
        static UserPrincipal user = UserPrincipal.Current;

        static void Main(string[] args)
        {
            ParseArgs(args);
            OutputUserInformation();
        }
        
        private static void OutputUserInformation()
        {
            Console.WriteLine("Name: " + user.Name);
            Console.WriteLine("User: " + user.UserPrincipalName);
            Console.WriteLine("GUID: " + user.Guid);
            Console.WriteLine(" SID: " + user.Sid);
        }

        private static void ParseArgs(string[] args)
        {
            foreach (var arg in args)
            {
                if (arg.StartsWith("user=", StringComparison.CurrentCultureIgnoreCase))
                {
                    string[] splitArgs = arg.Split("=".ToCharArray());
                    string userName = string.Empty;
                    if (splitArgs.Length == 2)
                        userName = splitArgs[1];
                    if (string.IsNullOrWhiteSpace(userName))
                    {
                        Syntax();
                    }

                    // set up domain context
                    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

                    // find a user
                    user = UserPrincipal.FindByIdentity(ctx, userName);
                    continue;
                }

                if (arg.StartsWith("user=", StringComparison.CurrentCultureIgnoreCase))
                {
                    Syntax();
                }

                // if arg not found treat it like /?
                {
                    Console.WriteLine("Argument not found: " + arg);
                    Syntax();
                }
            }
        }

        private static void Syntax()
        {
            String fullExeNameAndPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            String ExeName = System.IO.Path.GetFileName(fullExeNameAndPath);
            Console.WriteLine(ExeName + " user=[username]");
        }
    }
}

Here are the sample projects.
GetAdUserInfo.zip

Get Active Directory User’s GUID and SID in C#? (Part 1)

Get the Current User’s Active Directory info?

Here is how to get the currently logged in users Active Directory GUID and SID.

Step 1 – Create a new Console Application project in Visual Studio.

Step 2 – Add a .NET reference to System.DirectoryServices.AccountManagement.

Step 3 – Populate the Main Method as shown below.

using System;
using System.DirectoryServices.AccountManagement;

namespace GetAdUserInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Name: " + UserPrincipal.Current.Name);
            Console.WriteLine("User: " + UserPrincipal.Current.UserPrincipalName);
            Console.WriteLine("GUID: " + UserPrincipal.Current.Guid);
            Console.WriteLine(" SID: " + UserPrincipal.Current.Sid);
        }
    }
}

See Part 2 – Get a named User’s Active Directory info?

Using jQuery to enable/disable a button based on a text box

Since this is an html file, just create a blank file on your desktop called Test.html and copy and past the code below.

The steps for doing this are comments in the code.

Note: This should handle typing, pasting, code change, etc…

<!-- Step 1a - Create HTML File (see step 1b way below) -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
 
    <!-- Step 3 - Add script to run when page loads -->
    <script  type="text/javascript">
        jQuery(document).ready(function () { 
            <!-- Step 4 - Bind method to text box -->    
            $("#txtField").bind("propertychange keyup input paste", setButtonState);
			
            <!-- Step 4 - Set the default state -->
			setButtonState();
        });
		var setButtonState = function () {
			if ($("#txtField").val() == "")
				$("#btnEnter").attr("disabled","disabled");
			else
				$("#btnEnter").removeAttr("disabled"); 
		}
    </script>
</head>
<body>
<!-- Step 1b - Add HTML elements --> 
<input type="text" id="txtField" size="50"/>
<button type="button" id="btnEnter">Enter</button>
</body>

Update: 5/22/2013: Fixed example. Before if it was used on a page with links, going forward and back could result in the button being disabled even if the text box was populated. This new example solves this issue.

See a MVVM version of this here:
Using MVVM with HTML5 and JavaScript

C# Interview Questions

Comparing C# to other languages

  1. Q: What makes C# different than C++?
    A: C# has the CLR. C# has a Garbage collector, Properties, no globals, statics, C# has single inheritance with multiple interfaces while C++ has multiple inheritance. C# allows for the property syntax.
  2. Q: In what ways are C# and C++ the same?
    A: Object oriented. They both have classes, enums, methods, similar types (bool, int, double, etc…).

You can change the above to questions by replacing C++ with any language that candidate may say they are familiar with on their resume: Java, PHP, Ruby, Perl, Python. Of course, you may have to look up the answer. (Or not. You can usually tell by the interviewee’s confidence without knowing the answers yourself.)

C# Basics

Look the basics at least make sure they aren’t completely lying on there resume and they actually have at least done something in C#.

  1. Q: What is a benefit of having Properties over getters and setters?
    A: If you started using a variable and now you need to wrap code to have multiple actions on get and set, you don’t have to refactor as the Property has the same name and is used the same as a member variable.
    A: Readability. For syntactical purposes the getter and the setter always have to be in the same place in code because they are grouped. Other languages allow for the getter and setter to be anywhere in the object.
  2. Q: What is the syntax for instantiating an instance of each of the following:
    boolean
    A: bool b = true;
    integer
    A: int i = 0;
    real number
    A: double d = 1.0;
    array of integers
    A: int[] myArray = new int[10];
  3. Q: What is the standard way to create an empty string?
    A: string someEmptyValue = string.empty
  4. Q: Is a string mutable or immutable?
    A: immutable.
    Q: What does that mean when performing string manipulation functions?
    A: Any time the string changes, what really happens is a new string is created in a new location in memory.
  5. Q: Write both a for loop and a foreach loop that iterates through a List called myStrings.
    A:

    for (int i = 0; i < myStrings.Count; i++)
    {
        // put code here
    }
    
    foreach  (string str in myStrings)
    {
        // put code here
    }
    

    Q: Why would you use one method over another?
    A: Maybe you need the current id, so you use the for loop.

C# – Big O

  1. How to find the duplicate in an array using Big O of N?

C# – Open Ended Questions

  1. What design patterns do you use when developing? What design patterns do you hope to learn?
  2. What is the latest C# object or feature you have learned to use?
  3. Which areas of C# have your worked with? Which areas of C# have you not worked with?

C# – Security

  1. Q: What are some security related tools (executable files) included with .NET Framework?
    A: Caspol.exe (Code Access Security Policy Tool): Enables you to view and configure security policy for the machine policy level, the user policy level, and the enterprise policy level. In the .NET Framework 4 and later, this tool does not affect code access security (CAS) policy unless the element is set to true. For more information, see Security Changes in the .NET Framework.Cert2spc.exe (Software Publisher Certificate Test Tool): Creates a Software Publisher’s Certificate (SPC) from one or more X.509 certificates. This tool is for testing purposes only.Certmgr.exe (Certificate Manager Tool): Manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs).

    Makecert.exe (Certificate Creation Tool): Generates X.509 certificates for testing purposes only.

    Peverify.exe (PEVerify Tool): Helps you verify whether your Microsoft intermediate language (MSIL) code and associated metadata meet type safety requirements.

    SecAnnotate.exe (.NET Security Annotator Tool): Identifies the SecurityCritical and SecuritySafeCritical portions of an assembly.

    SignTool.exe (Sign Tool): Digitally signs files, verifies signatures in files, and time-stamps files.

    Sn.exe (Strong Name Tool): Helps create assemblies with strong names. This tool provides options for key management, signature generation, and signature verification.

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

  2. Q: What are some libraries in the System.Security namespace?
    A:System.Security
    System.Security.AccessControl
    System.Security.Authentication
    System.Security.Authentication.ExtendedProtection
    System.Security.Authentication.ExtendedProtection.Configuration
    System.Security.Claims
    System.Security.Cryptography
    System.Security.Cryptography.Pkcs
    System.Security.Cryptography.X509Certificates
    System.Security.Cryptography.Xml
    System.Security.Permissions
    System.Security.Policy
    System.Security.Principal
    System.Security.RightsManagementQ: Can you discuss any of these libraries?
    A: See what they have to say and compare it to the web site on MSDN for these libraries.Q: Which libraries have you used? Tell my about a project you used that library in.
  3. What are some of the Key Security Concepts in C#?
    A: Security Permissions, Type Safety and Security,  Principal, Authentication, Authorization, Security Concerns for Keywords
    Ref: http://msdn.microsoft.com/en-us/library/z164t8hs.aspx
  4. What is Code Access Permissions?
    A: permission objects that are used to help protect resources and operations from unauthorized use. They are a fundamental part of the common language runtime’s mechanism for enforcing security restrictions on managed code.
    Ref: http://msdn.microsoft.com/en-us/library/h846e9b3.aspx

More to come . . .

A Spreadsheet for Sprint Planning

As a follow-up to Why your story estimation was off!“, I have created a spreadsheet for sprint management. This spread is not for helping you size a story, but instead it is for helping you determine how many stories your team can really do a single sprint.

It has the documentation on a separate sheet inside it.

Sprint Planning Spread Sheet Template.xlsx

The Joel Test updated for 2013

Many of you have heard of The Joel Test. Joel Spolsky wrote it in 2000 and yet is still eye-opening to many development environments. Here is the Joel test if you haven’t read about it.

The Joel Test (written by Joel Spolsky in 2000)

  1. Do you use source control?
  2. Can you make a build in one step?
  3. Do you make daily builds?
  4. Do you have a bug database?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule?
  7. Do you have a spec?
  8. Do programmers have quiet working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have testers?
  11. Do new candidates write code during their interview?
  12. Do you do hallway usability testing?

This test is a good measuring stick. However, it has been a dozen years since Joel wrote this. Are updates needed? I think so. It is missing some important yet still simple yes/no questions. So here is my updated version. New stuff is in blue.

The Joel Test (Updated for 2013 by me)

Source Control

  1. Do you use distributed source control?
  2. Do you have a gated check-in?
  3. Do you have a branching strategy?

Build and Install

  1. After checking out source, can a developer build and debug with one click.
  2. Can you make a build and an installer in one step?
  3. Do you make daily builds and installers?
  4. Can a developer add to the build easily?
Coding Practices and Coding Architecture/Design
  1. Do you have coding best practices?
  2. Is your code considered decoupled?
  3. Do you analyse and design before you code?
Bugs and Enhancement Tracking
  1. Do you have an integrated bug database?
  2. Can customers/users see status of existing bugs, submit new bugs and enhancement ideas, and vote on them?
  3. Do you fix bugs before writing new code?
Testing
  1. Do you write a Unit Test exposing the bug before fixing the bug?
  2. Do you write Unit Tests and publish code coverage/complexity results buildly?
  3. Do you have automated tests and testers writing them?
  4. Do you do hallway usability testing?
Road Map/Development
  1. Do you have an up-to-date schedule?
  2. Do you have a spec?
  3. Are you practicing a successful software development methodology?
Developers
  1. Do you have a continuous education program for developers?
  2. Do developers interact with customers once a year?
  3. Do new candidates write code during their interview?
  4. Do you have a training program for newly hired developers?
Tools and Workplace
  1. Do programmers have quiet working conditions?
  2. Do you use the best software money can buy?
  3. Do you have the best hardware money can buy?
  4. Do you have a simple process for developers to request software or hardware?
User Experience
  1. Do you have a team dedicated to enhancing the user experience?
  2. Do you send a prototype to customers/users before you start coding?

So I think that the above changes are quite easy to use still. They are simple yes/no questions. The look is quite different, yet it seems much more clear as to why the questions are being asked. Even though there are a lot more questions (more than double), it is still easy and short.

So here is a list (probably not comprehensive) of the changes I made.

  1. I grouped the questions into categories so the failure areas become clear.
  2. I enhanced some questions taking into account some software development movements over the past dozen years.
  3. I added some questions, again taking into account some movements over the past dozen years.
  4. I added a questions that focus on the customer/user.
  5. Also, Joel has a lot of paragraphs explaining his questions and some of what he explains could be added to the question in one word, for example, I added “installer” to the build questions.

Well I suppose some people will hate the updates and some will love them.

If you want to add or alter some of these questions, feel free to comment.