Knockout.js defer applyBindings to avoid nodeType of null error

Knockout requires all html and the bound view model to be complete before applyBindings is called otherwise you might receive a nodeType of null error.  This is usually easily avoided by making sure the sequence of scripts is correct and applyBindings script is referenced at the end.

In more complex projects this may get messy especially when using a framework like MVC with partial views.  I found a simple technique worked for more: marking the reference as deferred.  For example if my applyBindings is located in the following javascript file, then I can reference my javascript in the logical location in the project but add the defer attribute:

<script type=”text/javascript” src=”viewmodel.js” defer=”defer”></script>

Posted in ASP.Net, HTML, JavaScript, Knockout.js, MVC, Uncategorized | Leave a comment

Azure Storage Client Version 3 – development storage not supported – 400 Bad Request

This post is just to save those unfortunates that have taken the latest Storage Client 3.0 and found that the storage emulator (re., local development storage) returns 400 Bad Request responses.  This is simply that the storage client version 3 is not compatible with the emulator (only version 2).  The advice provided by Microsoft is either use an older client or test against Azure storage and not the emulator.

http://blogs.msdn.com/b/windowsazurestorage/archive/2013/11/23/windows-azure-storage-known-issues-november-2013.aspx

This is not the first time but still a time waster:

http://social.msdn.microsoft.com/Forums/windowsazure/en-US/b1b66cc0-5143-41fb-b92e-b03d017ea3c1/400-bad-request-connecting-to-development-storage-using-azure-storage-client-ver-20?forum=windowsazuredata

 

Posted in Azure, AzureStorage, Uncategorized | Leave a comment

MVC 4 ApiController Session access

Nothing is accidental when it comes to the behavior of Microsoft technology. It was a conscious decision to not provide access to session state from the ApiController in the same manner as the Controller class. I assume this was an attempt to appear more RESTful in the eyes of the development community by being stateless. Yes, the session is not easily available but with a quick look at an ApiController request, the session cookie is being transferred:
Capture

There are many solutions to extending the ApiController to have access to session state and this post illustrates one for MVC version 4.

Starting with the basic template, the WebApiConfig class located in the App_Start folder can be easily change to extend the routing handler to have access to session.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;
 
namespace MySample.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            ).RouteHandler = new SessionRouteHandler();            
        }
 
        public class SessionRouteHandler : System.Web.Routing.IRouteHandler
        {
            System.Web.IHttpHandler System.Web.Routing.IRouteHandler.GetHttpHandler(System.Web.Routing.RequestContext requestContext)
            {
                return new SessionControllerHandler(requestContext.RouteData);
            }
        }
 
        public class SessionControllerHandler : System.Web.Http.WebHost.HttpControllerHandler, System.Web.SessionState.IRequiresSessionState
        {
            public SessionControllerHandler(System.Web.Routing.RouteData routeData)
                : base(routeData)
            { }
        }
    }
}

The session can then be referenced in the ApiController using HttpContext.Current.Session.

So why not plumb it in by default?  Yes, session should be used sparingly in order to maximize scalibility but one of the benefits of using MVC is its rich framework.  Good design is using the available resources and technology as effective as possible.

Posted in ASP.Net, C#, MVC | 4 Comments

MVC–Displaying Content from Ajax calls

This article illustrates two approaches to retrieving content from a service using an Ajax query in the MVC framework.  The first calls a method on a controller to paint a partial view.  The second retrieves html markup from a Web API controller.

Real World Scenario

For a project I worked on recently a majority of the content needed to be branded depending on the customer who was currently logged in.  The solution was to retrieve branded content from Azure storage.  For example, terms and conditions or contact us pages.  For most of the requirements I used an Web API controller to retrieve the content and I used a partial view when the html contained content updated by a model.

Sample Project

This sample starts with the ASP.NET MVC 4 Web Application template (Internet Application):

image

The template provides a simple website having two links: About and Contact.

image

The plan is to retrieve the content of the About via a Web API controller and the Contact via a partial view.

Ajax Web API controller

The project currently does not contain any apicontroller classes so we will add on into the project.  To make this sample a little more realistic, the purpose of the controller is to pull static html markup from a repository.  The first step is to create a Resources web API controller:

image

By convention, I create these in an Api folder but the folder name is not important

After removing the sample methods provided, I created the following method:

