Extending and Customizing authentication mechanism in Web Applications using ASP .NET Identity

Background

ASP.NET security module evolved time to time. First in 2005, Microsoft introduced ASP.Net Membership which is used to authenticate users using Forms authentication and the user names, password etc. stored in the SQL Server database. There were few limitations with this framework as the database schema was designed for SQL Server only and you cannot change it. Secondly, if you wanted to extend some more properties related to profile information etc. you have to create separate tables. Another limitation is OWIN. Since the authentication is based on Forms Authentication, the membership cannot use OWIN.

What is OWIN: OWIN includes middleware components for authentication that supports to log in users from external authentication namely Microsoft Accounts, Facebook, and Twitter etc. OWIN also includes support for OAuth 2.0, JWT and CORS.

Today, everyone maintains social network accounts like Twitter, Facebook, etc. and people most likely prefer to login or linking applications with these accounts rather creating new ones.

Keeping all these limitations Microsoft developed another framework “ASP.Net Identity” that does not only supports OWIN but more or less the extension and customizing of the authentication module is far easy and practical as compared to the ASP.Net Membership framework.

What is ASP.Net Identity?

ASP.Net Identity is a new membership framework to provide user logins and security in web applications. It allows adding login features in web application and also easily customizable to extend the user information.

Following are some of the feature of the ASP.NET Identity system taken from http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

One ASP.NET Identity system

  • ASP.NET Identity can be used with all of the ASP.NET frameworks such as ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR

Ease of plugging in profile data about the user

  • When you create new users in your application, it is now easy to add extra information about the user. For eg.. if you wanted to add a Birthdate option for users when they Register an account in your application.
  • ASP.NET Identity uses Entity Framework Code First and it is possible to extend the POCO classes.

Persistence control

  • By default the ASP.NET Identity system will store all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.
  • If your application requirements are that this information might be stored in a different storage mechanism such as SharePoint, Azure Table Service, No Sql databases etc. it is now possible to plug in different storage providers.

Unit testability

  • ASP.NET Identity makes the web application more unit testable. You can write Unit Tests for the parts of your application that use ASP.NET Identity

Simple Role provider

  • There is a Simple Role provider which lets you restrict access to parts of your application by Roles. You can easily create Roles such as “Admin” and add Users to Roles.

Claims Based

  • ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. There is a Claims

External Logins

  • You can easily add external logins such as Microsoft Account, Facebook, Twitter and Google to your application store the user specific data in your application using this system.
  • You can also add login functionality using Windows Azure Active Directory and store the user specific data in your application using this system.

ASP.Net Identity comes with ASP.Net MVC 5 or you can also add it using NuGet Package manager console. Identity framework is based upon three libraries namely

  • Microsoft.AspNet.Identity.EntityFramework

    This package has the Entity Framework implementation of ASP.NET Identity which will persist the ASP.NET Identity data and schema to SQL Server.

  • Microsoft.AspNet.Identity.Core

    This package has the core interfaces for ASP.NET Identity. This package can be used to write an implementation for ASP.NET Identity that targets different persistence stores such as Azure Table Storage, NoSQL databases etc.

  • Microsoft.AspNet.Identity.OWIN

    This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add log in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.

     

Steps to extend and configure ASP.NET Identity

Usually mid – large sized web applications are divided into different layers i.e. Presentation, Service, Business, Data Access etc. and usually models resides on the common layer which can be used by data access, service and presentation layers. When designing the architecture of web application and implementing security we have to follow the basic style of placing code in specific layers otherwise the code become shambolic.

In ASP.Net Identity, as the models are related to ASP.Net identity framework resides in Microsoft.AspNet.Identity.EntityFramework and with the help of Code First entity framework we can easily provide the association with other entities where needed.

Let’s proceed with some hands-on now

1. Open Visual Studio 2013 and create a new Web application project and select MVC template. If you create a web application project using Visual Studio 2013 you will automatically get these three assemblies referenced by default.

 2. In case if you have Visual Studio 2010 you can manually add it using NuGet Package manager console and search term ‘asp net identity’

 

 

3. Open AccountController, you will notice that its calling parameterized constructor from default AccountController constructor and initializing UserManager, UserStore and ApplicationDbContext


public class AccountController : Controller
{
public AccountController(): this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser> (new ApplicationDbContext()))){

  }
public AccountController(UserManager<ApplicationUser> userManager)

