Pages

Search

Monday, March 5, 2012

AjaxPro Example



Using AjaxPro it helps to call a function in server page from JavaScript directly.
This can be achieved but using XmlHttpRequest, however all these things are taken care by AajaxPro.
Below example is to display the server time in the label when user clicks on the button.
Aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script type="text/javascript" src="Scripts/Test/JScript.js" />

    </script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Server Time :
      
        <input type="button" value="Server Time" onclick="objTest.ServerTime();" />
         <label id="lblServerTime">
        </label>
    </div>
    </form>
</body>
</html>


Aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxPro;
public partial class TestPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(TestPage));
            Page.ClientScript.RegisterClientScriptInclude("test12", "Scripts/Test/App/UI/Base.js");
            Page.ClientScript.RegisterClientScriptInclude("test1", "Scripts/Test/App/UI/TestPage_Script.js");
            Page.ClientScript.RegisterStartupScript(typeof(TestPage), "ld", "<script>LoadTest();</script>");
        }
    }

    [AjaxPro.AjaxMethod]
    public string GetCurrentDate()
    {
        return DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
    }
}


Jscript.js
//defining the 'Test' object
if (typeof Test == 'undefined')
    Test = {};

//building the namespace
Test.namespace = function (nmspace) {
    var nms = nmspace.split(".");
    var obj = Test;
    for (i = 0; i < nms.length; i++) {
        obj[nms[i]] = (obj[nms[i]]) ? obj[nms[i]] : {};
        obj = obj[nms[i]];
    }
}

//implementing the inheritance for the given 2 classes
Test.extend = function (subclass, superclass) {
    var fun = function () { };
    fun.prototype = superclass.prototype;
    subclass.prototype = new fun();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass.prototype;
}

//building the logical namespaces
Test.namespace("App.UI");



Base.Js

//defining the functions in base class
Test.App.UI.Base = function () {
    alert('parent class constructor');
}

//to display the text in a label
Test.App.UI.Base.prototype.setInnerText = function (id, txt) {
    document.getElementById(id).innerText = txt;
}


TestPage_Script.js
    var objTest;

    //creating the object for "Test" Class
    function LoadTest() {
        objTest = new Test.App.UI.Test();
    }

    //building the derived class (Test)
    Test.App.UI.Test = function () {
        Test.App.UI.Test.superclass.constructor.call(this, Test.App.UI.Base);
    }

    //extending the "Base" class in "Test" class
    //this will help to copy the prototype of base class to test class
    //also adds "superclass" property to invoke constructor of "Base" class
    Test.extend(Test.App.UI.Test, Test.App.UI.Base);

    //server time javascript, which call server page function
    Test.App.UI.Test.prototype.ServerTime = function () {
        TestPage.GetCurrentDate(objTest.GetServerTime_Callback);
    }

    //response call back
    Test.App.UI.Test.prototype.GetServerTime_Callback = function (resp) {
    //calling the base class set text function
        objTest.setInnerText('lblServerTime', resp.value);
    }

Implementing Inheritance in JavaScript


Below example explains to build functions in a class and also implementing the inheritance.

if (typeof Test == 'undefined')
    Test = {};

Test.namespace = function (nmspace) {
    var nms = nmspace.split(".");
    var obj = Test;
    for (i = 0; i < nms.length; i++) {
        obj[nms[i]] = (obj[nms[i]]) ? obj[nms[i]] : {};
        obj = obj[nms[i]];
    }
}
Test.namespace("App.UI");

The above lines would help in creating namespaces and there after the functions are defined under specific namespace.

Test.App.UI.Base = function () {
    alert('parent class constructor');
}


Test.App.UI.Base.prototype.setInnerText = function (id, txt) {
    document.getElementById(id).innerText = txt;
}

Above functions are in class “Base” which falls in “Test.App.UI” namespace.


var objTest;

function LoadTest() {
    objTest = new Test.App.UI.Test();
}
Test.App.UI.Test = function () {
    Test.App.UI.Test.superclass.constructor.call(this, Test.App.UI.Base);
}

//calling below function will apply the iheritance
Test.extend(Test.App.UI.Test, Test.App.UI.Base);
Test.App.UI.Test.prototype.Hello = function () {
    alert(“hello”)
}

Test.App.UI.Test.prototype.SetValue = function (val) {
    objTest.setInnerText('lbl', resp.value);
}


Above functions are in“Test” class which also falls in “Test.App.UI” namespace.


Test.extend = function (subclass, superclass) {
    var fun = function () { };
    fun.prototype = superclass.prototype;
    subclass.prototype = new fun();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass.prototype;
}


Test.extend function is used to apply the inheritance for the given two classes.

Tuesday, February 28, 2012

Transferring File Using Name Pipe and Serialization


