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!