[System.Web.Mvc.OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public HttpResponseMessage Get(string id)
{
    var resource = GetResourceById(id);
 
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StringContent(resource);
    result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
    return result;
}

Because we are not sending a JSON result back we need to return a HttpResponseMessage with the content and the content type.  The GetResourceById() method simulates a call to some form of storage.  In this example it is just coded to return an html string:

private string GetResourceById(string id)
{
    return "&lt;article&gt;&lt;p&gt;Use this area to provide additional information.&lt;/p&gt;&lt;p&gt;Use this area to provide additional information.&lt;/p&gt;&lt;p&gt;Use this area to provide additional information.&lt;/p&gt;&lt;/article&gt;" 
}

The next step is to alter the About view so the content can be placed in a div when the result comes back:

<div id="aboutDiv"></div>
<img id="aboutImg" src="~/Images/ajax-loader.gif" />

Using jQuery the api controller is retrieved and the result is displayed:

<script type="text/javascript">
(function (spike, $) {
$.get('/Api/Resources/about',
function (data) {
$('#aboutDiv').html(data);
$('#aboutImg').hide();
});
}(this.spike = this.spike || {}, jQuery));
</script>

Ajax MVC Partial View

To make the Contact example a little more interesting, let’s create a new controller, partial view and model for the response.  The interesting thing to note is the HomeController will still return the main view but the contact details will be returned from the new controller.

Our new controller will be ContactController and will simply return a Contact model with the partial view:

public class ContactController : Controller
{
    public ActionResult Index()
    {
        var model = new Contact
        {
            Name = "John Smith",
            Email = "jsmith@spike.com"
        };
 
        return PartialView(model);
    }
}

The view itself if simple and uses Razor to apply the model to the markup:

@model Spike.Blog140131.Models.Contact
 
<section class="contact">
    <header>
        <h3>Email @Model.Name</h3>
    </header>
    <p>
        <span class="label">Support:</span>
        <span><a href="mailto:@Model.Email">@Model.Email</a></span>
    </p>
</section>

The javascript uses a similar structure and calls the Contact controller directly to get the partial view result:

<script type="text/javascript">
    (function (spike, $) {
        $.get('/Contact/Index',
               function (data) {
                  $('#contactDiv').html(data);
                  $('#aboutImg').hide();
                 });
     }(this.spike = this.spike || {}, jQuery));
</script>

The complete project is here: Spike.Blog140131

Posted in ASP.Net, C#, HTML, JavaScript, JQuery, MVC, Uncategorized | Tagged , | Leave a comment

The remote server returned an error: (407) Proxy Authentication Required.

Just a quick note… Several C# components support pulling from http endpoints directly. For example, the XDocument class in System.XML.Linq supports the Load method which takes a URL. If this throws a “The remote server returned an error: (407) Proxy Authentication Required.” error, then the likely cause is the proxy settings of the server (visible via Internet Explorer’s Options settings) is not being used.

To fix this, add the following in the application or web configuration file:

<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
</configuration>
Posted in C#, Uncategorized | Tagged , | 5 Comments

Azure Table Storage – DataServiceQueryException when using Count()

I have been expanding the Azure Storage Sample project. I came across an interesting limitation with the OData query projection currently supported by the Azure Storage Client. My desire was to have a rowkey that increments per partionkey entry. The concept would be each row would map to a note on a customer order. The partition would map to an order id and each rowkey would be an incrementing integer (like a table seed).

For a product system I would avoid this type of convention as in my example any unique rowkey would suffice.

My first attempt was to use Count() as illustrated below:

return dataContext.CreateQuery(this.tableName)
                  .Where(n =&gt; n.PartitionKey == partitionKey).Count();

This caused a runtime DataServiceQueryException with the message of “An error occurred while processing this request.” Digging into the inner exception of DataServiceClientException showed a message of

  <code>InvalidInput</code>
  One of the request inputs is not valid.

I found an Azure Storage post: http://blogs.msdn.com/b/windowsazurestorage/archive/2011/09/15/windows-azure-tables-introducing-upsert-and-query-projection.aspx stating that Count() was currently not supported. So based on their helpful sample, the offending code was changed to:

// http://blogs.msdn.com/b/windowsazurestorage/archive/2011/09/15/windows-azure-tables-introducing-upsert-and-query-projection.aspx
                //return dataContext.CreateQuery(this.tableName).Where(n =&gt; n.PartitionKey == partitionKey).Count();
 
                var qry = dataContext.CreateQuery(this.tableName)
                                     .Where(n =&gt; n.PartitionKey == partitionKey);
 
                int count = 0;
                foreach (var row in qry)
                {
                    count++;
                }
 
                return count;

Hope this saves someone time!

Posted in Azure, AzureStorage, C# | Tagged , , | Leave a comment

Unit Test WCF Clients

In general, I use SoapUI for mocking services. For rapid development this works well, but sometimes it is useful to mock services within your unit tests. The advantages here would include being able to automate the tests and to eliminate the dependency of the unit tests on an external technology. In other words, sometimes it is nice to just hit play on your unit tests.

First, I tend to create a mocked implementation of the service contract. This usually creates an in memory implementation of a repository (e.g., a Dictionary<>), populates itself with some initial data, and then performs some basic operations. Below provides the concept but for a more detail example, please view the source for the TestService project (Tests/Spike.SampleContracts.TestService.OrderService) in the ServiceFramework sample project.

public class OrderService : IOrderService
    {         
        object _lock;
        int _key = 0;
        Dictionary<int, Order> _orders = new Dictionary<int, Order>(); 
 
        #region IOrderService Members 
        public Order GetOrderById(int id) 
        { 
            return _orders[id]; 
        } 
 
        public bool UpdateOrder(int id, Order order) 
        { 
            lock(_lock) 
            {
                _orders[id] = order; 
            }
            return true; 
        } 
 
        public int AddOrder(Order order) 
        { 
           lock(_lock)
           {
              _key += 1; 
              _orders.Add(_key, order); 
           }
 
           return _key; 
        } 
}

Then in my unit test project, I start up the host as a task. I’ve written the following sample as a generic. Note: this will use the settings from the app.config.

 internal static Action StartService<T>(CancellationToken token) where T : class 
        { 
            return () => 
                       { 
                           using (ServiceHost host = new ServiceHost(typeof (T))) 
                           { 
                               host.Open(); 
                               try 
                               { 
                                   ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(); 
                                   manualResetEvent.Wait(token); 
                               } 
                               catch (OperationCanceledException) 
                               { 
                                   // intended behavior  
                               } 
                               finally 
                               { 
                                   if (host.State == CommunicationState.Opened) 
                                   { 
                                       // Close the ServiceHost. 
                                       host.Close(); 
                                   } 
                               } 
                           } 
                       }; 
        }

In order to start the service, a new cancellation token will need to be created and then supplied to the task factory: Note: you might need a pause (re., CurrentThread.Join) before sending requests to the service.

CancellationTokenSource token = new CancellationTokenSource();
var host = Task.Factory.StartNew(ServiceHostTask.StartService<CustomerService>(token);

Once the client has performed the required tests, then stopping the service is simple; just cancel the token:

cancellationTokenSource.Cancel();

For more information, take a look at the sample project ServiceFramework on MSDN.

Posted in C#, SoapUI, WCF | Tagged , , , , | Leave a comment

‘CloudStorageAccount’ does not exist in the namespace ‘Microsoft.WindowsAzure’

In case this helps someone, I upgraded my Azure Storage assemblies and found a breaking change to the Azure storage classes. The error manifests itself as:

The type or namespace name ‘CloudStorageAccount’ does not exist in the namespace ‘Microsoft.WindowsAzure’ (are you missing an assembly reference?)

And most likely stems from code similar to the following:

Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher( ( configName, configSetter ) =>
            {
                configSetter( Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue( configName ) );
            } );

It was simple enough to fix:

CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(ConfigurationManager.AppSettings[configName]);
 
            });

