Node.js For .Net Developers By WCF

This article illustrates how to use Node.js by WCF which is written in C# , and using node.js as real time communication technology, with the aid of C# code, to connect with MS Sql Server.

Introduction

Nowadays, having real time web applications as two way connections, is necessary in all kinds of fields. JavaScript is a good solution but it just works at client side while there are some scenarios where we really need to have solutions that work on server side too, for instance, storing data on database or processing data at server side. There are two popular technologies used for this - SignalR and Node.js.

Why do we use Node.js?

First and foremost, because we need real time solutions for our web application in two ways - client to server and server to client side so that the data can be shared between both sides. Another good advantage is that Node.js is cross platform and does not need  complex preparation and installation before using it. It establishes well for I/O and last, but not least, the probability of missing data is too rare.

Node.js
The architecture of Node.js is drawn in the following picture - flow of data can be seen between client and server. It is possible to have connection with database, by using some solutions which I have described below:
architecture

There are some situations when we need to stick to the .NET platform, and just take the benefits from node.js. In such a case, I have written this code, by the aid of WCF, to communicate with MS SQL Server instead of installing drivers, such as node-ts, node-sqlserver, mssqlhelper, mssqlx, edge.js.
architecture

Background

I strongly recommend you to read this article in order to learn how to trigger node.js on .NET platform.

