A day with .Net

My day to day experince in .net

Archive for the ‘AJAX’ Category

SignalR in Web Farm or Web Garden Enviornment

Posted by vivekcek on May 23, 2016

I was trying to use SignalR 2 for one of my project and successfully implemented a progress bar using it.
Everything was working fine in our test server also. But fortunately i tested this SignalR 2 based progress bar in Web-garden mode of IIS,
Woww surprised nothing is working. Thanks God, because our production servers are load balanced Web Farm.

Any way found solution in Microsoft documentation. I will discuss that below.

Hope you have an understanding of SignalR.

1. Create an MVC 5 app.

2. Add Nuget package for SignalR.

Install-Package Microsoft.AspNet.SignalR

3.Now Paste the below code in your cshtml.

<input type="button" value="Submit" id="btnSubmit" />
<input type="hidden" id="connectionid" />

<div id="uploadModal"></div>

@section scripts
{
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript">

        $(document).ready(function() {
            var con = $.connection.uploaderHub;
            $.connection.hub.start().done(function() {
                $("#connectionid").val($.connection.hub.id);

            }).fail(function(e) {
                alert('There was an error');
                console.error(e);
            });
            con.client.print = function() {
                $("#uploadModal").append("Vivek");
            };

            $("#btnSubmit").click(function() {

                var connectionid = $("#connectionid").val();
                var url = '@Url.Action("Test", "Home")';
                url = url + '?connectionid=' + connectionid;
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function(messages) {

                    },
                    error: function() {

                    }
                });

            });

        });
    </script>
}

4. Now create an action in your controller.

        [HttpPost]
        public ActionResult Test(string connectionid)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<UploaderHub>();
            hubContext.Clients.Client(connectionid).print();
            return Json(new { Success = "True" });
        }

5. Create a SignalR hub.

using Microsoft.AspNet.SignalR;

namespace SignalR.Controllers
{
    public  class UploaderHub:Hub
    {

    }
}

6. In your OWIN Startup.cs add the code below.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Deploy this to IIS and click submit button, Which will print the text defined in client side print method.

Now increase the worker process count in your application pool to 5, Also set processor affinity true.
Try the same after some refresh, You will found the messaging is not working.

1

To Solve this you can use another SignalR package for SQL Server

Install-Package Microsoft.AspNet.SignalR.SqlServer -Version 2.2.0

Then update your OWIN Startup.cs add this.

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            string sqlConnectionString = "Connecton string to your SQL DB";
            GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Which will create some tables, in the database you specified in your connection string.
And now debug…

Posted in AJAX, MVC, SignalR | Tagged: , , , | 2 Comments »

Error handling Ajax and MVC 4

Posted by vivekcek on May 27, 2013

Write a script

function handleError(ajaxContext) {
    alert(ajaxContext.status+" "+ajaxContext.statusText);
}

Now use the OnFailure property to point to error handling function

@using (
    Ajax.BeginForm("Index", "Home", new AjaxOptions
    {
        
        UpdateTargetId = "MovieTable",
        OnFailure = "handleError"
    }))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}

Posted in AJAX, MVC | Leave a Comment »

Partial Page Rendering MVC 4

Posted by vivekcek on May 27, 2013

1. Create a model

public class Movie
    {
        private string _title;

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
    }

2. Implement the home controllers Index action as given below.

public class HomeController : Controller
    {
             
        
        public ActionResult Index(string query)
        {
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            };
           
            var movies=Movies.Where(x=>x.ReleaseYear==(Convert.ToInt32(query))||query==null).ToList();
            if (Request.IsAjaxRequest())
            {
                return PartialView("_Movie", movies);
            }
            return View(movies);
        }
              
    }

3. Update the Razor of Index.cshtml as

@model IEnumerable<Learan.Models.Movie>
<h3>
    Move Search By year</h3>
@using (
    Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "MovieTable" }))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}
<div id="MovieTable">
    @Html.Partial("_Movie", Model)
</div>

4. Create the partial view _Movie.cshtml

@model IEnumerable<Learan.Models.Movie>

<p>
   Movie List
</p>
<table>
    <tr>
        <th>Title</th>
        <th>Year</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.Encode(item.Title)
        </td>
         <td>
            @Html.Encode(item.ReleaseYear)
        </td>
    </tr>
}

</table>

Posted in AJAX, MVC | Leave a Comment »

Update Progress in MVC 4

Posted by vivekcek on May 27, 2013

The below code is used for showing a progress bar when an ajax link is clicked. The ‘LoadingElementId’ attribute of AjaxOptions can be used to specify a progress div.

<div id="timeDiv">
@Ajax.ActionLink("Click to get Server time", "GetServerTime", new AjaxOptions
{
    LoadingElementId = "Progress",
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "timeDiv"
})
</div>

<div id="Progress" style="display:none">
    <img src="../../Content/spinner.gif" alt="IMG" />
</div>

Posted in AJAX, MVC | Leave a Comment »

Ajax in MVC 4

Posted by vivekcek on May 27, 2013

In MVC 4 the ajax related functions are included in a JS file named ‘jquery.unobtrusive-ajax.js’. So to include this file in our view’s, follow the below steps.

1. In BundleConfig.cs register our script bundle by adding the below code after all defult bundle registrations.

 bundles.Add(new ScriptBundle("~/bundles/Custom").Include(
                 "~/Scripts/jquery.unobtrusive-ajax.js"));

2. Now at the bottom of your master page _Layout.cshtml, add the below code.

@Scripts.Render("~/bundles/Custom");

3. Now in your Home View add this code.

<div id="timeDiv">
@Ajax.ActionLink("Click to get Server time", "GetServerTime", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "timeDiv"
})
</div>

4. In home controller.

 public class HomeController : Controller
    {
        public string GetServerTime()
        {
            return DateTime.Now.ToLongDateString();
        }
    }

Posted in AJAX, MVC | Leave a Comment »

XMLHttpRequest get server time

Posted by vivekcek on May 27, 2013

In your HTML put an anchor tag and div as given below.

<a href="#" id="timeLink">Click Get Time</a> 
<div id="timeDiv"></div>

Then in a script file add the below script and refer it in your page.

window.onload = function () {
    var link = document.getElementById("timeLink");
    link.onclick = getServerTime;
}

function getServerTime() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/Home/GetServerTime");
    xhr.onreadystatechange = function () {

        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                var timeDiv = document.getElementById('timeDiv');
                timeDiv.innerHTML = xhr.responseText;
                
            }
        }

    }
    xhr.send();

}

Posted in AJAX, MVC | Leave a Comment »