Sunday, June 17, 2018

SignalR

     SignalR Proejct.


SignalR Requirenment

1. Visual Studio 2013, 2015

2. Sql server 2008

1. Visual Studio, create a C# ASP.NET application that targets .NET Framework 4.5, name it SignalRChat, and click OK.


2.  In the “New ASP.NET” Project dialog, and select MVC, and click Change Authentication.


 Click OK in the New ASP.NET Project dialog.

3. Open the Tools | Library Package Manager | Package Manager Console and run the following command. This step adds to the project a set of script files and assembly references that enable SignalR functionality.
install-package Microsoft.AspNet.SignalR

 
4.  In Solution Explorer, expand the Scripts folder. Note that script libraries for SignalR have been added to the project.

5. In Solution Explorer, right-click the project, select Add | New Folder, and add a new folder named Hubs.

6. Right-click the Hubs folder, click Add | New Item, select the Visual C# | Web | SignalR node in the Installedpane, select SignalR Hub Class (v2) from the center pane, and create a new hub named autobind.cs. You will use this class as a SignalR server hub that sends messages to all clients.


7. code in the autobindhub class with the following code

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace signalr
{
    public class autobindhub : Hub
    {
        [HubMethodName("broadcastData")]
        public static void BroadcastData()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<autobindhub>();
            context.Clients.All.updatedData();
        }
    }
}

1.      8.Create a new class called Startup.cs. Change the contents of the file to the following.

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(signalr.Startup))]
namespace signalr
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
           
            app.MapSignalR();
                  }
               }
}


9 . Create a new class called SignalrContext.cs. Change the contents of the file to the following.
2.      Open the Tools | Library Package Manager | Package Manager Console and run the following command. This step adds to the project a set of script files and assembly references that enable EntityFramework functionality.
    
    Install-Package EntityFramework


1.   10. Change the contents of the file to the following.

using signalr.Models;
using System.Data.Entity;

namespace signalr
{
    public class SignalrContext : DbContext
    {
        public SignalrContext() : base("dbConnectionString")
        {
            Database.SetInitializer<SignalrContext>(new CreateDatabaseIfNotExists<SignalrContext>());
        }
       
    }

}
1.      dbConnectionString” is Connection string.

    11. Models Folder Create a model class “customer.cs” and copy following code

using System.ComponentModel.DataAnnotations; 
namespace signalr.Models
{
    public class customer
    {
        [Key]
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string surname { get; set; }
        public string address { get; set; }
        public string email { get; set; }
        public string gender { get; set; }

    }
} 











Then update class below code.


    


















  Create partial view “_CustomerList.cshtml” , put under share folder.
Copy below code and put in partialview.

@model IEnumerable<signalr.Models.customer>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.firstname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.lastname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.surname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.gender)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.lastname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.surname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.gender)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
            @Html.ActionLink("Details", "Details", new { id=item.id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id })
        </td>
    </tr>
} 
</table>
1.      Copy following code in index.cshtml

@model IList<signalr.Models.customer>
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Customer Form</h1>

</div>

<div class="row">
    <div class="col-md-8">
        <h2>Getting started</h2>
        <p>
            <div class="form-group">
                <label for="firstname">FirstName:<span style="color:red">*</span></label>
                <input type="text" class="form-control" id="firstname" placeholder="Enter FirstName" name="firstname">
              
            </div>
            <div class="form-group">
                <label for="lastname">LastName:<span style="color:red">*</span></label>
                <input type="text" class="form-control" id="lastname" placeholder="Enter LastName" name="lastname">
            </div>
            <div class="form-group">
                <label for="surname">Surname:<span style="color:red">*</span></label>
                <input type="text" class="form-control" id="surname" placeholder="Enter Surname" name="surname">
            </div>
            <div class="form-group">
                <label for="email">Email:<span style="color:red">*</span></label>
                <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
            </div>
            <div class="form-group">
                <label for="address">Address:<span style="color:red">*</span></label>
                <input type="text" class="form-control" id="address" placeholder="Enter Address" name="address">
            </div>
            <div class="form-group">
                <label for="gender">Gender:<span style="color:red">*</span></label>
                <div class="radio">
                    <label><input type="radio" name="radiooption" value="Male"> Male</label>
                    <br />
                    <label><input type="radio" name="radiooption" value="Female"> Female</label>
                </div>
            </div>
            <button type="submit" class="btn btn-default" onclick="InsertCustomer()">Submit</button>
        </p>

    </div>
    <div class="col-md-8">
      
        <div id="dataTable"></div>
    </div>
    <div class="col-md-8">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>