UserManager = userManager;

  }

 

4. UserManager is basically the entry point for performing signing operations, it takes UserStore as a parameter which is implemented by IUserLoginStore, IUserRoleStore, IUserClaimStore, IUserStore etc to provide repositories for user-related data such as user data, passwords, claims, roles etc. UserStore takes a DbContext as parameter and have the implementation details of how the particular User is stored. If you notice the ApplicationDbContext it is derived from IdentityDbContext and not the standard DbContext class this is because the IdentityDbContext is specific to the ASP .NET Identity framework and it allows entities to have String as a primary key.

5. Let’s generate a database from Identity framework entities using entity framework code first approach.

 a. In the visual studio, open Package Manager Console and select your web project as the startup project. In case if you have different layer for data access components you can select that specific layer and add the references to the ASP .NET Identity framework libraries via Nuget.

 b. Execute command enable-migration, that creates a Migration folder and create a Configuration class. Note: you can also enable the automatic migration by settings its AutomaticMigrationsEnabled property to true in the configuration class constructor.

 

c. Now open the ApplicationDBContext class and see which database connection name it’s pointing to. By default its pointing to DefaultConnection

 

 

d. To migrate the Identity tables into existing or separate database, we can change the connectionString as

 

<add name=DefaultConnection connectionString=Data Source=.\mssqlexpress;Initial Catalog=TestDB;Integrated Security=False;

User Id=sa; Password=sa123; Timeout=500000providerName=System.Data.SqlClient />

e. Now execute add-migration command in the package manager and name it Initial

 

f. It creates a class with two methods Up() and Down(), Up will be called to sync the changes from code first model to the database, and Down can be used to revert changes back to last state.

 

 

g. Now execute update-database command so the new database and identity tables will be created.

 

 

 

6. We can also create custom tables by adding DbSet properties for new tables in the ApplicationDbContext class and customize it according to our need.

7.  Let suppose, we want to extend the security module and provide page level security in which whenever the user navigates to any page system checks the feature set of user that belongs to particular role and redirect it to the login page if it does not exist. To handle this scenario we can follows below steps

a. Create a model named as View

public class View{

public String ViewName { set; get; }
public String ViewQualifiedName { set; get; }
public Int64 ViewParentId { set; get; }

}

b. Create another model named RolePermission

public class RolePermission{
public IdentityRole RoleId { set; get; }

 public View ViewId { set; get; }

          }

c. Add the DbSet property for RolePermission and View in the ApplicationDbContext class

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{
public ApplicationDbContext() : base(“SecurityTestDB”, throwIfV1Schema: false){
}
public DbSet<View> View { set; get; }

  public DbSet<RolePermission> RolePermissions { set; get; }

   public static ApplicationDbContext Create(){
    return new ApplicationDbContext();

  }
}

d. Follow the same steps as above to migrate model changes into database.

e. When we run the migration using add-migration and update-database commands it will create another table named as View in the SecurityTestDB and defines one to many relationship between ASPNetRoles and RolePermission table and View and RolePermission table.

8. Now let suppose we need to add more fields in the AspNetUsers or any other identities table we can customize it by adding a new class inheriting from Identity* class and specify new properties.

a. For example in the ASPNetRoles I need to add IsActive bit which can be used to enable/disable role rather deleting it completely I can create new class named SecurityRoles

b. Derive SecurityRoles with IdentityRole

c. Add IsActive Boolean property as follows

d. Enable migration

 public override void Up(){
AddColumn(“dbo.AspNetRoles”, “IsActive”, c => c.Boolean());

 }

 public override void Down()
{
DropColumn(“dbo.AspNetRoles”, “IsActive”);

}

 


 

 

 

With the power of Entity Framework and new Identity framework its quite easy now to customize security framework according to our need. The beauty is that the core classes remain intact and it doesn’t harm the underlying logic of the authentication mechanism provided by Microsoft.

 

Implementing Validation mechanism in ASP.Net MVC project using Unobtrusive JavaScript for validation

In this article I will walk you through the steps of implementing validation in the ASP.Net MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example

<input
type=”button”
id=”btn”
onclick=”alert(‘hello world’)
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {

$(‘#btn’).click(function (e) {

    alert(‘hello world’);

}

});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. In ASP.Net MVC, you know that there are many HTML helper functions like @Html.TextBoxFor, @Html.EditorFor, etc. that takes an expression and attributes. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example

