Friday, 20 January 2012

Explore Kaazing Websocket in .Net


Introduction

Kaazing WebSocket Gateway provides full duplex web communication. It provides an alternate way of communication from server to client for “polling” or “long-polling”.

WebSocket

WebSocket is a full-duplex single socket connection over which messages can be sent between a client and a server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management.

Kaazing WebSocket

Kaazing WebSocket Gateway is an HTML5-compliant WebSocket server with support to today's pre-HTML5 browsers. The Gateway provides a bridge between WebSocket clients and your back-end systems, servers, and applications. This enables you to implement your own custom protocol or run an existing protocol over WebSocket.

Installing Kaazing WebSocket

1.       Kaazing WebSocket can be installed in Windows 7, Windows Vista, Windows XP SP3
2.       Download the full Kaazing WebSocket Gateway - HTML5 Edition from the Kaazing download page.
3.       There are two type of download available
a.       Base: Contains a minimal download of the Gateway for experienced users who are ready to use the Gateway in production.
b.      Full: Contains the Base download plus the Gateway documentation and the services needed to run the Gateway demos.
4.       Unpack the Kaazing WebSocket Gateway distribution into a directory of your choice (for example, C:\kaazing or /home/username/Kaazing). Unpacking the distribution creates a directory containing the Gateway; this directory is referred to as GATEWAY_HOME in the documentation.
5.       On Windows you can use an Unzip program to unpack the Gateway *.zip file
6.       Start the demo services by navigating to the GATEWAY_HOME/bin directory and running the demo-services.start.bat (Windows) script.
a.       To start the demo service in Windows Explorer, navigate to the GATEWAY_HOME/bin directory where you installed the Gateway
b.      Use the following command to start the demo services, and substitute either the public IP address or the public DNS name for example.com: 
           demo-services.start.bat udp://example.com:50505
7.       Start Kaazing WebSocket Gateway by navigating to the GATEWAY_HOME/bin directory and running the gateway.start.bat (Windows) script.
a.       To start the gateway on Windows ; In Windows Explorer, navigate to the GATEWAY_HOME/bin directory where you installed the Gateway.
b.      Double-click the gateway.start.bat script.
8.       Verify the Gateway setup by navigating to http://localhost:8001/ in your browser.
9.       Verify Gateway
a.       To verify that the Gateway is up and running, open a browser and access the Gateway home page at http://localhost:8001/. Click the Documentation tab to see the documentation library and learn more about the Gateway. Click the Demos tab to view the demos.
b.      A WebSocket Echo demo service is bundled and started by default in the Full product. If you want to configure your own back-end service, see the Advanced configuration service and the client how-to guides on the Kaazing Documentation home page for more information.
c.       See the Release Notes (online only) for an overview of the certified browser versions for this release.
You are now done setting up Kaazing WebSocket Gateway locally.
Note:

When running the com.kaazing.gateway.client.dotnet.core.demo.exe demo for dotnet from GATEWAY_HOME/ demo/dotnet/bin/Release then exception is thrown as “Cannot load the System.Net assembly”.
In order to resolve this error you have to download .NET Framework 4 update from this url http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3556.

Configuring Kaazing WebSocket Gateway to use Multicast

To Multicast we have to specify the multicast URI (an IP address with the multicast address mask of 224.0.0.0) in the accept property.

The following is an example of a service configuration element in the file GATEWAY_HOME/conf/gateway-config.xml for a service using a multicast address. In this example, data packets sent to the multicast group 224.0.0.1:50505 (shown in line 8) will be broadcast to all clients connected to sse://localhost:8000/sse or sse+ssl://localhost:9000/sse.





