New Ways of Accessing Data : Presenting in Kolkata Community Tech Days

Hi Friends I will be delivering a session in Kolkata Community Tech Days on 2nd July.

image

Read Kolkata session details here

Register here

Session details are as follows,

Address:
Rotary Sadan
94/2 Chowringhee Road
Kolkata – 700020

Date: 2nd July 2011

Title: New ways of accessing your Data

Abstract:

This demo oriented session will explore various newest way of accessing data. Session would contain explanations and demo on LINQ, LINQ to SQL, LINQ to XML, LINQ to SQL Azure, ADO.Net Entity Model and OData. Data consumption and manipulation from rich clients like Silverlight and Windows Phone 7 would be also covered in the session.

Demo would probably contain below topics

1. LINQ

  • Applying LINQ against data in memory
  • LINQ to SQL Class ORM
  • Performing CRUD operation using LINQ to SQL Class
  • Stored Procedures in LINQ to SQL
  • Applying LINQ to data as XML
  • Logging and Connection string in LINQ to SQL
  • Data in cloud [SQL Azure] and LINQ

2. ADO.Net Entity Model

  • Creating Data model using ADO.Net Entity model
  • Performing CRUD operation using ADO.Net Entity model
  • SQL Azure with ADO.Net Entity model

 

3.  OData

  • Understanding OData
  • Exposing CRUD operation on Data using WCF Data Service
  • Stored Procedure with WCF Data Service

 

Consuming Data in different types of client like Silverlight, Mango Phone etc

Please be there. See you on 2nd July  Smile

DataContext in LINQ

To make a communication with Database a connection must be made. In LINQ this connection is created by DataContext.

Essentially Data Context class performs below two tasks

  1. Create connection to database.
  2. It submits and retrieves object to database.
  3. Converts objects to SQL queries and vice versa

image

You can say, it acts as exactly the same as SqlConnection class and perform some extra tasks as well like conversion of object to SQL query.

DataContext class is having four types of overloaded constructor.

image

It may take

  1. Connection string
  2. IDbConnection etc

Various public methods of DataContext class help us to perform below tasks

  1. Create data base
  2. Delete data base etc

You can create and drop a database like below,

Create database

clip_image002

Delete database

clip_image004

Full source code is as below,


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

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {

            DataContext context = new DataContext(GetConnectionString("Yourservername"));
            bool dbExist = context.DatabaseExists();
            if (dbExist == true)
            {

                context.DeleteDatabase();
                Console.WriteLine("Database deleted");
            }
            else
            {
                context.CreateDatabase();
                Console.WriteLine("Database created");
            }
            Console.ReadKey(true);

        }

        static string GetConnectionString(string serverName)
        {

            System.Data.SqlClient.SqlConnectionStringBuilder builder =
                           new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder["Data Source"] = serverName;
            builder["integrated Security"] = true;
            builder["Initial Catalog"] = "Sample2";
            Console.WriteLine(builder.ConnectionString);
            Console.ReadKey(true);
            return builder.ConnectionString;

        }
    }
}

Strongly Typed Data Context

Strongly typed Data context can be created by below steps

  1. Create class to represent strongly type data context
  2. Inherits the class from DataContext class.

clip_image002[5]

Advantage of using strongly typed data context is that each table is available in Table collections. So you do not need to fetch tables using GetTable method.

I hope this post was useful. Thanks for reading Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Connection string in LINQ

It is very common that you come across scenario when at run time you need to change the database server and so the connection string is used in your LINQ. This may come as requirement, if you are moving your application from dev server to staging and from staging to production.

There are two ways you can change connection string on fly

  1. Edit config file
  2. Build connection string to pass as constructor of DataContext.

Edit config file

You can do it in two ways. Open the configuration file and edit connection string here.

clip_image002

In other way, you can change connection string is open DBML file and right click then select Properties

clip_image002[5]

In properties tab create on Connection and click on Connection String

clip_image004

In connection properties dialog box you can change the connection so the connection string.

clip_image006

Editing Connection String in code

Assuming you is creating a function to return connection string. Crete function that it takes server name as input parameter. Your function should be like below.

clip_image008