If our model is


public
class
Person : Message

{

[GridColumn(“Id”, true)]


public
int Id { set; get; }

 

[Required]

[GridColumn(“Name”, false)]

[StringLength(10, ErrorMessage=“Length cannot exceed to 10 character”)]


public
string Name { set; get; }

}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this


@Html.EditorFor(model => model.Name)

This will generates an html as follows


<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

You can see that depending on the model it has automatically added the data-val-* properties in the html.

There is no magic, actually in order to make this work

  1. You have to add a jquery.validation.unobtrusive.js in your project.
  2. Then add the file path in the bundle like this

     

    bundles.Add(new
    ScriptBundle(“~/bundles/jqueryval”).Include(


    “~/Scripts/jquery.validate*”));

     

  3. Then add the script reference in the page as within the script section like this

@section scripts{


@Scripts.Render(“~/bundles/jqueryval”)

}

       4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this

$(‘#Save’).click(function (e) {


var $val = $(this).parents(‘form’);


if (!($val.valid()))


return
false;


else alert(‘form have no errors’);

}

Hope this helps!    

Adding Queryable Support to ASP.NET Web API Controller Action Methods

In this article I will show that how we can make our Web API methods queryable so the user can apply query operators and expressions to filter data.

We will use OData library for ASP.NET Web API that have the [Queryable] attribute provided, which facilitates in issuing queries.

1. Create ASP.Net Web API Project

2. Add sample model class which defines properties

3. In this example, I have created a Session class as follows

4. Now add a SessionController which will contain Get, Post, Put, Delete methods for CRUD operations.

5. It will create an empty controller. Now we will specify Get method and return session list as queryable.

6. Now add OData reference from Nuget Package Manager by searching as web api odata and click Install on Microsoft ASP.NET Web API 2 OData

7. Once you install, It will ask you to accept the license agreement, click I Accept and proceed

8. Now add [Queryable] attribute on GetSession method.

That’s it, build the solution and test.

9. Open fiddler and select GET HTTP Method and navigate to the URL i.e. http://[youraddress:port]/api/Session

10. Once you hit the above URI it will show you the complete session list in JSON format as follows

11. Now you can apply query operators on your request and filter data

Following are some query operators you can use to issue queries

$top=n: Returns only the first n entities in an entity set (or in Atom terms, the first n entries in a feed).

$skip=n: Skips the first n entities in an entity set. Using this option lets a client retrieve a series of distinct pages on subsequent requests.

$format: Determines whether data should be returned in JSON or the XML-based Atom/AtomPub format. (The default is Atom/AtomPub.)

$orderby=: Orders results, in ascending or descending order, by the value of one or more properties in those results.

$filter=: Returns only entities that match the specified expression.

$select=: Returns only the specified properties in an entity.

$inlinecount: Returns the server computed count of the number of entries produced by the query request.

Example

To select top 2, my URI would be like http://[youraddress:portNo[/api/Session?$top=2

Result:

Creating Custom Formatter in ASP.NET Web API for specific formatted response

In this article I will show you how to create a custom formatter in ASP.Net Web API to send formatted response.

Before diving into deep, let me give you a quick introduction to formatters

Formatters in ASP .NET Web API plays an important role, when the request comes to the server, depending on the media-type, determines which formatter has to be used to parse the request and assemble the data into appropriate format as response. In ASP.Net Web API when the request is made by the user, Web API framework checks if it is Simple Type or a Complex Type. All types like string, integers, etc. are simple types and by default ASP.Net Web API read those values from URI and uses Model binding. On the other hand for complex types, ASP.Net WEB API framework read it from request body by default (the behavior can be overridden) an depending on the content-type load specific formatter from the list of formatters available in HttpConfiguration list.

When you are creating a custom formatter in ASP.Net Web API, you have two options one is when the request is arrived on server and you want to return the data in specific format or when the request arrives and you want to read/parse the data in specific format.

In this example, we will see how you can return the response in PSV i.e. pipe separated value format.

Create a class that should be derived from BufferedMediaTypeFormatter or MediaTypeFormatter.

The difference is

  • MediaTypeFormatter – This class uses asynchronous read and write methods.
  • BufferedMediaTypeFormatter – This class derives from MediaTypeFormatter but wraps the asynchronous read/write methods inside synchronous methods. Deriving from BufferedMediaTypeFormatter is simpler, because there is no asynchronous code, but it also means the calling thread can block during I/O

