Using Signalr with MVC to create simple chat application

In this tutorial I am going to talk about creating a simple chat application using signalr library with MVC. If we are trying to do a chat application or any asynchronous actions with client so we have a lot of work to do using ajax and javascript. Now with signalr it’s so simple and easy.

Step 1: Create an Empty Asp.Net MVC 3 Application

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application (Make sure it’s .Net Framework 4).

Step 2: Add SignalR Package

Right click on references and click Manage NuGet Packages. Search for SignalR and click install. Or use NuGet package manager concole and install the SignalR package using

Step 3: Add HomeController

Right click on Controllers folder and click Add –> Controller. Then add index view to index action result by right click on index action method –> add view.

Step 4: Create Signalr Hub

Create a class that derives from Hub

Step 5: Adding Client

Append javascript references to the head of the page as follows

As you can notice there is a /signalr/hubs file included but its not in the project because its dynamically generated file in run time

Append the following javascript

I added commented lines above each line to declare how it works.

Append the following Html to your page

And that’s it you can run the application now in multiple browsers and all magic starts

You can download a sample from here


Login via Twitter inside your application step by step

In this blog post i am going to explain how to login via twitter inside your web application step by step


  • Twitter uses OAuth to provide authorized access to its information and data which gives
    • Secure – Users are not required to share their passwords with 3rd party applications, increasing account security.
    • Standard – A wealth of client libraries and example code are compatible with Twitter’s OAuth implementation.


  1. Create twitter application in order to connect to twitter with
    1. Go to Create a new application in twitter
    2. After creation completed successfully twitter will redirected to the main application page the most important information is “Consumer key”,”Consumer secret”
  2. Create a new MVC application “if you have already existing application skip this step”.
  3. Open Application Web.config file and add to appSettings section the following
  4. Make sure that Authentication section is configured like that
  5. I’ve created three controllers “if you have already existing application just add the code in the appropriate place in your application”
    1. AuthController: To perform all authentication actions including normal login and login via twitter.
    2. HomeController: Landing page for the application with no Authentication
    3. AccountController:include pages that requires authorization
  6. At AuthController we will create all twitter login functionality
    1. First we need to create loginToTwitter() method which check if the current request is coming from twitter callback or its calling the authentication
    2. if user is authenticated we have to get AccessTokenForTheFirstTime
    3. if user request authorization so we have to redirect user to authorization page in twitter
    4. make sure that after Authorization you have to redirect user again using TwitterCallbackAddress that we specified before in web.config here i am redirecting the user to Auth/LoginWithTwitter action method
    5. then we link that action method with a button in our view
      Explanation: first the user will go to action method LoginWithTwitter for the first time with no “oauth_token”,”oauth_verifier” so user will redirected to twitter login page according to LoginToTwitter function then returns again to the same action method LoginWithTwitter according to the link we specifie in web.config but this time with “oauth_token” and “oauth_verifier” so user will be authenticated according to LoginToTwitter function through getting GetAccessToken function if user authenticated successfully Twitter API will return OAuthTokenResponse in this step we can set user as authenticated user and with getting user information from twitter using GetsTwitterUser function and redirect to AccountController
  7. At AccountController make sure that the controller is Authorized to allow only authorized users to see its content
  8. at Index page in Account use ViewBag To view user Twitter Screen Name

You can download the full sample from here



Understanding Lazy Loading , Eager Loading and Explicit Loading with Entity Framework Implementation

In this article we are going to understand and differentiate between Lazy Loading, Eager Loading and Explicit Loading, first of all let’s define what are those.

Lazy Loading :

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. In other words when objects are returned by a query, related objects are not loaded at the same time. Instead they are loaded automatically when the navigation property is accessed.

Eager Loading :

Eager loading is the opposite of Lazy loading which is : The process of loading a specific set of related objects along with the objects that were explicitly requested in the query.

Explicit Loading :

Explicit loading is defined as : when objects are returned by a query, related objects are not loaded at the same time. By default, they are not loaded until explicitly requested using the Load method on a navigation property.