@section scripts{
    <script src="~/Scripts/jquery.signalR-2.2.3.min.js"></script>       
  @*<script src="/signalr/signalr/hubs" type="text/javascript"></script>*@
<script src="@Url.Content("~/signalr/hubs")"></script>
    <script type="text/javascript">  
        $(function () {
            // Create a proxy to signalr hub on web server. It reference the hub.
            var notificationFromHub = $.connection.autobindhub;
            debugger;
            // Connect to signalr hub
            $.connection.hub.start().done(function () {
                FetchCustomers();
            });
            // Notify to client with the recent updates
            notificationFromHub.client.updatedData = function () {
                FetchCustomers();
            };
        });
        function FetchCustomers() {
            var model = $('#dataTable');
            $.ajax({
                url: '/home/GetAllCustomerRecord',
                contentType: 'application/html ; charset:utf-8',
                type: 'GET',
                dataType: 'html'
            })
                .success(function (result) { model.empty().append(result); })
        }
        // Insert Employee Record
        function InsertCustomer() {
            var cm = {
                firstname: $('#firstname').val(),
                surname:$('#surname').val(),
                lastname: $('#lastname').val(),
                email: $('#email').val(),
                addreess: $('#address').val(),
                gender: 'male'
            };

            debugger;
            $.ajax({
                url: '/home/Insert',
                type: 'POST',
                data: JSON.stringify(cm),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    debugger;
                    alert('Customer added Successfully');
                },
                error: function () {
                    debugger;
                    alert('Customer not Added');
                }
            });
        }

        // Update Employee Record
        function UpdateEmployee() {
            var employee = {
                EmployeeID: $('#txtEmployeeId').val(),
                EmployeeName: $('#txtEmployeeName').val(),
                EmailAdress: $('#txtEmail').val(),
                MobileNumber: $('#txtMobile').val()
            };

            $.ajax({
                url: '/home/Update',
                type: 'POST',
                data: JSON.stringify(employee),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    alert('Employee updated Successfully');
                },
                error: function (e) {
                    alert('Employee could not be updated');
                }
            });
        }

        // Delete Employee Record
        function DeleteEmployee() {
            var employee = {
                EmployeeID: $('#txtEmployeeId').val()
            };

            $.ajax({
                url: '/home/Delete',
                type: 'POST',
                data: JSON.stringify(employee),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    alert('Employee deleted Successfully');
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }
        </script>
}

2.      Copy following code in homecontroller.cs

using signalr.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace signalr.Controllers
{
    public class HomeController : Controller
    {
        List<customer> cmList;

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        //Insert Employee Record
        public ActionResult Insert()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Insert(customer cm)
        {
            if (ModelState.IsValid)
            {
                //Insert into Employee table
                using (var context = new SignalrContext())
                {
                    context.customers.Add(cm);
                    context.SaveChanges();
                }
            }

            //Once the record is inserted , then notify all the subscribers (Clients)
            autobindhub.BroadcastData();
            return RedirectToAction("Index");
        }
        //Update Employee Record
        public ActionResult Update()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Update(customer cm)
        {
            using (var context = new SignalrContext())
            {
                var cmRecord = context.customers.Find(cm.id);

                cmRecord.firstname = cm.firstname;
                cmRecord.lastname = cm.lastname;
                cmRecord.email = cm.email;
                cmRecord.surname = cm.surname;
                cmRecord.gender = cm.gender;
                cmRecord.address = cm.address;


                context.customers.Add(cmRecord);

                context.Entry(cmRecord).State = EntityState.Modified;
                context.SaveChanges();
            }

            //Once the record is inserted , then notify all the subscribers (Clients)

            autobindhub.BroadcastData();
            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult Delete(customer cm)
        {
            using (var context = new SignalrContext())
            {
                var empRecord = context.customers.Find(cm.id);
                context.customers.Remove(empRecord);
                context.SaveChanges();
            }
            //Once the record is inserted , then notify all the subscribers (Clients)
            autobindhub.BroadcastData();
            return RedirectToAction("Index");
        }
        [HttpGet]
        public ActionResult GetAllCustomerRecord()
        {
            using (var context = new SignalrContext())
            {
                cmList = context.customers.ToList();
            }
            return PartialView("_CustomerList", cmList);
        }

    }
}


 At last Change properties of sql server database which you use.

No comments:

Post a Comment