Named Pipe is usually used for inter process communication. The example below demonstrates the same. Below sample helps to transfer file content from NamedPipeServer to NamedPipeClient.
Creating an instance to “NamedPipeServerStream” class providing a pipe name will register a named pipe server. A Named Pipe client can receive the stream from a specific Named Pipe Server based on the name.
This is something like a dedicated channel through which processes can communicate using NamedPipe Name. 
Using NamedPipe a process can also transfer messages (string).

In the below example, NamedPipeServer is started or registered with name “File Transfer”.
The NamedPipeServer reads the content of a source file and creates an instance for “TransferFile” class setting the attributes such as source file name and file content (stream).
Server then serializes the "TransferFile" object and writes to the stream.


NamedPipeClient connects to the NamedPipeServer based whose server name is “File Transfer”.
and reads the stream. After reading the stream, Client deserializes to get the “TransferFile” object.
from the “FileTransfer” object, client creates the target file in specific directory with name from “FileName” attribute and content(byte[]) from “FileContent”.

TransferFile.cs

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

namespace FileTransfer
{
    //file transfer class (serializable)
    [Serializable]
    public class TransferFile
    {
        public string FileName;
        public Stream FileContent;
    }
}

Named Pipe Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Runtime.Serialization;
using FileTransfer;

namespace ServerNamedPipe
{
    class Program
    {
        static void Main()
        {
            //creating object for file transfer
            using (NamedPipeServerStream pipeServer =
                new NamedPipeServerStream("File Transfer", PipeDirection.Out))
            {
                Console.WriteLine("File Transfer Named Pipe Stream is ready...");
                Console.Write("Waiting for client connection...");//waiting for any client connections
                pipeServer.WaitForConnection();
                Console.WriteLine("Client connected.");
                try
                {
                    string strFile = @"c:\Test\1\Srinivas.txt";

                    //creating FileTransfer Object ans setting the file name
                    TransferFile objTransferFile = new TransferFile() { FileName = new FileInfo(strFile).Name };
                    objTransferFile.FileContent = new MemoryStream();

                    //opening the source file to read bytes
                    using (FileStream fs = File.Open(strFile, FileMode.Open, FileAccess.Read))
                    {
                        byte[] byteBuffer = new byte[1024];
                        int numBytes = fs.Read(byteBuffer, 0, 1024);

                        //writing the bytes to file transfer content stream
                        objTransferFile.FileContent.Write(byteBuffer, 0, 1024);

                        //below code is to write the bytes directly to the pipe stream
                        //pipeServer.Write(byteBuffer, 0, 1024);

                        //Reading each Kbyte and writing to the file content
                        while (numBytes > 0)
                        {
                            numBytes = fs.Read(byteBuffer, 0, numBytes);
                            objTransferFile.FileContent.Write(byteBuffer, 0, 1024);

                            //below code is to write the bytes to pipe stream directly
                            //pipeServer.Write(byteBuffer, 0, numBytes);
                        }

                        //setting the file content (stream) position to begining
                        objTransferFile.FileContent.Seek(0, SeekOrigin.Begin);

                        //serializing the file transfer object to a stream
                        IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        try
                        {
                            //serialzing and writing to pipe stream
                            formatter.Serialize(pipeServer, objTransferFile);
                        }
                        catch (Exception exp)
                        {
                            throw exp;
                        }
                    }
                }
                // Catch the IOException that is raised if the pipe is
                // broken or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
            }
        }

    }

}

 Named Pipe Client

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

namespace ClientNamedPipe
{
    class Program
    {
        static void Main(string[] args)
        {
            //connecting to the known pipe stream server which runs in localhost
            using (NamedPipeClientStream pipeClient =
                new NamedPipeClientStream(".", "File Transfer", PipeDirection.In))
            {


                // Connect to the pipe or wait until the pipe is available.
                Console.Write("Attempting to connect to File Transfer pipe...");
                //time out can also be specified
                pipeClient.Connect();

                Console.WriteLine("Connected to File Transfer pipe.");

                IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                //deserializing the pipe stream recieved from server
                FileTransfer.TransferFile objTransferFile = (FileTransfer.TransferFile)formatter.Deserialize(pipeClient);

                //creating the target file with name same as specified in source which comes using
                //file transfer object
                byte[] byteBuffer = new byte[1024];

                using (FileStream fs = new FileStream(@"c:\Test\2\" + objTransferFile.FileName, FileMode.Create, FileAccess.Write))
                {
                    //writing each Kbyte to the target file
                    int numBytes = objTransferFile.FileContent.Read(byteBuffer, 0, 1024);
                    fs.Write(byteBuffer, 0, 1024);
                    while (numBytes > 0)
                    {
                        numBytes = objTransferFile.FileContent.Read(byteBuffer, 0, numBytes);
                        fs.Write(byteBuffer, 0, numBytes);
                    }
                }
                Console.WriteLine("File, Received from server: {0}", objTransferFile.FileName);
            }
            Console.Write("Press Enter to continue...");
            Console.ReadLine();
        }
    }
}