Tuesday 27 September 2016

Login with facebook

Here in This Article I am going to explain you how to implement Login with facebook in your website. first of all you need to create a new App in facebook developers. https://developers.facebook.com/apps/

1- Click On Add a New App button. a pop window will be open.
2- Select WWW (Website) Link.

3- Provide App Name and click on "Create New Facebook AppID" Button.

4- In the Opened pop window, Provide Display Name, Contact EmailId and Category.
     For Category Choose "Apps for Pages" option
Then Click on Create App ID button.



5-  Continue with Security Check window. Now, your app hes been created. you need to do some setting now.
6- Open the facebook apps home Page. https://developers.facebook.com/apps/
     You will see your App "socialLogin" in the list.


7- Click on your app. it'll redirect you on the new Page.


Now you have App ID and App Secret Key.

8- In the Settings menu on the left side, You can set other information's like Site Url, App logo and others.

9- Now, Go to Roles -> Test Users Option.
     Click On Add button to add a Test User.


A popup will be open. Just Click on Create Test Users button. 
A Test User will be created. see the below Image.


10- Now, Come to App Review Section.


Select the radio button to Yes. Now your App is Live to use.

11- Now, Come to Dashboard Basic Settings option. see the below.


Click On Quick Start button. it'll redirect you to the new page.
On the new Page Under Site Url Section you will see Next button. Click on the Next button. 
 A new section will be open. just Click On Login Option in that section. it'll open a new window again.

you don't need to follow the above red colored steps.


12- Copy the entire Html Code from Full Code Example Section. Create a new Html file named index.html in your any directory. Paste the Code in newly created file.

Note: for detailed knowledge please go through the Url https://developers.facebook.com/docs/facebook-login/web/

13- Open the html file and Add the AppId generated from your App.


14- You Can Change graph Api version based on your requirements. I've used 2.7.


15- Now Save your Html File. 

Now it's time to run the html. but before this you need to host your html on IIS server.

So, goto inetmgr and add a new Website. Provide Html file path and port that you have provided in facebook app and Host name as "localhost". Click on Ok button.



now browse the website from IIS.

Click On Log In button. facebook login window will be open. provide your user name and password., and click on Login button. 


Click on Continue button.

You will see your Username from facebook. now you're logged in with facebook.

Download html file here

Take more help from below video





Continue Reading →

Monday 26 September 2016

Login With Google

Here in This Article I am going to explain you how to implement Login with Google in your website. first of all you need to create a new project in Google developers console. https://console.developers.google.com/



Select your existing project. if you haven't created then first of all Create a new Project.

Provide Project Name. I have provided "LoginWithGoogle". click on Create button.
Now Click on Credentials Link on Left Side Menu.
Click On OAuth consent screen Link and Fill the information. finally click on Save button.


It will Redirect you to the Credentials Page. 


Click on Create credentials Button. it'll open a menu. Click on OAuth client ID.



Click on Web application Radio button.



Fill the Information and Click on Create Button. It'll generate Client ID and Client Secret Key.


Finally Click On Save Button. 
Now You have Client ID and Secret Key for your Login with Google functionality.

Now come to your Visual Studio Project.
Create a new MVC Project.

In the Model Folder Create a new Model class.

  public class GoogleDataModel  
   {  
     public string Email_address { get; set; }  
     public string Google_ID { get; set; }  
     public string firstName { get; set; }  
     public string LastName { get; set; }  
     public string fullName { get; set; }  
     public string Client_ID { get; set; }  
     public string Return_url { get; set; }  
     public string userProfilePic { get; set; }  
     public string Gender { get; set; }  
   }  

