Click here to Skip to main content
15,867,141 members
Articles / Web Development / Node.js

Node.js for .NET Developers by WCF

Rate me:
Please Sign up or sign in to vote.
4.92/5 (25 votes)
3 Apr 2019CPOL2 min read 33.8K   720   37   10
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 MS SQL Server.

Introduction

Nowadays, having real time web applications as two way connection is necessary in all kind of fields. JavaScript is a good solution, but it just works on the client side while there are some scenarios for which we really need to have solutions which work on the server side. For instance, storing data on database or processing data on server side. There are two popular technologies, one is SignalR and other Node.js.

Why Do We Use Node.js?

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

Image 1

While the architecture of Node.js is drawn as below picture to flow data between client and server, it is possible to have connection with database by using some solutions which I have described as follows:

Image 2

There are some situations which we need to keep on .NET platform and just use benefits from node.js. In such case, I have written this code with the help of WCF to communicate with MS SQL Server instead of installing drivers such as node-ts, node-sqlserver, mssqlhelper, mssqlx, edge.js.

Image 3

Background

I strongly recommend you read this article in order to know how trigger node.js works 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
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Data;
    using System.Data.Common;
    
    namespace DAL
    {
        public abstract class DataAccess
        {
            public string ConnectionString
            {
                get
                {
                    return "Data Source =DESKTOP-EVM02NE\\MAHSA; 
                    Initial Catalog = NodeByWCF; Integrated Security=true ";
                    //return ConfigurationSettings.AppSettings["ConnectionString"].ToString();
                }
            }
    
            protected Int32 ExecuteNonQuery(DbCommand cmd)
            {
                return cmd.ExecuteNonQuery();
            }
    
            protected IDataReader ExecuteReader(DbCommand cmd)
            {
                return ExecuteReader(cmd, CommandBehavior.Default);
            }
    
            protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)
            {
                return cmd.ExecuteReader(behavior);
            }
    
            protected object ExecuteScalar(DbCommand cmd)
            {
                return cmd.ExecuteScalar();
            }
        }
    }
  4. Add New Item-> Class -> CustomerDAL.cs
    C#
        using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DAL
    {
       public class CustomerDAL : DataAccess
        {
            public CustomerDAL()
            {
    
            }
            public IEnumerable<customer> Load()
            {
                SqlConnection conn = new SqlConnection(ConnectionString);
                SqlDataAdapter dAd = new SqlDataAdapter("select * from Customer", conn);
                dAd.SelectCommand.CommandType = CommandType.Text;
                DataTable dt = new DataTable();
                try
                {
                    dAd.Fill(dt);
    
                    foreach (DataRow row in dt.Rows)
                    {
                        yield return new Customer
                        {
                            ID = Convert.ToInt32(row["ID"]),
                            Name = (row["Name"]).ToString()
                        };
                    }
                }
    
                finally
                {                
                    dAd.Dispose();
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
    }
  5. Add New Item-> Class -> Customer.cs
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DAL
    {
        public class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    }
  6. Solution -> Right Click -> Add New Project -> Class Library -> BAL
  7. Add New Item-> Class -> CustomerBAL.cs:
    C#
    using DAL;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace BAL
    {
        public class CustomerBAL
        {
            public IEnumerable<dal.customer> Load()
            {
                CustomerDAL customer = new CustomerDAL();
                try
                {               
                    return customer.Load();
                }
    
                catch
                {
                    throw;
                }
                finally
                {
                    customer = null;
                }
            }
        }
    }
  8. Solution -> Right Click -> Add New Project -> WebApplication
  9. Add New Item-> WCF Service (Ajax-enabled)-> MyService.svc
    C#
        using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    using System.Text;
    using BAL;
    using DAL;
    using System.Web.Script.Serialization;
    
    namespace WebApplication
    {
        [ServiceContract(Namespace = "")]
        [AspNetCompatibilityRequirements(RequirementsMode = 
                                         AspNetCompatibilityRequirementsMode.Allowed)]
        public class MyService
        { 
            [OperationContract]
            [WebGet()]
            public string GetCustomer()
            {
                CustomerBAL  _Cust = new CustomerBAL();
                try
                {
                    var customers = _Cust.Load();
                    string json = new JavaScriptSerializer().Serialize(customers);
    
    
                    return json;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                   
                }
            }      
        }
    }

    Image 4

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

    Image 5

  11. Server.js:
    C#
    var http = require("http");
    var url = require('url');
    var fs = require('fs');
    var io = require('socket.io');
    var port = process.env.port || 1337;
    
    var server = http.createServer(function (request, response) {
        var path = url.parse(request.url).pathname;
        
        switch (path) {
            case '/':
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write('hello world');
                response.end();
                break;
            case '/Index.html':
                fs.readFile(__dirname + path, function (error, data) {
                    if (error) {
                        response.writeHead(404);
                        response.write("page doesn't exist - 404");
                        response.end();
                    }
                    else {
                        response.writeHead(200, { "Content-Type": "text/html" });
                        response.write(data, "utf8");
                        response.end();
                    }
                });
                break;
            default:
                response.writeHead(404);
                response.write("page this doesn't exist - 404");
                response.end();
                break;
        }
    });
    
    server.listen(port);
    
    var listener = io.listen(server);
    listener.sockets.on('connection', function (socket) {
        //Send Data From Server To Client
        socket.emit('message', { 'message': 'Hello this message is from Server' });
        
        //Receive Data From Client
        socket.on('client_data', function (data) {
            
            socket.emit('message', { 'message': data.name });
            socket.broadcast.emit('message', { 'message': data.name });
            
            process.stdout.write(data.name);
            console.log(data.name);
        });
    });
  12. Index.html:
    JavaScript
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
    
        <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
        <script src="http://localhost:8080/server.js"></script>
        <script src="/server.js"></script>
        <script>
            var socket = io.connect();
    
            socket.on('message', function (data) {
                $('#conversation').append('
    ' + data.message);
            });
    
            $(document).ready(function () {
                $('#send').click(function () {
    
                    $.ajax({
                        type: "GET", //GET or POST or PUT or DELETE verb
                        url: "http://localhost:28448/MyService.svc/GetCustomer", // Location 
                                                                 // of the service
                        //data: Data,                            //Data sent to server
                        contentType: "application/json; charset=utf-8", // content type sent to server
                        dataType: "text",                        //Expected data format from server
                        processdata: true,                       //True or False
                        success: function (msg) {                //On Successful service call
                            var obj = JSON.parse(msg);
                            var t = obj.d.length;
    
                            var completeMsg = "";
                            for (var i = 0; i < t; i++) {
                                completeMsg = completeMsg + "  " + obj.d[i].Name;
                            }
                            alert(completeMsg);
                            socket.emit('client_data', { 'name': completeMsg });
                        }
                    });
                })
            });
        </script>
    HTML
    <input id="text" type="text" /><button id="send">send</button>
    
This is our conversation.

Test and Run

Type: Localhost:1337/Index.html

Click on "send" button, Data will come from DB on Node.js.

Image 6

References

History

  • 4th July, 2016: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Doctorandin Technische Universität Berlin
Iran (Islamic Republic of) Iran (Islamic Republic of)
I have been working with different technologies and data more than 10 years.
I`d like to challenge with complex problem, then make it easy for using everyone. This is the best joy.

ICT Master in Norway 2013
Doctorandin at Technische Universität Berlin in Data Scientist ( currently )
-------------------------------------------------------------
Diamond is nothing except the pieces of the coal which have continued their activities finally they have become Diamond.

http://www.repocomp.com/

Comments and Discussions

 
QuestionCall WCF function into Server.js Pin
Hossein Ganjyar20-Nov-17 4:22
Hossein Ganjyar20-Nov-17 4:22 
AnswerRe: Call WCF function into Server.js Pin
Mahsa Hassankashi24-Nov-17 2:12
Mahsa Hassankashi24-Nov-17 2:12 
GeneralMy vote of 5 Pin
Dmitriy Gakh16-Aug-16 4:15
professionalDmitriy Gakh16-Aug-16 4:15 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi22-Sep-16 23:55
Mahsa Hassankashi22-Sep-16 23:55 
GeneralMy vote of 5 Pin
Igor Ladnik24-Jul-16 8:23
professionalIgor Ladnik24-Jul-16 8:23 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi14-Aug-16 4:20
Mahsa Hassankashi14-Aug-16 4:20 
GeneralThanks for sharing Pin
Alireza_136213-Jul-16 10:09
Alireza_136213-Jul-16 10:09 
GeneralRe: Thanks for sharing Pin
Mahsa Hassankashi13-Jul-16 12:26
Mahsa Hassankashi13-Jul-16 12:26 
GeneralMy vote of 5 Pin
Tridip Bhattacharjee12-Jul-16 22:01
professionalTridip Bhattacharjee12-Jul-16 22:01 
GeneralRe: My vote of 5 Pin
Mahsa Hassankashi13-Jul-16 2:59
Mahsa Hassankashi13-Jul-16 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.