Let’s try those three ways practically.

First create a project and use preferred tool to generate your DbContext , in my example I will use Northwind as a database , ADO.NET Entity Data Model and for class generator EF 4.x  DbContext Class Generator.

Add a MVC3 website project to your solution and start typing on HomeController the Index method :

start your SqlProfiler and notice in this case we have 4 queries which means calling the database 4 times , one for the categories and three times for the products associated to the categories

First query

[c].[CategoryID] AS [CategoryID],
[c].[CategoryName] AS [CategoryName],
[c].[Description] AS [Description],
[c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c]

Second query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=1

Third query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=2

Fourth query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=3

So in Lazy Loading pattern the Object comes with its associated/related Objects.

Now let’s turn off Lazy Loading and try Eager Loading in our example and notice what will happen. By default Lazy Loading is enabled in Entity Framework, so just add this line before our code and do the same process.

Notice in SqlProfiler that the query was just One , which means it ignored the Object related Objects

[c].[CategoryID] AS [CategoryID],
[c].[CategoryName] AS [CategoryName],
[c].[Description] AS [Description],
[c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c]

Now we are going to use  Include() method and notice what will happen. just change your code to be :

Notice in SqlProfiler that there is just one query looks like :

[Project1].[CategoryID] AS [CategoryID],
[Project1].[CategoryName] AS [CategoryName],
[Project1].[Description] AS [Description],
[Project1].[Picture] AS [Picture],
[Project1].[C1] AS [C1],
[Project1].[ProductID] AS [ProductID],
[Project1].[ProductName] AS [ProductName],
[Project1].[SupplierID] AS [SupplierID],
[Project1].[CategoryID1] AS [CategoryID1],
[Project1].[QuantityPerUnit] AS [QuantityPerUnit],
[Project1].[UnitPrice] AS [UnitPrice],
[Project1].[UnitsInStock] AS [UnitsInStock],
[Project1].[UnitsOnOrder] AS [UnitsOnOrder],
[Project1].[ReorderLevel] AS [ReorderLevel],
[Project1].[Discontinued] AS [Discontinued]
[Limit1].[CategoryID] AS [CategoryID],
[Limit1].[CategoryName] AS [CategoryName],
[Limit1].[Description] AS [Description],
[Limit1].[Picture] AS [Picture],
[Extent2].[ProductID] AS [ProductID],
[Extent2].[ProductName] AS [ProductName],
[Extent2].[SupplierID] AS [SupplierID],
[Extent2].[CategoryID] AS [CategoryID1],
[Extent2].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent2].[UnitPrice] AS [UnitPrice],
[Extent2].[UnitsInStock] AS [UnitsInStock],
[Extent2].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent2].[ReorderLevel] AS [ReorderLevel],
[Extent2].[Discontinued] AS [Discontinued],
FROM   (SELECT TOP (3) [c].[CategoryID] AS [CategoryID], [c].[CategoryName] AS [CategoryName], [c].[Description] AS [Description], [c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c] ) AS [Limit1]
LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Limit1].[CategoryID] = [Extent2].[CategoryID]
)  AS [Project1]
ORDER BY [Project1].[CategoryID] ASC, [Project1].[C1] ASC

This query shows the Object Category and its related Objects Projects in One query.

Finally we will try the Explicit Loading , just change your code to be like this :

Notice in SqlProfiler it looks like the Lazy Loading result , there are 4 queries to the database.

I hope you can differentiate between the three patterns.



Code Sample:


How to authenticate to FaceBook Graph Api – Part III

