Sunday, February 9, 2014

Exception when SignalR hosted using OWIN by Azure worker

I came across the following error when I tried to host SignalR using OWIN by Azure worker role.

Could not load file or assembly 'Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. 

Upon searching over the web, I came across few links (specified some in References).

Reason is specified over here.

Fix

We need to add few configuration (specified in Snippet 1) in app.config file of the project where we have specified the SignalR. mapping code.
While incorporating the fix, we need to observe it and tweak the new version accordingly, if required. Just verify the packages.config to understand which version of Microsoft.Owin and Microsoft.Owin.Security dll got installed. Most of the time, Microsoft.Owin dll version might have got changed. Ensure the new version specified in the app.config file to be matched with the one you've installed / specified in packages.config.

Snippet 1: (app.config)

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

Snippet 2: (packages.config)

<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Cors" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Diagnostics" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.HttpListener" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Hosting" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.SelfHost" version="2.0.2" targetFramework="net45" />

References:

http://stackoverflow.com/questions/20083185/fileloadexception-when-hosting-signalr-at-azure-worker-role-with-f
https://nuget.codeplex.com/workitem/3827

Thursday, March 21, 2013

Updating 'Microsoft.Data.OData 5.2.0' to 'Microsoft.Data.OData 5.3.0' failed


Updating 'Microsoft.Data.OData 5.2.0' to 'Microsoft.Data.OData 5.3.0' failed. Unable to find a version of 'Microsoft.AspNet.WebApi.OData' that is compatible with 'Microsoft.Data.OData 5.3.0'.

WCF Data Services 5.3.0 RTW has been released few days back. Once you install it using the tools installer, it will update the "Add Service Reference" tooling integration in Visual Studio, after which it'll create the code based on the WCF Data Services 5.3.0.  In such case, for now if you try to add service reference to a WCF Data Service in an ASP.NET MVC 4 project you might end up getting the error specified at the top of this page.

As mentioned in the error, it seems that the respective "Microsoft.AspNet.WebApi.OData" dll is not available in the last ASP.NET MVC 4 update. Hope this will be made available in the next related update.

Solution: Uninstall the respective program installed using the WCF Data Services 5.3.0 RTW tools installer. If you try the service reference now it'll get you with Microsoft.Data.OData 5.2.0 in the client. This way we can go with WCF Data Service created with 5.3.0 version and the respective client libraries (proxy....) with 5.2.0 (in ASP.NET MVC 4 client projects). Just tried locally, but didn't verified entire features.
As an alternate try with Nuget packages.

Friday, August 10, 2012

WCF Data Services - OData - Initial errors developers encounters

When authoring WCF Data Services - OData, lot of developers tries to view it in the browser during several stages of developement. Mostly they will come across the following error at initial stages.

The server encountered an error processing the request. See  server logs for more details.

When we think of creating WCF Data services, its better to have the following minimal understanding.

WCF Data services / OData service : A .Net framework component which is used to create services that uses Open Data Protocol (OData). This service exposes data through the endpoint which allows to access the data.

OData client libraries : Though not strictly required, several client libraries available for easy and effective access of OData format. Based on the client applications we create, we can make use of the respective client libraries. For example we have separate libraries for .Net, java, javascript, Silverlight, etc.

OData data model : Makes use of the exiting .Net member called Entity Data Model(EDM).  The data to be represented need to be modeled using EDM.

OData Protocol : This protocol is REST based. Defines  how the data model will be represented over the wire - either in XML based format defined by ATOM or in JSON format.

Now, let us look at the cause for the issue.

In the InitializeService method of the svc.cs file, do ensure whether the SetEntitySetAccessRule is specified for the respective entity and most important, the name of the entity set should be pluralized (if opted while creating the entity data model).

Snippet 1


// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("Employees", EntitySetRights.AllRead);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}

References

Saturday, June 16, 2012

OData : Cross domain OData request using jQuery, JSONP

I've been doing a POC where I had a situation to make a request to a OData Service (service which exposed the data as OData  - Open Data Protocol) using jQuery. During my initial attempt, I got an error from the web browser which is due to the same origin policy of the web browser.  Usually Client side (request from browser using javascript) cannot be allowed to make a request to a resource that exists in another domain of which HTML <script> element is an exception. In such cases JSONP (JSON with padding) and CORS (Cross Origin Resource Sharing) is made use. Among the two, JSONP requests are commonly used right now and CORS is expected to catch the mass. In this post we'll focus on the JSONP model request for OData Service.

To get a quick idea on the need for JSONP and how that stuff works, please have a quick glimpse here.  The code snippets I represent in this post will use the Nerd Dinner OData Feed for easier understanding.