In the example, we will use BufferedMediaTypeFormatter

Following are the methods available in BufferedMediaTypeFormatter class

// Summary:


// Represents a helper class to allow a synchronous formatter on top of the


// asynchronous formatter infrastructure.


public
abstract
class
BufferedMediaTypeFormatter : MediaTypeFormatter

{


// Summary:


// Initializes a new instance of the System.Net.Http.Formatting.BufferedMediaTypeFormatter


// class.


protected BufferedMediaTypeFormatter();

 


// Summary:


// Gets or sets the suggested size of buffer to use with streams in bytes.


//


// Returns:


// The suggested size of buffer to use with streams in bytes.


public
int BufferSize { get; set; }

 


// Summary:


// Reads synchronously from the buffered stream.


//


// Parameters:


// type:


// The type of the object to deserialize.


//


// readStream:


// The stream from which to read


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// formatterLogger:


// The System.Net.Http.Formatting.IFormatterLogger to log events to.


//


// Returns:


// An object of the given type.


public
virtual
object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger);


//


// Summary:


// Reads asynchronously from the buffered stream.


//


// Parameters:


// type:


// The type of the object to deserialize.


//


// readStream:


// The stream from which to read.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// formatterLogger:


// The System.Net.Http.Formatting.IFormatterLogger to log events to.


//


// Returns:


// A task object representing the asynchronous operation.


public
override
sealed
Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger);


//


// Summary:


// Writes synchronously to the buffered stream.


//


// Parameters:


// type:


// The type of the object to serialize.


//


// value:


// The object value to write. Can be null.


//


// writeStream:


// The stream to which to write.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


public
virtual
void WriteToStream(Type type, object value, Stream writeStream, HttpContent content);


//


// Summary:


// Writes asynchronously to the buffered stream.


//


// Parameters:


// type:


// The type of the object to serialize.


//


// value:


// The object value to write. It may be null.


//


// writeStream:


// The stream to which to write.


//


// content:


// The System.Net.Http.HttpContent, if available. Can be null.


//


// transportContext:


// The transport context.


//


// Returns:


// A task object representing the asynchronous operation.


public
override
sealed
Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext);

}

 

When we derive our custom formatter class from BufferedMediaTypeFormatter class we have to override following methods.

 

public
override
bool CanWriteType(Type type)

 

public
override
void WriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.HttpContent content)

 

We can put some logic inside CanWriteType method that checks the type and return true or false. If the resultant value is true the framework calls WriteToStream method otherwise the WriteToStream method won’t be called.

Here is the complete code of custom formatter.


public
class
PsvFormatter : BufferedMediaTypeFormatter

{


public PsvFormatter()

{

SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“text/pipe”));

 

}


public
override
bool CanWriteType(Type type)

{


if (type == typeof(Session))

{


return
true;

}


return
false;

}

 


public
override
void WriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.HttpContent content)

{


using (var writer = new
StreamWriter(stream))

{

 


var singleSession = value as
Session;


if (singleSession == null)

{


throw
new
InvalidOperationException(“Cannot serialize type”);

}

WriteItem(singleSession, writer);

}

stream.Close();

 

}

 


private
void WriteItem(Session session, StreamWriter writer)

{

writer.WriteLine(“{0}|{1}|{2}|{3}”, session.Id,

session.SessionName, session.SessionDateTime, session.Place);

}

 

}

 

In the above code snippet, if you see the constructor I have added the Media type header value in the SupportedMediaTypes list which will be used to pass in the request header information. While invoking WEB API method you can pass text/pipe as ACCEPT header attribute.

In the CanWriteType method I am checking if the type of the object which I am returning is of type Session. In my code example I have a Session whose structure is as follows.

public
class
Session

{


public
int Id { set; get; }


public
string SessionName { set; get; }


public
DateTime SessionDateTime { set; get; }


public
string Place { set; get; }

}

 

In the WriteToStream method I am using the stream writer and writing the object as pipe separated string.

Now in the DataController which is the Web API controller, I have a Get method which fetches the session object from database. After fetching the session object from database, web API framework calls CanWriteType and WriteToStream method and parse the object into Pipe separted string and send that string as the response.

public
class
DataController : ApiController

{


public
Session Get()

{


return repository.All<Session>().Where(i => i.Id == 3).First();

}

}