When the storage account is created, you need to identify the settings name that the connection string is defined in:

var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

To be complete, the following illustrates how the web.config or app.config could be defined:

<appSettings>
    <add key="DataConnectionString" value="UseDevelopmentStorage=true" />
</appSettings>
Posted in Azure, AzureStorage, C# | Tagged , | 1 Comment

jQuery UI Accordion and jQuery BBQ

The following illustrates how the jQuery UI Accordion can be used in combination with jQuery BBQ.  Using the accordion example as a base, I made the following changes:

Buttons

I added a series of buttons that set the active option of the accordion. This has the affect of triggering the appropriate section of the accordion widget.

1
2
3
4
<button onclick="$('#accordion').accordion('option', 'active', 0);">0</button>
<button onclick="$('#accordion').accordion('option', 'active', 1);">1</button>
<button onclick="$('#accordion').accordion('option', 'active', 2);">2</button>
<button onclick="$('#accordion').accordion('option', 'active', 3);">3</button>

Accordion Activate Event

The next step was to update the BBQ state when the accordion was activated.
This will be triggered by either the button click or if the accordion widget is updated directly

<script>        
        $(function () {
            $("#accordion").accordion({
                    activate: function (event, ui) {
                        var active = $("#accordion").accordion('option', 'active');
                        $.bbq.pushState({ 'active': active}, 0);
                    }
                }
            );
        });
</script>

Hashchange Event

The above works to keep the URL updated based on changes to the accordion. To affect the accordion widget based on changes to the URL, we need to subscribe to the hashchange event and update the accordion widget using the active option.

<script>
        $(function () {
            $(window).bind('hashchange', function () {                
                var x = $.bbq.getState();
                if (x.active == undefined) {
                    $("#accordion").accordion('option', 'active', 0);
                } else {
                    $("#accordion").accordion('option', 'active', x.active);
                }
            });
 
            // Since the event is only triggered when the hash changes, we need to trigger
            // the event now, to handle the hash the page may have loaded with.
            $(window).trigger('hashchange');
 
        });