After deciding to make the JSONP request, I used jQuery.ajax() method with url : http://www.nerddinner.com/Services/OData.svc/Dinners?$format=json & jsonpCallback option which resulted in error. Upon analyzing it, found out the error is "Uncaught SyntaxError: Unexpected token : " and the error is because the returned data is a simple JSON format and not wrapped with the callback method which is expected. Then I searched and found out the right format to make the OData JSONP request. The option is available as a OData query $callback.

Following are the three different alterations we can do to make a cross domain OData request using jQuery and JSONP.

Snippet 1:

$(document).ready(function () {

    $.ajax({
        url: 'http://www.nerddinner.com/Services/OData.svc/Dinners?$format=json&$callback=nerdCallback',
        dataType: "jsonp"
    });
});

function nerdCallback(result) {
    //Manipulate the resultant here....
    alert("Result count : " + $(result["d"]["results"]).length);
}

Snippet 2:

$(document).ready(function () {

    $.ajax({
        url: 'http://www.nerddinner.com/Services/OData.svc/Dinners?$format=json&$callback=?',
        dataType: "jsonp",
        jsonpCallback: "nerdCallback"
    });
});

function nerdCallback(result) {
    //Manipulate the resultant here....
    alert("Result count : " + $(result["d"]["results"]).length);
}

Snippet 3:

$(document).ready(function () {

    $.ajax({
        url: 'http://www.nerddinner.com/Services/OData.svc/Dinners?$format=json&$callback=?',
        dataType: "jsonp",
        success: function (result) {
            //Manipulate the resultant here....
            alert("Result count : " + $(result["d"]["results"]).length);
        }
    });
});

References:
http://en.wikipedia.org/wiki/JSONP
http://msdn.microsoft.com/en-us/library/ee834511.aspx
http://www.odata.org/

Wednesday, May 30, 2012

ASP.NET MVC 3 - Effectively using Model metadata

In ASP.NET MVC 3, most developers might have observed the existence of the HTML helpers - DisplayForModel and EditorForModel. This post is just to give a hint on how effectively we can use the specified HTML helpers and hence we won't have any code Snippets here.

I frequently come across situations of creating proof of concept and several sample applications to evaluate certain implementations / metrics. In such cases, lot of time I really worried on creating a sample data entry / display page which consumes my time, because my core objective is to evaluate my target as early as possible. The EditorForModel HTML helper in ASP.NET MVC actually saves me lot of time and help me to just focus on my target while doing such POCs.

While doing so I thought some simple tweaks, like a way to represent display name, order ... for the property might help me to tune my sample page further. To achieve that, I got the help of DataAnnotations / Metadata.

Some sample requirements are
  • Need to hide a column - ScaffoldColumn(false)
  • Hidden value - HiddenInput
  • Display a different name - Display(Name = "Employee Name")
  • Display in a custom order - Display(Order=1)
  • Display format with different type than default - DataType(DataType.MultilineText)

Using these Metadata, we can, hide a property from creating HTML elements for that, create a hidden value element for a property, display a different name than that of the property, display in a custom order we need, specify what type of HTML element and what format can be used, etc.

Once you start explore other parameters of attributes and options, you can achieve lot of cases with minimal effort. Really its a time saving mechanism. If none of the options fits our scenario, then we can do the regular way.   

Monday, April 30, 2012

ASP.NET MVC 3 - Using Ninject for Dependency Injection


This post is to show how to implement Dependency Injection in ASP.NET MVC 3 application with simple steps. For Details on Dependency Injection (DI) please refer to my article here.

For the sake of simplicity and to understand the idea, I have simply specified all the classes in same project(web application here). In real time scenario this might extend to multiple class libraries based on the nature of the project.

In our example, we're targeting a Mark sheet creation with minimal and predefined data. MarkSheetController expects a MarksheetModel and the MarkSheetModel expects a MarkEvaluator which we're going to achieve with Constructor injection as follows.

Implementaiton Details

First we need to install the Ninject.MVC3 Nuget package using Nuget manager. For details on Nuget manager please verify my post here. Upon installing the package, a file called NinjectWebCommon.cs will get created under the folder called App_Start.  In the  static method called RegisterServices, add the statement to register the dependencies with Ninject container. Following Snippets are self explanatory to understand the concept.

Snippet 1: (App_Start/NinjectWebCommon.cs => NinjectWebCommon.RegisterServices())

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IMarkSheetModel>().To<MarkSheetModel>();
    kernel.Bind<IMarkEvaluator>().To<MarkEvaluator>();
}

In the above snippet I've registered with Ninject that MarkSheetModel concrete class is bound to IMarkSheetModel and MarkEvaluator concrete class is bound to IMarkEvaluator interface. Based on this Ninject resolves the dependency by creating instance for the respective concrete class and pass it in the place of the related interface specification. Following snippet shows how we're making use of constructor injection to achieve that.

