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. namespace DAL
    10. {
    11. public abstract class DataAccess
    12. {
    13. public string ConnectionString
    14. {
    15. get
    16. {
    17. return "Data Source =DESKTOP-EVM02NE\\MAHSA; Initial Catalog = NodeByWCF; Integrated Security=true ";
    18. //return ConfigurationSettings.AppSettings["ConnectionString"].ToString();
    19. }
    20. }
    21. protected Int32 ExecuteNonQuery(DbCommand cmd)
    22. {
    23. return cmd.ExecuteNonQuery();
    24. }
    25. protected IDataReader ExecuteReader(DbCommand cmd)
    26. {
    27. return ExecuteReader(cmd, CommandBehavior.Default);
    28. }
    29. protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)
    30. {
    31. return cmd.ExecuteReader(behavior);
    32. }
    33. protected object ExecuteScalar(DbCommand cmd)
    34. {
    35. return cmd.ExecuteScalar();
    36. }
    37. }
    38. }
  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. namespace DAL
    9. {
    10. public class CustomerDAL : DataAccess
    11. {
    12. public CustomerDAL()
    13. {
    14. }
    15. public IEnumerable<customer> Load()
    16. {
    17. SqlConnection conn = new SqlConnection(ConnectionString);
    18. SqlDataAdapter dAd = new SqlDataAdapter("select * from Customer", conn);
    19. dAd.SelectCommand.CommandType = CommandType.Text;
    20. DataTable dt = new DataTable();
    21. try
    22. {
    23. dAd.Fill(dt);
    24. foreach (DataRow row in dt.Rows)
    25. {
    26. yield return new Customer
    27. {
    28. ID = Convert.ToInt32(row["ID"]),
    29. Name = (row["Name"]).ToString()
    30. };
    31. }
    32. }
    33. finally
    34. {
    35. dAd.Dispose();
    36. conn.Close();
    37. conn.Dispose();
    38. }
    39. }
    40. }
    41. }
    42. </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. namespace DAL
    7. {
    8. public class Customer
    9. {
    10. public int ID { get; set; }
    11. public string Name { get; set; }
    12. }
    13. }
  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. namespace BAL
    9. {
    10. public class CustomerBAL
    11. {
    12. public IEnumerable<dal.customer> Load()
    13. {
    14. CustomerDAL customer = new CustomerDAL();
    15. try
    16. {
    17. return customer.Load();
    18. }
    19. catch
    20. {
    21. throw;
    22. }
    23. finally
    24. {
    25. customer = null;
    26. }
    27. }
    28. }
    29. }
    30. </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. namespace WebApplication
    14. {
    15. [ServiceContract(Namespace = "")]
    16. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    17. public class MyService
    18. {
    19. [OperationContract]
    20. [WebGet()]
    21. public string GetCustomer()
    22. {
    23. CustomerBAL _Cust = new CustomerBAL();
    24. try
    25. {
    26. var customers = _Cust.Load();
    27. string json = new JavaScriptSerializer().Serialize(customers);
    28. return json;
    29. }
    30. catch (Exception)
    31. {
    32. throw;
    33. }
    34. finally
    35. {
    36. }
    37. }
    38. }
    39. }
    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. var server = http.createServer(function (request, response) {
    7. var path = url.parse(request.url).pathname;
    8. switch (path) {
    9. case '/':
    10. response.writeHead(200, { 'Content-Type': 'text/html' });
    11. response.write('hello world');
    12. response.end();
    13. break;
    14. case '/Index.html':
    15. fs.readFile(__dirname + path, function (error, data) {
    16. if (error) {
    17. response.writeHead(404);
    18. response.write("page doesn't exist - 404");
    19. response.end();
    20. }
    21. else {
    22. response.writeHead(200, { "Content-Type": "text/html" });
    23. response.write(data, "utf8");
    24. response.end();
    25. }
    26. });
    27. break;
    28. default:
    29. response.writeHead(404);
    30. response.write("page this doesn't exist - 404");
    31. response.end();
    32. break;
    33. }
    34. });
    35. server.listen(port);
    36. var listener = io.listen(server);
    37. listener.sockets.on('connection', function (socket) {
    38. //Send Data From Server To Client
    39. socket.emit('message', { 'message': 'Hello this message is from Server' });
    40. //Receive Data From Client
    41. socket.on('client_data', function (data) {
    42. socket.emit('message', { 'message': data.name });
    43. socket.broadcast.emit('message', { 'message': data.name });
    44. process.stdout.write(data.name);
    45. console.log(data.name);
    46. });
    47. });
  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. <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    4. <script src="http://localhost:8080/server.js"></script>
    5. <script src="/server.js"></script>
    6. <script>
    7. var socket = io.connect();
    8. socket.on('message', function (data) {
    9. $('#conversation').append('</br>' + data.message);
    10. });
    11. $(document).ready(function () {
    12. $('#send').click(function () {
    13. $.ajax({
    14. type: "GET", //GET or POST or PUT or DELETE verb
    15. url: "http://localhost:28448/MyService.svc/GetCustomer", // Location of the service
    16. //data: Data, //Data sent to server
    17. contentType: "application/json; charset=utf-8", // content type sent to server
    18. dataType: "text", //Expected data format from server
    19. processdata: true, //True or False
    20. success: function (msg) {//On Successfull service call
    21. var obj = JSON.parse(msg);
    22. var t = obj.d.length;
    23. var completeMsg = "";
    24. for (var i = 0; i < t; i++) {
    25. completeMsgcompleteMsg = completeMsg + " " + obj.d[i].Name;
    26. }
    27. alert(completeMsg);
    28. socket.emit('client_data', { 'name': completeMsg });
    29. }
    30. });
    31. })
    32. });
    33. </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