In the Home Controller add the Client Key and Secret Key.

  public class HomeController : Controller  
   {  
     string clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  
     string clientSecret = "qL78qLvihhfgf9VWT189898fG9";  
     public ActionResult Index()  
     {  
       ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";  
       return View();  
     }  
     public ActionResult GetGoogleAccount()  
     {  
       return View();  
     }  
  ------
  ---------

In the Index View Add the Login Button and Some Javascript Code.

  <input type="button" id="Button1" value="Login With Google" onclick="OpenGoogleLoginPopup();" />  
  
 <script type="text/javascript" language="javascript">  
     var clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  

     function OpenGoogleLoginPopup() {  
       var url = "https://accounts.google.com/o/oauth2/auth?";  
       url += "scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&";  
       url += "state=%2Fprofile&"  
       url += "redirect_uri=http://localhost:53285/Home/GetGoogleAccount&"  
       url += "response_type=token&"  
       url += "client_id="+clientId;  
       window.location = url;  
     }  
   </script>   

Now, In the GetGoogleAccount View Add the Below Code.

 @{  
   ViewBag.Title = "GetGoogleAccount";  
 }  
 <script type="text/javascript">  
   try {  
     debugger;  
     // First of all, parse the querystring  
     var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;  
     while (m = regex.exec(queryString)) {  
       params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);  
     }  
     var ss = queryString.split("&")  
     if (ss != undefined) {  
       window.location = "About?" + ss[1];  
       history.pushState("", "", "About");  
     }  
     else  
       window.location = "About";  
   } catch (exp) {  
   }  
 </script>  

Now, In the About Action add the below Code.

  public ActionResult About()  
     {  
       GoogleDataModel model = new GoogleDataModel();  
       if (Request.QueryString["access_token"] != null)  
       {  
         string test = Request.QueryString["access_token"];  
       }  
       if (Request.QueryString["access_token"] != null)  
       {  
         String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();  
         WebClient webClient = new WebClient();  
         Stream stream = webClient.OpenRead(URI);  
         string b;  
         /*I have not used any JSON parser because I do not want to use any extra dll/3rd party dll*/  
         using (StreamReader br = new StreamReader(stream))  
         {  
           b = br.ReadToEnd();  
         }  
         b = b.Replace("id", "").Replace("email", "");  
         b = b.Replace("given_name", "");  
         b = b.Replace("family_name", "").Replace("link", "").Replace("picture", "");  
         b = b.Replace("gender", "").Replace("locale", "").Replace(":", "");  
         b = b.Replace("\"", "").Replace("name", "").Replace("{", "").Replace("}", "");  
         /*  
         "id": "109124950535374******"  
          "email": "usernamil@gmail.com"  
          "verified_email": true  
          "name": "firstname lastname"  
          "given_name": "firstname"  
          "family_name": "lastname"  
          "link": "https://plus.google.com/10912495053537********"  
          "picture": "https://lh3.googleusercontent.com/......./photo.jpg"  
          "gender": "male"  
          "locale": "en" }   
         */  
         Array ar = b.Split(",".ToCharArray());  
         for (int p = 0; p < ar.Length; p++)  
         {  
           ar.SetValue(ar.GetValue(p).ToString().Trim(), p);  
         }  
         model.Email_address = ar.GetValue(1).ToString();  
         model.Google_ID = ar.GetValue(0).ToString();  
         model.firstName = ar.GetValue(4).ToString();  
         model.LastName = ar.GetValue(5).ToString();  
         model.fullName = model.firstName + " " + model.LastName;  
         model.Gender = ar.GetValue(8).ToString();  
         model.userProfilePic = ar.GetValue(7).ToString();  
         model.userProfilePic = model.userProfilePic.Replace("https", "https:");  
       }  
       return View(model);  
     }  

Add the Code in About.cshtml

 @model LoginWithFbDemo.Models.GoogleDataModel  
 @{  
   ViewBag.Title = "About";  
 }  
   <div id="ClientDetails">  
   <br ><br >  
     @Html.TextBoxFor(x=> x.fullName)  
   @Html.TextBoxFor(x=> x.Email_address)  
   <img id="imgProfile" src="@Model.userProfilePic" style="width:auto"/><br >  
   </div>  

Now you're done. Run the Application.


 Click On Login With Google Button.


Provide the Email Id and Password. Click on Sign In Button.

It'll ask the Permission. Click on Allow button.


It will redirect you to the About Page. You will see your Name, Email Id and Profile Pic.

Continue Reading →

Wednesday 31 August 2016

Object Caching

Caching is the technique for storing frequently used data on the server to fulfill subsequent requests. there are a lots of way to store data in cache. Object Caching is one of them. Object Cache stores data in simple name/value pairs.

To Use this we need to use System.Runtime.Caching namespace. this is introduced in .Net 4.0. 
here I'm going to create a simple example to store data in Object Cache.

first, you need to add a reference of System.Runtime.Caching object in your project.


