ASP.NET 4.0 WCF RESTful Services – Part 2

In the first part, we got a .NET 4.0 WCF Service (file-extension less, yep no .SVC in your service call) setup and running, and I showed how to call a basic “GET” service using jQuery’s $.getJSON() method. Now, we are going to explore allow the different RESTful methods GET, POST, PUT, and DELETE. The steps below are designed to work with the project created in Part 1 and they focus on show basic CRUD style services you would use in a Ajax application. Everything is being written with Visual Studio 2010 and .NET 4.0.

RESTful Methods ( GET / POST / PUT / DELETE )

Before we get going, it’s important to remember the following rules when building WCF Services.

  1. The UriTemplate can only use parameters of type string
  2. Uri Templates can have many forms, here are a few examples:

    Sample Uri Templates for .svc-less function calls

            [WebGet(UriTemplate = "Products/{name}")]
            public Product GetProduct(string name)
            // URL = "/InventoryService/Products/ProductXYZ"
    
            [WebGet(UriTemplate = "Products/Product({name})")]
            public Product GetProduct(string name)
            // URL = "/InventoryService/Products/Product(ProductXYZ)"
    
            [WebGet(UriTemplate = "Products/API.Service?Product={name}")]
            public Product GetProduct(string name)
            // URL = "/InventoryService/Products/API.Service?Product=ProductXYZ"
    
  3. When passing multiple objects, you must make the following changes:

    WCF Service (Sending 1 object vs 2 objects)

            //  PASS 1 Object.
    
            [WebInvoke(UriTemplate = "Products/API.Service?Product={productName}", Method = "POST")]
            public string APIGet(string productName, Product product1)
    
            // Passing 2 Objects or more.
            // Added "BodyStyle = WebMessageBodyStyle.WrappedRequest".
    
            [WebInvoke(UriTemplate = "Products/API.Service?Product={productName}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest )]
            public string APIGet(string productName, Product product1, Product product2)
    

    jQuery Ajax Call (Sending 1 object vs 2 objects)

                // Common Objects to use in examples below
                var Product1 = {};
                Product1.Name = 'Name1';
                Product1.Description = 'Desc1';
                Product1.Price = 1.0;
                Product1.Quantity = 1;
                Product1.IsDiscontinued = false;
    
                var Product2 = {};
                Product2.Name = 'Name2';
                Product2.Description = 'Desc2';
                Product2.Price = 2.0;
                Product2.Quantity = 2;
                Product2.IsDiscontinued = false;
    
                //  PASS 1 Object.
                $.ajax({
                    type: 'POST',
                    url: '/InventoryService/Products/API.Service?Product=ProductXYZ',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    data: JSON.stringify(Product1),  // Here we are sending the 1 object, no wrapper.
                    success: function (response)
                    {
                        // Do Something
                    }
                });
    
                // Passing 2 Objects or more.
    
                // Here we created a new jsonRequest object that wraps our 2 objects we want to send to our service.
                jsonRequest = { 'product1': Product1, 'product2': Product2 };
    
                $.ajax({
                    type: 'POST',
                    url: '/InventoryService/Products/API.Service?Product=ProductXYZ',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    data: JSON.stringify(jsonRequest),  // Here we are sending a object that wraps our 2 product objects.
                    success: function (response)
                    {
                        // Do Something
                    }
                });
    

GET / POST / PUT / DELETE WCF Services and their jQuery Ajax Calls

GET Method

Service

        [WebGet(UriTemplate = "Products/{name}")]
        [OperationContract]
        public Product GetProduct(string name)
        {
            // Get a Product
        }

jQuery Call

                    var name = 'ProductXYZ';

                    $.ajax({
                        type: 'GET',
                        url: '/InventoryService/Products/' + name,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data: '',
                        success: function (response)
                        {
                            // Do Something
                        }
                    });

                    // Alternative to $.ajax for a GET request is using $.getJSON.
                    $.getJSON('/InventoryService/' + name, '', function (result) { // Do Something });

This is probably the simplest service call to issue, but the amazing jQuery team made the process even easier with the getJSON() call that wraps up a ajax() GET request. Notice the svc-less call above, there’s no ugly “.svc” telling your consumers… Hay, I’m using WCF!!!

POST Method

Service

        [WebGet(UriTemplate = "Products/{name}", Method = "POST")]
        [OperationContract]
        public Product GetProduct(string name, Product product)
        {
            // Insert New Product
        }

jQuery Call

                    var name = 'ProductXYZ';
                    var Product = {};
                    Product.Name = 'ProductXYZ';
                    Product.Description = 'Product XYZ Description';

                    $.ajax({
                        type: 'POST',
                        url: '/InventoryService/Products/' + name,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data: JSON.stringify(Product),
                        success: function (response)
                        {
                            // Do Something
                        }
                    });

This has always been my go to method for sending data to a service, but according to a few RESTful people this method is only supposed to be used for inserts. I’m not really sure how “firm” this rule is, so I decided to do all Inserts and Updates with the POST method, since I almost always handle this in the same function call in my DAL. In addition to posting my Object to the service, I also include the primary key (“PK”) in the service path so I can use the IIS logs to show who touched a specific record.

PUT Method

Service

        [WebInvoke(UriTemplate = "Products/{name}", Method = "PUT")]
        [OperationContract]
        public Product GetProduct(string name)
        {
            // Update Product
        }

jQuery Call

                    var name = 'ProductXYZ';
                    var Product = {};
                    Product.Name = 'ProductXYZ';
                    Product.Description = 'Product XYZ Description';

                    $.ajax({
                        type: 'PUT',
                        url: '/InventoryService/Products/' + name,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data: JSON.stringify(Product),
                        success: function (response)
                        {
                            // Do Something
                        }
                    });

I don’t use this much, but when I do the calls look exactly the same as a POST except for the change in request type.

DELETE Method

Service

        [WebGet(UriTemplate = "Products/{name}", Method = "DELETE")]
        [OperationContract]
        public bool GetProduct(string name)
        {
            // Delete Product
        }

jQuery Call

                    var name = 'ProductXYZ';

                    $.ajax({
                        type: 'DELETE',
                        url: '/InventoryService/Products/' + name,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data: '',
                        success: function (response)
                        {
                            // Do Something
                        }
                    });

Since I always like “confirmation” when something has been done, I always return a boolean from my delete services. This allows me to confirm something was able to be deleted, if you expect to have various failure states you might want to consider using a string return type to provide a detailed “error” message whey the request failed (e.g. “Successfully Deleted”, “You don’t have permission.”, “Product is associated with other orders.”).

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • Facebook
  • Digg

ASP.NET 4.0 WCF RESTful Services – Part 1

Details, details, details… I just spend a few days moving over to svc-less WCF services with a ASP.NET 4.0 web application, and boy was it fun… The overall setup is pretty easy, once you’ve painfully gone through the process “a few” times. Since this is something I’ll no be doing by default on all new projects, I thought this would make a great write-up tutorial. During my discovery and learning phase, I found a bunch of helpful blog posts but nothing was 100% and there was lots of those “important” bits missing. Since most of my projects consume JSON, I plan to do a 4 part series on setting up a Web Application to support WCF services that will be called via jQuery.

Enough with the background, let’s start by creating a new “ASP.NET Web Application”.

What project to choose in VS 2010

  1. Remove everything inside the Scripts folder.
  2. Right Click on Project, and choose “Manage NuGet Packages…”

    Hopefully your familiar with NuGet, it’s a package manager for Visual Studio and you can install it by going to Tools -> Extension Manager… -> Online Gallery -> Download “NuGet Package Manager”. This is the most popular extension and it allows you to quickly add bits to your projects (e.g. Install jQuery, and be notified when a new version is available.).

  3. Use search to install the following NuGet Packages.
    • jQuery
    • JSON-js json2

    Required NuGet Packages

  4. Edit your “site.master” to and include your new scripts:
    	   <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    	   <script src="Scripts/jquery-ui-1.8.19.js" type="text/javascript"></script>
    	   <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
    	
  5. Also in the “site.master”, edit your asp:Menu to include 4 pages called Part1 – Part4:
                    <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
                        <Items>
                            <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
                            <asp:MenuItem NavigateUrl="~/Part1.aspx" Text="Part 1"/>
                            <asp:MenuItem NavigateUrl="~/Part2.aspx" Text="Part 2" />
                            <asp:MenuItem NavigateUrl="~/Part3.aspx" Text="Part 3" />
                            <asp:MenuItem NavigateUrl="~/Part3.aspx" Text="Part 4" />
                            <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
                        </Items>
                    </asp:Menu>
    	

    ** We are only going to use Part1.aspx right now, but I plan on 4 posts on this topic.

  6. Add 4 new “Web Form using Master Page” to the project called Page1.aspx, Page2.aspx, Page3.aspx, Page4.aspx.
    ** These will match the named used in the navigation menu in the site.master.
  7. Add a new folder to the root of the project called Service.
  8. Add a new “AJAX-enabled WCF Service” to the Service folder called “InventoryService.svc”.
    • Note, this will add the following references to your project.
      	     System.Runtime.Serialization
      	     System.ServiceModel
      	     System.ServiceModel.Web
      	
    • It will also add the following lines to your Web.config
      	  <system.webServer>
      		 <modules runAllManagedModulesForAllRequests="true"/>
      	  </system.webServer>
      
      	  <system.serviceModel>
      		<behaviors>
      		  <endpointBehaviors>
      			<behavior name="RESTfulWCF.Service.Service1AspNetAjaxBehavior">
      			  <enableWebScript />
      			</behavior>
      		  </endpointBehaviors>
      		</behaviors>
      		<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      		  multipleSiteBindingsEnabled="true" />
      		<services>
      		  <service name="RESTfulWCF.Service.Service1">
      			<endpoint address="" behaviorConfiguration="RESTfulWCF.Service.Service1AspNetAjaxBehavior"
      			  binding="webHttpBinding" contract="RESTfulWCF.Service.Service1" />
      		  </service>
      		</services>
      	  </system.serviceModel>
      	
    • Change the “system.serviceModel” section of your web.config to the following.
      	    <system.serviceModel>
      	        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      	        <standardEndpoints>
      	            <webHttpEndpoint>
      	                <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      	            </webHttpEndpoint>
      	        </standardEndpoints>
      	    </system.serviceModel>
      	

      Web.Config Key Points

      	// This allows your services to run under your sites app pool, giving access
      	// to your HttpContext.
      	aspNetCompatibilityEnabled="true"
      	
      	// See below, this allows you to type <service>/help to get information on your service
      	helpEnabled="true"
      	
      	// This is AWESOME, this tag allows your service to respond in any format you
      	// specify in your request (e.g. XML, JSON, etc...).
      	automaticFormatSelectionEnabled="true"
      	



      ** One last item to note, every time you add an additional AJAX service, it will edit your web.config and put back in the bad configuration. I strongly suggest you make a backup of your web.config, incase you run into problems in the future!!!

    • Manually add a project reference to System.ServiceModel.Activation.
  9. At this point, your project in solution explorer should look like this:

    Items Included in Solution Explorer

  10. Now, open InventoryService.svc and make the following changes:
    • Erase everything and add the following C# code:
      using System.ServiceModel;
      using System.ServiceModel.Activation;
      using System.ServiceModel.Web;
      
      namespace RESTfulWCF.Service
      {
          [ServiceContract(Namespace = "")]
          [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
          public class InventoryService
          {
              [WebGet(UriTemplate = "Part1")]
              [OperationContract]
              public string Part1GetRequest()
              {
                  return "I did work";
              }
          }
      }
      	

      In the code above, we are mapping the function “Part1GetRequest” to the name “Part1″. This will allow us to call the service with the following syntax “/InventoryService/Part1″ using a GET request.

  11. Add a route to call the service without referencing a “.svc” file.
    Open Global.asax and replace your Applicaiton_Start with the following.

            void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
                RouteTable.Routes.Add(new ServiceRoute("InventoryService", new WebServiceHostFactory(), typeof(Service.InventoryService)));
            }
    	
  12. Now we are ready to create a jQuery test call, open “Page1.aspx” in Source View:

    Erase everything and add the following HTML code

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Part1.aspx.cs" Inherits="RESTfulWCF.Part1" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <script type="text/javascript">
            $(document).ready(function ()
            {
                $('#doWork').click(function ()
                {
                    $.getJSON('/InventoryService/Part1', '', function (result) { alert(result); });
                });
            });
        </script>
        <h2>
            ASP.NET 4.0 WCF RESTful Demo - Part 1
        </h2>
        <p>
            <input type="button" id="doWork" value="Issue GET Request" />
        </p>
    </asp:Content>
    	

    We are able to use the $.getJSON() jQuery function because we applied the “WebGet” attribute to the WCF function “Part1GetRequest()”.

  13. Launch the application and navigate to “Page 1″. Click on the “Issue GET Request” button and you should see the followign results:

    jQuery Demo Results

  14. To get a list of all the functions your service offers, pass the “/help” parameter to your service.

    List of all WCF Service Accessible by Passing /help to the Service

As noted, here is the project I built above following all the steps one-by-one.
    >> ASP.NET 4.0 RESTful Web Application Project

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • Facebook
  • Digg

Making an Editiable Table (CRUD) with jQuery

I’ve been working on a form that needs to support a unknown number of rows, that the user will either enter 1-by-1 or bulk upload. Adding a few rows to a table is pretty easy in HTML, but as the rows increase page starts to slow down and the UI can become overwhelming with HTML input controls. I decided to test a few concepts to determine what would best fit my form, I started with doing rows of input controls, followed by trying to use jqGrid plug-in. I really liked jqGrid, but as I tried to get everything working I found myself having to “work around” lots of issues (read forum, apply fix, something else breaks, repeat), so I gave up after making the solution working 90% in jqGrid because the code was already a lot more complex than what I wanted. In the end, I decided that building my own table editor that supported CRUD with jQuery. In addition to following the KISS rule, I also had a list of goals I wanted to include.

Solution Goals

  1. Allow users to add 1 to 2,000 rows
  2. Keep the page quick when working with 500+ rows
  3. Make all edits in memory
  4. Create a Undo/Cancel button to undo a edit
  5. Capture dynamic HTML TABLE row contents for use in a server side postback
  6. (Not in DEMO) Enable validation for rows in Edit Mode
  7. (Not in DEMO) Enable default values for manually added rows

All of the goals above were in the final solution and 95% of the work is done client-side in ~300 lines of jQuery & JavaScript code. I choose to use jQuery templates for the rows, since it offers a simple model for merging data/HTML along with some advanced features to perform logic in how elements are rendered (e.g. If my Cross object has a Status set, it will display an alert icon on the row and notify the user something in wrong). Since most of these other features were case specific, I left them out of the demo to focus on doing the basic CRUD in HTML and how I got the dynamic rows back to ASP.NET

Final Product

My solution was designed to leverage ASP.NET, but all of the code below is 100% HTML.  You can take this code and apply it to any table and choose to leverage any server technology you want.  Part of step 5 is ASP.NET specific, but this shows a neat trick for getting the HTML table rows back to the server so you can access them in a traditional ASP.NET postback event.

Step 1: Prerequisites (Accessible via CDN)

  1. jQuery
  2. jQuery tmpl plug-in
  3. JSON.org library
    <!-- jQuery on GOOGLE CDN -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <!-- JSON.org on CDNJS CDN -->
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <!-- jQuery tmpl() plug-in on ASPNET CDN -->
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

Step 2: HTML Layout

<body>
    <h1>
        CRUD My Table</h1>
    <!-- Table where we will perform CRUD operations, data loaded via jQuery tmpl() -->
    <table id="CRUDthisTable" class="mediumTable">
        <thead>
            <tr class="rowHeader">
                <th></th>
                <th>Change Type </th>
                <th>Update Type </th>
                <th>Customer Part </th>
                <th>ROHM Part </th>
                <th>Rank Start </th>
                <th>Rank End </th>
                <th>Price </th>
                <th>UOM </th>
                <th>Apply Date </th>
                <th>Remarks </th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- jQuery tmpl() Templates -->
    <!-- Edit Rows -->
    <script id="editRowTemplate" type="text/x-jquery-tmpl">
        <tr class="editRow">
            <td>
                <span id="cancel" name="cancel" tooltip="Cancel" class="ui-icon ui-icon-close CancelRow">Cancel</span>
                <span id="save" name="save" tooltip="Save" class="ui-icon ui-icon-disk SaveRow">Save</span>
            </td>
            <td>
                <select id="field1" name="field1" class="changeType">
                    <option></option>
                    <option>All</option>
                    <option>Part</option>
                    <option>Price</option>
                </select></td>
            <td>
                <select id="field2" name="field2" class="updateType">
                    <option></option>
                    <option>Add</option>
                    <option>Update</option>
                    <option>Delete</option>
                </select></td>
            <td>
                <input type="text" id="field3" name="field3" class="customerPart required part" value="${CustomerPart}" /></td>
            <td>
                <input type="text" id="field4" name="field4" class="rohmPart validROHMpart part" value="${ROHMPart}" /></td>
            <td>
                <input type="text" id="field5" name="field5" class="rankStart rank" value="${RankStart}" /></td>
            <td>
                <input type="text" id="field6" name="field6" class="rankEnd rank" value="${RankEnd}" /></td>
            <td>
                <input type="text" id="field7" name="field7" class="price required number" value="${Price}" /></td>
            <td>
                <select  id="field8" name="field8" class="uomType required">
                    <option></option>
                    <option>1</option>
                    <option>1000</option>
                </select></td>
            <td>
                <input type="text" id="field9" name="field9" class="applyDate required date" value="${ApplyDate}" /></td>
            <td>
                <input type="text" id="field10" name="field10"class="remarks" value="${Remarks}" /></td>
        </tr>
    </script>
    <!-- View Rows -->
    <script id="viewRowTemplate" type="text/x-jquery-tmpl">
        <tr>
            <td style="width:50px;">
                <span id="edit" name="edit" title="Edit" class="ui-icon ui-icon-pencil EditRow">Edit</span>
                <span id="delete" name="delete" title="Delete" class="ui-icon ui-icon-trash DeleteRow">Delete</span>
            </td>
            <td style="width:120px;">${ChangeType}</td>
            <td style="width:120px;">${UpdateType}</td>
            <td>${CustomerPart}</td>
            <td>${ROHMPart}</td>
            <td style="width:45px;">${RankStart}</td>
            <td style="width:45px;">${RankEnd}</td>
            <td>${Price}</td>
            <td style="width:64px;">${UOM}</td>
            <!-- **** TIP: Here we use a function to format the date mm/dd/yyyy -->
            <td style="width:80px;">${FormatDate(ApplyDate)}</td>
            <td>${Remarks}</td>
        </tr>
    </script>
</body>

Step 3: Example Loading Data ( NO CRUD Functionality )

        // Helper Function to Format Date in View Row
        function FormatDate(date)
        {
            return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
        }

        // After the DOM has loaded, take the sample data and inject it into the table using the View Row template.
        $(document).ready(function ()
        {
            // Sample Data - Could be returned via AJAX or could be manual rows added to the TABLE
            var crosses = [
            { "ChangeType": "All", "UpdateType": "Add", "CustomerPart": "1SS355TE-17", "ROHMPart": "1SS355TE-17", "RankStart": "", "RankEnd": "", "Price": 0.0151, "UOM": 1, "ApplyDate": new Date(1335337200000), "Remarks": "", "Status": null, "StatusNote": null },
            { "ChangeType": "All", "UpdateType": "Add", "CustomerPart": "RB160M-60TR", "ROHMPart": "RB160M-60TR", "RankStart": "", "RankEnd": "", "Price": 0.0605, "UOM": 1, "ApplyDate": new Date(1335337200000), "Remarks": "", "Status": null, "StatusNote": null },
            { "ChangeType": "All", "UpdateType": "Add", "CustomerPart": "RR264M-400TR", "ROHMPart": "RR264M-400TR", "RankStart": "", "RankEnd": "", "Price": 0.031, "UOM": 1, "ApplyDate": new Date(1335337200000), "Remarks": "", "Status": null, "StatusNote": null },
            { "ChangeType": "All", "UpdateType": "Add", "CustomerPart": "1SR154-400TE25", "ROHMPart": "1SR154-400TE25", "RankStart": "", "RankEnd": "", "Price": 0.0309, "UOM": 1, "ApplyDate": new Date(1335337200000), "Remarks": "", "Status": null, "StatusNote": null },
            { "ChangeType": "All", "UpdateType": "Add", "CustomerPart": "RF071M2STR", "ROHMPart": "RF071M2STR", "RankStart": "", "RankEnd": "", "Price": 0.0638, "UOM": 1, "ApplyDate": new Date(1335337200000), "Remarks": "", "Status": null, "StatusNote": null}];

            if (crosses) {
                $("#viewRowTemplate").tmpl(crosses).appendTo("#CRUDthisTable");
            }
        });

CRUD Table – Data Loaded no CRUD Functions Activated

Demo of 100% CRUD Table in HTML ( no persistance or CRUD features activated )

** As you can see, I’m not using images links similar to the final product since I was aiming for simplicity.  If you want to use images, I suggest you use the jQuery UI icons as I did in the final product, they can easily be added to a span by adding two class values (e.g. class=”ui-icon ui-icon-close”).

Step 4: Enable CRUD

        // Global Parameters
        var rowNum = 1;
        var rowRemovedNum;
        var rowRemovedContents;

        // Read a row in Edit Mode into a Cross Object
        function GetEditRowObject()
        {
            var row = $('#CRUDthisTable tbody tr.editRow');

            var cross = {};

            cross.ChangeType = row.find('.changeType').val();
            cross.UpdateType = row.find('.updateType').val();
            cross.CustomerPart = row.find('.customerPart').val();
            cross.ROHMPart = row.find('.rohmPart').val();
            cross.RankStart = row.find('.rankStart').val();
            cross.RankEnd = row.find('.rankEnd').val();
            cross.Price = row.find('.price').val();
            cross.UOM = row.find('.uomType').val();
            var dateString = row.find('.applyDate').val();
            cross.ApplyDate = new Date(dateString);
            cross.Remarks = row.find('.remarks').val();

            return cross;
        }

        // Read a row in View Mode into a Cross Object
        function GetViewRowObject(rowNum)
        {
            var row = $('#CRUDthisTable tbody tr').eq(rowNum);

            var cross = {};

            cross.ChangeType = row.find('td:eq(1)').text();
            cross.UpdateType = row.find('td:eq(2)').text();
            cross.CustomerPart = row.find('td:eq(3)').text();
            cross.ROHMPart = row.find('td:eq(4)').text();
            cross.RankStart = row.find('td:eq(5)').text();
            cross.RankEnd = row.find('td:eq(6)').text();
            cross.Price = row.find('td:eq(7)').text();
            cross.UOM = row.find('td:eq(8)').text();
            cross.ApplyDate = row.find('td:eq(9)').text();
            cross.Remarks = row.find('td:eq(10)').text();

            return cross;
        }

        // Read all rows into Cross Object Array
        function GetAllViewRowsAsCrossObjects()
        {
            var crossTableRows = [];

            $('#CRUDthisTable tbody tr').each(function (index, value)
            {
                var row = GetViewRowObject(index);
                crossTableRows.push(row);
            });

            return crossTableRows;
        }

        // Check if any rows are in Edit Mode
        function IsExistingRowInEditMode()
        {
            var rowsInEditMode = $('#CRUDthisTable tbody tr.editRow').length;

            if (rowsInEditMode > 0) {
                alert('You have a row in Edit mode, please save or cancel the row changes before you continue.');
                return true;
            }

            return false;
        }

        // After the DOM has loaded, bind the CRUD events
        $(document).ready(function ()
            // Events
            $('.AddRow').click(function ()
            {
                if (IsExistingRowInEditMode())
                    return;

                rowRemovedNum = 0;
                rowRemovedContents = null;

                var data = { data: 1 };
                var output = $("#editRowTemplate").tmpl(data).html()

                $('#CRUDthisTable tbody').prepend('<tr class="editRow">' + output + '</tr>');
                var $rowEdit = $('#CRUDthisTable tbody tr.editRow');

                $('#CRUDthisTable tbody tr:first')[0].scrollIntoView();
            });

            $('.EditRow').live('click', function (e)
            {
                if (IsExistingRowInEditMode())
                    return;

                var row = $(this).parent().parent().parent().children().index($(this).parent().parent());

                var data = GetViewRowObject(row);

                var output = $("#editRowTemplate").tmpl(data).html()

                rowRemovedNum = row;
                rowRemovedContents = $('#CRUDthisTable tbody tr').eq(row).html();

                $('#CRUDthisTable tbody tr').eq(row).after('<tr class="editRow">' + output + '</tr>');

                var $editRow = $('#CRUDthisTable tbody tr.editRow');

                var changeType = $editRow.find('.changeType');
                $(changeType).val(data.ChangeType);

                var updateType = $editRow.find('.updateType');
                $(updateType).val(data.UpdateType);

                var uomType = $editRow.find('.uomType');
                $(uomType).val(data.UOM);

                $('#CRUDthisTable tbody tr').eq(row).remove();
            });

            $('.SaveRow').live('click', function (e)
            {
                var savedData = GetEditRowObject();

                var row = $(this).parent().parent().parent().children().index($(this).parent().parent());

                var output = $("#viewRowTemplate").tmpl(savedData).html();

                $('#CRUDthisTable tbody tr').eq(row).remove();

                var tableRows = $('#CRUDthisTable tbody tr').length;

                if (tableRows == 0 || row == 0) {
                    $('#CRUDthisTable tbody').prepend('<tr>' + output + '</tr>');
                }
                else {
                    $('#CRUDthisTable tbody tr').eq(row).before('<tr>' + output + '</tr>');
                }
            });

            $('.CancelRow').live('click', function (e)
            {
                var row = $(this).parent().parent().parent().children().index($(this).parent().parent());

                $('#CRUDthisTable tbody tr').eq(row).remove();

                if (rowRemovedContents)
                    $('#CRUDthisTable tbody tr').eq(row).before('<tr>' + rowRemovedContents + '</tr>');

                rowRemovedContents = null;
            });

            $('.DeleteRow').live('click', function (e)
            {
                e.preventDefault;
                $(this).parent().parent().remove();
            });
        });

Table is shows the results of clicking the Add New Row in the Table Footer

Step 5: Ajax POST Table Contents to the Server (before button event)

There is a ton of ways to do this, but my goal was to allow users to edit the table and when they were all done with all their edits they could hit “Save” and everything would then be written to the DB. Since ASP.NET doesn’t give you access to dynamic table rows, I bound a AJAX post event to the “Save” button that sends the table contents to the server, stores in cache, and then uses the cache in the traditional postback “Save” event.

        // After the DOM has loaded, bind the ASP.NET save button
        $(document).ready(function ()
            $('#<%= btnSave.ClientID %>').click(function (e) {
                return PostTable();
            });
        }

        // Post all rows to the server and put into Cache
        function PostTable()
        {
            // Normally I'll get the ID from the QueryString, but it could also be grabbed from a hidden element in the form.
            var crossId = 1;
            var jsonRequest = { crosses: GetAllViewRowsAsCrossObjects(), crossId: crossId };

            $.ajax({
                type: 'POST',
                url: 'Demo.aspx/CacheTable',
                data: JSON.stringify(jsonRequest),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data, text)
                {
                    return true;
                },
                error: function (request, status, error)
                {
                    return false;
                }
            });
        }

Important Note: If you want to access a page method via jQuery $.ajax(), then you must make the function static and pass the case sensitive parameters with the expected data type(s) in the ajax call.

    public partial class Demo: System.Web.UI.Page
    {
        private static string _cacheKey = "CacheTable_" + HttpContext.Current.User.Identity.Name;

        [WebMethod]
        public static void CacheTable(List<Cross> crosses, int crossId)
        {
            if (crosses != null && crosses.Count > 0)
            {
                HttpContext.Current.Cache.Remove(_cacheKey);
                HttpContext.Current.Cache.Insert(_cacheKey, crosses, null, DateTime.Now.AddSeconds(3600), Cache.NoSlidingExpiration);
            }
        }
    }

    // Custom Data Transfer Object (DTO)
    public class Cross
    {
        public string ChangeType { get; set; }
        public string UpdateType { get; set; }
        public string CustomerPart { get; set; }
        public string ROHMPart { get; set; }
        public string RankStart { get; set; }
        public string RankEnd { get; set; }
        public double Price { get; set; }
        public int UOM { get; set; }
        public DateTime ApplyDate { get; set; }
        public string Remarks { get; set; }
        public string Status { get; set; }
        public string StatusNote { get; set; }
    }

Working Demo of using jQuery to allow CRUD edits to a HTML TABLE.

ASP.NET Note **If you run into issues on the amount of rows you can postback to the server in ASP.NET via AJAX & JSON, you’ll need to edit your “maxJsonLength” in your web.config.

    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="2097152"/>
            </webServices>
        </scripting>
    </system.web.extensions>
These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • Facebook
  • Digg

Password Generator and Callsign Spelling with C#

If you need help building a random password, you should check out pctools.com random password generator. It’s great, it gives you a lot of options and you can have it generate a list of 50 passwords with their callsign spellings in seconds. I’ve found the callsign spelling to be very helpful for remembering and recognizing all the characters in a new password I generate. I liked this solution so much, I decided port this concept over to C# with a set of helpers. This can be used anywhere you want to generate a password, I am currently using it in a ASP.NET LOB app to suggest and show better passwords options.

Generating Random Passwords

using System;
using System.Collections.Generic;
using System.Linq;

public static class StringHelper
{
    // Shared Static Random Generator
    private static readonly Random CommonRandom = new Random();

    public static string GenerateRandomPassword(int passwordLength, bool canRepeatCharacters = false)
    {
        char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();

        string randomPassword = string.Empty;

        for (int l = 0; l < passwordLength; l++)
        {
            int x = CommonRandom.Next(1, chars.Length);

            if (canRepeatCharacters || !randomPassword.ToCharArray().Any(ch => ch == chars[x]))
                randomPassword += chars[x].ToString();
            else
                l--;
        }

        return randomPassword;
    }

    public static List<string> GenerateRandomPasswords(int quantity, int passwordLength = 8)
    {
        List<string> passwords = new List<string>();

        for (int i = 0; i < quantity; i++)
        {
            passwords.Add(GenerateRandomPassword(passwordLength));
        }

        return passwords;
    }
}

There are a few options on the generator, like not repeating a character and configuring the password length. In addition to the main method, I also have a helper that also returns a list of multiple passwords, to return in a list to give your users options.

Important note, Random() is not very random when your making quick consecutive calls. If you want to call Random() in a loop, you should move your instance of the Random() class to the outside to prevent duplicate seeds, which will result in duplicate passwords.

    public static string GetCallsignSpelling(string password)
    {
        if (string.IsNullOrEmpty(password))
            return string.Empty;

        Dictionary<char, string> callsigns = new Dictionary<char, string>()
            {
                {'$',"Dollar Symbol"},
                {'%',"Percent Symbol"},
                {'#',"Number Symbol"},
                {'@',"At Symbol"},
                {'!',"Exclamation Symbol"},
                {'*',"Asterisk Symbol"},
                {'a',"alpha"},
                {'b',"bravo"},
                {'c',"charlie"},
                {'d',"delta"},
                {'e',"echo"},
                {'f',"foxtrot"},
                {'g',"golf"},
                {'h',"hotel"},
                {'i',"india"},
                {'j',"juliet"},
                {'k',"kilo"},
                {'l',"lima"},
                {'m',"mike"},
                {'n',"november"},
                {'o',"oscar"},
                {'p',"papa"},
                {'q',"quebec"},
                {'r',"romeo"},
                {'s',"sierra"},
                {'t',"tango"},
                {'u',"uniform"},
                {'v',"victor"},
                {'w',"whiskey"},
                {'x',"xray"},
                {'y',"yankee"},
                {'z',"zulu"},
                {'1',"One"},
                {'2',"Two"},
                {'3',"Three"},
                {'4',"Four"},
                {'5',"Five"},
                {'6',"Six"},
                {'7',"Seven"},
                {'8',"Eight"},
                {'9',"Nine"},
                {'0',"Zero"},
                {'?',"Question Symbol"},
                {';',"SemiColon Symbol"},
                {':',"Colon Symbol"},
                {'A',"ALPHA"},
                {'B',"BRAVO"},
                {'C',"CHARLIE"},
                {'D',"DELTA"},
                {'E',"ECHO"},
                {'F',"FOXTROT"},
                {'G',"GOLF"},
                {'H',"HOTEL"},
                {'I',"INDIA"},
                {'J',"JULIET"},
                {'K',"KILO"},
                {'L',"LIMA"},
                {'M',"MIKE"},
                {'N',"NOVEMBER"},
                {'O',"OSCAR"},
                {'P',"PAPA"},
                {'Q',"QUEBEC"},
                {'R',"ROMEO"},
                {'S',"SIERRA"},
                {'T',"TANGO"},
                {'U',"UNIFORM"},
                {'V',"VICTOR"},
                {'W',"WHISKEY"},
                {'X',"XRAY"},
                {'Y',"YANKEE"},
                {'Z',"ZULU"},
                {'^',"Caret Symbol"},
                {'&',"Ampersand Symbol"}
            };

        char[] wordCharacters = password.ToCharArray();

        string callsignSpelling =
            wordCharacters.Aggregate(string.Empty,
                                         (current, passwordCharacter) =>
                                         current + (callsigns[passwordCharacter] + " - ")).TrimEnd(' ', '-');

        return callsignSpelling;
    }

The spelling is done using a Key/Value dictionary, and iterating over each character of the password one-by-one.

The result of using these two helpers is below.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • Facebook
  • Digg

JSON to HTML Form Using jQuery dForm Plug-in

In a previous posts, I’ve showed how to go from a JSON array of objects/values, to a HTML table. This is great when you want to display a bunch of data in column and rows, but what happens if you want to interact with the data. No problem, there is the jQuery dForm plug-in for that. In order to generate the form, you’ll need to redesign your server side / inline objects to provide the required rendering data for dForms. It’s pretty straight forward and there is a ton of options with the plug-in, see here.

Demo Screenshot

In the image above, we use an inline object that will feed the dForm “buildForm()” method. I’m using a static value here, but you could have easily setup dForm to load the data remotely using ajax.

Here is the jQuery dForm 0.1.3 Plug-in Demo used in the screenshot above, which includes everything you need to get up and running fast. If you have problems making dForm work, make sure you have included “ALL” the dForm libraries. The dForm.js file has dependencies on the other libraries, if you don’t load the correct libraries, you’ll end up with a blank form.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DotNetKicks
  • Facebook
  • Digg