Using the code

  1. File -> New Project -> WebApplication.

  2. Solution -> Right Click -> Add New Project -> Class Library -> DAL.

  3. Add New Item-> Class -> DataAccess.cs.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using System.Configuration;  
    7. using System.Data;  
    8. using System.Data.Common;  
    9.   
    10. namespace DAL  
    11. {  
    12.     public abstract class DataAccess  
    13.     {  
    14.         public string ConnectionString  
    15.         {  
    16.             get  
    17.             {  
    18.                 return "Data Source =DESKTOP-EVM02NE\\MAHSA; Initial Catalog = NodeByWCF; Integrated Security=true ";  
    19.                 //return ConfigurationSettings.AppSettings["ConnectionString"].ToString();  
    20.             }  
    21.         }  
    22.   
    23.         protected Int32 ExecuteNonQuery(DbCommand cmd)  
    24.         {  
    25.             return cmd.ExecuteNonQuery();  
    26.         }  
    27.   
    28.         protected IDataReader ExecuteReader(DbCommand cmd)  
    29.         {  
    30.             return ExecuteReader(cmd, CommandBehavior.Default);  
    31.         }  
    32.   
    33.         protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)  
    34.         {  
    35.             return cmd.ExecuteReader(behavior);  
    36.         }  
    37.   
    38.         protected object ExecuteScalar(DbCommand cmd)  
    39.         {  
    40.             return cmd.ExecuteScalar();  
    41.         }  
    42.   
    43.     }  
    44. }  
  4. Add New Item-> Class -> CustomerDAL.cs.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Data.SqlClient;  
    5. using System.Linq;  
    6. using System.Text;  
    7. using System.Threading.Tasks;  
    8.   
    9. namespace DAL  
    10. {  
    11.    public class CustomerDAL : DataAccess  
    12.     {  
    13.         public CustomerDAL()  
    14.         {  
    15.   
    16.         }  
    17.         public IEnumerable<customer> Load()  
    18.         {  
    19.             SqlConnection conn = new SqlConnection(ConnectionString);  
    20.             SqlDataAdapter dAd = new SqlDataAdapter("select * from Customer", conn);  
    21.             dAd.SelectCommand.CommandType = CommandType.Text;  
    22.             DataTable dt = new DataTable();  
    23.             try  
    24.             {  
    25.                 dAd.Fill(dt);  
    26.   
    27.                 foreach (DataRow row in dt.Rows)  
    28.                 {  
    29.                     yield return new Customer  
    30.                     {  
    31.                         ID = Convert.ToInt32(row["ID"]),  
    32.                         Name = (row["Name"]).ToString()  
    33.                     };  
    34.                 }  
    35.   
    36.   
    37.             }  
    38.   
    39.             finally  
    40.             {  
    41.                   
    42.                 dAd.Dispose();  
    43.                 conn.Close();  
    44.                 conn.Dispose();  
    45.             }  
    46.         }  
    47.     }  
    48. }  
    49.   
    50. </customer>  
  5. Add New Item-> Class -> Customer.cs.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace DAL  
    8. {  
    9.     public class Customer  
    10.     {  
    11.         public int ID { getset; }  
    12.         public string Name { getset; }  
    13.     }  
    14. }  
  6. Solution -> Right Click -> Add New Project -> Class Library -> BAL.

  7. Add New Item-> Class -> CustomerBAL.cs.
    1. using DAL;  
    2. using System;  
    3. using System.Collections.Generic;  
    4. using System.Data;  
    5. using System.Linq;  
    6. using System.Text;  
    7. using System.Threading.Tasks;  
    8.   
    9. namespace BAL  
    10. {  
    11.     public class CustomerBAL  
    12.     {  
    13.         public IEnumerable<dal.customer> Load()  
    14.         {  
    15.             CustomerDAL customer = new CustomerDAL();  
    16.             try  
    17.             {  
    18.                  
    19.                 return customer.Load();  
    20.   
    21.             }  
    22.   
    23.             catch  
    24.             {  
    25.                 throw;  
    26.             }  
    27.             finally  
    28.             {  
    29.                 customer = null;  
    30.             }  
    31.         }  
    32.     }  
    33. }  
    34.   
    35. </dal.customer>  
  8. Solution -> Right Click -> Add New Project -> WebApplication.

  9. Add New Item-> WCF Service (Ajax-enabled)-> MyService.svc.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Runtime.Serialization;  
    6. using System.ServiceModel;  
    7. using System.ServiceModel.Activation;  
    8. using System.ServiceModel.Web;  
    9. using System.Text;  
    10. using BAL;  
    11. using DAL;  
    12. using System.Web.Script.Serialization;  
    13.   
    14.   
    15. namespace WebApplication  
    16. {  
    17.     [ServiceContract(Namespace = "")]  
    18.     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
    19.     public class MyService  
    20.     {   
    21.         [OperationContract]  
    22.         [WebGet()]  
    23.         public string GetCustomer()  
    24.         {  
    25.             CustomerBAL  _Cust = new CustomerBAL();  
    26.             try  
    27.             {  
    28.                 var customers = _Cust.Load();  
    29.                 string json = new JavaScriptSerializer().Serialize(customers);  
    30.   
    31.   
    32.                 return json;  
    33.             }  
    34.             catch (Exception)  
    35.             {  
    36.                 throw;  
    37.             }  
    38.             finally  
    39.             {  
    40.                  
    41.             }  
    42.   
    43.         }  
    44.         
    45.     }  
    46. }  
    add

  10. Solution -> Right Click -> Add New Project ->Javascript -> Blank Node.js Web Application.

    Blank Node.js Web Application

  11. Server.js,
    1. var http = require("http");  
    2. var url = require('url');  
    3. var fs = require('fs');  
    4. var io = require('socket.io');  
    5. var port = process.env.port || 1337;  
    6.   
    7. var server = http.createServer(function (request, response) {  
    8.     var path = url.parse(request.url).pathname;  
    9.       
    10.     switch (path) {  
    11.         case '/':  
    12.             response.writeHead(200, { 'Content-Type''text/html' });  
    13.             response.write('hello world');  
    14.             response.end();  
    15.             break;  
    16.         case '/Index.html':  
    17.             fs.readFile(__dirname + path, function (error, data) {  
    18.                 if (error) {  
    19.                     response.writeHead(404);  
    20.                     response.write("page doesn't exist - 404");  
    21.                     response.end();  
    22.                 }  
    23.                 else {  
    24.                     response.writeHead(200, { "Content-Type""text/html" });  
    25.                     response.write(data, "utf8");  
    26.                     response.end();  
    27.                 }  
    28.             });  
    29.             break;  
    30.         default:  
    31.             response.writeHead(404);  
    32.             response.write("page this doesn't exist - 404");  
    33.             response.end();  
    34.             break;  
    35.     }  
    36. });  
    37.   
    38. server.listen(port);  
    39.   
    40.   
    41.   
    42. var listener = io.listen(server);  
    43. listener.sockets.on('connection'function (socket) {  
    44.     //Send Data From Server To Client  
    45.     socket.emit('message', { 'message''Hello this message is from Server' });  
    46.       
    47.     //Receive Data From Client  
    48.     socket.on('client_data'function (data) {  
    49.           
    50.         socket.emit('message', { 'message': data.name });  
    51.         socket.broadcast.emit('message', { 'message': data.name });  
    52.           
    53.         process.stdout.write(data.name);  
    54.         console.log(data.name);  
    55.     });  
    56. });  
  12. Index.html.
    1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
    2.  <script src="/socket.io/socket.io.js"></script>  
    3.   
    4.  <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>  
    5.  <script src="http://localhost:8080/server.js"></script>  
    6.  <script src="/server.js"></script>  
    7.  <script>  
    8.      var socket = io.connect();  
    9.   
    10.      socket.on('message', function (data) {  
    11.          $('#conversation').append('</br>' + data.message);  
    12.      });  
    13.   
    14.   
    15.      $(document).ready(function () {  
    16.          $('#send').click(function () {  
    17.   
    18.              $.ajax({  
    19.                  type: "GET", //GET or POST or PUT or DELETE verb  
    20.                  url: "http://localhost:28448/MyService.svc/GetCustomer", // Location of the service  
    21.                  //data: Data, //Data sent to server  
    22.                  contentType: "application/json; charset=utf-8", // content type sent to server  
    23.                  dataType: "text", //Expected data format from server  
    24.                  processdata: true, //True or False  
    25.                  success: function (msg) {//On Successfull service call  
    26.                      var obj = JSON.parse(msg);  
    27.                      var t = obj.d.length;  
    28.   
    29.                      var completeMsg = "";  
    30.                      for (var i = 0; i < t; i++) {  
    31.                          completeMsgcompleteMsg = completeMsg + "  " + obj.d[i].Name;  
    32.                      }  
    33.                      alert(completeMsg);  
    34.                      socket.emit('client_data', { 'name': completeMsg });  
    35.   
    36.                  }  
    37.   
    38.              });  
    39.   
    40.          })  
    41.      });  
    42.   
    43.  </script>  
    <input id="text" type="text" /><button id="send">send</button>

    Test and Rrun

    Type: Localhost:1337/Index.html

    Click on "send" button. The data will start coming from DB on Node.js.

    Data

References

History

  1. First Version 4th July 2016

Up Next
    Ebook Download
    View all
    Learn
    View all