目录
介绍
为什么我们使用Node.js?
使用代码
测试和运行
参考
- 通过WCF应用程序下载Node.js - 8.8 MB
如今,在各种领域中都需要将实时Web应用程序作为双向连接。Javascript是一个很好的解决方案,但它只是在客户端工作,而有一些场景,我们真的需要有在服务器端工作的解决方案。例如,在数据库中存储数据或在服务器端处理数据。有两种流行的技术,一种是SignalR 和另一种是Node.js.
为什么我们使用Node.js?首先,对大多数人来说,这是因为我们需要一个双向的Web应用程序的实时解决方案,从客户端到服务器,从服务器到客户端,这样数据就可以在双方之间共享。Node.js的另一个优点是它是跨平台的,使用前不需要复杂的准备和安装。它很好地建立了I/O,最后但并非最不重要的是,数据丢失的可能性太少了。
虽然Node.js的体系结构如下图所示,用于在客户端和服务器之间流动数据。但通过使用我所描述的一些解决方案,可以与数据库建立连接:
在某些情况下我们需要继续使用.net平台并只使用来自node.js的好处。在这种情况下,我已经借助WCF编写了这段代码,以便与MS Sql Server进行通信,而不是安装诸如node-ts,node-sqlserver,mssqlhelper,mssqlx,edge.js之类的驱动程序。
1.文件 - >新建项目 - > WebApplication
2.解决方案 - >右键单击 - >添加新项目 - >类库 - > DAL
3.添加New Item-> Class - > DataAccess.cs
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.添加New Item-> Class - > CustomerDAL.cs
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 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.添加New Item - > Class - > Customer.cs
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.解决方案 - >右键单击 - >添加新项目 - >类库 - > BAL
7.添加New Item-> Class - > CustomerBAL.cs
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 Load()
{
CustomerDAL customer = new CustomerDAL();
try
{
return customer.Load();
}
catch
{
throw;
}
finally
{
customer = null;
}
}
}
}
8.解决方案 - >右键单击 - >添加新项目 - > WebApplication
9.添加New Item-> WCF Service(启用Ajax) - > MyService.svc
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
{
}
}
}
}
10.解决方案 - >右键单击 - >添加新项目 - > Javascript - >空白Node.js Web应用程序
11. Server.js
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
send
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 });
}
});
})
});
测试和运行
键入:Localhost:1337/Index.html
点击“发送”按钮数据将来自Node.js上的数据库
http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery
http://www.infragistics.com/community/blogs/mihail_mateev/archive/2014/07/18/dealing-with-node-js-and-microsoft-sql-server-part-1.aspx
原文地址: https://www.codeproject.com/Articles/1111793/Node-js-For-Net-Developers-By-WCF