As I mentioned in the previous post we are going to complete how to connect to facebook graph Api programatically

  1. We are going to create a new web application and name it ConnectToFacebook
  2. In Default.aspx page we are going to but the login to facebook button and a label to show up the accesstoken after successfully login
  3. in code behind we implementing the code to connect to facebook
  4. we are going to explain the code we can begin with LoginToFacebook function
    we have to make sure that the user is authorized before getting access token if not so redirect user to authorize the application from facebook. After user authorize the application to access via facebook login page then facebook returned to the application via the return url which we specefied in the authorization url with code as a querystring

    so in page load i make a check on code querystring to make sure if the user loading the page after authorization or not if code querystring is exist so we can call GetAccessTokenFromRequest function,in this function we are going to connect to facebook by reading the stream of httpreqest to facebook and get accestoken and accesstoken time from the request.
  5. I usually store information about my api in web.config to be easy to change in the future if i want to do that, so i used

    to get facebook application id and application secret from web.config that keys which facebook generate after creating a new application as we described in a previous posts also there is scope users only grant your app access to their basic information. If you want to read additional data or write data to Facebook, you need to request additional permissions. In the various authentication flows, you should specify the additional permissions you require using the Scope parameter. so i put it in web.config to
  6. here is an example of web.config

    as we can see in the code sample I used HttpWebRequest and StreamReader to get data from facebook

You can download the sample from here ConnectToFacebook

Setup WordPress Using WebPlatform for Windows

1-    Go to website and click on install WordPress as in figure (1.0)

Figure (1.0)

2- Web Platform will open after click install to guide you throw setup steps as in figure (1.1)

Figure (1.1)

3- Web platform will ask you to download MySql on your machine or as a remote server as figure (1.2)
Figure (1.2)

4- Accept to download third party , application and components and Microsoft software to continue MySql install as figure(1.3)

Figure (1.3)

5- Next enter password for your database as in figure (1.4)

Figure (1.4)

6- Install MySql will start progress as  in figure (1.5)

Figure (1.5)


7- Next create new database or use existing one,note that database password can’t be empty as  in figure(1.6)


8- last step after downloading will congratulate you about download WordPress MySql and other products as in figure (1.7)

Figure (1.7)

9- Now you should have the Microsoft WebMatrix on your machine ready to use,open it and click on My Sites as  in figure (1.8)

Figure (1.8)

10- After click on My Sites click on WordPress and then OK button, will open a new window from there click on run you will find it at the top of your screen as  in figure(1.9)


11- Now WordPress will  Guide you through your Personal platform information(This Step will open on your browser as web page),Note that the Site Title field will be your blog name, After finish filling your information click on install WordPress button as  in figure(2.0)


12- Now you should see the success step and it’s ready to Login as  in figure(2.1)


13-  After Login it will guide you through your dashboard page, From there click on New then post to start your first blog post as  in figure(2.2)


14- In the add new post page there are many options helps you to start your first post, there is a field to write your post title and under it you can find an Upload/Insert link to help you insert audio or video on your post, on the right you can see three important buttons(save Draft.Preview and Publish) save Draft help you to save your post without publishing for all users online so you back edit or change it, preview help you to see your blog before publish, then if you click publish that means that your blog will be seen online for every one as in figure(2.3)


15- Now you can go to All Posts in you dashboard menu and you will find the posts you save to drafts or publish with info about its date and last modified if draft as  in figure(2.4)


This setup steps done using the following:

* Windows 7 Ultimate
* WordPress 3.3.1
* Web Platform 7.1.1070.1
* WebMatrix 7.1.1073.1

Html5 required attribute and CSS3 pseudo-classes (valid /invalid)

In Html5 there is an attribute called required it works as a validation when leave a required input empty for example:


Figure (1.0)

In this example if you click on submit Reservation the button will never do an action without filling the required input.
This required attribute returns true or false, CSS3 used this and created a pseudo class for valid and invalid required attribute.
For example:

In this example we can control the input style depend on the validation results if true (valid) the input background color will be green for the input that take the required attribute in html5 and if the result is false the CSS will fire the invalid styles rules .

Figure (1.1)

Figure 1.1 shows the styles when input required is invalid

Figure (1.2)

Figure 1.2 shows the styles when input required is valid

Html5 required and browsers Compatibility

The required attribute works in all major browsers, except Internet Explorer and Safari,But even so the required html5 popup style is different in every browser.

Figure (1.3)

Figure 1.3 shows the popup on Firefox