To add value in Cache, create a function like this

        public void SetCache(object value, string key)
        {
            ObjectCache cache = MemoryCache.Default;
            cache.Add(key, value, DateTime.Now.AddDays(1));
        }

In the above code, the first line is used to reference to the default MemoryCache instance. Using the new .NET Caching runtime, you can have multiple MemoryCaches inside a single application.

In the next line we are adding the object to the cache along with a key. The key allows us to retrieve this when you want.

To Get the Cache object you can create a new function like below

        public string GetCache(string key)
        {
            ObjectCache cache = MemoryCache.Default;
            return (string)cache[key];
        }

You can create the above function more reusable

        static readonly ObjectCache Cache = MemoryCache.Default;

        /// <summary>
        /// get cached data
        /// </summary>
        /// <typeparam name="T">Type of cached data</typeparam>
        /// <param name="key">Name of cached data</param>
        /// <returns>Cached data as type</returns>
        public static T Get<T>(string key) where T : class
        {
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }

I am attaching a little class, which you can easily use in your projects to use Caching.





Continue Reading →

Wednesday 3 August 2016

Calling WebApi from MVC layer

In this Project you will be able to learn how you can call Web Api functions from MVC Layer project.

Follow the Steps:

1- First Create a new MVC4 Project.
2- In the same solution add a Web Api Project.


3- In the API Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  

4- In the Values API Controller Replace this function to get Employee data.

   public class ValuesController : ApiController  
   {  
     // GET api/values  
     public IEnumerable<EmployeeModel> Get()  
     {  
       List<EmployeeModel> list = new List<EmployeeModel>();  
       for (int i = 0; i < 10; i++)  
       {  
         EmployeeModel emp = new EmployeeModel();  
         emp.EmpId = i;  
         emp.Name = "Emp" + i;  
         emp.Address = "Delhi" + i;  
         list.Add(emp);  
       }  
       return list;  
     }  
   }  

5- Now Run the Web Api Project.


6- Now come to your MVC Project. Add this key in Web.config file.
<add key="baseurl" value="http://localhost:6763" />

Above Key contains the base url of Web Api.

7- In the Home Controller,  Add the Below Code.

     string apiUrl = ConfigurationManager.AppSettings["baseurl"]+"/api/Values/";  
     HttpClient client;  
     public HomeController()  
     {  
       client = new HttpClient();  
       client.BaseAddress = new Uri(apiUrl);  
       client.DefaultRequestHeaders.Accept.Clear();  
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
     }  

The above Code is required for getting data from Web Api.

8- In the MVC Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  


9- Now we will write the Code to fetch data from Web Api. For this I am using Index Action method in Home Controller.

  //  
     // GET: /Home/  
     public async Task<ActionResult> Index()  
     {  
       List<EmployeeModel> emp = new List<EmployeeModel>();  
       HttpResponseMessage responseMessage = await client.GetAsync(apiUrl);  
       if (responseMessage.IsSuccessStatusCode)  
       {  
         var responseData = responseMessage.Content.ReadAsStringAsync().Result;  
         emp = JsonConvert.DeserializeObject<List<EmployeeModel>>(responseData);  
       }  
       return View(emp);  
     }  

10- Add/Replace Index View.

 @model IEnumerable<WebApiWithMVC.Models.EmployeeModel>  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 <p>  
   @Html.ActionLink("Create New", "Create")  
 </p>  
 <table>  
   <tr>  
     <th>  
       @Html.DisplayNameFor(model => model.EmpId)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Name)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Address)  
     </th>  
     <th></th>  
   </tr>  
 @foreach (var item in Model) {  
   <tr>  
     <td>  
       @Html.DisplayFor(modelItem => item.EmpId)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Name)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Address)  
     </td>  
   </tr>  
 }  
 </table>  

11- Now Debug your Mvc Project. But before running Mvc project make sure your Web Api is running.




12- Please do not forget to share with your techie friends. You can download the complete project here Download

Continue Reading →

Tuesday 5 July 2016

ASP.NET SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Examples include dashboards and monitoring applications, collaborative applications (such as simultaneous editing of documents), job progress updates, and real-time forms.

Now a days, Most of the web applications are multiuser application, where multiple users connected at the same time. But the problem is when any user does any changes (ex. insert a new record) other users doesn’t know it unless the request is initiated by the user for seeking the any updates.

