17 September 2014

Convert C# DataTable to JavaScript 2D Array

Hi All,

Lets see how to send the DataTable from Code behind to JavaScript.  Some time we face the problem when we need to array the value from C# code behind to JavaScript use use script tag <%=variable_name%> Right we are also going to use the same approach. But the main point is how to convert the DataTable(or Dictionary or List of object) from C# to JavaScript.

Someone might come up with the thought to use the Repeater control.  But its really typical,  What about if I say you can get the C# DataTable  as 2D array in JavaScript with no extra efforts??

:) Cool...

you just need to pass your DataTable in this method and it will create the Json Serialized array to be used in JavaScript. :)

   public partial class RepeaterControlTesting : System.Web.UI.Page
   {
      public string dataTable;        
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            dataTable = ConvertDataTabletoString(getDT());                
         }
      }
      public string ConvertDataTabletoString(DataTable dt)
      {            
          JavaScriptSerializer serializer = new JavaScriptSerializer();
                   
          List<List<object>> rows = new List<List<object>>();
          List<object> row;
          foreach (DataRow dr in dt.Rows)
          {
             row = new List<object>();
             foreach (DataColumn col in dt.Columns)
             {
                row.Add(dr[col]);
             }
             rows.Add(row);
          }

          return serializer.Serialize(rows);
      }
      public DataTable getDT()
      {
          /// or get the DataTable from Database.. 
          DataTable dt = new DataTable();
          dt.Columns.Add("Col_int", typeof (int));
          dt.Columns.Add("Col_string", typeof(string));
          dt.Columns.Add("Col_bool", typeof(bool));
          dt.Columns.Add("Col_4th", typeof(string));
          dt.Columns.Add("Col_float", typeof(float));

          DataRow dr;
          for (int i = 1; i <= 5; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = i + "  Col_string";
              dr[2] = (i%2 == 0);
              dr[3] = i + " Col_4th";
              dr[4] = (float)i;

              dt.Rows.Add(dr);
          }

          return dt;
      }

  }

Thats it.. now just goto you aspx file and access the "dataTable" in your JavaScript code..

<body>
    <div id="main">
                
    </div>
        
    <script>        
        var dataTable = <%= this.dataTable %>;
        for (var i = 0; i < dataTable.length; i++) {
            $("#main").append("| "+dataTable[i][0] + " | ");
            $("#main").append(dataTable[i][1] + " | ");
            $("#main").append(dataTable[i][2] + " | ");
            $("#main").append(dataTable[i][3] + " | ");
            $("#main").append(dataTable[i][4] + " |<br/><br/>");
        }
    </script>
</body>



Good to go.. :) Happy Code sharing.. :)

2 September 2014

SignalR - Real Time Communication

Hi All,

Today lets talk about "SignalR", I hope You might have heard about it.  But How to use it you might face some problem.
SignalR is used for real time communication, eg like - social networking site for notification, in your mail inbox for new mail arriving, real time chat application, group chatting forums and other.  Real time communication make sense and we know what does it mean.

When we try to implement real time relationship, the first way came in our mind it polling.. Long-polling or short-polling.. But what about if I say we have one more efficient method then polling?  Oh you got it? is that Web-Socket??  Yes it is.. but if you are going to use Web-Socket or any other HTML5 elements you have to make it sure you are going to support few old browsers as well which doesn't support HTML5 elements.

Now you  might think about long-polling with Web socket?  web-socket for new browser and polling for old browser? Right?

Yes that the way to support the old and new browser. But you have to code for polling and web-socket, then check the browser support, then call the supported coding snippet.  But I am saying no need to code for all SignalR here to do all this.  SignalR is enough intelligent to figure out what to use and how to use.  No need to code for polling and web-socket.

SignalR check the client and Server both, if both support the Web-Socket it goes for web-socket else efficient polling.  The best part is you no need to worry about it and coding part, it takes care for that. :)  Lets see for example and dependencies..


  • JQuery > 1.6 
  • SignalR  JS file
  • SignalR dll
  • Owin dll
  • Newtonsoft.Json dll


but again no worry, follow the below steps one by one - (Download Sample from here)

  • Open your Visual Studio and Create new blank Web Project.
  • Go to TOOLS >  NuGet Package Manager  >  Package Manager Console.  Type the following command on console and hit the  <Enter>, it will process and install and add the reference to your project..
    install-package Microsoft.AspNet.SignalR
  • install this package, it will automatically download all the dependencies and required dll all jquery files.
  • Right click project and add one class called as "Startup.cs"(name should be same) and paste the following code.
  • using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalR_For_Upload.Startup))]
    namespace SignalR_For_Upload
    {    
      public class Startup
      {
        public void Configuration(IAppBuilder app)
        {
           app.MapSignalR();
        }
      }
    }
    
    
  • Now create another class file and named it as "MyHub.cs", and paste the below code
  • using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalR_For_Upload
    {
      [HubName("newNameOfHub")]
      public class MyHub : Hub
      {
        public void SendMsg(string message)
        {
          Clients.All.ReceiveMsg(message);
        }
      }
    }
    
    
  • So the above is the Hub which keeps track of all the client and send the message to them using the statement stated above. 
  • Clients.All.ReceiveMsg(message);
    here 'Client.All' mean all the clients while 'ReceiveMsg(message)' is the dynamic expression which can be considered as event name for client 
    
  • Thats all now no more coding .. :) just need to bind up this event from client using javascript snippet. let have a look at that part as well.
  • Create your "Default.aspx" page and replace the "body" section with the following code(You can take the plain html page as well :) no worries).
  • <body>
      <input type="text" id="msg" value=" " />
      <input type="button" id="send" value="send" />
      <ul id="message">
      </ul>
        
      <script src="Scripts/jquery-1.6.4.min.js"></script>
      <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>    
      <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
      <script>        
        $(function () {
            
           var con = $.hubConnection();
           var hub = con.createHubProxy('newNameOfHub');
            
           hub.on('ReceiveMsg', function (message) {
              $('#message').append('<li>' + message + '</li>');
           });
    
           con.start().done(function () {
              $('#send').click(function () {
                 hub.invoke('sendMsg', $('#msg').val());                    
              });
           });
    
        });
      </script>
    </body>
    
  • So thats it.. just save the page. and run this in two browser and check they are communication in real time.  :)  Download Sample


Happy Code Sharing.. :)