Figure (1.4)

Figure 1.4 shows the popup on Chrome

Figure (1.5)

Figure 1.5 shows the popup on Opera

Download Sample Page

How to authenticate to FaceBook Graph Api – Part II

As I mentioned in the previous post we are going to complete the basic information on how to authenticate Facebook Graph Api

In this post I will show you how to authenticate users via simple url requests without any programming language just to explain how are things going.
After creating Facebook Application as mentioned in the previous post you can request Facebook authentication dialog as following

When invoking Facebook login dialog, you must pass in your app id that is generated when you create your application that we mention before (the client_id parameter) and the URL that the user’s browser will be redirected back to once app authorization is completed (the redirect_uri parameter). The redirect_uri must be within the same domain as the Site URL you specify in Web site tab of the Developer App that we just mention before.

After invoking Facebook dialog, If the user is already logged in, Facebook validate the login cookie which stored on the user’s browser, authenticating the user. If the user is not logged in, they are prompted to enter their credentials:After user login you will see another facebook screen asks for Application access but this time its your applicationnotice again that your application requests to access just basic information of user . A full list of permissions is available in facebook permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions.
If the user presses Don’t Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with the following error information:


If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with an authorization code:


In order to authenticate your app, you must pass the authorization code and your app secret to the Facebook Graph API token endpoint at The app secret that we get from Facebook Application and should not be shared with anyone or embedded in any code that you will distribute.

If your app is successfully authenticated and the authorization code from the user is valid, the authorization server will return the access token:

Now you are successfully grant user and have the access token that is required for all the rest Facebook Graph Api needs to be continued ….

MongoDB Series – .Net Driver

In the previous posts we learned how to install MongoDB on windows platform, and then we learned how to manipulate with MongoDB. In this post we are going to learn how to deal with MongoDB but from a programming view. MongoDB supported many programming language and its driver, we are going through .Net driver as it’s one of the most popular frameworks.

Starting from the beginning, visit the downloading driver page in MongoDB official website

After downloading finished we will create a project – in our example will be web project. and added the references to it.

Our scenario will be creating a Blog example, so first we are going to add the connection to blog DB in the connectionString tag

Create the Mongo Helper class which responsible on connecting with the server.

now assume that our project has two domains Post and Comment , so simply we are going to create the two domains. let’s do it in Post

I’ll talk later specifically about the attribute but for now let’s do the simple domain.

The Service layer for the domain which will manage the CRUD functions, so create the PostService class as

The Create method simply creates new row by calling save, the Edit method gets a specific post by Query and updates its fields , the Delete method for delete a post and The GetPosts, GetPost methods for querying one post or all posts.

Download sample.



How to authenticate to FaceBook Graph Api – Part I

Facebook uses the OAuth 2.0 protocol for authentication and authorization. To begin use Facebook new Graph Api you have first to perform user authentication and authorization. As facebook mention in their documentation there are  two different OAuth 2.0 flows for user login: server-side (know as the authentication code flow in the specification) and client-side (known as the implicit flow). The server-side flow is used whenever you need to call the Graph API from your web server. The client-side flow is used when you need to make calls to the Graph API from a client, such as JavaScript running in a Web browser or from a native mobile or desktop app.
So, each OAuth flow (server-side or client-side) there are three different steps to pass

a- User authentication: ensures that the user is who they say they are
b- app authorization: ensures that the user knows exactly what data and capabilities they are providing to your app. Ex read permissions – write permissions – page permissions
c- app authentication: ensures that the user is giving their information to your app and not someone else

after completing this 3 steps your application is now granted user access token

To authenticate user and application authorization you have to redirect user to facebook OAuth Dialog.
First of all you have to create facebook application just by go to ,after login to facebook this page will appear to ensure that you want to allow Facebook Developer Application to access your data

If you notice that Facebook Developer Application asks for accessing you basic information. If you don’t allow the application, the application will forward you directly to nowhere because there is no redirect url. If you click on Allow then you will proceed to developer welcome page with some useful links that may help you in building applications

