Sunday, October 26, 2014

How to create a simple http server in node.js


Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.


Start by creating a new file named “app.js”. Insert the following code into the file and save it.


var http = require("http");
var app = http.createServer(function(request, response) {  
    response.writeHead(200, {
        "Content-Type": "text/html"
    });  
    response.write("<!DOCTYPE "
        html ">");  
    response.write("<html>");  
    response.write("<head>");  
    response.write("<title>Hello Node Server Page</title>");  
    response.write("</head>");  
    response.write("<body>");  
    response.write("Hello World!");  
    response.write("</body>");  
    response.write("</html>");  
    response.end();
}); 
app.listen(9090);
console.log("Server is listening");

To start the server, type the command shown below. If everything works properly, you will see a message that the server is listening. Note that the example server attempts to bind to port 9090, the standard HTTP port. If this port is already in use, or is restricted on your machine, you will experience an error.

node app.js

How to stream large file using node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.




var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
    var newFile = fs.createWriteStream("x.wmv");
    var fileBytes = req.headers['content-length'];
    var uploadedBytes = 0;
    req.pipe(newFile);
    req.on('data', function(chunk) {
        uploadedBytes += chunk.length;
        var progress = (uploadedBytes / fileBytes) * 100;
        res.write("progress:" + parseInt(progress, 10) + "\n");
    });
    res.write("Done");

}).listen(8888);

Saturday, October 25, 2014

Understand WebMessage Format


In this post I will show how how to use WebMessageBodyStyle parameter attribute in REST Service.WebMessageBodyStyle is an enumeration that specifies whether to wrap parameter and return values.WebMessageBodyStyle contains four member.

I have listed down all the members and there discription in following table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestLoginService
{

    [ServiceContract]
    public interface ILoginService
    {

        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        AuthResult Login(User user);
    }


}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestLoginService
{
    public class LoginService : ILoginService
    {

        public AuthResult Login(User user)
        {
            if (user.UserName == "john" && user.Password == "password")
            {
                return new AuthResult { UserName = user.UserName, IsAuthenticated = true };

            }
            return new AuthResult { UserName = user.UserName, IsAuthenticated = false };
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestLoginService
{
   public class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace RestLoginService
{
    [DataContract]
    public class AuthResult
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public bool IsAuthenticated { get; set; }
    }
}

Web.Config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http"/>
    </protocolMapping>
    <behaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>