You can pass server name to this function to create connection string and use output of this function in constructor of DataContext

clip_image010

So here you can pass any server name to create DataContext as of server.

For reference code is as below ,

 static string GetConnectionString(string serverName)
        {

            System.Data.SqlClient.SqlConnectionStringBuilder builder =
                           new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder["Data Source"] = serverName;
            builder["integrated Security"] = true;
            builder["Initial Catalog"] = "Sample2";
            Console.WriteLine(builder.ConnectionString);
            Console.ReadKey(true);
            return builder.ConnectionString;

        }

I hope this post was useful. Thanks for reading.  Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Learn ADO.Net Entity Framework: Performing basic CRUD Operation

In this post I will walkthrough you on performing basic CRUD operation using ADO.Net Entity framework.

Database design

I am going to use School Database. You can find School database script here . To be precise, I am going perform CRUD operation on only one table Person. Schema of Person table is as below.

image

I am going to perform CRUD Operation on Person table from a console application.

Create Data Model

  1. Right click on Console Application and add new Item
  2. From Data Tab select ADO.Net Entity Data Model .If you want you can change name of the model.

image

3.   Click on Add button; you will get dialog box. From there select Generate from database option

image

4.  Create a new connection

image

5. Give database server name and choose database from the drop down as given below,

image

After clicking on Ok button, you will notice that you come to previous dialog box and a connection setting got created. Name of the connection setting is as below,

Database name + Entities = default connection setting name

If database is School then default connection setting name would be schoolentites. However, if you want you can change default connection setting name as desired.

image

6. Now you need to choose Data objects to make them part of Data Model. From below dialog box you can choose tables, stored procedures and views.

Since we are going to perform CRUD operation only on Person table , so I will choose only Person table to be part of Data Model.

image

If you want you can change Model Namespace name. By default it would be Database name suffixed with Model.

Now click Finish to create data model.

Performing CRUD operation

Retrieving all the records

You can fetch all the records as below.

image

Add a person

You can add a person in three steps

  1. Create object of Person
  2. Call add object on pluralize Person entity. In this case this is People
  3. Call save changes on entities

image

Modify a Person

To modify a person you need to perform three steps

  1. Fetch the Person to be modified
  2. Modify the desired values of the columns
  3. Call save changes on the entities

image

Delete a Person

To modify a person you need to perform three steps

  1. Fetch the Person to be deleted
  2. Call delete object on entities
  3. Call save changes on the entities

image

Full source code is given below,


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

namespace ADONetEntityModelfirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {


            #region Reterive a Person

            SchoolEntities entities = new SchoolEntities();
            var result = from r in entities.People select r;
            foreach (var r in result)
            {
                Console.WriteLine(r.PersonID + r.LastName);
            }

            Console.ReadKey(true);

            #endregion

            #region Add a Pesron
            entities.People.AddObject(new Person
                                       { FirstName = "dhananjay",
                                         LastName = "kumar"
                                       });
            entities.SaveChanges();


            #endregion
            #region Modify a Person

            Person personToModofy = (from r in entities.People.Where
                                         (a => a.PersonID == 1)
                                         select r).FirstOrDefault();
            personToModofy.LastName = "Jamshedpur";
            entities.SaveChanges();

#endregion

            #region Delete  a Person

            Person personToDelete = (from r in entities.People.Where
                                        (a => a.PersonID == 1)
                                     select r).FirstOrDefault();
            entities.People.DeleteObject(personToDelete);
            entities.SaveChanges();


            #endregion
            #region Reterive  a Person

            var result1 = from r in entities.People select r;
            foreach (var r in result1)
            {
                Console.WriteLine(r.PersonID + r.LastName);
            }
            Console.ReadKey(true);
        }

#endregion
    }
}


In further post, we will discuss other aspects of ADO.Net Entity framework. I hope this post was useful. Thanks for reading  Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Tracing in WCF: Understanding basic steps

Theory behind WCF Tracing is not an exception of classical definition of Tracing. Through Tracing an application provides information about itself. Information may vary from internal state of object to passed input parameter to method. This information should be logged, persisted or saved somewhere.

WCF Tracing can be used for the instrumentation of the WCF Service.

There are essentially four steps involved in WCF Tracing

image

Emitting Trace information from Service

To emit trace information WCF provides different sources. However you have choice to create trace source using TraceSource class as well. You can choose any of WCF Assembly level trace source to emit the tracing information.

WCF Assembly level Trace Sources are as below,

  1. System.ServiceModel
  2. System.ServiceModel.MessageLogging
  3. System.ServiceModel.IdentityModel
  4. System.ServiceModel.Activation
  5. System.Runtime.Serilization
  6. System.IO.Log

Setting the Trace level

You can define the level of messages you want to trace. If you are tracing all level of messages then size of message generated for tracing would be very bulky and it may affect application negatively.

WCF supports below tracing levels

image

Trace level information is set by using the switchValue attribute for trace source.

Configuring the listener

You need to configure a listener to persist the messages at any desired location. There must be at least one listener configured for WCF tracing.

Listener can be configured either

  1. Through code
  2. Or in configuration file.

You can configure listener directly in source element of the configuration.

Note: In further post, I will discuss in detail on configuring the listener.

Enabling Message logging

Last step you need to perform is to enable message logging in configuration. WCF logs message at two levels.

image

Different attributes of Message loggings are as below,

image

Enough of theory Smile Now let us go ahead and capture basic trace in WCF service.

  1. Create a basic WCF Service
  2. Consume service in a client. I am assuming that you are consuming service in a console client.
  3. Open App.config of console client

Emit Trace Information

Add a source in System.Diagostics

image

Set the Trace Level

image

We are setting here trace level to Information and Activity tracing

Configure the Listener

image

We are using listener System.Diagnostics.XmlWriterTraceListener. Trace information would be find at Traces.svclog file under bin/debug folder .

Trace information gets buffered, so to make it visible you need to flush it using below configuration

image

After performing above three steps your System.Diagnostics should look like below,

image

Enable Message Logging

Last step you need to perform is enabling Message logging. Add below diagnostic in System.ServiceModel.

image

Eventually client side App.Config should look more or less like below, Smile


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
      <diagnostics>
        <messageLogging logEntireMessage="true"
                        logMalformedMessages="false"
                        logMessagesAtServiceLevel="false"
                        logMessagesAtTransportLevel="true"
                        maxMessagesToLog="3000"
                        maxSizeOfMessageToLog="2000"/>
      </diagnostics>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IService1" 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" establishSecurityContext="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:2934/Service1.svc" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
                name="WSHttpBinding_IService1">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging"
              switchValue="Information, ActivityTracing">
        <listeners>
          <add name="log"
               type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="Traces.svclog"/>
        </listeners>
      </source>
    </sources>
    <trace autoflush ="true"/>
  </system.diagnostics>
</configuration>

After configuring as said above when you run client application you will get a file in

Bin\debug\Traces.svclog

Open above file to view the trace Smile I hope this post was useful. In further post I will take you to dipper in tracing. Thanks for reading Smile

 

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Viewing Flickr Images on Windows 7.1 Phone or Mango Phone

In this post I will show you how you can create a Photo Viewer from images of the Flickr Service.

Flickr Service

Flickr expose a REST based feed to access images. You can find information about Flickr public feed at below link.

http://www.flickr.com/services/feeds/docs/photos_public/

Public images feed can be find at

http://api.flickr.com/services/feeds/photos_public.gne

Expected Output

imageimage

Approach

  1. Call Flickr Service
  2. Parse XML feed
  3. Bind it to List Box.

Create Windows Phone 7.1 Application

Create Windows 7 Phone Application and select Windows Phone 7.1 as target Windows Phone version.

clip_image002

clip_image003

Create Photo class

To bind images to the ListBox, let us create Photo class. Right click and add a class called Photo in the project. When we parse Flickr Image feeds, we will bind public Image URL here

Photo.cs

clip_image005

Parsing Image Feed of Flickr Service

When you open public feed URL of Flicker in browser; you can view the feeds in browser itself.

clip_image007

We are going to give value of link element from the feed in Image as source value.

We will have to make asynchronous calls as below,

image

Then in DonwnloadStringCompleted event, we will have to perform below tasks,

  1. Create a Observable collection of Photos
  2. Parse the Feed
  3. Iterate through all the public image url in feed and add to collection.

image

Parsing of feeds can be done as below,

  1. We are parsing Link URL.
  2. Fetching the value of href attribute in Link URL.
  3. There are two link elements and we are fetching value of link element having rel attribute value as enclosure

image

Design the Page

We are going to put a ListBox in content grid and inside ItemTemplate of ListBox , we will put Image control.

clip_image001

As source of the Image you need to bind PhotoSource property of Photo class.

For Reference full source codes are given below. Feel free to use for your purpose  Smile

MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="FlickerImageFeed.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Mango Phone" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Flicker Images" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="lstImage" Width="450" Margin="3,6">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding PhotoSource}"
                                   Width="425"
                                   Height="auto"
                                   Stretch="Uniform"
                                   HorizontalAlignment="Center" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace FlickerImageFeed
{
    public partial class MainPage : PhoneApplicationPage
    {

        IEnumerable<List<string>> imageURL;
        List<string> lstImageURl;
        Photo P;
        ObservableCollection<Photo> photos;
        public MainPage()
        {
            InitializeComponent();
            GetAllPhotos();
        }

        private ImageSource GetImageSource(string fileName)
        {
            return new BitmapImage(new Uri(fileName, UriKind.Absolute));
        }
        private void  GetAllPhotos()
        {

            WebClient proxy = new WebClient();
            proxy.DownloadStringAsync(new Uri("http://api.flickr.com/services/feeds/photos_public.gne"));
            proxy.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);

        }

        void proxy_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            photos = new ObservableCollection<Photo>();
            lstImageURl = new List<string>();
            imageURL = ParseXML(e.Result);
            foreach (var r in imageURL)
            {
                foreach (var a in r)
                {
                    P = new Photo { PhotoSource = GetImageSource(a.ToString()) };
                    photos.Add(P);
                }
            }

            lstImage.ItemsSource = photos;

        }
        private IEnumerable<List<string>> ParseXML(string xmlData)
        {
            XNamespace ns = "http://www.w3.org/2005/Atom";
            XDocument doc = XDocument.Parse(xmlData);
            var photo = from r in doc.Descendants(ns + "entry")
                        select r.Elements(ns + "link")
                        .Where(f => (string)f.Attribute("rel") == "enclosure")
                        .Select(f => f.Attribute("href").Value).ToList();
            return photo;
        }
    }
}

Run the Application

Press F5 to run Photo viewer from images of Flicker service Smile

imageimage

I hope this post was useful. Thanks for reading  Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Reading XML file through LINQ: few Tips

In this post I will discuss how could be read XML file using LINQ. We will see some tips as well.

Let us say we have XML file as below, this file is stored on D drive. This XML contains information about books.

Data.Xml

 


<?xml version="1.0" encoding="utf-8" ?>
<catalog>
 <books>
<book id="bk101">
  <author id="1">Gambardella, Matthew</author>
  <title>XML Developer’s Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
   <description> An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
  <author id="2">Ralls, Kim</author>
  <title>Midnight Rain</title>
  <genre>Fantasy</genre>
  <price>5.95</price>
  <publish_date>2000-12-16</publish_date>
  <description> A former architect battles corporate zombies,an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
<book id="bk103">
  <author id="3">Corets, Eva</author>
  <title>Maeve Ascendant</title>
  <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society. </description>
  </book>

<book id="bk104">
    <author id="4">Corets, Eva</author>
    <title>Oberon’s Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description>

  </book>

<book id="bk105">
    <author id="5">Corets, Eva</author>
    <title>The Sundered Grail</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-09-10</publish_date>
    <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon’s Legacy.</description>

  </book>
  </books>
</catalog>

 

Fetching all the Books

To fetch all the Books, just we need to parse the XML file. Find the descendants book and fetch it in anonymous class.

 

image

 

Fetching a Particular Book

 

If you want to fetch a particular book, we need to apply where condition while parsing XML file.

 

image

 

Fetching Attribute Value of a particular Book

Imagine you need to fetch author Id of a particular book with Id bk102. To do that you need to select as below,

 

image

 

Fetching all the Authors Name only

To fetch the entire author name, we need to execute below query.

 

image

 

For your reference full source code is as below,

Program.cs

 



using System;
using System.Linq;
using System.Xml.Linq;


namespace ConsoleApplication23
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument document = XDocument.Load("D:\\Data.xml");
            #region Fetch All the Books
            var books = from r in document.Descendants("book")
                        select new
                            {
                                Author = r.Element("author").Value,
                                Title = r.Element("title").Value,
                                Genere = r.Element("genre").Value,
                                Price = r.Element("price").Value,
                                PublishDate = r.Element("publish_date").Value,
                                Description = r.Element("description").Value,

                            };

            foreach (var r in books)
            {
                Console.WriteLine(r.PublishDate + r.Title + r.Author);
            }

            Console.ReadKey(true);
            #endregion

            #region Fetching a particular  Book
            var selectedBook = from r in document.Descendants("book").Where
                                   (r=>(string)r.Attribute("id")=="bk102")
                        select new
                        {
                            Author = r.Element("author").Value,
                            Title = r.Element("title").Value,
                            Genere = r.Element("genre").Value,
                            Price = r.Element("price").Value,
                            PublishDate = r.Element("publish_date").Value,
                            Description = r.Element("description").Value,

                        };

            foreach (var r in selectedBook)
            {
                Console.WriteLine(r.PublishDate + r.Title + r.Author);
            }
            Console.ReadKey(true);
            #endregion



            #region Fetching a particular  Book


            var selectedBookAttribute = (from r in document.Descendants("book").Where
                                        (r => (string)r.Attribute("id") == "bk102")
                                        select r.Element("author").Attribute("id").Value).FirstOrDefault();

            Console.WriteLine(selectedBookAttribute);

            Console.ReadKey(true);

            #endregion


            #region Fetching all Authors


            var allauthors = from r in document.Descendants("book")
                                         select r.Element("author").Value;
            foreach(var r in allauthors)
            {
                Console.WriteLine(r.ToString());
            }


            Console.ReadKey(true);

            #endregion



        }
    }
}



Output

image

 

I hope this post was useful. Thanks for reading  Smile

Presented Demo on Mango Phone in Ahmedabad Community Tech Days on Road

On 11th June 2011 I presented a demo on various new features of Mango Phone. It was a great time presenting there in front of more than 500 audiences.

image

Session details are as follows

Topic New Features of Windows Phone 7.1
Duration 20 minutes
Venue Ahmedabad
Number of Audiences Around 500

Below are the links to have a further reading on topics I presented there.

 

Looking forward to share my learning in other community events as well  Smile

Internal classes to understand WCF Message: XmlDictionaryWriter Class

XmlDictionaryWriter class is one of the most important classes to work with Message in WCF. This class is inherited form XmlWriter class. Essentially this takes as Stream as input parameter. This class mainly performs serialization and encoding of the stream to send as Message in WCF.

 

 

image

There are four factory methods of this class being used extensively. Each method has their own uses as of requirement.

image

image

CreateDictionaryWriter method

It takes as input parameter object of XmlWriter. This method is not being used very extensively. This method could be very handy when we do not have any choice but XmlWriter object as input parameter.

 

image

If you see below code, we are creating a stream. Using stream we are creating a XmlWriter object and passing to XmlDictionaryWriter to create object of the same.


using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Xml;
using System.Collections.Generic;
using System.IO;
namespace XML
{
    class Program
    {

        static void Main(string[] args)
        {


            MemoryStream stream = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(stream);
            XmlDictionaryWriter dctWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);
            Console.WriteLine(dctWriter.ToString());
            Console.ReadKey(true);


        }
    }

}


 

CreateTextWriter method

This method helps us to create text encoded XML. This is overloaded with three different types of input set.

It can take only a Stream to write to. It writes output with default encoding UTF8.

 

image

It can as input Stream to write to and character Encoding of the output

 

image

It can take Stream to write, character encoding of output and a Boolean value. If Boolean input is true then Stream is closed by writer once writing is done. Else Stream will not be closed by the writer.

image

CreateTextWriter supports only,

  1. UTF8 Encoding
  2. UTF 16 little endian
  3. UTF16 big endian

 