To verify this configuration, you can start the newsfeed data source that ships with the Kaazing WebSocket Gateway bundle and pass the multicast URI you have configured as a startup argument. To do this, perform the following steps:
In a command prompt or shell, navigate to GATEWAY_HOME/bin.
Run gateway.demos.start mcp://multicast-uri:port-number (for example, gateway.demos.start mcp://224.0.0.1:50505) to start the newsfeed data source.
Run gateway.start to start the Gateway.
In a browser, navigate to the server-sent events demo page (by default, this is located at http://localhost:8001/demo/sse.html) and watch the streaming news feed data.
You can now configure and run a second Kaazing WebSocket Gateway to serve server-sent event streams from a different host and port for the same newsfeed multicast data packets. Note that services cannot send UDP packets to an MCP acceptor, nor MCP packets to a UDP acceptor.

After configuring the gateway create .Net console server application and add below listed code in your server application.

private void MultiCastMessage()
{
      Console.WriteLine("Start Transmitting the message ");
      Console.WriteLine("");
      Console.Read();

      UdpClient udpClient = new UdpClient();
      try
      {
          string hName = Dns.GetHostName();
          var address = Dns.GetHostAddresses(hName);
          udpClient.Connect(new IPEndPoint(address[1], 50505));
        
          List<String> messages = new List<string>();
          messages.Add("Sending message from  Origin(Server).");

          Byte[] msgByte = default(Byte[]);
          foreach (String msg in messages)
          {
              Console.WriteLine("Sending Message ......... ");
              Console.WriteLine(msg);
              System.Threading.Thread.Sleep(1000);

              msgByte = Encoding.ASCII.GetBytes(msg);
              int i = udpClient.Send(msgByte, msgByte.Length);

              System.Threading.Thread.Sleep(3000);

              Console.WriteLine("----------------------------------------------");
          }
          Console.WriteLine("");
          Console.WriteLine("Completed Transmitting the message ");

          udpClient.Close();
          Console.ReadLine();
     }
     catch (Exception ex)
     {
        Console.WriteLine("Error : " + ex.Message);
     }
}

In Main method of your console application call method MultiCastMessage()

static void Main(string[] args)
{
     MultiCastMessage();
}

Create Windows Form Client application to send and receive messages.

  • Add Reference to “com.kaazing.gateway.client.html5.dll”
  • Include in your code as “using com.kaazing.gateway.client.html5;”
  • Set the default location as  String defaultLocation = "http://localhost:8001/sse";

 Add HandleLog method to client application

private void HandleLog(String message)
{
     this.BeginInvoke((InvokeDelegate)(() =>
     {
        Log("LOG: " + message);
     }));
}

Add “Connect ” button and add code for ConnectButton_Click event

private void ConnectButton_Click(object sender, EventArgs e)
{
      // Immediately disable the connect button
      ConnectButton.Enabled = false;
      eventSource = new EventSource();
      Log("CONNECT:" + LocationText.Text);

      eventSource.OpenEvent += new OpenEventHandler(OpenHandler);
      eventSource.ErrorEvent +=new ErrorEventHandler(ErrorHandler);
      eventSource.MessageEvent += new MessageEventHandler(MessageHandler);

      eventSource.Connect(LocationText.Text);
}

Add “Disconnect ” button and add code for DisconnectButton_Click event

private void DisconnectButton_Click(object sender, EventArgs e)
{
       Log("DISCONNECTED");
       eventSource.Disconnect();
       ConnectButton.Enabled = true;
 }

Add LOG_LIMIT  and logLines Variables

private const int LOG_LIMIT = 50;
private Queue<string> logLines = new Queue<string>();

Add Log method

private void Log(string arg)
{
    logLines.Enqueue(arg);
    if (logLines.Count > LOG_LIMIT)
    {
         logLines.Dequeue();
    }
    string[] o = logLines.ToArray<string>();

    o = o.Reverse<string>().ToArray<string>();

    Output.Text = string.Join("\r\n", o);
}

Add “ClearLogButton ” button and add code for ClearLogButton_Click event

private void ClearLogButton_Click(object sender, EventArgs e)
{
     logLines.Clear();
     Output.Text = "";
}

Add  code for OpenHandler

private void OpenHandler(object sender, OpenEventArgs args)
{
    this.BeginInvoke((InvokeDelegate)(() =>
    {
        Log("CONNECTED");

        DisconnectButton.Enabled = true;
    }));
}

Add  code for MessageHandler

private void MessageHandler(object sender, MessageEventArgs args)
{
     string messageData = args.Data;
     string origin = args.Origin;
     string lastEvent = args.EventId;

     this.BeginInvoke((InvokeDelegate)(() =>
     {
          Output.Text = Output.Text + Environment.NewLine + " Recieved : " +
          messageData + Environment.NewLine + "-----";
     }));
}

Add code for ErrorHandler

private void ErrorHandler(object sender, ErrorEventArgs args)
{
    this.BeginInvoke((InvokeDelegate)(() =>
    {
        Exception ex = args.GetException;
        Output.Text = ex.InnerException.ToString();
    }));
}

  
1.       Start Kaazing WebSocket Gateway by navigating to the GATEWAY_HOME/bin directory and running the gateway.start.bat (Windows) script.

     

2.       Start Server application



3.       Start Client application

       


4.       In Client App Conncet to Gateway by clicking on “Connect” button.
5.       From Client App Send a message from Client App



As you can see in above screen shot client received the message sent from server.

Wednesday, 18 January 2012

ASP.NET Cache dependency example


In this article we will learn how to implement file dependency in caching.


In this method the cache["messageDependency"]  loads the file "DependencyFile.txt" in memory(cache) only when its content is changed in the disk.

public void displayMessage()
{
         String message;
         String Path = "~/DependencyFile.txt";
         if (Cache["messageDependency"] == null)
         {
                  System.IO.StreamReader sReader = new StreamReader(Server.MapPath(Path));
                  message = sReader.ReadToEnd();
                  sReader.Close();

                  System.Web.Caching.CacheDependency msgDependency = new System.Web.Caching.CacheDependency(Server.MapPath(Path));
                  Cache.Insert("messageDependency", message, msgDependency);
         }
         Response.Write(Cache["messageDependency"].ToString());
}

Sending email in SSIS using script task


Sending mail using script task. We can send email with attachments and also either in text format or in HTML format


Public Sub SendMail(ByVal message As String)
        Dim vars As Variables
        Dim myHtmlMessage As MailMessage
        Dim mySmtpClient As SmtpClient
    
        myHtmlMessage = New MailMessage()
        Dim FromAddress As String
        Dts.VariableDispenser.LockOneForWrite("from", vars)
        FromAddress = vars("from").Value.ToString().Trim()
        vars.Unlock()
        Dim ToAddress As String
        Dts.VariableDispenser.LockOneForWrite("to", vars)
        ToAddress = vars("to").Value.ToString().Trim()
        vars.Unlock()
        Dim CCAddress As String
        Dts.VariableDispenser.LockOneForWrite("cc", vars)
        CCAddress = vars("cc").Value.ToString().Trim()
        vars.Unlock()
        Dim SmtpClient As String
        Dts.VariableDispenser.LockOneForWrite("smtpServer", vars)
        SmtpClient = vars("smtpServer").Value.ToString().Trim()
        vars.Unlock()
       myHtmlMessage.From = New Mail.MailAddress(FromAddress)
        Dim tt As String()
        If (ToAddress.ToString().Trim().Length > 0) Then
            If (ToAddress.IndexOf(";") > 0) Then
                tt = ToAddress.Split(";")
                Dim c As String
                If (tt.Length > 0) Then
                    For Each c In tt
                        myHtmlMessage.To.Add(c)
                    Next
                End If
            Else
                myHtmlMessage.To.Add(ToAddress.ToString().Trim())
            End If
        End If
        Dim cc As String()
        If (CCAddress.ToString().Trim().Length > 0) Then
            If (CCAddress.IndexOf(";") > 0) Then
                cc = CCAddress.Split(";")
                Dim c As String
                If (cc.Length > 0) Then
                    For Each c In cc
                        myHtmlMessage.CC.Add(c)
                    Next
                End If
            Else
                myHtmlMessage.CC.Add(CCAddress)
            End If
        End If
        Dim MailSubject As String = " Email scheduling process"
        Dim mailBody As String = "Hi, </BR>" + message + "</BR> Thanks, </BR> XXX"
        myHtmlMessage.Subject = MailSubject
        myHtmlMessage.IsBodyHtml = True
        mySmtpClient = New SmtpClient(SmtpClient)
        mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
        mySmtpClient.Send(myHtmlMessage)
                  
    End Sub

How to embed an image in your Email


In this code we will learn how to embed an image in mail using VB.NET.


Public Sub SendMail(ByVal message As String)
        Dim vars As Variables
        Dim myHtmlMessage As MailMessage
        Dim mySmtpClient As SmtpClient
        Dim retVal As Int32 = -1
        myHtmlMessage = New MailMessage()
        Dim FromAddress As String
        Dts.VariableDispenser.LockOneForWrite("from", vars)
        FromAddress = vars("from").Value.ToString().Trim()
        vars.Unlock()
        Dim ToAddress As String
        Dts.VariableDispenser.LockOneForWrite("to", vars)
        ToAddress = vars("to").Value.ToString().Trim()
        vars.Unlock()
        Dim CCAddress As String
        Dts.VariableDispenser.LockOneForWrite("cc", vars)
        CCAddress = vars("cc").Value.ToString().Trim()
        vars.Unlock()
        Dim SmtpClient As String
        Dts.VariableDispenser.LockOneForWrite("smtpServer", vars)
        SmtpClient = vars("smtpServer").Value.ToString().Trim()
        vars.Unlock()

        myHtmlMessage.From = New Mail.MailAddress(FromAddress)
        Dim tt As String()
        If (ToAddress.ToString().Trim().Length > 0) Then
            If (ToAddress.IndexOf(";") > 0) Then
                tt = ToAddress.Split(";")
                Dim c As String
                If (tt.Length > 0) Then
                    For Each c In tt
                        myHtmlMessage.To.Add(c)
                    Next
                End If
            Else
                myHtmlMessage.To.Add(ToAddress.ToString().Trim())
            End If
        End If
        Dim cc As String()
        If (CCAddress.ToString().Trim().Length > 0) Then
            If (CCAddress.IndexOf(";") > 0) Then
                cc = CCAddress.Split(";")
                Dim c As String
                If (cc.Length > 0) Then
                    For Each c In cc
                        myHtmlMessage.CC.Add(c)
                    Next
                End If
            Else
                myHtmlMessage.CC.Add(CCAddress)
            End If
        End If
        Dim MailSubject As String = " Email scheduling process"
        Dim mailBody As String = "Hi, </BR>" + message + "</BR> Thanks, </BR> XXX"
        Dim ApplicationPath As String ' Physical path of an image. Example: C:/images/
        Dts.VariableDispenser.LockOneForWrite("ApplicationPath", vars)
        ApplicationPath = vars("ApplicationPath").Value.ToString().Trim()
        vars.Unlock()
        ' EMBEDING IMAGE
        Dim contentId As String = "image1" ' giving ID to an image content
        Dim path As String = ApplicationPath + "\\myLogo.JPG"
        Dim myImage As String = "<img src=""cid:image1""/><br />"
        Dim mybody As String = String.Empty
        Dim linkedResource As System.Net.Mail.LinkedResource = New System.Net.Mail.LinkedResource(path)
        Dim av1 As System.Net.Mail.AlternateView
        linkedResource.ContentId = contentId
        linkedResource.ContentType.Name = path
        av1 = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody + "</BR>" + myImage, Nothing, System.Net.Mime.MediaTypeNames.Text.Html)
        av1.LinkedResources.Add(linkedResource)
        myHtmlMessage.AlternateViews.Add(av1)
    
        myHtmlMessage.Subject = MailSubject
        myHtmlMessage.IsBodyHtml = True
        mySmtpClient = New SmtpClient(SmtpClient)
        mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
        mySmtpClient.Send(myHtmlMessage)
     
    End Sub

