Showing posts with label c# programming. Show all posts
Showing posts with label c# programming. 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.

 

Tuesday, November 26, 2013

jQuery Ajax: Create HTML Table with User details at Client based on Server Data

[This post initially posted on my MS Technical blog here. Visit http://onlyms.net for better readability]. 

I am sharing information on JQuery-AJAX on ASP.Net in incremental order to learn it properly. In last post on this topic I shared information about how to change some HTML control based on server data using jQuery. Now I shall share information how to create a user data list or table with some data which is coming from server. Here I am taking example of some user data with one image. In my project I am using one sample JPG image with IMG folder in project (available in 1st post attached project on that topic). 

Step 1: Create back-end server code to provide data. Look carefully at below server code to prepare a web-service [webmethod] method.


[WebMethod]public static string CreateUserList(){        List<object> user = new List<object>();        user.Add(new { Id = "10", Name = "A", Image = "img/sample.jpg" });        user.Add(new { Id = "20", Name = "B", Image = "img/sample.jpg" });        user.Add(new { Id = "30", Name = "C", Image = "img/sample.jpg" });        user.Add(new { Id = "40", Name = "D", Image = "img/sample.jpg" });
        return (new JavaScriptSerializer().Serialize(user));
}
In the above code I am creating a List object with property ID, Name and Image. For my case ID and Name is different but all are same image. In real life project you can change it with some different image name. I am adding these user data into List object and finally I am serializing the array/list to send it to client as JSON data format.  Using below line of code:

return (new JavaScriptSerializer().Serialize(user));
Step 2: Prepare HTML section as below:
< fo rm id="form1" runat="server">    
        jQuery Ajax: Create HTML Table with User details at client based on server data.


        
        < t able id="tblList">
        
        "btnClick" type="button" value="Click Me!" />    

In this HTML code I have declared a HTML Table where I shall append rows to design a table with server provided user data. The button will be used to invoke server method using JQuery. HTML section is extremely easy and simple.

Step 3: Invoke server webmethod/web service using JQuery AJAX.



"server">
"js/jquery-1.9.1.js">

< scr ipt type="text/javasc ript">    $(document).ready(function () {
        $("#btnClick").click(function () {
            $.ajax({                type: "POST",                url: "ArrayToList.aspx/CreateUserList",             
                contentType: "application/json; charset=utf-8",                dataType: "json",
                success: function (msg) {
                    var user = eval(msg.d);                    $.each(user, function () {                        $("#tb lList").app end("
User Id: "
+ thi s.Id + ",Name:"
+ this.Name + "< i m g al t= '' hei ght ='100' sr c='"
+ this.Image + "' /></ t r>");                    });                }            });        });    });
</ he ad>

Here I am coping full HEAD section where I have called JQuery 1.9.1 and then have written JQuery code (to know more about these part on each step by step from here). Here I am calling 'CreateUserList' web method and on successful AJAX call 'Success:' will executed where main table design will performed.
All JSON data will come at client as serialized and it will be parsed by eval() method based on message's properly. Next it will start looping with 'each' method will concatenate string with column value like 'this.Id','this.Name','this.Image'. Here need to note that Id, Name and Image was the column/parameter name in List. Finally this concatenated string is adding or appending at as row in declared table.

The whole thing will look like below image in browser.



Get source code from below attached files.
Thank you for reading my blow, please comeback again for next post, how to create a user search list as like facebook.

Wednesday, July 17, 2013

Small File Transfer Client to Client (via Server) using C#.Net socket programming



After long days I am writing this article and this is the complete package of these all articles about file transfer from one computer to another. Till now I have shown how to transfer file from client to server or server to client. But now I am merging these two things and creating one single application which can send data/file from one client to another client. It seems data is going directly from one client to another but actually it’s rotating via Server, I will explain here these things.

I am planning to stop this article series on Socket Programming in Desktop using C#.Net here for now and ignoring large file transfer sample from client to client because now a day is era of Web Programming. Long ago I tried to write code in web application with socket but I failed because web and desktop is totally different type of architecture. 

But in HTML5 is very powerful and it has introduced new thing to develop socket programming on web as well. In HTML5 there has Web Socket and using Web Socket Micorsoft has created SignalR which will be my next attraction of discussion. I shall try to explain and shall create multiple applications including Web Chat, message broadcasting system using these technologies. 

Before going to discuss Client to Client application I would like to recap earlier two post:


I am trying to explain how these were working.

   File Transfer from Client to Server

Server
Client
1. Server creates an IP End Point and a socket object then bind socket object with IP end point and sends it to listen mode for incoming client request.








5. Server receive client request and accept it. Once connection established, server create another socket object which will handle this client all requests until connection ends. Client will be informed internally by TCP about connect success.

6. Start preparations to store incoming byte data from client.



8. Server receives file byte data along with file name and stores it in byte array.

9. Server retrieve file name from byte data.

10. Server opens a binary stream writer with file name to store byte data in it. 

11. Once file save complete server closes binary stream writer and server socket objects.



14 Server program ends here.



2. Client creates an IP End Point and a socket object. 

3. Prepare byte data from file which will be sent to server.

4. Try to connect to server using client socket by help of IP end point.









7. Client starts sending byte data over connected socket.











12. Once data transfer complete and server closes socket connection, client also close client socket object.

13. Client program work ends here.



File Transfer from Client to Server
Server
Client
1. Server creates an IP End Point and a socket object then bind socket object with IP end point and sends it to listen mode for incoming client request.





4. Server receive client request and accept it. Once connection established, server create another socket object which will handle this client all requests until connection ends. Client will be informed internally by TCP about connect success.




6. Prepare byte data from file which will be sent to client.

7. Server starts sending byte data over connected socket.











12. Once data transfer complete and client closes socket connection, server also close server socket object.

13. Server program work ends here.



2. Client creates an IP End Point and a socket object.

3. Try to connect to server using client socket by help of IP end point.







5. Start preparations to store incoming byte data from server.






8. Client receives file byte data along with file name and stores it in byte array.

9. Client retrieve file name from byte data.

10. Client opens a binary stream writer with file name to store byte data in it.

11. Once file save complete client closes binary stream writer and server socket objects.






14. Client program work ends here.

So from these two tables it’s clear that in (1) Client to Server data transfer and (2) Server to Client program server and client is doing just like opposite execution.
 


When we transfer file over internet one client cannot connect to another directly because maximum client do not use static/global IP, so they cannot reach over other internet location directly. So to transfer file from client to client need server help. Server stays internet with a static IP which is accessible globally.  We will use server as temporary storage and to connect other client via server. Overall architecture will be as below:



In above picture, Client A is trying to send file to client B and both are taking help of Server in between to make connection. Client A and B both are inaccessible from outside internet because these are may be in DHCP inside a LAN or its IP has generated by some other local router. So both will connect to server and transfer data.
Now follow below communication chart to understand how data will be transferred. This chart is combination of first two chart. 


      Data Transfer      -- > -------------->-----------------------> -------------->----------------------->
Client A
Server
Client B





2. Client-A create IP End Point and a socket object.



4. Client A Prepare byte data from file which will be sent to server.

5. Client A tries to connect server using client socket by help of IP end point.





















8. Connection established with client A and server.







11. Client A starts sending byte data over connected socket.





































20. Client A receive file transfer success message from server.







22. Socket object closes and dispose.





24. Client A process ends here.
1. Server creates an IP End Point and a socket object then bind socket object with IP end point and sends it to listen mode for incoming client request.

















7. Server receives two client requests and accept these. Once connection established, server create new socket object for each connection (here total two, suppose sockObjectA for Client A and sockObjectB for Client B). These will handle client’s all requests until connection ends. Client will be informed internally by TCP about connect success. In our case sockObjectA will receive data and sockObjectB will send data.
For real life application can use socket object list (say array list or hash table) with some hash table to track client name and socket object name.






10. Start preparations to store incoming byte data from client A through sockObjectA.




12. Server receives file byte data along with file name and stores it in byte array. For large file can store in temporary file but I would suggest to store in array for faster processing. 

13. Server starts sending byte data over connected socket sockObjectB to client B.






















19. Server receive EOF successful message from client B and pass information to client A about file transfer success.





21. Server initiate to disconnect socket connection for sockObjectA and sockObjectB, so connection break with server and client A and B.
















26. Server process ends here for my case. For real life project server will stay in listen mode for next client request.








3. Client B creates IP End Point and a socket object.








6. Client B tries to connect server using client socket by help of IP end point.




















9. Connection established with client A and server.

















14. Client B receives file byte data along with file name and stores it in byte array.

15. Client retrieve file name from received byte data.

16. Client opens a binary stream writer with file name to store byte data in it.

17. Once file save complete client (do some technique to understand End Of File - EOF) closes binary stream writer and server socket objects.

18. Send a message to server to inform client A about file transfer success.


















23. Socket object closes and dispose.






25. Client B process here.
If you send large file then logic will be same and you need to loop step 11 to 20 until file ends. Here I have used EOF and then can use some fixed data packet every time. So once each packet receive in Client B, it will inform that successful receive of packet number and ask server to send next packet. 

For large file server will store file temporarily because connection speed in client A and B may not be same. Client A can send much faster data but client B may get it very slow. So buffering concept need to implement in server.

If possible I shall write this code in future.

Now I am posting this logic next will write code and once finish will post it for you with downloadable source code.