Let’s proceed to create your first Facebook Application just click on Create New App in the top right. You are just one step away from creating your first application by adding application name and continue, but before you continue there is two optional fields first is App Namespace that is an optional field for defining custom Open Graph actions and objects (e.g., namespace:action) and for the URL for Canvas apps used on Facebook (e.g.,

You have to enter security check pic 

And here is your First Facebook application 

Notice: you will use App Id and App Secret in your application to connect to Facebook.Also you have to define site url under web section you can  if you are working in localhost you can add site url as http://locahost:{port if exist}

Now you are ready to authenticate users by redirecting them to Facebook login page by any programming language to be continued ….

Lucene.Net – LINQ to Lucene using Entity Framework

What is Lucene ?

Lucene is an Information Retrieval System used for full-text searching and scoring results commonly referred to as a search engine (similar to google-type-searching).

Lucene.Net is a port of the Lucene search engine library, written in C# and targeted at .NET runtime users. The Lucene search library is based on an inverted index.

LINQ is Microsoft’s extensible Language Integrated Query platform that provides querying directly in a managed CLR. LINQ comes out of the box with LINQ to Objects, LINQ to DataSets, LINQ to XML, LINQ to SQL and LINQ to Entities. The goal of LINQ to Lucene is to provide developers with the ability to enjoy full-text searching using a fast-proven search-engine within the .Net managed CLR.

What is LINQ to Lucene?

CodePlex providing a custom LINQ solution for the Lucene Information Retrieval System, commonly referred to as a search-engine.

Since the format of Lucene, which stores its data in an Index as Documents with fields, the project will be capable of mapping custom business object types, a kind of Object-Index-Mapper (OIM) similar to the typical Object-Relational-Mapper (ORM) that LINQ to SQL provides. LINQ to Lucene uses attributes and reflection on classes to be indexed and their members, similar to the Table and Column decorators for SQL mapped objects. Types can easily support LINQ to SQL decorations for a larger number of members while co-supporting LINQ to Lucene decorations for the few members that support it. Classes stored in the lucene index are decorated with the [Document] attribute and its properties are decorated with the [Field] attribute. lets start practically.

Create Search Solution

Mainly there are two faces to a search solution , Indexing the data you wish to search on it, and actually searching the content.

First create a project and add the required references. We are going to use Lucene.Net.dll and Lucene.Linq.dll and finally the EntityFramework.dll.

Using Entity Framework capability “Reverse Engineer Code First” we are going to create our data context – we will use Northwind as a model , simply r-click on your project , choose Entity Framework , Reverse Engineer Code First , it will show a dialog to connect to your model database.

Entity Framework will do all the jobs for you to create all mapping and entity classes.

Now we got the NorthwindContext which represent the DbContext for the Northwind database. As we mentioned above we need to make IndexContext for the indexed data so we will create NorthwindIndexContext to manage our indexed data

Notice it must inherit from EfDatabaseIndexSet as we use Entity Framework DbContext. NorthwindIndexContext will hold all the entities that will be indexed and ready for search just like the NorthwindContext for the DbContext. Now we must specify the Entities that will be indexed, we will take the Customer entity as example.

As we mentioned above , to specify an entity for indexing you have to decorate the entity class by [Document] attribute , this attribute will tell Lucene that this entity is ready for indexing and searching. Other requirements is to Implement IIndexable Interface , INotifyPropertyChanging and INotifyPropertyChanged.

The next step is to specify fields that you would like to index.

The [Field] attribute is used for telling Lucene that field will be indexable and searchable, it has many parameters I will let you discover.

Back to the NorthwindIndexContext and add the property for the Customer entity

Now we are ready to write our program

In the previous code we specified the directory where Lucene will index the data in, instantiate the NorthwindIndexContext giving the path and the NorthwindContext , now we can index Customer entity by calling

The SimpleDemo method is an example for how to query from the indexed data , you will notice that it’s look similar to Linq and Entity querying.

There is a lot of features and solutions in Lucene you can discover it in the sample code.

Download sample