Handling error while connecting to FTP server using SSIS FTP task

This summary is not available. Please click here to view the post.

Error handling in SSIS


In this article we will learn how to handle the errors in SSIS package. In SSIS when package throws an error then these error details is stored in following variables ErrorCode, ErrorDescription and SourceName.


Below is the code to handle error in SSIS package.
When a SSIS task encounters an error these error details are stored in three system variables.
Dts.VariableDispenser.LockForRead("ErrorCode")
Dts.VariableDispenser.LockForRead("ErrorDescription")
Dts.VariableDispenser.LockForRead("SourceName")
ErrorCode variables returns error code which will be numeric.
ErrorDescription will give us a brief description of an error encountered by the SSIS task.
SourceName give us the task name from which error occured.

Private Sub GetErrorValues(ByRef errNumber As Integer, ByRef errDescription As String, ByRef errSource As String)
       
            Dts.VariableDispenser.LockForRead("ErrorCode")
            Dts.VariableDispenser.LockForRead("ErrorDescription")
            Dts.VariableDispenser.LockForRead("SourceName")
            Dts.VariableDispenser.GetVariables(vars)
            Try
                errNumber = CType(vars("ErrorCode").Value, Integer)
                errDescription = vars("ErrorDescription").Value.ToString()
                errSource = vars("SourceName").Value.ToString()
            Catch ex As Exception
                Throw ex
            Finally
                vars.Unlock()
            End Try
        Catch ex As SystemException
            Throw ex
        End Try
    End Sub

