Tracing and Logging web service request in ASP.Net

This topic describes how to enable tracing and message logging in Web services built with ASP.NET. Enable tracing to identify how to increase performance and stability as well as increasing the ability to troubleshoot Web service issues. Tracing is only enabled when the application is fully trusted. Enable logging to log all the requests, which are posted to the endpoint.
For enabling the logging and tracing we need to make some configuration in application WEB.Config file and also need to ensure the permission of folder, that we specified in tag.
Configurations are given below:

<configuration>
<system.serviceModel>
  <diagnostics>
    <messageLogging 
         logEntireMessage="true" 
         logMalformedMessages="true"
         logMessagesAtServiceLevel="true" 
         logMessagesAtTransportLevel="false"
         maxMessagesToLog="3000"
         maxSizeOfMessageToLog="20000"/>
  </diagnostics>
</system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelMessageLoggingListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning,ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelTraceListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\Messagelog\app_messages.svclog"
          type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
          name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
      <add initializeData="C:\Messagelog\app_tracelog.svclog"
          type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
         name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>
</configuration>

Reliable Messaging with MSMQ and .NET

MSMQ stands for Microsoft Message Queuing is one of the most reliable way to sending and receiving messages from one system to another system; both system can be located at different geographical locations. The benefit of MSMQ is that the receiving application doesn’t have to run at the time of sending the message. Messages are stored in the queue of the system (Microsoft Operating System) and once the receiving application runs, it starts peeking the messages one by one.

To perform a task asynchronously is to execute it without waiting for a result. This type of processing allows we to start a time-consuming process and continue working without having to wait for that process to finish executing.
Asynchronous processing is ideal to use in many situations—especially on the Web, where a user’s request could take a long time to process, but we want to provide a response back to the user immediately. By handling the user’s request asynchronously, our system can respond regardless of how long that request may actually take to execute.

To install Message Queuing 4.0 on Windows Server 2008 or Windows Server 2008 R2

In Server Manager, click Features.
In the right-hand pane under Features Summary, click Add Features.
In the resulting window, expand Message Queuing.
Expand Message Queuing Services.
Click Directory Services Integration (for computers joined to a Domain), then click HTTP Support.
Click Next, then click Install.

To install Message Queuing 4.0 on Windows 7 or Windows Vista

Open Control Panel.
Click Programs and then, under Programs and Features, click Turn Windows Features on and off.
Expand Microsoft Message Queue (MSMQ) Server, expand Microsoft Message Queue (MSMQ) Server Core, and then select the check boxes for the following Message Queuing features to install:
MSMQ Active Directory Domain Services Integration (for computers joined to a Domain).
MSMQ HTTP Support.
Click OK.
If we are prompted to restart the computer, click OK to complete the installation.

To install Message Queuing 3.0 on Windows XP and Windows Server 2003

Open Control Panel.
Click Add Remove Programs and then click Add Windows Components.
Select Message Queuing and click Details.
System_CAPS_noteNote
If we are running Windows Server 2003, select Application Server to access Message Queuing.
Ensure that the option MSMQ HTTP Support is selected on the details page.
Click OK to exit the details page, and then click Next. Complete the installation.
If we are prompted to restart the computer, click OK to complete the installation.

To Check MSMQ interface:
My Computer -> Manage -> Services and Applications -> Message Queueing.

There are two types of Messaging Queue:
1. Public Queue:
Provide Message routing.
Public queues are accessed through “Machine nameQueue name”
2. Private Queue:
Do not Provide any routing.
Private queues are accessed through “Machine namePrivate$Queue name”.
If MSMQ is installed on the same machine as our application then we can replace the machine name with a dot, for example “.Private$testQue”

Creating a Queue in the system
Creating a queue in the system is an easy task. Go to My Computer and right click, select Manage and explore the nodes as displayed in the picture below.
IC163748
Right click the Private Queues and select New > Priovate Queue and create a queue. Alternatively, this can be done using C# code as well. My code snippet below does that automatically (ie. if queue doesn’t exists, it creates otherwise use the existing one).

Creating Queues Programmatically
Although the MSMQ interface is available for creating, deleting, and exploring message queues, we can also work with queues through the System.Messaging namespace. Several static methods (meaning we can call them without creating an actual instance of the class) have been provided on the MessageQueue class that give we the ability to check if a queue exists (Exists), create a queue (Create), and delete a queue (Delete). Using these methods, our application can check for the existence of a queue, and create it automatically if it does not exist. The function, GetQ, listed next provides the exact functionality just described:

 if (MessageQueue.Exists(@".\Private$\MyQueue"))
 {
     myQueue = new MessageQueue(@".\Private$\MyQueue");
 }
 else
 {
     myQueue = MessageQueue.Create(@".\Private$\MyQueue");
 }
Delete
 MessageQueue.Delete(@".\Private$\MyQueue")

Now, let’s send a message to the MSMQ
The following code example shows how to  send a message, setting a few options including formatting and encryption before using the MessageQueue object’s Send method with the preconfigured Message object:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessageSender
{
    class Program
    {
        static void Main(string[] args)
        {
            do
            {
                Console.WriteLine("Enter Message to be send");
                Console.WriteLine("High Priority Message should be start with HP:");
                string text = Console.ReadLine();

                MessageQueue myQueue;

                if (MessageQueue.Exists(@".\Private$\MyQueue"))
                {
                    myQueue = new MessageQueue(@".\Private$\MyQueue");
                }
                else
                {
                    myQueue = MessageQueue.Create(@".\Private$\MyQueue");
                }
                Message message = new System.Messaging.Message();
                message.Formatter = new BinaryMessageFormatter();
                message.Body = text;
                message.Label = "myTestMessage";

                if (text.Contains("HP:")) { message.Priority = MessagePriority.High; }
                else { message.Priority = MessagePriority.Normal; }
                myQueue.Send(message);
                Console.WriteLine("Message has sent");
            } while (Console.ReadKey().Key != ConsoleKey.Q);
        }
    }
}

One of the key message options we may wish to specify controls how the message is serialized for sending. By default, this is set to use XMLMessageFormatter, which serializes objects into an XML representation and is suitable for most purposes. Two other formatters are available, however: the BinaryMessageFormatter and ActiveXMessageFormatter, both of which serialize objects into a binary (not human-readable like XML) format.

Receiving messages from MSMQ
To receive a message from queue, we need to first instantiate the queue using MessageQueue. we will need to make sure that the queue exists, otherwise we shall get an error.
Once we have placed messages onto our queue, someone will likely wish to retrieve those messages, taking the data off the queue in the order in which it was added. To obtain a message from the queue, and then retrieve the data it contains, requires a few important steps:

* First, as with sending a message, obtain a MessageQueue object pointing at the       appropriate queue:
var myQueue = new MessageQueue(@”.\Private$\MyQueue”);
* Next, use the Receive method of the queue to obtain the first message from the queue:
Message message = myQueue.Receive();
* Then, if we are using the XML formatter (the default), set up the formatter of the Message object with a list of possible data types that might be contained in the message. In this case, we are expecting only one possible data type, String:
Message message = myQueue.Receive();
message.Formatter = new BinaryMessageFormatter();
* Finally, use the Body property to retrieve our data, casting it into the appropriate type:
Console.WriteLine(message.Body.ToString())

With large messages and slow network links in mind, the MessageQueue object provides an asynchronous way to receive messages in addition to the Receive method. To receive a message asynchronously, we proceed as before and obtain a reference to the appropriate queue, and then, instead of calling Receive, we will call BeginReceive (specifying a time-out if desired). This starts the receive process, and execution will continue immediately with the next line of code.
When a message has been successfully retrieved,and the MessageQueue object’s ReceiveCompleted event will fire and our event handler will be called. The retrieved message is sent to our event handler as part of one of its parameters, and we can use that object to retrieve the actual data as usual.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessageReceiver
{
    class Program
    {
        private static MessageQueue myQueue = null;
        private static object lockObject = new object();

        static void Main(string[] args)
        {
            Console.WriteLine("Received Messages");

            myQueue = new MessageQueue(@".\Private$\MyQueue");
            // Setup an event to listen for new messages.
            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);

            // Start listening.
            myQueue.BeginReceive();
            /*Message message = myQueue.Receive();
            message.Formatter = new BinaryMessageFormatter();
            Console.WriteLine(message.Body.ToString());*/
            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                // Press q to exit.
            }
        }


        static void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            lock (lockObject)
            {
                // The message is plain text.
                e.Message.Formatter = new BinaryMessageFormatter();
                string text = (string)e.Message.Body;
                Console.WriteLine("Message received: " + text);
            }

            // Listen for the next message.
            myQueue.BeginReceive();
        }
    }
}

tutorial: https://www.youtube.com/watch?v=ZHiu81Gqb_o

Browser Definition File

Browser definition files contain definitions for individual browsers. At run time, ASP.NET uses the information in the request header to determine what type of browser has made the request. Then ASP.NET uses browser files to determine the capabilities of the browser, and how to render markup to that browser. This is useful to Web developers who want to create applications that can be viewed on mobile devices, making use of control adapters that adapt the behavior of an ASP.NET Web server control depending on the type of device.

Note:
Browser definition files are new in the .NET Framework version 2.0. 
In earlier versions of the .NET Framework, the browserCaps element was used to define browser definitions in configuration files.

ASP.NET fails to detect IE10+ causing _doPostBack is undefined JavaScript error or maintain FF5 scrollbar positionimage_3
There is a bug in the browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10+) aren’t within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

We can fix this problem by updating Browser Definition File, One of the simplest way to update the Browser Definition File is just install the latest Frame Work version to the hosted server

Author : Rony T Sam

C# and Framework Versions

FrameworkThere are lots of different versions of different elements of development. You need to distinguish between the versions of Visual Studio (the IDE), C# (the language) and .NET (the framework). It’s quite hard to talk about each of these individually without bringing in other pieces, but I’ll see what I can do… Note that I’ll avoid introducing the CLR versions as well, as most developers don’t really need to know about that.

These are the versions of C# known about at the time of this writing:

.NET Framework versions

There have been seven significant releases of the .NET Framework, excluding service packs. The framework includes the compilers, runtime, and libraries. Additionally, there are other profiles such Silverlight which complicate matters.

1.0 – released in 2002
1.1 – released in 2003
2.0 – released in 2005, with a new CLR (to handle generics and nullable types) and compilers for C# 2 and VB 8.
3.0 – released in 2006, this is just 2.0 plus new libraries: Windows Presentation Foundation, Windows Communication Foundation, Workflow Foundation, and Cardspace
3.5 – released in 2007, this is 3.0 plus new libraries (primarily LINQ and some extra “base” libraries such as TimeZoneInfo) and new compilers (for C# 3 and VB 9)
4.0 – released in 2010, this includes a new CLR (v4), new libraries, and the DLR (Dynamic Language Runtime)
4.5 – released in 2012, this allows for WinRT development on Windows 8 as well as extra libraries – with much wider async APIs
C# language versions

There are five significant language versions:

C# 1
C# 2, introducing generics, nullable types, anonymous methods, iterator blocks and some other more minor features
C# 3, introducing implicit typing, object and collection initializers, anonymous types, automatic properties, lambda expressions, extension methods, query expressions and some other minor features
C# 4, introducing dynamic typing, optional parameters, named arguments, and generic variance
C# 5, introducing asynchronous functions, caller info attributes, and a tweak to foreach iteration variable capture
See the specifications page for downloads for each version, from Microsoft and ECMA.

Visual Studio versions

For a long time, releases of Visual Studio were closely tied to framework releases. The picture has become a bit more flexible and complicated, however:

VS.NET 2002 – support for C# 1 and .NET 1.0
VS.NET 2003 – support for C# 1 and .NET 1.1
VS 2005 – support for C# 2 and .NET 2.0, and .NET 3.0 with an extension
VS 2008 – support for C# 3 and .NET 2.0, 3.0 and 3.5 (multi-targeting)
VS 2010 – support for C# 4 and .NET 2.0, 3.0, 3.5 and 4
VS 2012 – support for C# 5 and .NET 2.0 to 4.5 (including WinRT on Windows 8), and portable class libraries

More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site.

Author : Rony T Sam

What is the Difference Between ViewBag and ViewData in MVC 3?

Introduction

ViewBag and ViewData serve the same purpose in allowing developers to pass data from controllers to views. When we put objects in either one, those objects become accessible in the view. This is one way we interact between the view and the controller in ASP.NET MVC. We pass data from the view to the controller by placing it in these objects.

How ViewData Works

ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:

In the Controller

public ActionResult Index()
{
    var softwareDevelopers = new List<string>
    {
        "Brendan Enrick", 
        "Kevin Kuebler", 
        "Todd Ropog"
    };

    ViewData["softwareDevelopers"] = softwareDevelopers;

    return View();
}

In the View

<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
    <li>
        @developer
    </li>
}
</ul>

Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.

How ViewBag Works

ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:

In the Controller

public ActionResult Index()
{
    var softwareDevelopers = new List<string>
    {
        "Brendan Enrick", 
        "Kevin Kuebler", 
        "Todd Ropog"
    };

    ViewBag.softwareDevelopers = softwareDevelopers;

    return View();
}

In the View

<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
    <li>
        @developer
    </li>
}
</ul>

Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.

ViewBag and ViewData Under the Hood

So these two things seem to work almost exactly the same. What’s the difference? The difference is only in how you access the data. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you use dynamics to access the data instead of using magic strings. Some people prefer one style over the other. You can pick whichever you like. In fact, because they’re the same data just with two different ways of accessing it, you can use them interchangeably. (I don’t recommend this, but you can do it.) If you want you are able to put data into the ViewBag and access it from the ViewData or put stuff in the ViewData and access it in the ViewBag.

This is all that the ViewBag property is. It’s just a DynamicViewDataDictionary with the ViewData as its data.

public dynamic ViewBag 
{ 
    get 
    { 
        if (_dynamicViewData == null) 
        {
            _dynamicViewData = 
                new DynamicViewDataDictionary(() => ViewData); 
        }
        return _dynamicViewData;
    }
}

Then when we access the dynamic members of the DynamicViewDataDictionary, we are actually just getting this override of the DynamicObject’s TryGetMember. In this method, it’s just using the name of the member we tried to access as the string key for the ViewData dictionary.

public override bool TryGetMember(
    GetMemberBinder binder, out object result)
{
    result = ViewData[binder.Name]; 
    return true;
}

These two objects are two different ways of accessing the exact same data. The ViewBag is just a dynamic wrapper around the ViewData dictionary.

How to call Server Side function from Client Side in ASP.NET?

Call Server Side function from Client Side Code using PageMethods in ASP.NET and jQuery

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. Here we are using jQuery AJAX to call serverside method.

1. Create a new website.
2. Open the Default.aspx include jquery library to the page.
<script src=”Scripts/jquery-1.4.1.js” type=”text/javascript”></script>
3. Add an html button in the page

<input type=”button” value=”Get Methhod” id=”btnGetMethod” />

4. Go the Code behind file of the page and add a static method and mark them as WebMethod. Lets Say the method name is GetPageMethod which returns a status value

[System.Web.Services.WebMethod]        
public static string GetPageMethod()
{
      return “Welcome PageMethods”;
}

5. Go back to the aspx page and write the following jquery script.
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#btn1’).live(‘click’, function () {
$.ajax({
type: “POST”,
url: “Default.aspx/GetPageMethod”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (msg) {
alert(msg.d);
}
});
});

});

</script>
6. Run the application.

                                                       Author: Aneesh Sivan

What is a Web service?

Definition:

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

  • Web Services can convert your applications into Web-applications.
  • Web Services are published, found, and used through the Web.

What are Web Services?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

Web Services have three basic platform elements: SOAP, WSDL and UDDI.

1.SOAP (Simple Object Access Protocol)

SOAP is a protocol for accessing a Web Service. SOAP provides a standard, extensible, composable framework for packaging and exchanging XML messages.

  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is a format for sending messages
  • SOAP is designed to communicate via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP is a W3C standard

2. WSDL (Web Services Description Language ).

WSDL is an XML-based language for locating and describing Web services.WSDL describes Web services starting with the messages that are exchanged between the requester and provider agents. The messages themselves are described abstractly and then bound to a concrete network protocol and message format.

  • WSDL stands for Web Services Description Language
  • WSDL is based on XML
  • WSDL is used to describe Web services
  • WSDL is used to locate Web services
  • WSDL is a W3C standard

3. UDDI (Universal Description Discovery and Integration)

UDDI is a directory service where companies can register and search for Web services. UDDIis a platform-independent, Extensible Markup Language (XML)-based registry for businesses worldwide to list themselves on the Internet and a mechanism to register and locate web service applications.

  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory for storing information about web services
  • UDDI is a directory of web service interfaces described by WSDL
  • UDDI communicates via SOAP
  • UDDI is built into the Microsoft .NET platform

Learn ASP.NET Web Services  from MSDN >>

What is the difference between VB.NET and C#?

Advantages VB.NET

• Has support for optional parameters that makes COM interoperability much easy.
• With Option Strict off late binding is supported.Legacy VB functionalities can be
used by using Microsoft.VisualBasic namespace.
• Has the WITH construct which is not in C#.
• The VB.NET parts of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very
large projects have found that the IDE slows down considerably as the project
gets larger.

Advantages of C#

• XML documentation is generated from source code but this is now been
incorporated in Whidbey.
• Operator overloading which is not in current VB.NET but is been introduced in
Whidbey.
• Use of this statement makes unmanaged resource disposal simple.
• Access to Unsafe code. This allows pointer arithmetic etc, and can improve
performance in some situations. However, it is not to be used lightly, as a lot of
the normal safety of C# is lost (as the name implies).This is the major difference
that you can access unmanaged code in C# and not in VB.NET.

Reference:
.NET Interview Questions 4 th Edition By Shivprasad Koirala

What is Serialization in .Net?

Serialization

Serialization is the process of saving the current state of any object into persistent storage (like file system), so that it can be retrieved later (Deserialize) and re create the same object.
For example, you have an object called student. You assign some values into the properties of this student object and serialze this object into a file. You can keep this file and de serialize any time later to re produce your student to the saved state.

What is serializable class ?

If a class can be serialized by using the builtin serialization features in .NET, that class is called serializable class. Most of the classes provided by .NET Framework is serializable.

Different types of Serialization

There are two broad categories of serialization in .NET
1. XML Serialization
2. Binary Serialization

XML Serialization serializes the object into an xml file. This file is human readable and can be shared with other applications.

Binary serialization is more efficient, but the serialized file is in binary format. It may not make any sense for a human being to open this file and understand what it contains. It is a stream of bytes.

Can I make my own classes serializable ?

Yes, it is very easy to make any class serializable. Simply add an attribute called ‘Serializable’ just above the class declaration and your class is serializable – means anybody can write few lines of C# code to save the state of the instance of your class into disk and retrieve (deserialize) later.

[Serializable]
public class MyClass
{
public string name;
public string adress;
}

How to serialize classes ?

The following samples demonstrate how to do XML Serialization and Binary Serialization using .NET classes.
We are serializing an ‘ArrayList’ object into disk and deserializing it again from the disk into another array list.
If you are not familiar with ArrayList – it is a collection class provided by .NET Framework, which can hold a list of any objects. The sample shown below uses an ArrayList which holds a list of strings.

XML Serialization

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( “john” );
itemsToSerialize.Add ( “smith” );
XmlSerializer serializer = new XmlSerializer( typeof(ArrayList) );
TextWriter writer = new StreamWriter( @”MyApplicationData.xml” );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

In the first step, we are creating an array list and adding two strings into it. next step is to create an instance of XmlSerializer class, which is provided by .NET Framework to help serialize any objects. In the constructor of XmlSerializer class, we have to specify what type of object we want to serialize using this. Since we are going to serialize an ArrayList, we are specifying ‘typeof(ArrayList)’.
Next, we are going to do the real thing – saving the state of the ArrayList into an XML file. We will create a TextWriter object and specify the xml file name to which we will save the ArrayList.

The following lines will save the arraylist ‘itemsToSerialize’ into the file ‘MyApplicationData.xml’:

TextWriter writer = new StreamWriter( @”MyApplicationData.xml” );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

Now, you can check the folder where your application executable is. A file with the name ‘MyApplicationData.xml’ will be created and you can open the file in any text editor to see the content.

Deserialization

We have serialized an arraylist into an xml file. This means, the state of the arraylist is saved into the xml file. So, we should be able to retrieve the same arraylist from this xml file. The following code will deserialize the arraylist from the xml file.

Stream stream = new FileStream( @”MyApplicationData.dat”, System.IO.FileMode.Open );
IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );
stream.Close();

Just few lines of code ! The above code will read the XML file ‘MyApplicationData.dat’ and restore the arraylist ‘itemsDeserialized’ – means the list of items we originally saved into the XML file will be loaded back to the array list. Now the arraylist ‘itemsDeserialized’ will contain two strings ‘john’ 7 ‘smith’ whcih we saved as part of the serialization process.

Binary Serialization

Binary serialization is pretty much same as XML serialization, except that the data stored in a stream of bytes, not in XML format. See the sample code :

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( “john” );
itemsToSerialize.Add ( “smith” );

Stream stream = new FileStream( @”MyApplicationData.dat”, System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );
stream.Close();

The above code sample will serialize the arraylist ‘itemsToSerialize’ into the file ‘MyApplicationData.dat’.

Deserializing the binary data

The objects serialized using binary formatter can be deserialized the same way.

Stream stream = new FileStream( @”MyApplicationData.dat”, System.IO.FileMode.Open );
IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );
stream.Close();

The above sample will read the file ‘MyApplicationData.dat’ and restore the arraylist ‘itemsDeserialized’.

Where is Serialization used?

Serialization has lot of uses in application development. One important purpose is to transmit data between application domains. Webservices and remoting uses serialization/deserialization technique to exchange data.
When you call a webservice and pass parameters, the parameters are serialized into XML data and send to the server. When the webservice return data, the result is serialized into XML and returned to the caller. This means, you can pass only serializable data in web service calls.
In Remoting, you can choose either Binary or SOAP(XML) formatting. Depending on what format you choose, data is serialized using xml or binary format and exchanged between the server and client.
In addition to the above, you can use serialization as a way to store the application data into files. For example, you want to save the last logged in user name, but you don’t have a database. You can serialize the user object itself or serialize just the name of the user into disk. When you start the application next time, you can deserialize the user name from the serialized data. Many of the applications use this serialization mechanism to remember the user settings and application data.

 Author: Anju Philip

How to setup an SQL connection in .Net (C#)?

SQL connection setup Steps

Step1: Create a Database (Eg MyFirstDB)
Step2: Create a table in MyFirstDB (Eg Tbl_MyFirstTable)
Step3: Create a new project in Visual Studio.
Step4: Establish Connection using SQL Client (As Shown below)

Open the aspx.cs page (Eg: Default.aspx.cs)
Use the following code.

Using System.Data;
Using System.Data.SqlClient;
public partial class Home : System.Web.UI.Page
{
string conString = @”Data Source=SERVER1;Initial Catalog=MyFirstDB;User ID=sa;Password=password”;
SqlConnection objConnection;

protected void Page_Load(object sender, EventArgs e)
{

objConnection=new SqlConnection(conString);

}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
objConnection.Open();
Label1.Text = “Connection opened successfully”;
objConnection.Close();
Label1.Text = “Connection closed successfully”;
}
catch
{
Label1.Text = “Connection failed”;
}
}
}

Read More from MSDN