Monday, February 27, 2012

WebSocket


What is WebSocket?

The WebSocket specification—developed as part of the HTML5 initiative—introduced the WebSocket JavaScript interface, which defines a full-duplex single socket connection over which messages can be sent between client and server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management.
WebSocket represents the next evolutionary step in web communication compared to Comet and Ajax. However, each technology has its own unique capabilities. Learn how these technologies vary so you can make the right choice.


About HTML5 WebSockets

The HTML5 WebSockets specification defines an API that enables web pages to use the WebSockets protocol for two-way communication with a remote host. It introduces the WebSocket interface and defines a full-duplex communication channel that operates through a single socket over the Web. HTML5 WebSockets provide an enormous reduction in unnecessary network traffic and latency compared to the unscalable polling and long-polling solutions that were used to simulate a full-duplex connection by maintaining two connections.
HTML5 WebSockets account for network hazards such as proxies and firewalls, making streaming possible over any connection, and with the ability to support upstream and downstream communications over a single connection, HTML5 WebSockets-based applications place less burden on servers, allowing existing machines to support more concurrent connections. The following figure shows a basic WebSocket-based architecture in which browsers use a WebSocket connection for full-duplex, direct communication with remote hosts.
HTML5 WebSockets Architecture
One of the more unique features WebSockets provide is its ability to traverse firewalls and proxies, a problem area for many applications. Comet-style applications typically employ long-polling as a rudimentary line of defense against firewalls and proxies. The technique is effective, but is not well suited for applications that have sub-500 millisecond latency or high throughput requirements. Plugin-based technologies such as Adobe Flash, also provide some level of socket support, but have long been burdened with the very proxy and firewall traversal problems that WebSockets now resolve.
A WebSocket detects the presence of a proxy server and automatically sets up a tunnel to pass through the proxy. The tunnel is established by issuing an HTTP CONNECT statement to the proxy server, which requests for the proxy server to open a TCP/IP connection to a specific host and port. Once the tunnel is set up, communication can flow unimpeded through the proxy. Since HTTP/S works in a similar fashion, secure WebSockets over SSL can leverage the same HTTP CONNECT technique. Note that WebSockets are just beginning to be supported by modern browsers (Chrome now supports WebSockets natively). However, backward-compatible implementations that enable today's browsers to take advantage of this emerging technology are available.
WebSockets—like other pieces of the HTML5 effort such as Local Storage and Geolocation—was originally part of the HTML5 specification, but was moved to a separate standards document to keep the specification focused. WebSockets has been submitted to the Internet Engineering Task Force (IETF) by its creators, the Web Hypertext Application Technology Working Group (WHATWG). Authors, evangelists, and companies involved in the standardization still refer to the original set of features, including WebSockets, as "HTML5."

The WebSocket Protocol

The WebSocket protocol was designed to work well with the existing Web infrastructure. As part of this design principle, the protocol specification defines that the WebSocket connection starts its life as an HTTP connection, guaranteeing full backwards compatibility with the pre-WebSocket world. The protocol switch from HTTP to WebSocket is referred to as a the WebSocket handshake.
The browser sends a request to the server, indicating that it wants to switch protocols from HTTP to WebSocket. The client expresses its desire through the Upgrade header:
GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Origin: http://websocket.org Cookie: __utma=99as Connection: Upgrade Host: echo.websocket.org Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13 
If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.
HTTP/1.1 101 WebSocket Protocol Handshake Date: Fri, 10 Feb 2012 17:38:18 GMT Connection: Upgrade Server: Kaazing Gateway Upgrade: WebSocket Access-Control-Allow-Origin: http://websocket.org Access-Control-Allow-Credentials: true Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU= Access-Control-Allow-Headers: content-type 
At this point the HTTP connection breaks down and is replaced by the WebSocket connection over the same underlying TCP/IP connection. The WebSocket connection uses the same ports as HTTP (80) and HTTPS (443), by default.
Once established, WebSocket data frames can be sent back and forth between the client and the server in full-duplex mode. Both text and binary frames can be sent in either direction at the same time. The data is minimally framed with just two bytes. In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. WebSocket text frames use a terminator, while binary frames use a length prefix.
WebSocket Frame

Using the HTML5 WebSocket API