</script>

Hope this saves someone some time!

Posted in HTML, JavaScript, JQuery, jQuery BBQ, jQuery UI | Tagged , | Leave a comment

WCF Soap Services without a Soap Action

I’ve run into an issue twice now when integrating to an externally hosted service with WCF.  This post will hopefully save someone some time on a rather obscure issue.

For WCF services that contain multiple operations, a unique Action should be given to each operation (according to WS-* guidelines).  For example, the following service breaks this rule as both GetData() and GetDataUsingDataContract() have the same action:

[ServiceContract]

public interface IService1

{

    [OperationContract(Action="", ReplyAction="*")]

    string GetName(GetNameRequest value);

 

    [OperationContract(Action = "", ReplyAction = "*")]

    CompositeType GetData(GetDataRequest composite);

}

Some non-Microsoft technologies (e.g., Java, WebSphere) do not enforce this in the same way that WCF does.  In general this does not pose an issue as WCF can build a compatible proxy for communicating with the service.  The issue arises when there is a need to strictly adhere to a definition or when mocking the service.

In order to be able to host the service, we need to use a custom dispatcher.  Simply put, the dispatcher is used to match up the message received by the service to the correct operation.  The normal dispatcher uses the soap Action for this.

This solution is based on the Microsoft DispatchByBody sample.  I adapted it because the service definition I needed to mock was outside of my control (re., a compiled library) so I was not able to easily add custom attributes to solve this.

Custom Dispatcher

By extending the IDispatchOperationSelector, the message can be routed to the appropriate method.  In this example, I use the incoming request’s root node to match against the operation.  This will work in the scenario where an operation is GetData and the request is GetDataRq.  Not the most interesting example…

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Channels;

using System.ServiceModel.Dispatcher;

using System.Xml;

 

namespace Spike.DispatchByMessage.Dispatcher

{

    class DispatchByBodyElementOperationSelector : IDispatchOperationSelector

    {

        List<string> dispatchDictionary;

        string defaultOperationName;

 

        public DispatchByBodyElementOperationSelector(List<string> dispatchDictionary, string defaultOperationName)

        {

            this.dispatchDictionary = dispatchDictionary;

            this.defaultOperationName = defaultOperationName;

        }

 

        #region IDispatchOperationSelector Members

 

        private Message CreateMessageCopy(Message message, XmlDictionaryReader body)

        {

            Message copy = Message.CreateMessage(message.Version,message.Headers.Action,body);

            copy.Headers.CopyHeaderFrom(message,0);

            copy.Properties.CopyProperties(message.Properties);

            return copy;

        }

 

        public string SelectOperation(ref System.ServiceModel.Channels.Message message)

        {

            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);

            message = CreateMessageCopy(message,bodyReader);

 

            var operationName = dispatchDictionary.FirstOrDefault(e => lookupQName.Name.ToLower().Contains(e.ToLower()));            

 

            if(operationName!=null)

            {

                return operationName;

            }

            

            return defaultOperationName;            

        }

 

        #endregion

    }

}

And the plumbing…

First we will associate the operation selector with a new contract behavior:

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel.Description;

using System.Xml;

using System.ServiceModel.Dispatcher;

 

namespace Spike.DispatchByMessage.Dispatcher

{

    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]

    sealed class DispatchByBodyElementBehaviorAttribute : Attribute, IContractBehavior

    {

        #region IContractBehavior Members

 

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)

        {

            return;

        }

 

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)

        {

            return;

        }

 

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)

        {

            List<string> operations = new List<string>();

            foreach( OperationDescription operationDescription in contractDescription.Operations )

            {

                operations.Add(operationDescription.Name);

            }

            

            dispatchRuntime.OperationSelector = new DispatchByBodyElementOperationSelector(operations, dispatchRuntime.UnhandledDispatchOperation.Name);

        }

 

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)

        {

        }

 

        #endregion

    }

}

I then defined a service attribute to apply the contract behavior to all endpoints:

using System;

using System.Collections.Generic;

using System.Linq;

using System.ServiceModel.Description;

using System.Text;

using Spike.DispatchByMessage.Dispatcher;

 

namespace Spike.DispatchByMessage

{

    public class DispatchByBodyElementServiceBehaviorAttribute : Attribute, IServiceBehavior

    {

        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)

        {

            //

        }

 

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)

        {

            //

            foreach (var endpoint in serviceDescription.Endpoints)

            {

                endpoint.Contract.Behaviors.Add(new DispatchByBodyElementBehaviorAttribute());

            }

        }

 

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)

        {

            //

        }

    }

 

}

Last, I apply the attribute to my service:

[DispatchByBodyElementServiceBehaviorAttribute]

public class Service1 : IService1

Posted in C#, Java, SoapUI, WCF | 10 Comments