File handling in VB.Net

Append data to existing file

Here I am using FileStream object to write contents to a file.
First a FileSteam and File object is created. Using file object we will compare wether file is exists are not.
If file exits in the disk then we will truncate it otherwise we will create new file and allow that file for read and write using file steam object.
If file already exists then we will open that file in append mode.
Then we will point the stream reader to last line using streamwriter.
Example : sw.BaseStream.Seek(0, SeekOrigin.End)
If file does't exists then we will create new file and open that file in create mode.
Then we will point the stream reader to first line using streamwriter.
Example: sw.BaseStream.Seek(0, SeekOrigin.Begin)


Public Sub ExportToFile(ByVal oFileName As String, ByVal myContent As String)
     
        Dim file As FileStream
        Dim f As IO.File
        If (f.Exists(oFileName)) Then
            file = New FileStream(FileToWrite, FileMode.Append, FileAccess.Write)
        Else
            file = New FileStream(FileToWrite, FileMode.Create, FileAccess.ReadWrite)
        End If
        Dim sw As New StreamWriter(file, System.Text.Encoding.Default)
        If (f.Exists(oFileName)) Then
            sw.BaseStream.Seek(0, SeekOrigin.End)
        Else
            sw.BaseStream.Seek(0, SeekOrigin.Begin)
        End If
        sw.Write(myContent)
     
        sw.Close()
    End Sub

To create file and write to it using FileStream 


Public Sub WriteErrorReport(ByVal message As String, ByVal FileName As String)
Dim f As File
Dim fstream As FileStream
If f.Exists(FileName) Then
            fstream = New FileStream(FileName, FileMode.Truncate, FileAccess.ReadWrite)
Else
            fstream = New FileStream(FileName, FileMode.Create, FileAccess.ReadWrite)
End If
Dim sWriter As New StreamWriter(fstream)
sWriter.BaseStream.Seek(0, SeekOrigin.Begin)
sWriter.Write(message)
sWriter.Close()
End Sub