Using fiddler, I made a request to my data controller and passed text/pipe as ACCEPT attribute this tells the framework that the return response should be text/pipe. Web API framework checks the formatter and uses my custom formatter to serialize the response in pipe separated string.


And the response is here


You can see how easy it is to implement custom formatter in ASP.Net WEB API and in the next series of article I will blog a post about handling custom content type requests in ASP.Net Web API

Hosted two Sessions on MS Dynamics CRM and ASP .NET Web API @ Microsoft

As a group leader of Microsoft Technology Practices User Group i.e. http://meetup.com/mstpug, organized two sessions this week at Microsoft Innovation Center, Karachi.

First Session: Customizing MS Dynamics CRM

Speaker: Asif Fattah

Linked In Profile: http://www.linkedin.com/pub/asif-fattah/20/69b/972

Session Duration : 1 hour

 

Second Session: Detailed Overview on ASP .NET Web API

Speaker: Me (Ovais Mehboob Ahmed Khan)

Linked In Profile: http://pk.linkedin.com/in/ovaismehboob/

Session Duration: 1 hour

 

It was both online and on-location event in which some of our group members have attended the event by visiting onsite and few joined online via Lync.

We are planning to organize more events in future and in order to get updates please join us and become a group member by following this link http://meetup.com/mstpug. Group members can get benefitted by monthly Plural Sight subscriptions depending on how active they participate. Also, the presentations and webcast of previous sessions are available on the user group website.

Few snaps:





At last, I would like to thank Microsoft for providing us space and services to organize our events.

Production deployment Issues when ASP.Net Web Application access COM+ component

Earlier last month we developed one project in which we had to use Office Excel COM+ component to save documents into .mht formats after manipulating them which finally displays on the browser window. It was the web application and everything was running fine at the development machine.

SYMPTOMS

The project got approved and when we deployed on the production server we came across several exceptions pertaining of accessing Office COM component on server.

Event ID: 10016

Event Source: DCOM

Description: The application permission settings do not grant Local Launch permission for the COM Server application This security permission can be modified using the Component Services administrative tool.

CAUSE

User does not have required permission to start COM component.

RESOLUTION

I tried searching on google and then find this useful link which solves my problem i.e. http://support.microsoft.com/kb/899965

Below steps taken from the above URL

Grant the user permissions to start the COM component

Grant the user permissions to start the COM component. To do this, follow these steps:

  • Click Start, click Run, type regedit in the Open box, and then click OK.
  • Locate and then click the following registry subkey:

    HKEY_CLASSES_ROOT\CLSID\CLSID value

    Note In this subkey, “CLSID value” is a placeholder for the CLSID information that appears in the message.

  • In the right pane, double-click AppID.

    The Edit String dialog box appears. Leave this dialog box open and continue to the next step.

  • Click Start, click Run, type dcomcnfg in the Open box, and then click OK.

    If a Windows Security Alert message prompts you to keep blocking the Microsoft Management Console program, click to unblock the program.

  • In Component Services, double-click Component Services, double-click Computers, double-click My Computer, and then click DCOM Config.
  • In the details pane, locate the program by using the friendly name.

    If the AppGUID identifier is listed instead of the friendly name, locate the program by using this identifier.

  • Right-click the program, and then click Properties.
  • Click the Security tab.
  • In the Launch and Activation Permissions area, click Customize, and then click Edit.
  • Click Add, type the user’s account name, and then click OK.
  • While the user is selected, click to select the Allow check boxes for the following items:
    • Local Launch
    • Remote Launch
    • Local Activation
    • Remote Activation
  • Click OK two times.
  • Quit Registry Editor.

Grant the correct permissions to the Network Service account

To grant the correct permissions to the Network Service account, follow these steps:

  • Click Start, click Run, type dcomcnfg in the Open box, and then click OK.
  • In Component Services, double-click Component Services, and then double-click Computers.
  • Right-click My Computer, and then click Properties.
  • Click the COM Security tab.
  • In the Launch and Activation Permissions area, click Edit Default.
  • Click Add, type Network Service, and then click OK.
  • While Network Service is selected, click to select the Allow check boxes for the following items:
    • Local Launch
    • Remote Launch
    • Local Activation
    • Remote Activation

    Click OK two times.

After this, I tested the application deployed on production and it works. Few days later client reported that I am unable to view documents on my browser and sometimes it work sometimes not. She was using IE 10. Initially I was thinking that maybe it’s due to IE 10 as the application is running smoothly at my end and I had IE 9. But later on when I debugged the error I came to know that it’s again related to some security permissions of COM component.