Snippet 2: (MarkSheetController - note the IMarkSheetModel parameter in the constructor)

public class MarkSheetController : Controller
{
    private IMarkSheetModel model;


    public MarkSheetController(IMarkSheetModel modelParam)
    {
        model = modelParam;
    }

    //
    // GET: /MarkSheet/

    public ActionResult Index()
    {
        model.LoadDetails();
        return View(model);
    }

}

Snippet 3: (MarkSheetController - note the IMarkEvaluator parameter in the constructor)

public class MarkSheetModel : IMarkSheetModel
{
    private IMarkEvaluator evaluator;

    public string StudentId { get; set; }
    public string StudentName { get; set; }
    public IEnumerable<Subject> SubjectList { get; set; }
    public int Total { get; private set; }
    public decimal Average { get; private set; }
    public string Grade { get; private set; }
    
    public MarkSheetModel(IMarkEvaluator evaluatorParam)
    {
        evaluator = evaluatorParam;
    }

    public void LoadDetails()
    {
        this.StudentId = "S1001";
        this.StudentName = "Sample";

        this.SubjectList = new List<Subject> { new Subject{ SubjectId="Sub0001", SubjectName ="Sub 1", Score = 78},
        new Subject{ SubjectId="Sub0002", SubjectName ="Sub 2", Score = 84},
        new Subject{ SubjectId="Sub0003", SubjectName ="Sub 3", Score = 72},
        new Subject{ SubjectId="Sub0004", SubjectName ="Sub 4", Score = 69}};

        this.Total = this.evaluator.CalculateTotal(this.SubjectList);
        this.Average = this.evaluator.CalculateAverage(this.SubjectList);
        this.Grade = this.evaluator.CalculateGrade(this.SubjectList);
    }

}

public interface IMarkSheetModel
{
    void LoadDetails();
    IEnumerable<Subject> SubjectList { get; set; }
    string StudentId { get; set; }
    string StudentName { get; set; }
}

public class Subject
{
    public string SubjectId { get; set; }
    public string SubjectName { get; set; }
    public int Score { get; set; }
}

Snippet 4:

public class MarkEvaluator : IMarkEvaluator
{
    public int CalculateTotal(IEnumerable<Subject> subjectList)
    {
        return subjectList.Sum(su => su.Score);
    }

    public decimal CalculateAverage(IEnumerable<Subject> subjectList)
    {
        return Convert.ToDecimal(CalculateTotal(subjectList)) / subjectList.Count();
    }

    public String CalculateGrade(IEnumerable<Subject> subjectList)
    {
        decimal averageScore = CalculateAverage(subjectList);

        if (averageScore > 80)
        {
            return "Grade A";
        }
        else if (averageScore > 70)
        {
            return "Grade B";
        }
        else if (averageScore > 60)
        {
            return "Grade C";
        }
        else
        {
            return "Grade D";
        }
    }
}

public interface IMarkEvaluator
{
    decimal CalculateAverage(IEnumerable<Subject> subjectList);
    string CalculateGrade(IEnumerable<Subject> subjectList);
    int CalculateTotal(IEnumerable<Subject> subjectList);
}


While executing the above snippets, the constructor of the MarkSheetController and MarkSheetModel is supplied with the respective instance.

References:
https://github.com/ninject/ninject.web.mvc/wiki/MVC3


Friday, March 30, 2012

ASP.NET MVC 3 - Converting / Serializing .Net objects into JSON format in View


In ASP.NET MVC often we might need to use / manipulate Model objects or its property inside the javascript. In order to achieve that, we usually try to serialize the .Net object and store it in a javascript variable which will then be accessed further in javascript.

Using Razor view engine, we can achieve this easily. In the following, I'll explain two approaches with a simple View(.cshtml) snippet to understand the concept. 

Approach 1: (Using Json.Encode(...))

Snippet 1: (Index.cshtml)

@model Web.POC.Models.FeedModel
@{
    ViewBag.Title = "Feed viewer";
}

<script type="text/javascript">
    var entries = @Html.Raw(Json.Encode(Model.FeedEntries));    
</script>


Approach 2: (Using JavaScriptSerializer)

Snippet 2: (Index.cshtml)

@model Web.POC.Models.FeedModel
@{
    ViewBag.Title = "Feed viewer";
}

@{
   System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
}
<script type="text/javascript">
    var entries = @Html.Raw(serializer.Serialize(Model.FeedEntries));    
</script>


Assumptions:

As specified, the above snippets are just to understand the concept. In that, consider that we're having a model "FeedModel" which holds a property called "FeedEntries" of some custom type which we're trying to convert into JSON object.

Also note that we need to use the HTML.Raw() to indicate that the output should not be HTML encoded.


Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.