So, we must have a way to notify all the connected clients if there is any changes happens on the server without a refresh or update the web page. This is the scenario in which asp.net SignalR comes.

Creating a push notification system with SignalR

Follow the below steps in order to implement "push notification system with SignalR in asp.net MVC".

Here In this Example, I am using Visual Studio 2012

Step-1: Create New Empty MVC Project.


Step-2: Add a SQL Server Database.

Create database SignalRDB;

Create table tblEmployee(
ID int Identity,
Name varchar(50) null

)

Step-3: Enable Service Broker on the database.

ALTER DATABASE SignalRDB SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

Step-4: Add Entity Data Model.

Go to Solution Explorer (Visual studio) > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.

A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Install SignalR NuGet Package.

Solution Explorer > Right Click on References > Manage NuGetPackages > Search for "SignalR"> Install > Close.

Or you can also install from package manager console.

Go to Tools (top menu) > Library Package  Manager > Open "Package Manager Console"
Type below command

PM> Install-Package Microsoft.AspNet.SignalR

Step-6: Add an Owin startup file. 

Add an Owin startup class in your application for enabling the SignalR in our application.
Add a new class in the project named "Startup.cs"

Write following code in Startup.cs file.

 
 using Microsoft.Owin;  
 using Owin;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 [assembly: OwinStartup(typeof(SignalRDemo.Startup))]  
 namespace SignalRDemo  
 {  
   public class Startup  
   {  
     public void Configuration(IAppBuilder app)  
     {  
       app.MapSignalR();  
     }  
   }  
 }  

Step-7: Add a SignalR hub class. 

Now, you need to create a SignalR Hub class, this makes possible to invoke the client side JavaScript method from the server side. In this application, we will use this for showing notification.
SignalR uses ‘Hub’ objects to communicate between the client and the server.
Add a new class named "NotificationHub.cs"

Enter the following contents into the file.

 using Microsoft.AspNet.SignalR;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace SignalRDemo  
 {  
   public class NotificationHub : Hub  
   {  
     //Nothing required here  
     //public void Hello()  
     //{  
     //  Clients.All.hello();  
     //}  
   }  
 }  

you can see above, the NotificationHub.cs class is empty. Left the class empty as we will use the class later from another place.

Step-8: Add connection string into the web.config file

Open the application root Web.config file and find the element. Add the following connection string to the element in the Web.config file.

  <add name="sqlConString" connectionString="data source=VL32-PC-SURAJ\SQLEXPRESS;initial catalog=SignalRDB;user id=sa;password=Test@123;" />  

Step-9: Add another class file for register notification for data changes in the database
In this class, you need to create a SQL dependency which allows your application to be notified when a data has changed in the database (Microsoft SQL Server).  Write the following in this class...

1. RegisterNotification- void method for register notification 
2. SqlDependency_OnChange- SqlDependency onchnage event, get fired when assigned SQL command produced a different 
3. GetContacts- This is a method for return the changes happened on the server, here our new inserted contact data 


using Microsoft.AspNet.SignalR;  
 using System;  
 using System.Collections.Generic;  
 using System.Configuration;  
 using System.Data.SqlClient;  
 using System.Linq;  
 using System.Web;  
 namespace SignalRDemo  
 {  
   public class NotificationComponent  
   {  
     //Here we will add a function for register notification (will add sql dependency)  
     public void RegisterNotification(DateTime currentTime)  
     {  
       string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;  
       string sqlCommand = @"SELECT [ID],[Name] from [dbo].[tblEmployee] where [AddedOn] > @AddedOn";  
       //you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency  
       using (SqlConnection con = new SqlConnection(conStr))  
       {  
         SqlCommand cmd = new SqlCommand(sqlCommand, con);  
         cmd.Parameters.AddWithValue("@AddedOn", currentTime);  
         if (con.State != System.Data.ConnectionState.Open)  
         {  
           con.Open();  
         }  
         cmd.Notification = null;  
         SqlDependency sqlDep = new SqlDependency(cmd);  
         sqlDep.OnChange += sqlDep_OnChange;  
         //we must have to execute the command here  
         using (SqlDataReader reader = cmd.ExecuteReader())  
         {  
           // nothing need to add here now  
         }  
       }  
     }  
     void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)  
     {  
       //or you can also check => if (e.Info == SqlNotificationInfo.Insert) , if you want notification only for inserted record  
       if (e.Type == SqlNotificationType.Change)  
       {  
         SqlDependency sqlDep = sender as SqlDependency;  
         sqlDep.OnChange -= sqlDep_OnChange;  
         //from here we will send notification message to client  
         var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();  
         notificationHub.Clients.All.notify("added");  
         //re-register notification  
         RegisterNotification(DateTime.Now);  
       }  
     }  
     public List<tblEmployee> GetData(DateTime afterDate)  
     {  
       using (SignalRDBEntities dc = new SignalRDBEntities())  
       {  
         return dc.tblEmployees.Where(a => a.AddedOn > afterDate).OrderByDescending(a => a.AddedOn).ToList();  
       }  
     }  
   }  
 }  