Exception:
Sys.WebForms.PageRequestManagerServerErrorException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a The server process could not be started because the configured identity is incorrect. Check the username and password. (Exception from HRESULT: 0x8000401A).

After doing some search, I found the resolution which fixed my problem. Following are the symptoms, cause and resolution taken from http://support.microsoft.com/kb/305761

SYMPTOMS

This error occurs when no user is interactively login to the server and if you start COM+ from remote client or terminal the application fails.

Actually I used to connect to my server hosted in US through VPN connection. And the reason it worked sometimes was that I already logged in interactively to the server. And when I’m not, client faced error.

CAUSE

This problem occurs because the default identity is set as Interactive user.

RESOLUTION

In order to resolve this problem I changed the Excel Application identity account from Interactive to local Administrator account.

Steps

  1. Open Component Services
  2. Select COM+ component (in my case it was Excel Application) and click Properties
  3. Go to Identity tab
  4. Select Custom Account
    1. Specify Username and password that have permissions to start the COM+ component.

Hence, this solved my problem.

 

Bridging data between ASP.Net and Silverlight

A task comes up to me in which I have to develop a private chat application for some product. I did some research on the XMPP protocol used by Facebook, Google etc. XMPP is a powerful protocol for public chat applications where thousands of users connect with each other. It has a separate XMPP server which listens to request and respond on it. There are also bunch of free XMPP servers available in the market.

Our goal is to provide a private chat where mid amount of users coordinate with particular resources time to time and the message format is not just simple like normal chat applications. We need to pass some advanced set of information to the recipient depending on which chat mode he has chosen. Then I chose WCF Duplex messaging where I can put all the business logic and intercept messages easily.

In order to make a chat application just like Facebook which have panel on the right and load chat popups that remains on the page I have to used Silverlight and ASP.Net and provide a special bridging between them. The reason of using Silverlight is that the ASP.Net doesn’t work with WCF Duplex Messaging because the framework of ASP.Net is request/response, whereas the Silverlight client is downloaded at client side and on each connection with WCF Service, service can send data back to client using default port 80.

I will not share how WCF Duplex messaging works, as I already published one article before on that but I will highlight the scenarios that can be implemented using very easy and simple code snippet provided to accomplish a bridging between ASP.Net and Silverlight.

Calling JavaScript function from Silverlight

string username = “Ovais”;

HtmlPage.Window.Invoke(“JSFunction”, username);

    

JSFunction is the javascript function implemented on the page where the Silverlight control is hosted. You can also pass the complete class object using Invoke method but that class object should be annotated by [ScriptableType()]attribute

[ScriptableType()]

public
class
ChatInfo

{

public
string UserName { get; set; }

public
int UserType {get; set; }

}

 

ChatInfo cInfo = new
ChatInfo() { UserName = “Ovais”, UserType = 1 };

HtmlPage.Window.Invoke(“JSFunction”, cInfo);

 

Getting Data in Silverlight from ASP.Net

In Silverlight you can read the HTML DOM using HTMLPage.Document object

HtmlPage.Document.GetElementById(“hiddenField1”).GetAttribute(“value”).ToString();

 

Using above two scenarios I succeeded passing data between both.

 

Happy coding!

 

Basic Introduction about T4 Templates & How to customize them for ASP.NET MVC Project

In ASP.Net MVC 3 you can easily generate views from predefined scaffolding templates provided for Create, Edit, List, Delete and Details views out of the box which seems quite riveting. Actually, there are some *.tt template files (known as T4 templates) stored at following path C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web that contains the basic structure and page layout for these views and based on those templates it generates the Create, Edit, Delete, List, Details and Empty .cshtml or .aspx files depends on which project language you have chosen for ASP.Net MVC project.

In this post I will discuss about T4 templates and how we can customize by taking a simple example.

What is T4

T4 stands for Text Template Transformation Toolkit. T4 generates text based on Text based template files, Template is a combination of text and control logic that you can define using C# or VB.net. Transformation actually executes the code written in template and brings out a final output whereas the Toolkit contains some assemblies leverage to produce the desire output file.

Now, let’s quickly open the sample Create.tt file to see what it looks like and how we can customize. When you open the file you can see directives

<#@ template language=”C#” HostSpecific=”True” #>

<#@ output extension=”.cshtml” #>

language specifies which language we are using either C# or VB.net and HostSpecific =”True” used only with custom hosts. If you set the value of parameter to true, you can access a property called Host in your text template. The property is a reference to the object that hosts the engine. At last, the output extension tells the extension in which the new file this will be generated.

T4 contains 4 types of blocks

  • Expression block

    Used as <#= expression #>, we can write C# or VB.net code but don’t use semi-colon at the end of statement

  • Statement block

    Used as <# code…. #>, define any C# or VB.net code and initialize variables, define loops etc. Here we have to specify semi-colon at the end of the code statement just like as we program in a class file.

  • Class feature block

    Used as <#+ code… #>, define methods, classes, properties and constants and can we called from anywhere within the template file. For example, we can create a function that perform some calculation based on the parameters passed and return a Boolean through which we can handle the UI designing.

Below is the actual page content that dynamically generates the page based on the model attached to it.

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

<legend><#= mvcHost.ViewDataType.Name #></legend>

<#

foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {

if (!property.IsPrimaryKey && !property.IsReadOnly && property.Scaffold) {

#>

<div class=”editor-label”>

<#

if (property.IsForeignKey) {

#>

@Html.LabelFor(model => model.<#= property.Name #>, “<#= property.AssociationName #>”)

<#

} else {

#>

@Html.LabelFor(model => model.<#= property.Name #>)

<#

}

#>

</div>

<div class=”editor-field”>

<#

if (property.IsForeignKey) {

#>

@Html.DropDownList(“<#= property.Name #>”, String.Empty)

<#

} else {

#>

@Html.EditorFor(model => model.<#= property.Name #>)

<#

}

#>

@Html.ValidationMessageFor(model => model.<#= property.Name #>)

</div>

<#

}

}

#>

<p>

<input type=”submit” value=”Create” />

</p>

</fieldset>

}

<div>

@Html.ActionLink(“Back to List of Main Page”, “Index”)

</div>

In the above mentioned code there is if statement that checks whether the property is a foreign key or not and based on that it generates a drop down code otherwise an input control.

Let’s create a sample application in ASP.Net MVC 3 and check it out by customizing a Create T4 template.

  1. Create a sample project in ASP.Net MVC3 in Visual Studio.
  2. Create a model class for Person and Designation. Person record contains some basic information and Designation holds the list of designations. Below is the Code First model Approach using Entity Framework ver. 4.3.1.


    public
    class
    Person    

    {


    public
    long PersonId { set; get; }


    public
    String FirstName { set; get; }


    public
    String LastName { set; get; }


    public
    String EmailAddress { set; get; }


    public
    String Phone { set; get; }


    public
    long DesignationId { set; get; }


    public
    virtual
    Designation Designation { set; get; }

    }


    public
    class
    Designation

    {


    public
    long DesignationId { set; get; }


    public
    String DesignationName { set; get; }


    public
    virtual
    ICollection<Person> Persons { get; set; }

    }

  3. Create a DBContext class and define DBSet for these entities.

public
class
DBContext : System.Data.Entity.DbContext, IDisposable

{


public
DbSet<Person> Persons { get; set; }


public
DbSet<Designation> Designations { set; get; }

}

  1. Now create a Person controller selecting Controller with read/write actions and select Person as a Model class and DB Context as you Database Context class.

  1. Now if you open the Create.cshtml file you will see a drop down list for designation. As in the template file there was a foreign key check. If you run the application form will be shown as below.

  1. Now let’s change a drop down to list box in the Create.tt file.

    <div class=”editor-field”>

    <#

    if (property.IsForeignKey) {

    #>


    @Html.ListBox(“<#= property.Name #>”)

    <#

    } else {

    #>

    Is not a foreign key baba: <#= property.IsForeignKey #> : @Html.EditorFor(model => model.<#= property.Name #>)

    <#

    }

    #>

    @Html.ValidationMessageFor(model => model.<#= property.Name #>)

    </div>

  1. Delete the previous controller and generate it again. It will generate a ListBox as specified in a tt file.

This was the simple example showing how developers can modify existing templates based on their needs and reduce development time. Hope this helps!

Develop and Consume OData Web Services in WCF

What is OData?

OData is an Open Data Protocol used to access data from various sources like Relational databases, file systems, etc. and exposes it to the consumers that can query or update data. OData is based upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from variety of data sources. Consumers can query the data using HTTP protocol and get the results in AtomPub and JSON formats. These are the formats through which the service can deliver the requested resources or collection of entities.

OData is released under the Open Specification Promise http://www.microsoft.com/openspecifications/en/us/programs/osp/default.aspx and anyone can freely interoperate with OData implementations.

Developing WCF Service using OData Protocol

Microsoft has first introduced OData support in Visual Studio 2008 SP1 in terms of ADO.Net Data Services (subsequently known as WCF Data Services). Developers can create services on the fly and exposes data using Entity Framework or LINQ 2 SQL ORM tools.

Let’s create a simple WCF Data Service and expose data using Entity Framework.

  1. Start Visual Studio 2010 and create a new WCF Service Application project.


  1. Right click the WCF Service Application project and click on the “Add New Item”, then select WCF Data Service.


  2. If you open the WCF Data Service class file you can see the Class will be derived from the generic DataService class. This is the main entry point for developing WCF Data services. We have to specify the data source class name. In order to proceed further I will add entity framework model which creates the entities model on the fly.
  3. Right click on the Service Project and Add “ADO.Net Entity Data Model” from the dialog.


    When you add ADO.Net Entity Model it will ask you to select the data source, go through the wizard by selecting the data source and finish a dialog.

  4. Now open the .edmx file click on properties.


    Here’s the entity container named as “DDMSEntities”. Just specify the name DDMSEntities in your WCF Data Service base class like below

public class WcfDataService1 : DataService<DDMSEntities>

  1. You can now add the SetEntitySetAccessRule for each entity you want to expose. Default configuration is to deny access to resources. When a service is initialized the access rights must be enabled.

    Sample code snippet below


public static void InitializeService(DataServiceConfiguration config)
{

// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

config.SetEntitySetAccessRule (“Levels”, EntitySetRights.AllRead);

config.SetEntitySetAccessRule (“NodeTypes”, EntitySetRights.All);

}

In Above code, I have added two tables i.e. Levels and NodeTypes and given permissions as AllRead. There are many permission levels you can set as follows. Below are the enums of EntitySetRights with their description

  • All – Authorize to create, read, update and delete data.
  • AllRead- Authorize to read data.
  • AllWrite- Authorize to write data.
  • None- Denies all rights to access data.
  • ReadMultiple – Authorize to read sets of data.
  • ReadSingle – Authorize to read single data of items.
  • WriteAppend- Authorize to create new data items in the data sets.
  • WriteDelete –Authorize to delete data items from the data sets.
  • WriteMerge – Authorize to merge data.
  • WriteReplace – Authorize to replace data.
  1. Now let’s build a service and test it. Once you hit the web service in a browser, you will see the page as below


    The above feed representing the data as per Atom Syndication format. There are two entity collections namely “Levels” and “NodeTypes”.

                                      http://localhost:32555/WcfDataService1.svc/Levels?filter= LevelTree gt

                                     “gt” is used for greater than where as “lt” is used for less than.

Consuming WCF Data Service in Web Application

  1. Create a new Web Application project in Visual Studio
  2. Add a service reference by right clicking on Add Service Reference and select the newly service created.


  3. Add a button to call the service on its click event.
  4. On the click event you can consume the service like below

Services.DMSEntities.DDMSEntities entities = new Services.DMSEntities.DDMSEntities(new
Uri(http://localhost:32555/WcfDataService1.svc&#8221;));

var lst = entities.Levels.FirstOrDefault();

This will return the first item in the collection. You can execute all CRUD operations depending on the rule set in the Service for that entity.

Hope this helps, happy coding!

Problem loading ASP.Net project after installing VS 2010 SP1

Sometimes developer faces this problem on loading existing web projects that were hosted on local IIS server and using the same port number that has been used by the IIS Express for particular websites. IIS Express installed by default when you apply the SP1 for Visual Studio 2010.

In my case, I installed VS 2010 SP1 to install Silverlight 5 Tools for VS 2010 and when opened my existing web project which was earlier hosted on my Local IIS server using the same port no i.e. 8080, came across this error.

In order to rectify, the simplest way is to change the port no in the applicationhost.config file placed under [Win_Drive]:\Users\[User]\Documents\IISExpress\config folder. When open the applicationhost.config file you will find the <bindings> tag under <site> tag followed with the port no.

Change the port no and don’t forget to save the file. Now try reloading the project and it opens without any issue.