With the introduction of one succinct interface (see the following listing), developers can replace techniques such as long-polling and "forever frames," and as a result further reduce latency.
[Constructor(in DOMString url, optional in DOMString protocol)] interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount;  // networking attribute Function onopen; attribute Function onmessage; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget;
Utilizing the WebSocket interface couldn't be simpler. To connect to an end-point, just create a new WebSocket instance, providing the new object with a URL that represents the end-point to which you wish to connect, as shown in the following example. Note that a ws:// and wss:// prefix are proposed to indicate a WebSocket and a secure WebSocket connection, respectively.
var myWebSocket = new WebSocket("ws://www.websockets.org"); 
A WebSocket connection is established by upgrading from the HTTP protocol to the WebSockets protocol during the initial handshake between the client and the server. The connection itself is exposed via the "onmessage" and "send" functions defined by the WebSocket interface.
Before connecting to an end-point and sending a message, you can associate a series of event listeners to handle each phase of the connection life-cycle as shown in the following example.
myWebSocket.onopen = function(evt) { alert("Connection open ..."); }; myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); }; myWebSocket.onclose = function(evt) { alert("Connection closed."); }; 
To send a message to the server, simply call "send" and provide the content you wish to deliver. After sending the message, call "close" to terminate the connection, as shown in the following example. As you can see, it really couldn't be much easier.
myWebSocket.send("Hello WebSockets!"); myWebSocket.close();

Friday, February 3, 2012

UPLOADING AND IMPORTING CSV FILE TO SQL SERVER IN ASP.NET WEBFORMS


UPLOADING AND IMPORTING CSV FILE TO SQL SERVER IN ASP.NET WEBFORMS



Few weeks ago I was working with a small internal project  that involves importing CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project.

In this post I will demonstrate how to upload and import CSV file to SQL Server database. As some may have already know, importing CSV file to SQL Server is easy and simple but difficulties arise when the CSV file contains, many columns with different data types. Basically, the provider cannot differentiate data types between the columns or the rows, blindly it will consider them as a data type based on first few rows and leave all the data which does not match the data type. To overcome this problem, I used schema.ini file to define the data type of the CSV file and allow the provider to read that and recognize the exact data types of each column.

Now what is schema.ini?
Taken from the documentation: The Schema.ini is a information file, used to define the data structure and format of each column that contains data in the CSV file. If schema.ini file exists in the directory, Microsoft.Jet.OLEDB provider automatically reads it and recognizes the data type information of each column in the CSV file. Thus, the provider intelligently avoids the misinterpretation of data types before inserting the data into the database. For more information see: http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx

Points to remember before creating schema.ini:

  1. The schema information file, must always named as 'schema.ini'.
  2. The schema.ini file must be kept in the same directory where the CSV file exists.
  3. The schema.ini file must be created before reading the CSV file.
  4. The first line of the schema.ini, must the name of the CSV file, followed by the properties of the CSV file, and then the properties of the each column in the CSV file.

Here's an example of how the schema looked like:

[Employee.csv]
ColNameHeader=False
Format=CSVDelimited
DateTimeFormat=dd-MMM-yyyy
Col1=EmployeeID Long
Col2=EmployeeFirstName Text Width 100
Col3=EmployeeLastName Text Width 50
Col4=EmployeeEmailAddress Text Width 50



To get started lets's go a head and create a simple blank database. Just for the purpose of this demo I created a database called TestDB.

After creating the database then lets go a head and fire up Visual Studio and then create a new WebApplication project.

Under the root application create a folder called UploadedCSVFiles and then place the schema.ini on that folder. The uploaded CSV files will be stored in this folder after the user imports the file. 
Now add a WebForm in the project and set up the HTML mark up and add one (1) FileUpload control one(1)Button and three (3) Label controls.
After that we can now proceed with the codes for uploading and importing the CSV file to SQL Server database. Here are the full code blocks below:
   1:  using System;
   2:  using System.Data;
   3:  using System.Data.SqlClient;
   4:  using System.Data.OleDb;
   5:  using System.IO;
   6:  using System.Text;
   7:   
   8:  namespace WebApplication1
   9:  {
  10:      public partial class CSVToSQLImporting : System.Web.UI.Page
  11:      {
  12:          private string GetConnectionString()
  13:          {
  14:              return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
  15:          }
  16:          private void CreateDatabaseTable(DataTable dt, string tableName)
  17:          {
  18:   
  19:              string sqlQuery = string.Empty;
  20:              string sqlDBType = string.Empty;
  21:              string dataType = string.Empty;
  22:              int maxLength = 0;
  23:              StringBuilder sb = new StringBuilder();
  24:   
  25:              sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
  26:   
  27:              for (int i = 0; i < dt.Columns.Count; i++)
  28:              {
  29:                  dataType = dt.Columns[i].DataType.ToString();
  30:                  if (dataType == "System.Int32")
  31:                  {
  32:                      sqlDBType = "INT";
  33:                  }
  34:                  else if (dataType == "System.String")
  35:                  {
  36:                      sqlDBType = "NVARCHAR";
  37:                      maxLength = dt.Columns[i].MaxLength;
  38:                  }
  39:   
  40:                  if (maxLength > 0)
  41:                  {
  42:                      sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
  43:                  }
  44:                  else
  45:                  {
  46:                      sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
  47:                  }
  48:              }
  49:   
  50:              sqlQuery = sb.ToString();
  51:              sqlQuery = sqlQuery.Trim().TrimEnd(',');
  52:              sqlQuery = sqlQuery + " )";
  53:   
  54:              using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
  55:              {
  56:                  sqlConn.Open();
  57:                  SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
  58:                  sqlCmd.ExecuteNonQuery();
  59:                  sqlConn.Close();
  60:              }
  61:   
  62:          }
  63:          private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
  64:          {
  65:              string sqlQuery = string.Empty;
  66:              StringBuilder sb = new StringBuilder();
  67:   
  68:              sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
  69:              sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
  70:              sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
  71:   
  72:              sqlQuery = sb.ToString();
  73:   
  74:              using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
  75:              {
  76:                  sqlConn.Open();
  77:                  SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
  78:                  sqlCmd.ExecuteNonQuery();
  79:                  sqlConn.Close();
  80:              }
  81:          }
  82:          protected void Page_Load(object sender, EventArgs e)
  83:          {
  84:   
  85:          }
  86:          protected void BTNImport_Click(object sender, EventArgs e)
  87:          {
  88:              if (FileUpload1.HasFile)
  89:              {
  90:                  FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
  91:                  if (fileInfo.Name.Contains(".csv"))
  92:                  {
  93:   
  94:                      string fileName = fileInfo.Name.Replace(".csv", "").ToString();
  95:                      string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name;
  96:   
  97:                      //Save the CSV file in the Server inside 'MyCSVFolder' 
  98:                      FileUpload1.SaveAs(csvFilePath);
  99:   
 100:                      //Fetch the location of CSV file 
 101:                      string filePath = Server.MapPath("UploadedCSVFiles") + "\\";
 102:                      string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
 103:                      string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
 104:   
 105:                      // load the data from CSV to DataTable 
 106:   
 107:                      OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
 108:                      DataTable dtCSV = new DataTable();
 109:                      DataTable dtSchema = new DataTable();
 110:   
 111:                      adapter.FillSchema(dtCSV, SchemaType.Mapped);
 112:                      adapter.Fill(dtCSV);
 113:   
 114:                      if (dtCSV.Rows.Count > 0)
 115:                      {
 116:                          CreateDatabaseTable(dtCSV, fileName);
 117:                          Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
 118:   
 119:                          string fileFullPath = filePath + fileInfo.Name;
 120:                          LoadDataToDatabase(fileName, fileFullPath, ",");
 121:   
 122:                          Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
 123:                      }
 124:                      else
 125:                      {
 126:                          LBLError.Text = "File is empty.";
 127:                      }
 128:                  }
 129:                  else
 130:                  {
 131:                      LBLError.Text = "Unable to recognize file.";
 132:                  }
 133:   
 134:              }
 135:          }
 136:      }
 137:  }

The code above consists of three (3) private methods which are the GetConnectionString(), CreateDatabaseTable() and LoadDataToDatabase(). The GetConnectionString() is a method that returns a string. This method basically gets the connection string that is configured in the web.config file. The CreateDatabaseTable() is method that accepts two (2) parameters which are the DataTable and the filename. As the method name already suggested, this method automatically create a Table to the database based on the source DataTable and the filename of the CSV file. The LoadDataToDatabase() is a method that accepts three (3) parameters which are the tableName, fileFullPath and delimeter value. This method is where the actual saving or importing of data from CSV to SQL server happend.
The codes at BTNImport_Click event handles the uploading of CSV file to the specified location and at the same time this is where the CreateDatabaseTable() and LoadDataToDatabase() are being called. If you notice I also added some basic trappings and validations within that event.
Now to test the importing utility then let's create a simple data in a CSV format. Just for the simplicity of this demo let's create a CSV file and name it as "Employee" and add some data on it. Here's an example below:

1,VMS,Durano,email1@email.com
2,Jennifer,Cortes,email2@email.com
3,Xhaiden,Durano,email3@email.com
4,Angel,Santos,emai4@email.com
5,Kier,Binks,emai5@email.com
6,Erika,Bird,emai6@email.com
7,Vianne,Durano,emai7@email.com
8,Lilibeth,Tree,emai8@email.com
9,Bon,Bolger,email9@email.com
10,Brian,Jones,email10@email.com 


Now save the newly created CSV file in some location in your hard drive.


Okay let's run the application and browse the CSV file that we have just created.
 Take a look at the sample screen shots below:
After browsing the CSV file.
After clicking the Import Button
Now if we look at the database that we have created earlier you'll notice that the Employee table is created with the imported data on it. See below screen shot.

That's it! I hope someone find this post useful!
Posted By:Vinz' Blog (ProudMonkey)

ProudMonkey MessageBox Controls for WebForms



USING THE CONTROLS
The MessageBox Control - This control give you the option to prompt different message types such as information, Warning, Success operations and Error message types. This control can be called via server side or client side. Here are some screen shots of the MessageBox control.
How to Use it?
1. Download and extract the ProudMonkey.Common.Controls.dll
2. Add the ProudMonkey.Common.Controls.dll and the AjaxControlToolkit.dll in your project solution
3. Right click on the project and select Add Reference
4. Click on the Browse tab and locate the two dlls mentioned in step 2
5. Click OK
6. Register the controls by adding the following lines below at the top most part of your page (ASPX).

<%@ Register assembly="ProudMonkey.Common.Controls"
             namespace="ProudMonkey.Common.Controls" tagprefix="cc1" %>
<%@ Register assembly="AjaxControlToolkit" 
             namespace="AjaxControlToolkit" tagprefix="asp" %>



7. Since the MessageBox control uses ASP.NET AJAX (AjaxControlToolKit 3.0.1106.0) then be sure to use the ToolkitScriptManager instead of ScriptManager. The ToolkitScriptManager can be found at the AjaxControlToolKit controls.
8. After that define the MessageBox control like below:

<cc1:MessageBox ID="MessageBox1" runat="server" />

 
9. Then you're good to go =}
Using The MessageBox Control
A . Server Side Approach (code behind)
MessageBox1.ShowError("Your Message");//Displaying an Error message 
MessageBox1.ShowWarning("Your Message");//Displaying a Warning message
MessageBox1.ShowInfo("Your Message");//Displaying an Information message
MessageBox1.ShowSuccess("Your Message");//Displaying a Successful message
Using the code above allows you to display the message box with its default size [ H(125) and W(300)]. If you want to set the MessageBox size by hand then you can use the overload method like: 

MessageBox1.ShowError("Your Message",300,400);
 

B. Client Side Approach (JavaScript)

ShowMsgBox('Error','Sample Error Message.');

Using the code above allows you to display the message box with its default size [H(125) and W(300)].If you want to set the MessageBox size by hand then you can use the overload method like:

ShowMsgBox('Error','Sample Success Message.',125,300);


Note that if you don't want to postback to the server after clicking OK then be sure to include "return false;" after calling the ShowMsgBox() method in the client.
The client side usage of the MessageBox control is quite different because we'll need to tell the method which message type we want to show to the user by specifying the first parameter as demonstrated above. So if you are going to display different message types via JavaScript then you can use either of these values below as the first parameter:
  • error
  • success
  • info
  • warning

The ConfirmBox Control - this customized control was created to provide a fancier look and feel confirmation message and added the “Don’t ask me again” option to end users. As we know, our standard thus far has been to include this confirmation step at every place within the application where we allow the user to perform a delete or critical operations.  For some users this confirmation step has become a little annoying.  So I have decided to look into what it would take to include the typical 'don't ask me question again' checkbox to my ConfirmationBox control.

Below is a sample screen shot of the ConfirmBox control:
Notes:
  • The "Don't ask me again" option will only be remembered across session, so if the page will be loaded again or refreshed then the confirmation box will display as normal.
  • The "Don't ask me again" option is unique for each control who calls it, so if you opt to display the confirm box for the Delete button then "Don't ask me again" will ONLY be applied for that control.
  • The default focus is set to NO
  • This control can only be called via client side

Sample Usage of the ConfirmBox Control:
ASPX Source:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <cc1:ConfirmBox ID="ConfirmBox1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
         OnClientClick="ShowConfirmBox(this,'Are you Sure'); return false;" />
    </div>
    </form>
</body>
CODE BEHIND:

using System;
using System.Web;
public partial class YetAnotherTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) {

    }
    protected void Button1_Click(object sender, EventArgs e) {
        Label1.Text = "PostBack Occured!";
    }
}

The FrameBox Control – This customized control was created to allow you to display a modal type of window for displaying external or internal sites within it. This control also provides an attribute in which developers can dynamically changed the header text of the frame. Take a look at the sample screen show below:
Sample Usage of FrameBox Control:

<%
@ Register assembly="ProudMonkey.Common.Controls" namespace="ProudMonkey.Common.Controls" tagprefix="cc1" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
    <cc1:FrameBox ID="FrameBox1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ShowFrameBox('Vinz Blog','http://geekswithblogs.net/dotNETvinz/Default.aspx');return false;" />
    </form>
</body>
</html>
That's it! I hope you'll find this control useful. Please let me know if you find any bugs. Also comments, suggestions and criticisms are welcome! =}


NOTE: Thanks To Vinz's Blog Credit Foes To Him...Iam Just the Media


For More Details Visit:http://proudmonkeycontrols.codeplex.com/