Showing posts with label Asynchronous. Show all posts
Showing posts with label Asynchronous. Show all posts

Sunday, December 22, 2013

Hello World with SignalR

[Original Post from my blog OnlyMS.Net for better visibility read it from OnlyMS.Net]  

Programming with distributed technology is my passion. Earlier I have worked with Remoting, Socket, Web Service and a bit with WCF. So when I first came to know about SignalR technolog, really I can not wait to start coding on it. Now I can able to write own chat application for AlapMe and really its working fine. Most of all by using SignalR I can use socket of HTML5. I shall write multiple posts on SignalR as tutorial as I did in past with C# Socket programming. I shall publish these posts on this blog and on my socket programming blog as well.

I have started SignalR programming with Visual Studio Express 2013 which is freely downloadable from here. Also you can read full documentation from Microsoft from this link. As my target to share some practical example with ready to use code hence I shall not describe in detail about the technology. You can follow Microsoft documentation website for it. 

To start with SignalR first coding you need to follow steps are below.
Lunch your VS 2013 and create a blank project and add new item of SignalR Hub Class (v2) set its name as you wish, for my case its MyHub.cs. When you will add this class Visual Studio automatically add all related references and jquery classes. To add these things it may take some time may be 2-3 minutes. This new item will come with a sample method 'Hello()', for now just follow these later I shall describe what is these things and why these are. Full code will look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalR_Learning
{
    public class MyHub : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}


Now go to next step and add next item in project, that is OWIN Startup class. I am giving its default name 'Startup1.cs' for my sample project. Visual Studio will create this file with some pre-added code. We will extend these code as per your needs. Code as below:

 

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR_Learning.Startup1))]
namespace SignalR_Learning
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }
}
 In method Configuration I shall add just a line of code 'app.MapSignalR();' so full method will look like:

 

public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
    app.MapSignalR();
}
 Now we will move to front end coding and this part will develop with simple HTML page, however you can use ASPX page as well. Now I have added a HTML page with name 'index.html'

  < me ta http-equiv="X-UA-Compatible" content="IE=edge" / >

    < ! --Script references. -->
    < ! --Reference the jQuery library. -->
    < s cript src="Scripts/jquery-1.10.2.js">< / scr ipt>
    < s cript src="Scripts/jquery-1.10.2.min.js">< / scr ipt>   
    < s cript src="Scripts/json2.js"></ scr ipt>
    < ! --Reference the SignalR library.  - - >
    < s cript src="Scripts/jquery.signalR-2.0.0.js">< / scr ipt>
    < s cript src="Scripts/jquery.signalR-2.0.0.min.js">< / scri pt>
    < ! --Reference the autogenerated SignalR hub script. - - >
    "/signalr/hubs">
    < ! --Add script to update the page and send messages.-- >

 < s cript type="text/java scri pt" >

        var chat;
        $(function () {
            // Declare a proxy to reference the hub.
            //chat = $.hubConnection.myhub;
            chat = $.connection.myhub;
            //alert(chat);
            chat.client.hello = function (message) {
                alert(message);
            };
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#btnhello').click(function () {                   
                    alert(chat);
                });
            });
        });
< / scr ipt> 
 < in put ty pe="button" value="Hello" id="btnhello" / >

 

 Thank you for visiting my blog.

 

Saturday, November 16, 2013

JQuery-AJAX: Change a HTML control name from server



I want to share a very basic and simple but a bit advance sample code on ASP.Net Ajax using JSON and JQuery. Now I want to change a control name or text based on server response data.

To demonstrate this thing I shall change my clicked button name based on server. This type of sample code is very easy to learn and you can use similar concept to develop solution for lots of requirement. Say you are developing some code where you have a button to 'Like' but after clicking on it the button  name will change to 'Unlike', or in a social network one user will start following some group or person; so when user will click on 'Follow' button will be changed to 'Following' etc.
Lets have a look in to the code:

HTML for this solution as below -
in put id="btnClick" type="button" value="Click Me!"

Here button 'btnClick' text will be changed. Next look into the back-end C# code.


[WebMethod]
public static string ChangeButtonNameJQuery(string btnName)
{     
      return btnName+ " - changed from Server";
}



Very simple Web Method or WebService in page 'ChangeButtonName.aspx'. To declare a page method as WebService we need to use namespace 'System.Web.Services', which I have used in using namespace section. Besure this method is 'static' type and its 'public'. Return type of webservice is string and invoking with one string parameter 'btnName'.

Now look at the jQuery code.



"js/jquery-1.9.1.js">
"text/javascript">
      $(document).ready(function () {
            $("#btnClick").click(function () {               
                
                $.ajax({
                    type: "POST",
                    url: "ChangeButtonName.aspx/ChangeButtonNameJQuery",
                    data: JSON.stringify({ btnName: $("#btnClick").val() }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {                       
                        $("#btnClick").val(msg.d);                       
                    }
                });
            });
        });

I have used here Jquery version 1.9.1 and calling my method when document becomes ready to execute which will call just after loading completion of page.



$(document).ready(function ()
{
}

the above code is doing this thing (to know details about Jquery Ajax calling from ASP.Net, read my 1st post on Jquery-Ajax). In my present code We are calling web method 'ChangeButtonNameJQuery' from current page (ChangeButtonName.aspx/ChangeButtonNameJQuery). Once successful web method execution client browser is getting response and invoking method 'success:' with response in object 'msg'. We can access server response from 'msg' property 'd' by using 'msg.d' and that I am setting to change button value, by


$("#btnClick").val(msg.d);

I hope you have enjoyed this post and has helped to learn little more on ASP.Net ajax using JQuery. Continue reading my next blog post to know more on Ajax using JQuery.

Thank you for visiting my blog. Happy coding.