We have been doing much of technical talk and I am sure you do not like it Smile so to please you let me show you, how we could use CreateTextWriter class.

In below code we are reading stream and writing using CreateTextWriter .

 


using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace XML
{
    class Program
    {

        static void Main(string[] args)
        {


            MemoryStream streamToWrite = new MemoryStream();

            using (XmlDictionaryWriter wrt = XmlDictionaryWriter.CreateTextWriter(streamToWrite, Encoding.UTF8, false))
            {
                wrt.WriteStartDocument();
                wrt.WriteElementString("SongName", "urn:Mysong", "F:\\a.wmv");
                wrt.Flush();
            }

            Console.WriteLine("Number Of Bytes wriiten {0} ", streamToWrite.Position);
            Console.ReadKey(true);
            streamToWrite.Position = 0;
            Byte[] bytes = streamToWrite.ToArray();
            Console.WriteLine(bytes.Length);
            Console.ReadKey(true);
            Console.WriteLine(BitConverter.ToString(bytes));
            Console.WriteLine("Data Read from stream : {0}", new StreamReader(streamToWrite).ReadToEnd());
            Console.ReadKey(true);


        }
}
}



On running you will get output as below,

image

If you would have noticed we used empty stream. So as a resultant we are getting 86 bytes written.

CreateMtomWriter method

This method is used to create MTOM-encoded XML.

We can pass Stream to write and other parameters like encoding.

image

This method allows us to pass boundary of MIME type also along with Stream to write.

image

We are just modifying the write method in above code and you can see the change in output behavior as below,



using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace XML
{
    class Program
    {

        static void Main(string[] args)
        {


            MemoryStream streamToWrite = new MemoryStream();


            using (XmlDictionaryWriter wrt = XmlDictionaryWriter.CreateMtomWriter(streamToWrite,
                                                                                  Encoding.UTF8,
                                                                                  1000,
                                                                                  "startinfo",
                                                                                  "Boundary",
                                                                                  "urn:stratUri",
                                                                                  false,
                                                                                  false))
            {
                wrt.WriteStartDocument();
                wrt.WriteElementString("SongName", "urn:Mysong", "F:\\a.wmv");
                wrt.Flush();

            }

            Console.WriteLine("Number Of Bytes wriiten {0} ", streamToWrite.Position);

            streamToWrite.Position = 0;
            Byte[] bytes = streamToWrite.ToArray();


            Console.WriteLine(BitConverter.ToString(bytes));
            Console.WriteLine("Data Read from stream : {0}", new StreamReader(streamToWrite).ReadToEnd());
            Console.ReadKey(true);


        }}}




Expected output you would get as below,

image

I hope this post was useful. I am taking a break here. In next post we will see CreateBinaryWriter method. Thanks for reading Smile

Internal classes to understand WCF Message: XmlDictionary Class

In last post we discussed the way we could create WCF Message. If you go back and reexamine CreateMessage() function , you will find this function is overloaded with 11 different set of inputs.

It is common when you will create Message, you may use XmlDictionary class.

XmlDictionary class allows us to create a private pair of Key and Value. This key-value pair can be used to represent

  • Element name
  • Attribute name
  • XML namespace declaration.

XmlDictionary class uses XmlDictionaryString class object to create key value pair. If you see below code, we are creating a XmlDictionary object and List of XmlDictionaryString.

 

image

dct is object of XmlDictionary and while adding string value in this it returns XmlDictionaryString object.

 


XmlDictionary dct = new XmlDictionary();
            List<XmlDictionaryString> lstData = new List<XmlDictionaryString>();
            lstData.Add(dct.Add("Bat"));
            lstData.Add(dct.Add("Ball"));
            lstData.Add(dct.Add("Wicket"));
            foreach (var r in lstData)
            {
                Console.WriteLine("Key  = {0}  and Value = {1}", r.Key, r.Value);
            }
            Console.ReadKey(true);


 

If you run above code you will get output as below,

image

We are simply adding returned XmlDictionaryString object to list of XmlDictionaryString.

I hope now you have understanding of XmlDictionary class. In next post we will discuss some other important class required to understand Message in WCF.

Thanks for reading  Smile