Step-10: Create an MVC Controller
Add a new Controller named "HomeController.cs"


Step-11: Add new action into your controller.

Here I have added "Index" Action into "Home" Controller.

       public ActionResult Index()
        {
            return View();

        }

Step-12: Add view for your Action named "Index.cshtml"

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<a target="_blank" href="Add/">Add Employe</a>

Step-13: Add another action in HomeController tofetch Employee data.

  public JsonResult GetNotifications()  
     {  
    var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;  
       NotificationComponent NC = new NotificationComponent();  
       var list = NC.GetData(notificationRegisterTime);  
       //update session here for get only new added contacts (notification)  
       Session["LastUpdate"] = DateTime.Now;  
       return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
     }  

Step-14: Add and update _Layout.cshtml for showing notification.

 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width, initial-scale=1.0">  
   <title>@ViewBag.Title - MY SignalR Demo</title>  
   <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
   <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
   <script src="~/Scripts/modernizr-2.6.2.js"></script>  
 </head>  
 <body>  
   <div class="navbar navbar-inverse navbar-fixed-top">  
     <div class="container">  
       <div class="navbar-header">   
           <span class="noti glyphicon glyphicon-bell"><span class="count">&nbsp;</span></span>  
           <div class="noti-content">  
             <div class="noti-top-arrow"></div>  
             <ul id="notiContent"></ul>  
           </div>  
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
         </button>  
         @Html.ActionLink("SignalR Demo", "Index", "Home", null, new { @class = "navbar-brand" })  
       </div>  
       <div class="navbar-collapse collapse">  
         <ul class="nav navbar-nav">  
         </ul>  
       </div>  
     </div>  
   </div>  
   <div class="container body-content">  
     @RenderBody()  
     <hr />  
     <footer>  
       <p>&copy; @DateTime.Now.Year - My SignalR Demo</p>  
     </footer>  
   </div>  
     @* Add Jquery Library *@  
     <script src="~/Scripts/jquery-2.2.3.min.js"></script>  
     <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>  
     <script src="/signalr/hubs"></script>  
     <script src="~/Scripts/bootstrap.min.js"></script>  
     @* Add css *@  
     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />    
   <style type="text/css">  
     /*Added css for design notification area, you can design by your self*/  
     /* COPY css content from youtube video description*/  
     .noti-content{  
       position:fixed;  
       right:100px;  
       background:#e5e5e5;  
       border-radius:4px;  
       top:47px;  
       width:250px;  
       display:none;  
       border: 1px solid #9E988B;  
     }  
     ul#notiContent{  
       max-height:200px;  
       overflow:auto;  
       padding:0px;  
       margin:0px;  
       padding-left:20px;  
     }  
       ul#notiContent li {  
         margin:3px;  
         padding:6px;  
         background:#fff;  
       }  
       .noti-top-arrow{  
         border-color:transparent;  
         border-bottom-color:#F5DEB3;  
         border-style:dashed dashed solid;  
         border-width: 0 8.5px 8.5px;  
         position:absolute;  
         right:32px;  
         top:-8px;  
       }  
       span.noti{  
         color:#FF2323;  
         margin:15px;  
         position:fixed;  
         right:100px;  
         font-size:18px;  
         cursor:pointer;  
       }  
       span.count{  
         position:relative;  
         top:-3px;  
       }  
   </style>   
     @* Add jquery code for Get Notification & setup signalr *@  
     <script type="text/javascript">  
       $(function () {  
         // Click on notification icon for show notification  
         $('span.noti').click(function (e) {  
           debugger;  
           e.stopPropagation();  
           $('.noti-content').show();  
           var count = 0;  
           count = parseInt($('span.count').html()) || 0;  
           //only load notification if not already loaded  
           if (count > 0) {  
             updateNotification();  
           }  
           $('span.count', this).html('&nbsp;');  
         })  
         // hide notifications  
         $('html').click(function () {  
           $('.noti-content').hide();  
         })  
         // update notification  
         function updateNotification() {  
           $('#notiContent').empty();  
           $('#notiContent').append($('<li>Loading...</li>'));  
           $.ajax({  
             type: 'GET',  
             url: '/home/GetNotifications',  
             success: function (response) {  
               debugger;  
               $('#notiContent').empty();  
               if (response.length == 0) {  
                 $('#notiContent').append($('<li>No data available</li>'));  
               }  
               $.each(response, function (index, value) {  
                 $('#notiContent').append($('<li>New contact : ' + value.Name + ' (' + value.ID + ') added</li>'));  
               });  
             },  
             error: function (error) {  
               console.log(error);  
             }  
           })  
         }  
         // update notification count  
         function updateNotificationCount() {  
           var count = 0;  
           count = parseInt($('span.count').html()) || 0;  
           count++;  
           $('span.count').html(count);  
         }  
         // signalr js code for start hub and send receive notification  
         var notificationHub = $.connection.notificationHub;  
         $.connection.hub.start().done(function () {  
           console.log('Notification hub started');  
         });  
         //signalr method for push server message to client  
         notificationHub.client.notify = function (message) {  
           if (message && message.toLowerCase() == "added") {  
             updateNotificationCount();  
           }  
         }  
       })  
     </script>  
 </body>  
 </html>  

Step-15: Update global.asax.cs to start, stop SQL dependency

 using System;  
 using System.Collections.Generic;  
 using System.Configuration;  
 using System.Data.SqlClient;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Http;  
 using System.Web.Mvc;  
 using System.Web.Routing;  
 namespace SignalRDemo  
 {  
   // Note: For instructions on enabling IIS6 or IIS7 classic mode,  
   // visit http://go.microsoft.com/?LinkId=9394801  
   public class MvcApplication : System.Web.HttpApplication  
   {  
     string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;  
     protected void Application_Start()  
     {  
       AreaRegistration.RegisterAllAreas();  
       // WebApiConfig.Register(GlobalConfiguration.Configuration);  
       // FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
       RouteConfig.RegisterRoutes(RouteTable.Routes);  
       //here in Application Start we will start Sql Dependency  
       SqlDependency.Start(con);  
     }  
     protected void Session_Start(object sender, EventArgs e)  
     {  
       NotificationComponent NC = new NotificationComponent();  
       var currentTime = DateTime.Now;  
       HttpContext.Current.Session["LastUpdated"] = currentTime;  
       NC.RegisterNotification(currentTime);  
     }  
     protected void Application_End()  
     {  
       //here we will stop Sql Dependency  
       SqlDependency.Stop(con);  
     }  
   }  
 }  


Step-16: Run Application.



Step-17: Now add a new Controller/Action To add Employee Data.

1- I have created AddController.cs in Controller directory.
2- Add action named "Index"

   public ActionResult Index()
        {
            return View();

        }

3- Create View for Index action to add Employee

 @model SignalRDemo.tblEmployee  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Add Employee</h2>  
 @using (Html.BeginForm()) {  
   @Html.ValidationSummary(true)  
   <fieldset>  
     <legend>Add Employee</legend>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Name)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Name)  
       @Html.ValidationMessageFor(model => model.Name)  
     </div>  
     <p>  
       <input type="submit" value="Create" />  
     </p>  
   </fieldset>  
 }  


4- Add Post action for Index and add code to insert Employee

     [HttpPost]  
     public ActionResult Index(tblEmployee model)  
     {  
       SignalRDBEntities entity = new SignalRDBEntities();  
       model.AddedOn = DateTime.Now;  
       entity.tblEmployees.Add(model);  
       entity.SaveChanges();  
       return View();  
     }   


Step-18: Run Application.

Click On Add Employee Link. it will open a new Page.


Type Name in textbox and click on Create button.it saves data in the table. Now go to first tab to see notification.



Click here to download this project Download

Like and share if you liked this post.

Thanks-
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives