Rashim's Blog


Today my team lead shoves me into an R&D to trace and log WCF soap messages. Then I have started reading different blogs post and books as well. After reading couple of useful blog specially my favorite one MSDN I come across the solutions that I want to share with you guys.

First of all, we know that, by default WCF does not record any messages. To initiate message logging, we have to add a trace listener to the System.ServiceModel.MessageLogging trace source and set attributes for the messageLogging element in the configuration file.To permit logging and tracing we have to inset and stipulate some extra options in the formation.

The following example shows how to allow logging and specify essential options.

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging">
      <listeners>
        <add name="ServiceModelMessageLoggingListener">
          <filter type=""/>
        </add>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add initializeData="D:\SoapLog\Messages.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
      <filter type=""/>
    </add>
  </sharedListeners>
</system.diagnostics>

In the example configuration I have used sharedListeners which contains listeners but listeners in the sharedListeners collection are not placed in a Listeners collection. They must be added by name to the trace Element. In the example, the Listener name is “ServiceModelMessageLoggingListener” which is added to the sharedListeners collection and which adds the standard .NET Framework trace listener (System.Diagnostics.XmlWriterTraceListener) as the type to use. If we use System.Diagnostics.XmlWriterTraceListener, we have to stipulate the output file location and name in the configuration file. This is done by setting initializeData to the name of the log file. Otherwise, the system throws an exception. We can also implement a custom listener that releases logs to a default file.

WCF logs messages at two different levels, service and transport. Malformed messages are also logged. The three categories are self-governing from each other and can be triggered separately in configuration.We can control these levels by setting the logMessagesAtServiceLevel, logMalformedMessages, and logMessagesAtTransportLevel attributes of the messageLogging element.

So the messageLogging attributes can be look like below,

<messageLogging
logEntireMessage="true"
logMalformedMessages="true"
logMessagesAtServiceLevel="false"
logMessagesAtTransportLevel="true"
maxMessagesToLog="2147483647"
maxSizeOfMessageToLog="2147483647"
/>

Like Logging, tracing is not also supported by default. To initiate tracing, we have to form a trace listener and set a trace level for the trace source in configuration. Otherwise, WCF does not produce any traces.

WCF outputs the following data for diagnostic tracing:

  • Operation calls
  • Code exceptions
  • Warnings and other significant processing events.
  • Windows error events when the tracing feature malfunctions.

As like logging the following example shows how to allow tracing and specify essential options.

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="ServiceModelTraceListener">
          <filter type=""/>
        </add>
      </listeners>
    </source>
    <sharedListeners>
      <add initializeData="D:\SoapLog\Tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
        <filter type=""/>
      </add>
    </sharedListeners>
  </system.diagnostics>

So the configuration file looks like,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <diagnostics>
      <messageLogging
      logEntireMessage="true"
      logMalformedMessages="true"
      logMessagesAtServiceLevel="false"
      logMessagesAtTransportLevel="true"
      maxMessagesToLog="2147483647"
      maxSizeOfMessageToLog="2147483647"
/>
    </diagnostics>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="00:01:00"
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
        bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
        maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
        allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
          enabled="false" />
          <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
            realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
            algorithmSuite="Default" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:8732/Design_Time_Addresses/Rashim.RnD.TracingSoapMessage.Services/Service/"
      binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
      contract="ServiceReference.IService" name="WSHttpBinding_IService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="ServiceModelTraceListener">
            <filter type=""/>
          </add>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="ServiceModelMessageLoggingListener">
            <filter type=""/>
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="D:\SoapLog\Tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
        <filter type=""/>
      </add>
      <add initializeData="D:\SoapLog\Messages.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
        <filter type=""/>
      </add>
    </sharedListeners>
    <trace autoflush="true"/>
  </system.diagnostics>
</configuration>

In order, to prevent anti-virus blocking, you should open Visual Studio and open your project, then from Project menu select “Properties” and you will come to the properties page.

Now click “Security” tab and check the “Enable ClickOnce Security Settings” also provide information inside the assembly info dialog.

Then you need to create the Application Manifest file and put the input here like below

<requestedExecutionLevel level="asInvoker"/>

What it means is that the application runs with the same access token as the parent process. If you want to know more please have a look on that [^].


We, the developers, always try to look into the performance when we develop an application. Is there any developer who wants his application to freeze or smash? But what are the steps a developer should yield to keep it all smooth going. When I used to develop this application, I saw whenever I attempt to copy files from one directory to other it includes CPU as well as hard drive. The major fallback of it is to limit a user to execute one task at a time. So how do we deal with application freezing and smashing?

By using threads through which we can handle all the jobs simultaneously under one main application thread. You can perform smaller operations with the help of threading class; instead I prefer using Background Worker class to implement to perform all my heavy duty operations. Background Worker is used to execute long running operations on a separate thread, support cancellation, progress reporting and marshalling results back to the UI thread. As I have offered the smooth UI which shows the operation details and at the same time the operation will continue in the background, I choose this one to use. If you want to know in details about the Background Worker, you can read this article.

The main mechanism is that when the user clicks the start button, it issues the event OnCopyStarted and the event handler is responsible for Copying data while at the same time OnUIChanged was getting issued and do some enable/disable UI Controls, when we click stop button, it issued the OnCopyStoppedEvent and at the same time it checks the Background worker’s working status does Background worker finish/Cancel its task or not. If not, it pops up the dialog window for a moment and waits for Background worker to be free, once the Backgroundworker gets free, the Dialogue will automatically dispose. Here I have used one way binding. So any changes in property value will reflect to the UI but changing the UI will not reflect on the properties.

You will find the full article here[^]


Some days ago when I was working in PRISM I needed to send some notifications from one view to another based on some business logic. This is something like that, if a view receives any notification from other resources, the view requires changing its appearance. To handle this type of situation we usually remove the view, update its properties and add the view in the particular region again. Another way we do it by using the .NET framework’s Events mechanism but this is not loosely coupled.

In PRISM there is a nice way to do that specially to communicate in different view/Module (User controls, Entities, External project resources and so forth) by using EventAggregator service.

The EventAggregator service is primarily a container for events that allow decoupling of originators and receivers so that they can develop autonomously.

I share with you some of my code portion in which I have used EventAggregator service,

This is the entity class,

public class Company
{
    public Company()
    { }

    public int CompanyID { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Postcode { get; set; }
    public Country Country { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
}

The event that i have used has been given below. The publisher and subscriber will use this event to communicate with themselves,

public class CompanyAddedEvent : CompositePresentationEvent<Company>
{
}

MyEventAggregator class which is basically for the EventAggregator instance,

public class MyEventAggregator
{
    private static EventAggregator myEventAggregator = null;

    private static readonly object syncLock = new object();

    private MyEventAggregator() { }

    public static EventAggregator GetEventAggregator()
    {
        lock (syncLock)
        {
            if (myEventAggregator == null)
            {
                myEventAggregator = new EventAggregator();
            }

            return myEventAggregator;
        }
    }
}

Event Publishing,

MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Publish(your company Object);

Event Subscription,

MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Subscribe((company) =>
        {
            ////DO Whatever you want
        }, false);

One thing here i need to add, the publisher and subscriber do not have a direct reference to each other.That is multiple publishers can raise the same event and multiple subscribers can listen to the same event.

In this way, the event may subscribe by the different view/module and, once the event is published, the subscriber will get the notification and can start its task according that. This is a very easy stuff but by using this facility you could do very nice and cool things..However,If you want to know in details please have a look on that [^]


I wanna to introduce you with a nice and exciting thing. I assume you will be promoted from it. The web designer always passes his time in pain as his design work sometimes works perfectly in Mozilla but not in IE, or works in latest versions of the browser but not in the previous versions of many browsers and many more … So; will it not be superior for him to trial his work in all browsers with all/possible versions? Is it possible for him to test his design in all browsers with all versions in a single place?

Yes, this is possible. By using Browsershots you could do it.

Browsershots creates screenshots of your web design in diverse operating systems and browsers. It is a  online web application providing developers a convenient way to test their website’s browser compatibility in one place. When you submit your web address, it will be added to the job queue. A number of distributed computers will open your website in their browser. Please have a look on [^]


Last year I was assigned to develop a IoC container for R&D purposes which make me to start working with the IoC Cointainer

Anyway…
I share with you part of it as I think that, it might help you a lot to develop your own container.

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about eliminating dependencies from your code. Dependency injection is also usually well-known as “inversion of control” who’s Principle is – “Don’t call us, we’ll call you”. So simply we can say that IoC is the principle whereas DI is the way of implementation. There are three popular ways of inversion of control namely

  1.  Constructor Injection
  2.  Method Injection
  3.  Property Injection

Well,I am not going to discuss about IoC or DI rather i wanna to show how to implement our own IoC Container. However if you wanna to know in details about IoC and DI please have a look on the Link[^]

Lets move to our code portion,

public static class IoC
{
    private static readonly IDictionary<Type, Type> types = new Dictionary<Type, Type>();
    private static readonly IDictionary<Type, object> typeInstances = new Dictionary<Type, object>();
    public static void Register<TContract, TImplementation>()
    {
        types[typeof(TContract)] = typeof(TImplementation);
    }
    public static void Register<TContract, TImplementation>(TImplementation instance)
    {
        typeInstances[typeof(TContract)] = instance;
    }
    public static T Resolve<T>()
    {
        return (T)Resolve(typeof(T));
    }
    public static object Resolve(Type contract)
    {
        if (typeInstances.ContainsKey(contract))
        {
            return typeInstances[contract];
        }
        else
        {
            Type implementation = types[contract];
            ConstructorInfo constructor = implementation.GetConstructors()[0];
            ParameterInfo[] constructorParameters = constructor.GetParameters();
            if (constructorParameters.Length == 0)
            {
                return Activator.CreateInstance(implementation);
            }
            List<object> parameters = new List<object>(constructorParameters.Length);
            foreach (ParameterInfo parameterInfo in constructorParameters)
            {
                parameters.Add(Resolve(parameterInfo.ParameterType));
            }
            return constructor.Invoke(parameters.ToArray());
        }
    }
}

Now from your bootStrapper class you need to register your class like,

 Service svc = new Service();
 IoC.Register<IService, Service>(svc);

On a subsequent Classes you just need to inject the Interface or class that you register like,

private IService currentSvc = null;
public LoginServices(IService  submittedService)
{
   this.currentSvc =submittedService;
}

Very very Simple!!!! We love simple, don’t we?

Updated:19th March2012

Example: Say this is my Interface,

public interface ILogger
    {
        void Log(string submittedMsg);
    }

The Logger class implements this interface.

public class Logger : ILogger
{
    public void Log(string submittedMsg)
    {
        if (this != null && !string.IsNullOrEmpty(submittedMsg))
        {
            Console.WriteLine(string.Format("[{0}] {1}\r\n", DateTime.Now, submittedMsg));
            Console.Read();
        }
    }
}

In this ConsoleLogger class I inject the ILogger to its constructor,

public class ConsoleLogger
{
    private ILogger logger = null;

    public ConsoleLogger(ILogger submittedLogger)
    {
        this.logger = submittedLogger;
        this.DisplayMessage();
    }

    public void DisplayMessage()
    {
        logger.Log("Hi!!");
    }
}

Register and Resolve options,

class Program
{
    static void Main(string[] args)
    {
        IoC.Register<ILogger, Logger>();

        IoC.Register<ConsoleLogger, ConsoleLogger>();
        ConsoleLogger objCOnsoleLogger = IoC.Resolve<ConsoleLogger>();
    }
}

We always need to work with images to display it on the landscape or portrait mode. To do that we need to calculate the image size also need to generate the image dimension. This is very easy stuff though we are fighting a lot!!!

private Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
    {
        double multiplier = 0;
        string layout;
        if (currH > currW)
        {
            layout = "portrait";
        }
        else
        {
            layout = "landscape";
        }

        switch (layout.ToLower())
        {
            case "portrait":
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }
                break;
            case "landscape":
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }

                break;
        }

        return new Size((int)(currW * multiplier), (int)(currH * multiplier));
    }

Say i have a Database table name Employee and has 4 columns like ID, Firstname, Lastname,Email etc. That is, there is no Fullname Column but we need it to display it on the UI. So what we usually do?
We fetch all data; iterate over the list of data to make the Fullname String, right?
But there is another nice way to do that, if we get the property Fullname like Firstname or Lastname then it might help us a lot for further processing.
What I did for that, I have an Employee class in my dbml file. So I have created a partial Class name Employee in which I have define a Property Fullname as read-only. So when we get the Object Employee we will get the property Fullname also.

public partial class Employee
{
    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", this.Firstname, this.LastName);
        }
    }
}

Very Simple but Handy !!!!!!


Sometimes we need to save data to Excel file using Microsoft Excel. To do that we might need to create the Excel file, need to create table on that with some columns and then save data to the table of Excel file. This is pretty easy enough. Have a look on that.

Save Data to Excell Table,


        private void InsertDataOnExcellTable(string submitttedExcellPath, Test submittedExcellData)
        {
            if (!string.IsNullOrEmpty(submitttedExcellPath) && submittedExcellData != null)
            {
                if (!string.IsNullOrEmpty(submittedExcellData.FileName))
                {
                    var fullFileName = submitttedExcellPath + Path.DirectorySeparatorChar + submittedExcellData.FileName;

                    var xlFileExtension = ".xls";

                    if (!fullFileName.Contains(xlFileExtension))
                    {
                        fullFileName = fullFileName + xlFileExtension;
                    }

                    string connectionString = ConnectionString.GetConStr(fullFileName);

                    if (!string.IsNullOrEmpty(connectionString))
                    {
                        if (this.CreateTableOnExcell(fullFileName, connectionString) == true)
                        {
                            lock (new object())
                            {
                                System.Data.OleDb.OleDbConnection myConnection;
                                var myCommand = new System.Data.OleDb.OleDbCommand();
                                string sql = null;

                                myConnection = new System.Data.OleDb.OleDbConnection(connectionString);
                                myConnection.Open();
                                myCommand.Connection = myConnection;
                                sql = "Insert into [Sheet1$] "
                                + "( "
                                + "[Title],[FirstName],[Surname],[Email],[TelePhoneNumber],[OrderNumber],[SubmissionDate]"
                                + " )"
                                + " values "
                                + "('" + submittedExcellData.Title + "','" + submittedExcellData.FirstName + "','" + submittedExcellData.SurName + "','" + submittedExcellData.Email + "','" + submittedExcellData.TelePhoneNumber + "','" + submittedExcellData.OrderNumber + "','" + submittedExcellData.SubmissionDate + "')";

                                myCommand.CommandText = sql;
                                myCommand.ExecuteNonQuery();
                                myConnection.Close();
                            }
                        }
                    }
                }
            }
        }

Create table on Excell file,


        private bool CreateTableOnExcell(string submittedFullPath, string submittedConnStr)
        {
            if (!string.IsNullOrEmpty(submittedConnStr) && !string.IsNullOrEmpty(submittedFullPath))
            {
                if (this.CreateExcellFile(submittedFullPath))
                {
                    lock (new object())
                    {
                        OleDbConnection connExcel = new OleDbConnection(submittedConnStr);
                        OleDbCommand cmdExcel = new OleDbCommand();
                        cmdExcel.Connection = connExcel;
                        System.Data.DataTable excelSchema = null;

                        try
                        {
                            ////Check if the Sheet Exists
                            connExcel.Open();
                            excelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        }
                        catch
                        {
                        }
                        finally
                        {
                            connExcel.Close();
                        }

                        DataRow[] dr = excelSchema != null ? excelSchema.Select("TABLE_NAME = 'Sheet1'") : null;

                        ////if not Create the Sheet
                        if (dr == null || dr.Length == 0)
                        {
                            string excelCommand = "CREATE TABLE";

                            string sheetName = "[Sheet1]";

                            ////All Column Name
                            StringBuilder tableColumn = new StringBuilder();
                            tableColumn.Append("(");
                            tableColumn.Append("Title varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("FirstName varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("Surname varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("Email varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("TelePhoneNumber varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("OrderNumber varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("SubmissionDate varchar(20)");
                            tableColumn.Append(")");
                            tableColumn.Append(";");

                            StringBuilder exelQuery = new StringBuilder();
                            exelQuery.Append(excelCommand);
                            exelQuery.Append(" ");
                            exelQuery.Append(sheetName);
                            exelQuery.Append(" ");
                            exelQuery.Append(tableColumn.ToString());

                            if (cmdExcel != null)
                            {
                                cmdExcel.CommandText = exelQuery.ToString();
                                connExcel.Open();
                                cmdExcel.ExecuteNonQuery();
                                connExcel.Close();
                            }
                        }
                    }

                    return true;
                }
            }

            return false;
        }

Create Excel file,


        private bool CreateExcellFile(string submittedFullPath)
        {
            if (!string.IsNullOrEmpty(submittedFullPath))
            {
                lock (new object())
                {
                    if (!File.Exists(submittedFullPath))
                    {
                        ////Ex = Microsoft.Office.Interop.Excel;
                        Ex.Application exelApp = null;
                        Ex.Workbook exelWorkBook = null;
                        Ex.Worksheet exelWorkSheet = null;
                        object misValue = System.Reflection.Missing.Value;

                        try
                        {
                            ////Create an Excell Application
                            exelApp = new Ex.ApplicationClass();

                            if (exelApp != null)
                            {
                                if (exelApp.Workbooks != null)
                                {
                                    ////Add an Workbook to the current Excell Application
                                    exelWorkBook = exelApp.Workbooks.Add(misValue);
                                }
                            }

                            if (exelWorkBook != null)
                            {
                                ////Getting Sheet1
                                exelWorkSheet = (Ex.Worksheet)exelWorkBook.Worksheets.get_Item(1);

                                if (exelWorkSheet != null)
                                {
                                    //// Naming the Table Data Column
                                    exelWorkSheet.Cells[1, 1] = "Title";
                                    exelWorkSheet.Cells[1, 2] = "FirstName";
                                    exelWorkSheet.Cells[1, 3] = "Surname";
                                    exelWorkSheet.Cells[1, 4] = "Email";
                                    exelWorkSheet.Cells[1, 5] = "TelePhoneNumber";
                                    exelWorkSheet.Cells[1, 6] = "OrderNumber";
                                    exelWorkSheet.Cells[1, 7] = "SubmissionDate";
                                }

                                ////Save the Excell file to its Specified location
                                exelWorkBook.SaveAs(submittedFullPath, Ex.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Ex.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                            }
                        }
                        catch
                        {
                        }
                        finally
                        {
                            if (exelWorkBook != null)
                            {
                                exelWorkBook.Close(true, misValue, misValue);
                            }

                            if (exelApp != null)
                            {
                                exelApp.Quit();
                            }
                        }

                        this.ReleaseObject(exelWorkSheet);
                        this.ReleaseObject(exelWorkBook);
                        this.ReleaseObject(exelApp);
                    }

                    return true;
                }
            }

            return false;
        }

Release the Object by force,

private void ReleaseObject(object submittedObj)
        {
            try
            {
                //// By force realeasing the Object if the Garbage Collector not doing it right now
                System.Runtime.InteropServices.Marshal.ReleaseComObject(submittedObj);
            }
            catch
            {
            }
            finally
            {
                GC.Collect();
            }
        }

And then the Connection String,


        public static string GetConStr(string submittedPath)
        {
            var connectionString = string.Empty;

            if (!string.IsNullOrEmpty(submittedPath))
            {
                connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + submittedPath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=0\"";
            }

            return connectionString;
        }


Object Serialization, which is also called deflating or marshaling, is a progression through which an object’s state is converted into some serial data format, such as XML or binary format, in order to be stowed for some advanced use whereas Deserialization is the opposite process of Serialization which is also called inflating or unmarshalling. The code showing the very simple way for serializing and deserializing from XML to any Object and vice versa as well,

Use this method for serialization,


        public static string Serialize<T>(T value)
        {
            if (value == null)
            {
                return null;
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UnicodeEncoding(false, false);
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;

            using (StringWriter textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }

                return textWriter.ToString();
            }
        }

Use this method for Deserialization,


        public static T Deserialize<T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return default(T);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlReaderSettings settings = new XmlReaderSettings();

            using (StringReader textReader = new StringReader(xml))
            {
                using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                {
                    return (T)serializer.Deserialize(xmlReader);
                }
            }
        }

Blog Stats

  • 189,442 hits

Categories

%d bloggers like this: