<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" gd:etag="W/&quot;C08FR3Y6eip7ImA9WhRUGEs.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347</id><updated>2012-01-29T10:30:16.812-08:00</updated><title>Islam ElDemery</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>14</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/IslamEldemery" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="islameldemery" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;DEMNR3w8eip7ImA9WxVSEk4.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-1973124243915095909</id><published>2009-01-05T23:56:00.000-08:00</published><updated>2009-01-06T02:08:16.272-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-06T02:08:16.272-08:00</app:edited><title>Xmlawy - XML Framework-C# freindly</title><content type="html">&lt;div&gt;&lt;br /&gt;        &lt;span id="ArticleContent"&gt;&lt;br /&gt;            &lt;ul class="download"&gt;&lt;br /&gt;                &lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/Xmlawy.zip"&gt;Download source code - 242&lt;br /&gt;                    KB&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;            &lt;/ul&gt;&lt;br /&gt;            &lt;h2&gt;&lt;br /&gt;                Introduction&lt;/h2&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                This framework provides an easy way to access XML files with support for inserting,&lt;br /&gt;                updating, deleting, and selecting by querying the XML like querying SQL.&lt;/p&gt;&lt;br /&gt;            &lt;h2&gt;&lt;br /&gt;                Using the code&lt;/h2&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                I'll start by writing simple lines of code that demonstrate the operations of inserting,&lt;br /&gt;                updating, deleting, and selecting, and then show the results in an XML file.&lt;/p&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                Here is how we create an XML file and access an object:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;    BaseDataAccess access = &lt;br /&gt;      new BaseDataAccess(&amp;quot;D:/xmltest.xml&amp;quot;, &amp;quot;Objects&amp;quot;);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Simple inserting&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                The &lt;code&gt;Insert&lt;/code&gt; method takes an object of type &lt;code&gt;BaseDataObject&lt;/code&gt;&lt;br /&gt;                as a parameter, which contains the name of the node, the value, the attributes,&lt;br /&gt;                and a list of children which are of the same type as well.&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;access.Insert(new BaseDataObject(&amp;quot;type&amp;quot;, &amp;quot;human&amp;quot;)).Execute();&lt;br /&gt;access.Insert(new BaseDataObject(&amp;quot;type&amp;quot;, &amp;quot;animal&amp;quot;)).Execute();&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="229" alt="2.png" src="http://www.geocities.com/issy.issy/2.png" width="514" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Simple selecting&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                You can query the XML to select specific nodes:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;List&amp;lt;BaseDataObject&amp;gt; dataList = access.Select(&amp;quot;type&amp;quot;).&lt;br /&gt;                                          Where(&amp;quot;type&amp;quot;).&lt;br /&gt;                                          IsEqualTo(&amp;quot;animal&amp;quot;).&lt;br /&gt;                                          ExecuteSelect&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt; &lt;br /&gt;for (int i = 0; i &amp;lt; dataList.Count; i++)&lt;br /&gt;{&lt;br /&gt;    Console.WriteLine(dataList[i].Name + &amp;quot; : &amp;quot; + dataList[i].Value);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="218" alt="3.png" src="http://www.geocities.com/issy.issy/3.png" width="477" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Updating&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                It is also easy to update specific nodes:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;access.Update(&amp;quot;type&amp;quot;).Set(&amp;quot;type&amp;quot;).EqualTo(&amp;quot;animal&amp;quot;).&lt;br /&gt;       Where(&amp;quot;type&amp;quot;).IsEqualTo(&amp;quot;human&amp;quot;).Execute();&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="225" alt="4.png" src="http://www.geocities.com/issy.issy/4.png" width="537" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Deleting&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                And here is how we delete:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;access.Delete(&amp;quot;type&amp;quot;).Where(&amp;quot;type&amp;quot;).IsEqualTo(&amp;quot;animal&amp;quot;).Execute();&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="214" alt="6.png" src="http://www.geocities.com/issy.issy/6.png" width="506" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Advanced inserting&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                The way to insert children of children is to make a list of &lt;code&gt;BaseDataObject&lt;/code&gt;s&lt;br /&gt;                and insert them in the list of the children of another &lt;code&gt;BaseDataObject&lt;/code&gt;.&lt;br /&gt;                (The best way to do this is recursively.) The following code inserts three levels&lt;br /&gt;                of children in depth:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;    // ACCESS&lt;br /&gt;    BaseDataAccess access = &lt;br /&gt;      new BaseDataAccess(&amp;quot;test.xml&amp;quot;, &amp;quot;objects&amp;quot;);&lt;br /&gt; &lt;br /&gt;    // INSERTING 3 LEVELS IN DEPTH&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; parents = new List&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt;    for (int i = 0; i &amp;lt; 5; i++)&lt;br /&gt;    {&lt;br /&gt;        parents.Add(new BaseDataObject(&amp;quot;Parent&amp;quot;, MakeChilds(5)));&lt;br /&gt;    }&lt;br /&gt;    BaseDataObject parentOfParents = &lt;br /&gt;       new BaseDataObject(&amp;quot;GrandParent&amp;quot;, parents);&lt;br /&gt;    access.Insert(parentOfParents).Execute();&lt;br /&gt; &lt;br /&gt;    Console.WriteLine(access.XmlString);&lt;br /&gt; &lt;br /&gt;    Console.ReadLine();&lt;br /&gt;}&lt;br /&gt; &lt;br /&gt;private static List&amp;lt;BaseDataObject&amp;gt; MakeChilds(int count)&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; childs = new List&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt;    for (int i = 0; i &amp;lt; count; i++)&lt;br /&gt;    {&lt;br /&gt;        childs.Add(new BaseDataObject(&amp;quot;N&amp;quot; + i.ToString(), &lt;br /&gt;                   &amp;quot;V &amp;quot; + i.ToString()));&lt;br /&gt;    }&lt;br /&gt;    return childs;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="527" alt="7.png" src="http://www.geocities.com/issy.issy/7.png" width="557" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Advanced selecting&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                Here is how we select any child in the selected objects, recursively, with the method&lt;br /&gt;                &lt;code&gt;PrintObject(obj)&lt;/code&gt;:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;    // ACCESS&lt;br /&gt;    BaseDataAccess access = new BaseDataAccess(&amp;quot;test.xml&amp;quot;, &amp;quot;objects&amp;quot;);&lt;br /&gt; &lt;br /&gt;    // INSERTING 3 LEVELS IN DEPTH&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; parents = new List&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt;    for (int i = 0; i &amp;lt; 5; i++)&lt;br /&gt;    {&lt;br /&gt;        parents.Add(new BaseDataObject(&amp;quot;Parent&amp;quot;, MakeChilds(5)));&lt;br /&gt;    }&lt;br /&gt;    BaseDataObject parentOfParents = new BaseDataObject(&amp;quot;GrandParent&amp;quot;, parents);&lt;br /&gt;    access.Insert(parentOfParents).Execute();&lt;br /&gt; &lt;br /&gt;    // SELECTING&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; objects = &lt;br /&gt;      access.Select(&amp;quot;GrandParent&amp;quot;).ExecuteSelect&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt;    for (int i = 0; i &amp;lt; objects.Count; i++)&lt;br /&gt;    {&lt;br /&gt;        PrintObject(objects[i]);&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    Console.ReadLine();&lt;br /&gt;}&lt;br /&gt; &lt;br /&gt;private static List&amp;lt;BaseDataObject&amp;gt; MakeChilds(int count)&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; childs = new List&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt;    for (int i = 0; i &amp;lt; count; i++)&lt;br /&gt;    {&lt;br /&gt;        childs.Add(new BaseDataObject(&amp;quot;N&amp;quot; + i.ToString(), &lt;br /&gt;                   &amp;quot; V&amp;quot; + i.ToString() + &amp;quot; &amp;quot;));&lt;br /&gt;    }&lt;br /&gt;    return childs;&lt;br /&gt;}&lt;br /&gt; &lt;br /&gt;private static void PrintObject(BaseDataObject obj)&lt;br /&gt;{&lt;br /&gt;    if (obj.Childs.Count &amp;gt; 0)&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(obj.Name + &amp;quot; &amp;gt;&amp;quot;);&lt;br /&gt;        for (int i = 0; i &amp;lt; obj.Childs.Count; i++)&lt;br /&gt;        {&lt;br /&gt;            PrintObject(obj.Childs[i]);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(obj.Name + &amp;quot; : &amp;quot; + obj.Value);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="446" alt="8.png" src="http://www.geocities.com/issy.issy/8.png" width="502" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Inserting simple objects&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                If you want to quickly save the properties of an object in XML (simple serialization),&lt;br /&gt;                there is another generic &lt;code&gt;Insert&lt;/code&gt; method which takes any object as a&lt;br /&gt;                parameter and inserts all the properties of type &lt;code lang="cs"&gt;string&lt;/code&gt; or&lt;br /&gt;                &lt;code lang="cs"&gt;int&lt;/code&gt; in the XML file.&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;class MyClass&lt;br /&gt;{&lt;br /&gt;    public MyClass()&lt;br /&gt;    {&lt;br /&gt;        Age = 20;&lt;br /&gt;        FirstName = &amp;quot;Islam&amp;quot;;&lt;br /&gt;        LastName = &amp;quot;Eldemery&amp;quot;;&lt;br /&gt;        Address = &amp;quot;Egypt, Cairo, bla bla bla&amp;quot;;&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    public int Age { get; set; }&lt;br /&gt;    public string FirstName { get; set; }&lt;br /&gt;    public string LastName { get; set; }&lt;br /&gt;    public string Address { get; set; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt; &lt;br /&gt;class Program&lt;br /&gt;{&lt;br /&gt;    static void Main(string[] args)&lt;br /&gt;    {&lt;br /&gt;        MyClass obj = new MyClass();&lt;br /&gt; &lt;br /&gt;        // ACCESS&lt;br /&gt;        BaseDataAccess access = new BaseDataAccess(&amp;quot;test.xml&amp;quot;, &amp;quot;objects&amp;quot;);&lt;br /&gt; &lt;br /&gt;        // INSERT&lt;br /&gt;        access.Insert&amp;lt;MyClass&amp;gt;(obj).Execute();&lt;br /&gt; &lt;br /&gt;        Console.WriteLine(access.XmlString);&lt;br /&gt; &lt;br /&gt;        Console.ReadLine();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                &lt;img height="195" alt="9.png" src="http://www.geocities.com/issy.issy/9.png" width="483" /&gt;&lt;/p&gt;&lt;br /&gt;            &lt;h2&gt;&lt;br /&gt;                So far so good, let's dig deeper..&lt;/h2&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Overriding the virtual methods in the base class&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                Imagine you want to encrypt the XML after inserting, and decrypt it before selecting.&lt;br /&gt;                This can be easily done by overriding the base methods as follows:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;class XmlAccess : BaseDataAccess&lt;br /&gt;{&lt;br /&gt;    XMLEncryptor encryptor;&lt;br /&gt; &lt;br /&gt;    public XmlAccess(string path, string rootElement)&lt;br /&gt;        : base(path, rootElement)&lt;br /&gt;    {&lt;br /&gt;        encryptor = new XMLEncryptor(path);&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    public override bool Execute()&lt;br /&gt;    {&lt;br /&gt;        bool executed = base.Execute();&lt;br /&gt; &lt;br /&gt;        ///////////////////////////////////////////////////&lt;br /&gt;        // ENCRYPTOR GOES HERE&lt;br /&gt;        encryptor.Encrypt(base._objectToInsert.Name, &amp;quot;myKey&amp;quot;);&lt;br /&gt;        ///////////////////////////////////////////////////&lt;br /&gt; &lt;br /&gt;        return executed;&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    public override List&amp;lt;T&amp;gt; ExecuteSelect&amp;lt;T&amp;gt;()&lt;br /&gt;    {&lt;br /&gt;        ///////////////////////////////////////////////////&lt;br /&gt;        // ENCRYPTOR GOES HERE&lt;br /&gt;        encryptor.Decrypt(&amp;quot;myKey&amp;quot;);&lt;br /&gt;        ///////////////////////////////////////////////////&lt;br /&gt; &lt;br /&gt;        return base.ExecuteSelect&amp;lt;T&amp;gt;();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Select From&lt;/h4&gt;&lt;br /&gt;            &lt;pre&gt;&lt;br /&gt;&lt;br /&gt;            // ACCESS&lt;br /&gt;            // True will delete the file if exist (for debugging purposes)&lt;br /&gt;            BaseDataAccess access = new BaseDataAccess(@"test4.xml", "doc", true);&lt;br /&gt;&lt;br /&gt;            // Initialize 6 childs&lt;br /&gt;            List&amp;lt;BaseDataObject&gt; childs = new List&amp;lt;BaseDataObject&gt;();&lt;br /&gt;            for (int i = 0; i &lt; 6; i++)&lt;br /&gt;            {&lt;br /&gt;                childs.Add(new BaseDataObject("Name" + i.ToString(), "Value" + i.ToString()));&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Insert&lt;br /&gt;            access.Insert(new BaseDataObject("Human", childs)).Execute();&lt;br /&gt;            access.Insert(new BaseDataObject("Animal", childs)).Execute();&lt;br /&gt;&lt;br /&gt;            // Select&lt;br /&gt;            List&amp;lt;BaseDataObject&gt; selected = access.Select("Human").Where("Name2").IsEqualTo("Value2").ExecuteSelect&amp;lt;BaseDataObject&gt;();&lt;br /&gt;            // (Prints 1)&lt;br /&gt;            Console.WriteLine(selected.Count);&lt;br /&gt;            // selected[0] is the Human osbject and holds 6 childs objects&lt;br /&gt;&lt;br /&gt;            // Select&lt;br /&gt;            List&amp;lt;BaseDataObject&gt; selectedN = access.Select("Name2").From("Human").Where("Name3").IsEqualTo("Value3").ExecuteSelect&amp;lt;BaseDataObject&gt;();&lt;br /&gt;            // (Prints 1)&lt;br /&gt;            Console.WriteLine(selectedN.Count);&lt;br /&gt;            // selected[0] is the child osbject&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;            &lt;h4&gt;&lt;br /&gt;                Select all nodes&lt;/h4&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                You can also select all the nodes in the root node with all children and children&lt;br /&gt;                of children, in one line of code:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;List&amp;lt;BaseDataObject&amp;gt; objects = access.SelectAll&amp;lt;BaseDataObject&amp;gt;();&lt;/pre&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                And again, this is to loop on them recursively:&lt;/p&gt;&lt;br /&gt;            &lt;pre lang="cs"&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;    // ACCESS&lt;br /&gt;    BaseDataAccess access = &lt;br /&gt;      new BaseDataAccess(@&amp;quot;D:\XmlFiles\StructureMap.xml&amp;quot;, &lt;br /&gt;                         &amp;quot;doesntMatter&amp;quot;);&lt;br /&gt; &lt;br /&gt;    // SELECTING&lt;br /&gt;    List&amp;lt;BaseDataObject&amp;gt; objects = access.SelectAll&amp;lt;BaseDataObject&amp;gt;();&lt;br /&gt; &lt;br /&gt;    // DISPLAYING&lt;br /&gt;    for (int i = 0; i &amp;lt; objects.Count; i++)&lt;br /&gt;        PrintObject(objects[i]);&lt;br /&gt; &lt;br /&gt;    Console.ReadLine();&lt;br /&gt;}&lt;br /&gt; &lt;br /&gt;private static void PrintObject(BaseDataObject obj)&lt;br /&gt;{&lt;br /&gt;    if (obj.Childs.Count &amp;gt; 0)&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(obj.Name + &amp;quot; &amp;gt;&amp;quot;);&lt;br /&gt; &lt;br /&gt;        for (int i = 0; i &amp;lt; obj.Childs.Count; i++)&lt;br /&gt;            PrintObject(obj.Childs[i]);&lt;br /&gt;    }&lt;br /&gt;    else&lt;br /&gt;        Console.WriteLine(obj.Name + &amp;quot; : &amp;quot; + obj.Value);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;            &lt;h2&gt;&lt;br /&gt;                History&lt;/h2&gt;&lt;br /&gt;            &lt;p&gt;&lt;br /&gt;                The code in the library is fully commented. This is version 1. I hope we can add&lt;br /&gt;                more and more features in the future.&lt;/p&gt;&lt;br /&gt;        &lt;/span&gt;&lt;br /&gt;    &lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-1973124243915095909?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/1973124243915095909/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=1973124243915095909" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/1973124243915095909?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/1973124243915095909?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2009/01/xmlawy-xml-framework-c-freindly.html" title="Xmlawy - XML Framework-C# freindly" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>9</thr:total></entry><entry gd:etag="W/&quot;Dk4MQXg5fyp7ImA9WxdREEg.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-283608109304544140</id><published>2008-05-28T06:43:00.000-07:00</published><updated>2008-05-29T02:56:20.627-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-05-29T02:56:20.627-07:00</app:edited><title>WCF Server/Client Chat Sample</title><content type="html">&lt;p&gt;&lt;br /&gt;&lt;img alt="WCF Server/Client Chat" src="http://www.geocities.com/issy.issy/WCFServerClient.JPG"/&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;b&gt;Download&lt;/b&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/ServClnt.zip"&gt;Download Server/Client Chat&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/ServClntSrc.zip"&gt;Download Server/Client Chat Source Code&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Screen Shots&lt;/b&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/1_All_Connected.JPG"&gt;1- All Connected&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/2_Test1_Disconnected.JPG"&gt;2- Test1 Disconnected&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/3_Server_Stoped.JPG"&gt;3- Server Stopped while clients are running&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;This is a simple and smart WCF Client/Server Chat sample, Amit Gupta (visitor to my blog) asked how to convert a&lt;br /&gt;client/server sockets app. into client/server WCF app., which got me interested to make this sample.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;It consists of two apps. both are windows forms, the server one includes the contracts and implements the service.&lt;br /&gt;The client one implements the callcack.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;WCF server/client sample features:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Handling concurrency&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Handling server state&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Handling client state&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Checking server availability&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Reliable sessions&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Asynchronous operations&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Code will be as follows:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Server:&lt;ul&gt;&lt;br /&gt;&lt;li&gt;form1.cs&lt;/li&gt;&lt;br /&gt;&lt;li&gt;app.config&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;Client:&lt;ul&gt;&lt;br /&gt;&lt;li&gt;form1.cs&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Server&lt;/h3&gt;&lt;br /&gt;&lt;h4&gt;Form1.cs&lt;/h4&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.ComponentModel;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Drawing;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using System.Windows.Forms;&lt;br /&gt;using System.ServiceModel;&lt;br /&gt;&lt;br /&gt;namespace Server&lt;br /&gt;{&lt;br /&gt;    [ServiceContract(CallbackContract=typeof(ISampleChatCallback), SessionMode=SessionMode.Required)]&lt;br /&gt;    public interface ISampleChat&lt;br /&gt;    {&lt;br /&gt;        [OperationContract(IsInitiating=true, IsOneWay=true)]&lt;br /&gt;        void Connect(string name);&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsOneWay = true)]&lt;br /&gt;        void SayToServer(string name, string msg);&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsTerminating = true, IsOneWay = true)]&lt;br /&gt;        void Disconnect(string name);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;br /&gt;    public interface ISampleChatCallback&lt;br /&gt;    {&lt;br /&gt;        [OperationContract(IsOneWay = true)]&lt;br /&gt;        void SayToClient(string msg);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, InstanceContextMode=InstanceContextMode.Single)]&lt;br /&gt;    public partial class Form1 : Form, ISampleChat&lt;br /&gt;    {&lt;br /&gt;        ServiceHost host;&lt;br /&gt;        private Dictionary&lt; string, ISampleChatCallback&gt; clients = new Dictionary&lt; string, ISampleChatCallback&gt;();&lt;br /&gt;        private object syncObj = new object();&lt;br /&gt;&lt;br /&gt;        public Form1()&lt;br /&gt;        {&lt;br /&gt;            InitializeComponent();&lt;br /&gt;            EnableControls(false);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonStart_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            host = null;&lt;br /&gt;            host = new ServiceHost(this);&lt;br /&gt;            host.Opened += new EventHandler(host_Opened);&lt;br /&gt;            host.Closed += new EventHandler(host_Closed);&lt;br /&gt;            host.Faulted += new EventHandler(host_Faulted);&lt;br /&gt;&lt;br /&gt;            //start listening..&lt;br /&gt;            host.Open();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void host_Faulted(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleHost();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void host_Closed(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleHost();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void host_Opened(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleHost();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void HandleHost()&lt;br /&gt;        {&lt;br /&gt;            switch (host.State)&lt;br /&gt;            {&lt;br /&gt;                case CommunicationState.Closed:&lt;br /&gt;                    labelStatus.Text = "Closed";&lt;br /&gt;                    EnableControls(false);&lt;br /&gt;                    break;&lt;br /&gt;                case CommunicationState.Faulted:&lt;br /&gt;                    labelStatus.Text = "Faulted";&lt;br /&gt;                    EnableControls(false);&lt;br /&gt;                    host.Abort();&lt;br /&gt;                    break;&lt;br /&gt;                case CommunicationState.Opened:&lt;br /&gt;                    labelStatus.Text = "Opened";&lt;br /&gt;                    EnableControls(true);&lt;br /&gt;                    break;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void EnableControls(bool opened)&lt;br /&gt;        {&lt;br /&gt;            if (opened)&lt;br /&gt;            {&lt;br /&gt;                buttonStart.Enabled = false;&lt;br /&gt;                buttonStop.Enabled = true;&lt;br /&gt;                buttonSend.Enabled = true;&lt;br /&gt;                richTextBox1.Enabled = true;&lt;br /&gt;                textBox1.Enabled = true;&lt;br /&gt;                listBox1.Enabled = true;&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                buttonStart.Enabled = true;&lt;br /&gt;                buttonStop.Enabled = false;&lt;br /&gt;                buttonSend.Enabled = false;&lt;br /&gt;                richTextBox1.Enabled = false;&lt;br /&gt;                textBox1.Enabled = false;&lt;br /&gt;                listBox1.Enabled = false;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonStop_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            host.Close();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonSend_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            //send message to all clients&lt;br /&gt;            foreach (ISampleChatCallback cb in clients.Values)&lt;br /&gt;            {&lt;br /&gt;                cb.SayToClient("Server : " + textBox1.Text.ToString());&lt;br /&gt;            }&lt;br /&gt;            richTextBox1.Text += "\n" + "Server : " + textBox1.Text.ToString();&lt;br /&gt;            textBox1.Text = "";&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private ISampleChatCallback CurrentCallback &lt;br /&gt;        {&lt;br /&gt;            get &lt;br /&gt;            {&lt;br /&gt;                return OperationContext.Current.GetCallbackChannel&lt;ISampleChatCallback&gt;();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #region ISampleChat Members&lt;br /&gt;&lt;br /&gt;        public void Connect(string name)&lt;br /&gt;        {&lt;br /&gt;            if (!clients.ContainsKey(name))&lt;br /&gt;            {&lt;br /&gt;                lock (syncObj)&lt;br /&gt;                {&lt;br /&gt;                    clients.Add(name, CurrentCallback);&lt;br /&gt;                    listBox1.Items.Add(name);&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                richTextBox1.Text += "\n" + name + " connected..";&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;                //u may want to tell other clients that someone just connected&lt;br /&gt;                foreach (ISampleChatCallback cb in clients.Values)&lt;br /&gt;                {&lt;br /&gt;                    cb.SayToClient("Client " + name + " connected.");&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Disconnect(string name)&lt;br /&gt;        {&lt;br /&gt;            if (clients.ContainsKey(name))&lt;br /&gt;            {&lt;br /&gt;                lock (syncObj)&lt;br /&gt;                {&lt;br /&gt;                    clients.Remove(name);&lt;br /&gt;                    listBox1.Items.Remove(name);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            richTextBox1.Text += "\n" + name + " disconnected..";&lt;br /&gt;&lt;br /&gt;            //u may want to tell other clients that someone just disconnected&lt;br /&gt;            foreach (ISampleChatCallback cb in clients.Values)&lt;br /&gt;            {&lt;br /&gt;                cb.SayToClient("Client " + name + " disconnected.");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void SayToServer(string name, string msg)&lt;br /&gt;        {&lt;br /&gt;            //here u get the message from the client&lt;br /&gt;            //do whatever u want..&lt;br /&gt;            richTextBox1.Text += "\n" + name + " : " + msg;&lt;br /&gt;&lt;br /&gt;            //u may want to tell other clients that someone said something&lt;br /&gt;            foreach (ISampleChatCallback cb in clients.Values)&lt;br /&gt;            {&lt;br /&gt;                cb.SayToClient(name + " : " + msg);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;App.config&lt;/h4&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;&lt; ?xml version="1.0" encoding="utf-8" ?&gt;&lt;br /&gt;&lt; configuration&gt;&lt;br /&gt;  &lt; system.serviceModel&gt;&lt;br /&gt;&lt;br /&gt;    &lt; services&gt;&lt;br /&gt;      &lt; service name="Server.Form1" behaviorConfiguration="serviceBehaviorConfiguration"&gt;&lt;br /&gt;        &lt; host&gt;&lt;br /&gt;          &lt; baseAddresses&gt;&lt;br /&gt;            &lt; add baseAddress="net.tcp://localhost:4477/SampleWCFChat/"/&gt;&lt;br /&gt;            &lt; add baseAddress="http://localhost:4478/SampleWCFChat/"/&gt;&lt;br /&gt;          &lt; /baseAddresses&gt;&lt;br /&gt;        &lt; /host&gt;&lt;br /&gt;        &lt; endpoint address="tcp"&lt;br /&gt;                  binding="netTcpBinding"&lt;br /&gt;                  bindingConfiguration="tcpBindingConfiguration"&lt;br /&gt;                  contract="Server.ISampleChat"/&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; endpoint address="mex"&lt;br /&gt;                  binding="mexTcpBinding"&lt;br /&gt;                  contract="IMetadataExchange"/&gt;&lt;br /&gt;      &lt; /service&gt;&lt;br /&gt;    &lt; /services&gt;&lt;br /&gt;    &lt; bindings&gt;&lt;br /&gt;      &lt; netTcpBinding&gt;&lt;br /&gt;        &lt; binding name="tcpBindingConfiguration" &lt;br /&gt;                 closeTimeout="00:00:05"&lt;br /&gt;                 maxBufferSize="1048576"&lt;br /&gt;                 maxBufferPoolSize="1048576"&lt;br /&gt;                 maxConnections="10"&lt;br /&gt;                 maxReceivedMessageSize="1048576"&lt;br /&gt;                 openTimeout="00:00:05"&lt;br /&gt;                 receiveTimeout="01:00:00"&lt;br /&gt;                 sendTimeout="01:00:00"&lt;br /&gt;                 transferMode="Buffered"&gt;&lt;br /&gt;          &lt; readerQuotas maxArrayLength="1048576" maxBytesPerRead="1048576" maxStringContentLength="1048576"/&gt;&lt;br /&gt;          &lt; reliableSession enabled="true" inactivityTimeout="01:00:00"/&gt;&lt;br /&gt;        &lt; /binding&gt;&lt;br /&gt;      &lt; /netTcpBinding&gt;&lt;br /&gt;    &lt; /bindings&gt;&lt;br /&gt;    &lt; behaviors&gt;&lt;br /&gt;      &lt; serviceBehaviors&gt;&lt;br /&gt;        &lt; behavior name="serviceBehaviorConfiguration"&gt;&lt;br /&gt;          &lt; serviceDebug includeExceptionDetailInFaults="true"/&gt;&lt;br /&gt;          &lt; serviceMetadata httpGetEnabled="true"/&gt;&lt;br /&gt;        &lt; /behavior&gt;&lt;br /&gt;      &lt; /serviceBehaviors&gt;&lt;br /&gt;    &lt; /behaviors&gt;&lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;  &lt; /system.serviceModel&gt;&lt;br /&gt;&lt; /configuration&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Client&lt;/h3&gt;&lt;br /&gt;&lt;h4&gt;Form1.cs&lt;/h4&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.ComponentModel;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Drawing;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using System.Windows.Forms;&lt;br /&gt;using System.ServiceModel;&lt;br /&gt;using System.ServiceModel.Description;&lt;br /&gt;&lt;br /&gt;namespace Client&lt;br /&gt;{&lt;br /&gt;    public partial class Form1 : Form, SampleService.ISampleChatCallback&lt;br /&gt;    {&lt;br /&gt;        public Form1()&lt;br /&gt;        {&lt;br /&gt;            InitializeComponent();&lt;br /&gt;            EnableControls(false);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        SampleService.SampleChatClient proxy;&lt;br /&gt;        private string name = string.Empty;&lt;br /&gt;        private delegate void MyInvoker();&lt;br /&gt;&lt;br /&gt;        #region ISampleChatCallback Members&lt;br /&gt;&lt;br /&gt;        public void SayToClient(string msg)&lt;br /&gt;        {&lt;br /&gt;            richTextBox1.Text += "\n" + msg;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public IAsyncResult BeginSayToClient(string msg, AsyncCallback callback, object asyncState)&lt;br /&gt;        {&lt;br /&gt;            throw new NotImplementedException();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void EndSayToClient(IAsyncResult result)&lt;br /&gt;        {&lt;br /&gt;            throw new NotImplementedException();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private void EnableControls(bool connected)&lt;br /&gt;        {&lt;br /&gt;            if (connected)&lt;br /&gt;            {&lt;br /&gt;                buttonDisconnect.Enabled = true;&lt;br /&gt;                buttonConnect.Enabled = false;&lt;br /&gt;                buttonSend.Enabled = true;&lt;br /&gt;                richTextBox1.Enabled = true;&lt;br /&gt;                textBoxMsg.Enabled = true;&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                richTextBox1.Text = "";&lt;br /&gt;                richTextBox1.Enabled = false;&lt;br /&gt;                textBoxMsg.Enabled = false;&lt;br /&gt;                buttonDisconnect.Enabled = false;&lt;br /&gt;                buttonConnect.Enabled = true;&lt;br /&gt;                buttonSend.Enabled = false;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonDisconnect_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            proxy.DisconnectAsync(name);&lt;br /&gt;            richTextBox1.Text = "";&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonSend_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            proxy.SayToServerAsync(name, textBoxMsg.Text.ToString());&lt;br /&gt;            textBoxMsg.Text = "";&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonConnect_Click(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            //u may want to skip CheckServer to boost speed &lt;br /&gt;            if (CheckServer())&lt;br /&gt;            {&lt;br /&gt;                proxy = null;&lt;br /&gt;                InstanceContext context = new InstanceContext(this);&lt;br /&gt;                proxy = new Client.SampleService.SampleChatClient(context);&lt;br /&gt;&lt;br /&gt;                proxy.InnerDuplexChannel.Opened += new EventHandler(InnerDuplexChannel_Opened);&lt;br /&gt;                proxy.InnerDuplexChannel.Closed += new EventHandler(InnerDuplexChannel_Closed);&lt;br /&gt;                proxy.InnerDuplexChannel.Faulted += new EventHandler(InnerDuplexChannel_Faulted);&lt;br /&gt;&lt;br /&gt;                name = textBoxName.Text.ToString();&lt;br /&gt;                proxy.ConnectAsync(name);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                MessageBox.Show("Sorry, Server is not available");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private bool CheckServer()&lt;br /&gt;        {&lt;br /&gt;            MetadataExchangeClient mexClient;&lt;br /&gt;            bool serverIsUp = false;&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                string address = "net.tcp://localhost:4477/SampleWCFChat/mex";&lt;br /&gt;                mexClient = new MetadataExchangeClient(new Uri(address), MetadataExchangeClientMode.MetadataExchange);&lt;br /&gt;                MetadataSet metadata = mexClient.GetMetadata();&lt;br /&gt;&lt;br /&gt;                serverIsUp = true;&lt;br /&gt;            }&lt;br /&gt;            catch&lt;br /&gt;            {&lt;br /&gt;                serverIsUp = false;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            return serverIsUp;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerDuplexChannel_Faulted(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            if (InvokeRequired)&lt;br /&gt;            {&lt;br /&gt;                this.Invoke(new MyInvoker(HandleProxy));&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerDuplexChannel_Closed(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            if (InvokeRequired)&lt;br /&gt;            {&lt;br /&gt;                this.Invoke(new MyInvoker(HandleProxy));&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerDuplexChannel_Opened(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            if (InvokeRequired)&lt;br /&gt;            {&lt;br /&gt;                this.Invoke(new MyInvoker(HandleProxy));&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void HandleProxy()&lt;br /&gt;        {&lt;br /&gt;            switch (proxy.State)&lt;br /&gt;            {&lt;br /&gt;                case CommunicationState.Closed:&lt;br /&gt;                    labelStatus.Text = "Disconnected";&lt;br /&gt;                    EnableControls(false);&lt;br /&gt;                    break;&lt;br /&gt;                case CommunicationState.Faulted:&lt;br /&gt;                    labelStatus.Text = "Faulted";&lt;br /&gt;                    EnableControls(false);&lt;br /&gt;                    break;&lt;br /&gt;                case CommunicationState.Opened:&lt;br /&gt;                    labelStatus.Text = "Connected";&lt;br /&gt;                    EnableControls(true);&lt;br /&gt;                    break;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-283608109304544140?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/283608109304544140/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=283608109304544140" title="11 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/283608109304544140?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/283608109304544140?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/05/wcf-serverclient-chat-sample.html" title="WCF Server/Client Chat Sample" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>11</thr:total></entry><entry gd:etag="W/&quot;CUABRno7eSp7ImA9WxZbGUU.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-3983071128198831039</id><published>2008-04-23T13:29:00.000-07:00</published><updated>2008-04-23T13:49:17.401-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-04-23T13:49:17.401-07:00</app:edited><title>A SilverLight-WCF Chat</title><content type="html">&lt;ul class="Download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/SilverLightWCFChat.zip"&gt;Download SilverLightWCFChat - 658.12 KB&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt; &lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fislameldemery.blogspot.com%2f2008%2f04%2fsilverlight-wcf-chat.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fislameldemery.blogspot.com%2f2008%2f04%2fsilverlight-wcf-chat.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This is very simple and basic SilverLight-WCF chat application that uses basicHttpBinding and a timer to call the&lt;br /&gt;WCF service in order to refresh the SilverLight client each certain amount of time.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;img height="349" src="http://www.geocities.com/issy.issy/chat.JPG" width="553" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Technique&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;The solution consists of:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;ASP.NET Web Project &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;ASP.NET page to host the SilverLight application&lt;/li&gt;&lt;br /&gt;&lt;li&gt;WCF Service which contains two generic lists to hold online chatters and messages history&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;SilverLight Project (Client)&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;SilverLight client calls the &lt;code lang="cs"&gt;Join()&lt;/code&gt; method and starts the timer, the timer ticks every two seconds&lt;br /&gt;and calls &lt;code lang="cs"&gt;GetChatters()&lt;/code&gt; and &lt;code lang="cs"&gt;GetMessages()&lt;/code&gt; methods, client now is free to call &lt;br /&gt;&lt;code lang="cs"&gt;Say()&lt;/code&gt; method to send message to other clients or call &lt;code lang="cs"&gt;Leave()&lt;/code&gt; method to disconnect&lt;br /&gt;from the service and stop the timer.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;WCF service responds to client calls to add or remove &lt;code lang="cs"&gt;Client&lt;/code&gt; or &lt;code lang="cs"&gt;Message&lt;/code&gt; from&lt;br /&gt;the generic lists, or send these lists back to the client.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;WCF Service&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;This is the service contract&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    [ServiceContract]&lt;br /&gt;    public interface IbasicChatService&lt;br /&gt;    {&lt;br /&gt;        [OperationContract(IsOneWay = false)]&lt;br /&gt;        bool Join(Chatter _chatter);&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsOneWay = true)]&lt;br /&gt;        void Say(Message _msg);&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsOneWay = false)]&lt;br /&gt;        List&lt; Chatter&gt; GetChatters();&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsOneWay = false)]&lt;br /&gt;        List&lt; Message&gt; GetMessages();&lt;br /&gt;&lt;br /&gt;        [OperationContract(IsOneWay = true)]&lt;br /&gt;        void Leave(Chatter _chatter);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This is the client and message data contracts&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    [DataContract]&lt;br /&gt;    public class Chatter&lt;br /&gt;    {&lt;br /&gt;        private string _name;&lt;br /&gt;        private DateTime _time;&lt;br /&gt;&lt;br /&gt;        [DataMember]&lt;br /&gt;        public string Name&lt;br /&gt;        {&lt;br /&gt;            get { return _name; }&lt;br /&gt;            set { _name = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [DataMember]&lt;br /&gt;        public DateTime Time&lt;br /&gt;        {&lt;br /&gt;            get { return _time; }&lt;br /&gt;            set { _time = value; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [DataContract]&lt;br /&gt;    public class Message&lt;br /&gt;    {&lt;br /&gt;        private string _sender;&lt;br /&gt;        private string _content;&lt;br /&gt;        private DateTime _time;&lt;br /&gt;&lt;br /&gt;        [DataMember]&lt;br /&gt;        public string Sender&lt;br /&gt;        {&lt;br /&gt;            get { return _sender; }&lt;br /&gt;            set { _sender = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [DataMember]&lt;br /&gt;        public string Content&lt;br /&gt;        {&lt;br /&gt;            get { return _content; }&lt;br /&gt;            set { _content = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [DataMember]&lt;br /&gt;        public DateTime Time&lt;br /&gt;        {&lt;br /&gt;            get { return _time; }&lt;br /&gt;            set { _time = value; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This is the service implementation&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]&lt;br /&gt;    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,&lt;br /&gt;                    ConcurrencyMode=ConcurrencyMode.Multiple)]&lt;br /&gt;    public class basicChatService : IbasicChatService&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        private List&lt; Chatter&gt; chatters = new List&lt; Chatter&gt;();&lt;br /&gt;        private List&lt; Message&gt; messages = new List&lt; Message&gt;();&lt;br /&gt;&lt;br /&gt;        private object syncObj = new object();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        #region IbasicChatService Members&lt;br /&gt;&lt;br /&gt;        public bool Join(Chatter _chatter)&lt;br /&gt;        {&lt;br /&gt;            foreach (Chatter chtr in this.chatters)&lt;br /&gt;            {&lt;br /&gt;                if (chtr.Name == _chatter.Name)&lt;br /&gt;                {&lt;br /&gt;                    return false;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            lock (syncObj)&lt;br /&gt;            {&lt;br /&gt;                this.chatters.Add(_chatter);&lt;br /&gt;&lt;br /&gt;                Message msg = new Message();&lt;br /&gt;                msg.Sender = "Service";&lt;br /&gt;                msg.Content = "---- " + _chatter.Name + " joined chat ----";&lt;br /&gt;                msg.Time = DateTime.Now;&lt;br /&gt;&lt;br /&gt;                this.messages.Add(msg);&lt;br /&gt;            }&lt;br /&gt;            &lt;br /&gt;            return true;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Say(Message _msg)&lt;br /&gt;        {&lt;br /&gt;            lock (syncObj)&lt;br /&gt;            {&lt;br /&gt;                this.messages.Add(_msg);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public List&lt; Chatter&gt; GetChatters()&lt;br /&gt;        {&lt;br /&gt;            return this.chatters;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public List&lt; Message&gt; GetMessages()&lt;br /&gt;        {&lt;br /&gt;            return this.messages;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Leave(Chatter _chatter)&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            foreach (Chatter chtr in this.chatters)&lt;br /&gt;            {&lt;br /&gt;                if (chtr.Name == _chatter.Name)&lt;br /&gt;                {&lt;br /&gt;                    this.chatters.Remove(chtr);&lt;br /&gt;&lt;br /&gt;                    if (this.chatters.Count &lt; 1)&lt;br /&gt;                    {&lt;br /&gt;                        this.messages.Clear();&lt;br /&gt;                        return;&lt;br /&gt;                    }&lt;br /&gt;                    Message msg = new Message();&lt;br /&gt;                    msg.Sender = "Server";&lt;br /&gt;                    msg.Content = "---- " + _chatter.Name + " leftt chat ----";&lt;br /&gt;                    msg.Time = DateTime.Now;&lt;br /&gt;&lt;br /&gt;                    this.messages.Add(msg);&lt;br /&gt;&lt;br /&gt;                    return;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To integrate SilverLight application with WCF service you have to use basicHttpBinding as followed in the &lt;br /&gt;service configuarion file&lt;/p&gt;&lt;br /&gt;&lt;pre lang="xml"&gt;&lt;br /&gt;    &lt; system.serviceModel&gt;&lt;br /&gt;        &lt; serviceHostingEnvironment aspNetCompatibilityEnabled="true"&gt;&lt;br /&gt;        &lt; /serviceHostingEnvironment&gt;&lt;br /&gt;        &lt; services&gt;&lt;br /&gt;            &lt; service behaviorConfiguration="SilverlightApp_Host.basicChatServiceBehavior" &lt;br /&gt;                     name="SilverlightApp_Host.basicChatService"&gt;&lt;br /&gt;                &lt; host&gt;&lt;br /&gt;                    &lt; baseAddresses&gt;&lt;br /&gt;                        &lt; add baseAddress="http://localhost:6464/localsystem"/&gt;&lt;br /&gt;                    &lt; /baseAddresses&gt;&lt;br /&gt;                &lt; /host&gt;&lt;br /&gt;                &lt; endpoint address="" &lt;br /&gt;                          binding="basicHttpBinding" &lt;br /&gt;                          contract="SilverlightApp_Host.IbasicChatService"&gt;&lt;br /&gt;                    &lt; identity&gt;&lt;br /&gt;                        &lt; dns value="localhost"/&gt;&lt;br /&gt;                    &lt; /identity&gt;&lt;br /&gt;                &lt; /endpoint&gt;&lt;br /&gt;                &lt; endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt;&lt;br /&gt;            &lt; /service&gt;&lt;br /&gt;        &lt; /services&gt;&lt;br /&gt;        &lt; behaviors&gt;&lt;br /&gt;            &lt; serviceBehaviors&gt;&lt;br /&gt;                &lt; behavior name="SilverlightApp_Host.basicChatServiceBehavior"&gt;&lt;br /&gt;                    &lt; serviceMetadata httpGetEnabled="true"/&gt;&lt;br /&gt;                    &lt; serviceDebug includeExceptionDetailInFaults="true"/&gt;&lt;br /&gt;                &lt; /behavior&gt;&lt;br /&gt;            &lt; /serviceBehaviors&gt;&lt;br /&gt;        &lt; /behaviors&gt;&lt;br /&gt;        &lt; bindings&gt;&lt;br /&gt;            &lt; basicHttpBinding&gt;&lt;br /&gt;                &lt; binding name="basicBinding"&lt;br /&gt;                         closeTimeout="00:00:20"&lt;br /&gt;                         maxBufferPoolSize="1048576"&lt;br /&gt;                         maxBufferSize="1048576"&lt;br /&gt;                         maxReceivedMessageSize="1048576"&lt;br /&gt;                         openTimeout="00:00:20"&lt;br /&gt;                         receiveTimeout="01:00:00"&lt;br /&gt;                         sendTimeout="00:01:00"&lt;br /&gt;                         transferMode="Buffered"&gt;&lt;br /&gt;                    &lt; readerQuotas maxArrayLength="1048576" maxBytesPerRead="1048576"&lt;br /&gt;                                  maxStringContentLength="1048576"/&gt;&lt;br /&gt;                    &lt; security mode="None"&gt;&lt;br /&gt;                        &lt; transport clientCredentialType="Windows"/&gt;&lt;br /&gt;                    &lt; /security&gt;&lt;br /&gt;                &lt; /binding&gt;&lt;br /&gt;            &lt; /basicHttpBinding&gt;&lt;br /&gt;        &lt; /bindings&gt;&lt;br /&gt;    &lt; /system.serviceModel&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;SilverLight Client&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I'm a very bad designer so I'll let you imagine any design for this application which of course will be better than&lt;br /&gt;this, this is just two list boxes to hold the online chatters and messages history coming from the service, other&lt;br /&gt;controls are three buttons to join, leave the chat or send a message, and two textboxes for chatter name, and message.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This is the application xaml code&lt;/p&gt;&lt;br /&gt;&lt;pre lang="xml"&gt;&lt;br /&gt;&lt; UserControl x:Class="SilverlightApp.Page"&lt;br /&gt;    xmlns="http://schemas.microsoft.com/client/2007" &lt;br /&gt;    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;  &lt;br /&gt;    &lt; Grid x:Name="LayoutRoot" &gt;&lt;br /&gt;&lt;br /&gt;        &lt; Grid.Background&gt;&lt;br /&gt;            &lt; LinearGradientBrush StartPoint="0,0" EndPoint="1,1"&gt;&lt;br /&gt;                &lt; GradientStop Color="Black" Offset="0"/&gt;&lt;br /&gt;                &lt; GradientStop Color="LavenderBlush" Offset="1"/&gt;&lt;br /&gt;            &lt; /LinearGradientBrush&gt;&lt;br /&gt;        &lt; /Grid.Background&gt;&lt;br /&gt;&lt;br /&gt;        &lt; Grid.RowDefinitions&gt;&lt;br /&gt;            &lt; RowDefinition Height="50"/&gt;&lt;br /&gt;            &lt; RowDefinition Height="25"/&gt;&lt;br /&gt;            &lt; RowDefinition Height="25"/&gt;&lt;br /&gt;            &lt; RowDefinition Height="200"/&gt;&lt;br /&gt;            &lt; RowDefinition Height="30"/&gt;&lt;br /&gt;            &lt; RowDefinition Height="50"/&gt;&lt;br /&gt;        &lt; /Grid.RowDefinitions&gt;&lt;br /&gt;        &lt; Grid.ColumnDefinitions&gt;&lt;br /&gt;            &lt; ColumnDefinition Width="70"/&gt;&lt;br /&gt;            &lt; ColumnDefinition Width="360"/&gt;&lt;br /&gt;            &lt; ColumnDefinition Width="120"/&gt;&lt;br /&gt;            &lt; ColumnDefinition Width="70"/&gt;&lt;br /&gt;        &lt; /Grid.ColumnDefinitions&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; TextBlock x:Name="labelStatus"&lt;br /&gt;                   Margin="8, 5, 2, 2"&lt;br /&gt;                   Grid.Row="1" &lt;br /&gt;                   Grid.Column="2"&lt;br /&gt;                   FontFamily="Consolas"&lt;br /&gt;                   FontSize="13" &lt;br /&gt;                   Foreground="White"&gt;Offline&lt; /TextBlock&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; Grid x:Name="layoutLogin" Grid.Row="2" Grid.Column="1"&gt;&lt;br /&gt;            &lt; Grid.RowDefinitions&gt;&lt;br /&gt;                &lt; RowDefinition Height="25" /&gt;&lt;br /&gt;            &lt; /Grid.RowDefinitions&gt;&lt;br /&gt;            &lt; Grid.ColumnDefinitions&gt;&lt;br /&gt;                &lt; ColumnDefinition Width="80"/&gt;&lt;br /&gt;                &lt; ColumnDefinition Width="160"/&gt;&lt;br /&gt;                &lt; ColumnDefinition Width="*"/&gt;&lt;br /&gt;            &lt; /Grid.ColumnDefinitions&gt;&lt;br /&gt;&lt;br /&gt;            &lt; TextBlock  FontFamily="Consolas"&lt;br /&gt;                        Margin="4, 2, 2, 0" &lt;br /&gt;                        Grid.Row="0"&lt;br /&gt;                        Grid.Column="0"&lt;br /&gt;                        FontSize="12" &lt;br /&gt;                        Foreground="White"&gt;User Name:&lt; /TextBlock&gt;&lt;br /&gt;            &lt;br /&gt;            &lt; TextBox x:Name="textboxName"&lt;br /&gt;                     Margin="2, 2, 2, 2" &lt;br /&gt;                     Grid.Row="0" &lt;br /&gt;                     Grid.Column="1"&gt;&lt; /TextBox&gt;&lt;br /&gt;            &lt;br /&gt;            &lt; Button x:Name="buttonJoin"&lt;br /&gt;                    Background="Transparent" &lt;br /&gt;                    Margin="2, 2, 2, 2" &lt;br /&gt;                    Grid.Row="0"&lt;br /&gt;                    Grid.Column="2"&lt;br /&gt;                    Click="buttonJoin_Click" &lt;br /&gt;                    Content="Join"&gt;&lt; /Button&gt;&lt;br /&gt;&lt;br /&gt;        &lt; /Grid&gt;&lt;br /&gt;&lt;br /&gt;        &lt; Button x:Name="buttonLeave" &lt;br /&gt;                Background="Transparent"&lt;br /&gt;                Margin="2, 2, 2, 2" &lt;br /&gt;                Click="buttonLeave_Click" &lt;br /&gt;                Grid.Row="2"&lt;br /&gt;                Grid.Column="2" &lt;br /&gt;                Content="Leave"&gt;&lt; /Button&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; ListBox x:Name="listBoxMsgs"&lt;br /&gt;                 LayoutUpdated="listBoxMsgs_LayoutUpdated"&lt;br /&gt;                 Margin="2, 2, 2, 2"&lt;br /&gt;                 Grid.Row="3" &lt;br /&gt;                 Grid.Column="1"&gt;&lt; /ListBox&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; ListBox x:Name="listBoxNames" &lt;br /&gt;                 Margin="2, 2, 2, 2"&lt;br /&gt;                 Grid.Row="3" &lt;br /&gt;                 Grid.Column="2"&gt;&lt; /ListBox&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; TextBox x:Name="textboxMsg"&lt;br /&gt;                 Margin="2, 2, 2, 2" &lt;br /&gt;                 Grid.Row="4" &lt;br /&gt;                 Grid.Column="1"&gt;&lt; /TextBox&gt;&lt;br /&gt;        &lt;br /&gt;        &lt; Button x:Name="buttonSend"&lt;br /&gt;                Background="Transparent"&lt;br /&gt;                Margin="2, 2, 2, 2"&lt;br /&gt;                Grid.Row="4"&lt;br /&gt;                Grid.Column="2"&lt;br /&gt;                Click="buttonSend_Click"  &lt;br /&gt;                Content="Send"&gt;&lt; /Button&gt;&lt;br /&gt;        &lt;br /&gt;    &lt; /Grid&gt;&lt;br /&gt;&lt; /UserControl&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;SilverLight client implementation consists of some feilds, constructor, connection event handlers, private methods, and UI event handlers&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Feilds&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;namespace SilverlightApp&lt;br /&gt;{&lt;br /&gt;    public partial class Page : UserControl&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        #region Feilds&lt;br /&gt;&lt;br /&gt;        //TIMER&lt;br /&gt;        DispatcherTimer _timer = null;&lt;br /&gt;&lt;br /&gt;        SVC.IbasicChatServiceClient proxy = null;&lt;br /&gt;        SVC.Chatter localChatter = null;&lt;br /&gt;&lt;br /&gt;        //List to hold online chatters&lt;br /&gt;        List&lt; SVC.Chatter&gt; chatters = new List&lt; SilverlightApp.SVC.Chatter&gt;();&lt;br /&gt;&lt;br /&gt;        //List to hold messages history&lt;br /&gt;        List&lt; SVC.Message&gt; messages = new List&lt; SilverlightApp.SVC.Message&gt;();&lt;br /&gt;&lt;br /&gt;        //To enable listbox auto scroll&lt;br /&gt;        bool flag = false;&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;        &lt;br /&gt;        ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Page constructor&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;        public Page()&lt;br /&gt;        {&lt;br /&gt;            InitializeComponent();&lt;br /&gt;            buttonLeave.IsEnabled = false;&lt;br /&gt;            buttonSend.IsEnabled = false;&lt;br /&gt;            textboxMsg.KeyDown += new KeyEventHandler(textboxMsg_KeyDown);&lt;br /&gt;&lt;br /&gt;            //Create Timer and set interval&lt;br /&gt;            _timer = new DispatcherTimer();&lt;br /&gt;            _timer.Interval = TimeSpan.FromSeconds(2);&lt;br /&gt;            _timer.Tick += new EventHandler(_timer_Tick);&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Connection event handlers&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;&lt;br /&gt;        #region Connection Event Handlers&lt;br /&gt;&lt;br /&gt;        void proxy_JoinCompleted(object sender, SilverlightApp.SVC.JoinCompletedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            if (e.Result)&lt;br /&gt;            {&lt;br /&gt;                labelStatus.Text = "Online";&lt;br /&gt;                this._timer.Start();&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                proxy.Close();&lt;br /&gt;                labelStatus.Text = "Name Found";&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void proxy_LeaveCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            proxy.Close();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void proxy_GetMessagesCompleted(object sender, SilverlightApp.SVC.GetMessagesCompletedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            listBoxMsgs.Items.Clear();&lt;br /&gt;            foreach (SVC.Message msg in e.Result)&lt;br /&gt;            {&lt;br /&gt;                //This will not scroll the listbox&lt;br /&gt;                //listBoxMsgs.Items.Add(msg.Sender + " : " + msg.Content);&lt;br /&gt;&lt;br /&gt;                //Auto scroll, AddItem() is a private method&lt;br /&gt;                AddItem(msg.Sender + " : " + msg.Content);&lt;br /&gt;                flag = true;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void proxy_GetChattersCompleted(object sender, SilverlightApp.SVC.GetChattersCompletedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            listBoxNames.Items.Clear();&lt;br /&gt;            foreach (SVC.Chatter chtr in e.Result)&lt;br /&gt;            {&lt;br /&gt;                listBoxNames.Items.Add(chtr.Name);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerChannel_Opened(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerChannel_Faulted(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void InnerChannel_Closed(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            HandleProxy();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Private methods&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;        #region Private Methods&lt;br /&gt;        &lt;br /&gt;        public void AddItem(String messageText)&lt;br /&gt;        {&lt;br /&gt;            listBoxMsgs.Items.Add(new ListBoxItem { Content = messageText });&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        private void Join()&lt;br /&gt;        {&lt;br /&gt;            proxy = null;&lt;br /&gt;            //CREATE PROXY&lt;br /&gt;            proxy = new SilverlightApp.SVC.IbasicChatServiceClient();&lt;br /&gt;            proxy.InnerChannel.Closed += new EventHandler(InnerChannel_Closed);&lt;br /&gt;            proxy.InnerChannel.Faulted += new EventHandler(InnerChannel_Faulted);&lt;br /&gt;            proxy.InnerChannel.Opened += new EventHandler(InnerChannel_Opened);&lt;br /&gt;&lt;br /&gt;            //CREATE LOCAL CLIENT&lt;br /&gt;            this.localChatter = new SilverlightApp.SVC.Chatter();&lt;br /&gt;            this.localChatter.Name = textboxName.Text.ToString();&lt;br /&gt;            this.localChatter.Time = DateTime.Now;&lt;br /&gt;&lt;br /&gt;            //JOIN()&lt;br /&gt;            proxy.JoinAsync(this.localChatter);&lt;br /&gt;            proxy.JoinCompleted += &lt;br /&gt;            new EventHandler&lt; SilverlightApp.SVC.JoinCompletedEventArgs&gt;(proxy_JoinCompleted);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void Send()&lt;br /&gt;        {&lt;br /&gt;            if (proxy != null &amp;&amp; proxy.State == CommunicationState.Opened)&lt;br /&gt;            {&lt;br /&gt;                SVC.Message msg = new SilverlightApp.SVC.Message();&lt;br /&gt;                msg.Sender = this.localChatter.Name;&lt;br /&gt;                msg.Content = textboxMsg.Text.ToString();&lt;br /&gt;                msg.Time = DateTime.Now;&lt;br /&gt;&lt;br /&gt;                proxy.SayAsync(msg);&lt;br /&gt;                textboxMsg.Text = "";&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                HandleProxy();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void HandleProxy()&lt;br /&gt;        {&lt;br /&gt;            if (proxy != null)&lt;br /&gt;            {&lt;br /&gt;                switch (proxy.State)&lt;br /&gt;                {&lt;br /&gt;                    case CommunicationState.Closed:&lt;br /&gt;                        proxy = null;&lt;br /&gt;                        labelStatus.Text = "Offline";&lt;br /&gt;                        buttonJoin.IsEnabled = true;&lt;br /&gt;                        buttonLeave.IsEnabled = false;&lt;br /&gt;                        buttonSend.IsEnabled = false;&lt;br /&gt;                        listBoxMsgs.Items.Clear();&lt;br /&gt;                        listBoxNames.Items.Clear();&lt;br /&gt;                        break;&lt;br /&gt;                    case CommunicationState.Closing:&lt;br /&gt;                        break;&lt;br /&gt;                    case CommunicationState.Created:&lt;br /&gt;                        break;&lt;br /&gt;                    case CommunicationState.Faulted:&lt;br /&gt;                        proxy.Abort();&lt;br /&gt;                        proxy = null;&lt;br /&gt;                        labelStatus.Text = "Offline";&lt;br /&gt;                        buttonJoin.IsEnabled = true;&lt;br /&gt;                        buttonLeave.IsEnabled = false;&lt;br /&gt;                        buttonSend.IsEnabled = false;&lt;br /&gt;                        listBoxMsgs.Items.Clear();&lt;br /&gt;                        listBoxNames.Items.Clear();&lt;br /&gt;                        break;&lt;br /&gt;                    case CommunicationState.Opened:&lt;br /&gt;                        buttonJoin.IsEnabled = false;&lt;br /&gt;                        buttonLeave.IsEnabled = true;&lt;br /&gt;                        buttonSend.IsEnabled = true;&lt;br /&gt;                        labelStatus.Text = "Online";&lt;br /&gt;                        break;&lt;br /&gt;                    case CommunicationState.Opening:&lt;br /&gt;                        break;&lt;br /&gt;                    default:&lt;br /&gt;                        break;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                //Join();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;And finally the UI event handlers&lt;/p&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;        #region UI Events&lt;br /&gt;&lt;br /&gt;        void _timer_Tick(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            //Refresh online chatters and messages by calling GetChattersAsync() and GetMessagesAsync()&lt;br /&gt;            proxy.GetChattersAsync();&lt;br /&gt;            proxy.GetChattersCompleted += &lt;br /&gt;            new EventHandler&lt; SilverlightApp.SVC.GetChattersCompletedEventArgs&gt;(proxy_GetChattersCompleted);&lt;br /&gt;&lt;br /&gt;            proxy.GetMessagesAsync();&lt;br /&gt;            proxy.GetMessagesCompleted += &lt;br /&gt;            new EventHandler&lt; SilverlightApp.SVC.GetMessagesCompletedEventArgs&gt;(proxy_GetMessagesCompleted);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void textboxMsg_KeyDown(object sender, KeyEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            if (e.Key == Key.Enter)&lt;br /&gt;            {&lt;br /&gt;                Send();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonJoin_Click(object sender, RoutedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            Join();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonSend_Click(object sender, RoutedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            Send();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void buttonLeave_Click(object sender, RoutedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            this._timer.Stop();&lt;br /&gt;            if (proxy != null &amp;&amp; proxy.State == CommunicationState.Opened)&lt;br /&gt;            {&lt;br /&gt;                proxy.LeaveAsync(this.localChatter);&lt;br /&gt;                proxy.LeaveCompleted += &lt;br /&gt;                new EventHandler&lt; System.ComponentModel.AsyncCompletedEventArgs&gt;(proxy_LeaveCompleted);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                HandleProxy();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private void listBoxMsgs_LayoutUpdated(object sender, EventArgs e)&lt;br /&gt;        {&lt;br /&gt;            if (flag &amp;&amp; listBoxMsgs.Items.Count &gt; 1)&lt;br /&gt;            {&lt;br /&gt;                listBoxMsgs.ScrollIntoView(listBoxMsgs.Items[listBoxMsgs.Items.Count - 1]);&lt;br /&gt;                flag = false;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Other Stuff&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Enable cross domain calls for SilverLight application&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In order to enable cross domain calls just copy this file clientaccesspolicy.xml to your host root, if you use IIS then&lt;br /&gt;copy the file to WWWRoot folder and then restart IIS. (file is included in the source code).&lt;br /&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-3983071128198831039?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/3983071128198831039/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=3983071128198831039" title="120 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3983071128198831039?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3983071128198831039?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/04/silverlight-wcf-chat.html" title="A SilverLight-WCF Chat" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>120</thr:total></entry><entry gd:etag="W/&quot;CUcDQn04cCp7ImA9WxZbGUs.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-6353624357692732066</id><published>2008-04-15T09:49:00.000-07:00</published><updated>2008-04-23T08:04:33.338-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-04-23T08:04:33.338-07:00</app:edited><title>WCF WPF Internet Chat Application with File Transefer</title><content type="html">&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fislameldemery.blogspot.com%2f2008%2f04%2fwcf-wpf-internet-chat-application-with.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fislameldemery.blogspot.com%2f2008%2f04%2fwcf-wpf-internet-chat-application-with.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Try The Chat Online &lt;/h3&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/WPFClient.zip"&gt;Download Chat&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Online Service IP : (service is stand by)&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="Chat Login" src="http://www.codeproject.com/KB/IP/WCFWPFChatRoot/login.JPG" /&gt;&lt;br /&gt;&lt;br/&gt;&lt;br /&gt;&lt;img alt="Chat Login" src="http://www.codeproject.com/KB/IP/WCFWPFChatRoot/chat.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.codeproject.com/KB/IP/WCFWPFChatRoot.aspx"&gt;See the article on CodeProject for better reading&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.geocities.com/issy.issy/WCFWPFApp.zip"&gt;Download Source Code&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;About Online Chat..&lt;/h4&gt;&lt;br /&gt;As I let the service opened 24x7 , I expected to see some people who will try the demo chat online, this picture shows some (I wished I could talk to them, Thank you for trying).&lt;br /&gt;&lt;br/&gt;&lt;br /&gt;&lt;img alt="Try Chat Online" src="http://www.geocities.com/issy.issy/liveTry.JPG" /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-6353624357692732066?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/6353624357692732066/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=6353624357692732066" title="20 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/6353624357692732066?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/6353624357692732066?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/04/wcf-wpf-internet-chat-application-with.html" title="WCF WPF Internet Chat Application with File Transefer" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>20</thr:total></entry><entry gd:etag="W/&quot;CU4MRH08fSp7ImA9WxZbFEw.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-3487564684236215797</id><published>2008-03-07T16:13:00.000-08:00</published><updated>2008-04-16T23:33:05.375-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-04-16T23:33:05.375-07:00</app:edited><title>ASP.NET Ajax Chat Web Application</title><content type="html">&lt;ul class="Download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.codeproject.com/KB/ajax/ChatRoom/ChatRoom.zip"&gt;Download ChatRoom - 281.73 KB&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I've developed a simple chat web application that deals with xml files to store information about online chatters,&lt;br /&gt;using ASP.NET, C#, Linq to XML, Ajax -Anthem Framework-.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="Chat UI" src="http://www.codeproject.com/KB/ajax/ChatRoom/chat.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Technique&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The application includes a class to handle the xml file by some methods to create the xml or load it, to save info, &lt;br /&gt;modify it, or remove it.&lt;br /&gt;The public methods of this class are:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;---------------------------------------------------------------------------&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;void Join(string userName, DateTime dateTime)&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;void Say(string userName, string msg, DateTime dateTime)&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;void Leave(string userName, DateTime dateTime)&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;---------------------------------------------------------------------------&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;List&lt; string &gt; GetOnlineNames()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;int GetNumberOfOnlines()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;code lang="cs"&gt;List&lt; string &gt; GetMessagesHistory()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;---------------------------------------------------------------------------&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The Client-side calls (asynchronously using ajax) these methods Join(), Say(), Leave().&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;And a timer on the Server-side ticks every fixed time (2 seconds in our app.), &lt;br /&gt;to read the xml (by calling these methods GetOnlineNames(), GetNumberOfOnlines(), GetMessagesHistory())&lt;br /&gt;and refresh our controls (asynchronously).&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;Starting with our XHandle.cs class which is like a chat room, lets see its members:&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Xml.Linq;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;&lt;br /&gt;public class XHandle&lt;br /&gt;{&lt;br /&gt;    private string _path;&lt;br /&gt;    private string _xPageName;&lt;br /&gt;    private string _FullPath;&lt;br /&gt;&lt;br /&gt;    private XDocument _xDoc;&lt;br /&gt;    private bool _xDocCreated;&lt;br /&gt;&lt;br /&gt;    private XElement _usersRoot;&lt;br /&gt;    private int _onlineUsers;&lt;br /&gt;    &lt;br /&gt;    ....&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The constructor job is to:&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Know the path of the App_Data folder (&lt;code&gt;_path&lt;/code&gt;),&lt;br /&gt;and the name of the xml file (&lt;code&gt;_xPageName&lt;/code&gt;), to set the &lt;code&gt;_FullPath&lt;/code&gt;&lt;br /&gt;that we will be using shortly.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Check to see if the xml file is already created, or create it if it is not.&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;public XHandle(string _path)&lt;br /&gt;    {&lt;br /&gt;        this._path = _path;&lt;br /&gt;        this._xDocCreated = false;&lt;br /&gt;        this._xPageName = &amp;quot;Default&amp;quot;;&lt;br /&gt;        this._FullPath = this._path + @&amp;quot;\&amp;quot; + this._xPageName + &amp;quot;.xml&amp;quot;;&lt;br /&gt;        this._onlineUsers = 0;&lt;br /&gt;&lt;br /&gt;        //Check the xml page if already exist&lt;br /&gt;        LoadXPage();&lt;br /&gt;&lt;br /&gt;        //or create it if it doesnt&lt;br /&gt;        if (!_xDocCreated)&lt;br /&gt;        {&lt;br /&gt;            CreateXPage();&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public XHandle(string _path, string ChatRoomName)&lt;br /&gt;    {&lt;br /&gt;        this._path = _path;&lt;br /&gt;        this._xDocCreated = false;&lt;br /&gt;        this._xPageName = ChatRoomName;&lt;br /&gt;        this._FullPath = this._path + @&amp;quot;\&amp;quot; + this._xPageName + &amp;quot;.xml&amp;quot;;&lt;br /&gt;&lt;br /&gt;        //Check the xml page if already exist&lt;br /&gt;        LoadXPage();&lt;br /&gt;&lt;br /&gt;        //or create it if it doesnt&lt;br /&gt;        if (!_xDocCreated)&lt;br /&gt;        {&lt;br /&gt;            CreateXPage();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Private Methods&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;LoadXPage()&lt;/code&gt; and &lt;code&gt;CreateXPage()&lt;/code&gt; are private methods to load or create&lt;br /&gt;the xml file and set the &lt;code&gt;_xDocCreated&lt;/code&gt; bool to true or false;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    private void CreateXPage()&lt;br /&gt;    {&lt;br /&gt;        _xDoc = new XDocument();&lt;br /&gt;        XDeclaration dec = new XDeclaration(&amp;quot;1.0&amp;quot;, &amp;quot;utf-8&amp;quot;, &amp;quot;yes&amp;quot;);&lt;br /&gt;        _xDoc.Declaration = dec;&lt;br /&gt;        _usersRoot = new XElement(&amp;quot;users&amp;quot;);&lt;br /&gt;        _xDoc.Add(_usersRoot);&lt;br /&gt;        _xDoc.Save(_FullPath);&lt;br /&gt;        _xDocCreated = true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void LoadXPage()&lt;br /&gt;    {&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            _usersRoot = XElement.Load(_FullPath);&lt;br /&gt;            _xDocCreated = true;&lt;br /&gt;        }&lt;br /&gt;        catch&lt;br /&gt;        {&lt;br /&gt;            _xDocCreated = false;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Creating the xml file will end up with this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="XML File" src="http://www.codeproject.com/KB/ajax/ChatRoom/xmlCreated.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Public Methods&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When a user joins the chat, we save their information as name, message, and dateTime,&lt;br /&gt;when a user say something we also save their information as name, message, and dateTime,&lt;br /&gt;and when they leave we just remove any info that corresponds to their name.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This is the xml file when a user named Ahmed joins the chat&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="join" src="http://www.codeproject.com/KB/ajax/ChatRoom/join.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This is the xml file when a user named Ahmed says hello&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="say" src="http://www.codeproject.com/KB/ajax/ChatRoom/say.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;And finally this is the xml file when the user(s) leave&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="XML File" src="http://www.codeproject.com/KB/ajax/ChatRoom/xmlCreated.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The three methods &lt;code&gt;Join(..)&lt;/code&gt;, &lt;code&gt;void Say(..)&lt;/code&gt;, &lt;code&gt;void Leave(..)&lt;/code&gt;:&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    public void Say(string userName, string msg, DateTime dateTime)&lt;br /&gt;    {&lt;br /&gt;        XElement user = new XElement(&amp;quot;user&amp;quot;);&lt;br /&gt;        XElement elementName = new XElement(&amp;quot;name&amp;quot;, userName);&lt;br /&gt;        XElement elementLastMsg = new XElement(&amp;quot;message&amp;quot;, msg);&lt;br /&gt;        XElement elementDate = new XElement(&amp;quot;date&amp;quot;, dateTime.ToString());&lt;br /&gt;        user.Add(elementName);&lt;br /&gt;        user.Add(elementLastMsg);&lt;br /&gt;        user.Add(elementDate);&lt;br /&gt;        _usersRoot.Add(user);&lt;br /&gt;        _usersRoot.Save(_FullPath);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Join(string userName, DateTime dateTime)&lt;br /&gt;    {&lt;br /&gt;        string systemMsg = userName + &amp;quot; joined chat room.&amp;quot;;&lt;br /&gt;        this.Say(userName, systemMsg, dateTime);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Leave(string userName, DateTime dateTime)&lt;br /&gt;    {&lt;br /&gt;        var user = from o in _usersRoot.Elements(&amp;quot;user&amp;quot;)&lt;br /&gt;                   where (string)o.Element(&amp;quot;name&amp;quot;).Value == userName&lt;br /&gt;                   select o;&lt;br /&gt;&lt;br /&gt;        user.Remove();&lt;br /&gt;&lt;br /&gt;        _usersRoot.Save(_FullPath);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Other public methods are methods to get the names, number of all online chatters, &lt;br /&gt;and the messages history.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    public List&lt; string&gt; GetOnlineNames()&lt;br /&gt;    {&lt;br /&gt;        List&lt; string&gt; names = new List&lt; string&gt;();&lt;br /&gt;        var users = (from o in _usersRoot.Elements(&amp;quot;user&amp;quot;)&lt;br /&gt;                    select o).Distinct();&lt;br /&gt;&lt;br /&gt;        foreach (var user in users)&lt;br /&gt;        {&lt;br /&gt;            if (!names.Contains(user.Element(&amp;quot;name&amp;quot;).Value))&lt;br /&gt;            {&lt;br /&gt;                names.Add(user.Element(&amp;quot;name&amp;quot;).Value);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        _onlineUsers = names.Count;&lt;br /&gt;&lt;br /&gt;        return names;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public int GetNumberOfOnlines()&lt;br /&gt;    {&lt;br /&gt;        var users = (from o in _usersRoot.Elements(&amp;quot;user&amp;quot;)&lt;br /&gt;                     select o).Distinct();&lt;br /&gt;        List&lt; string&gt; names = new List&lt; string&gt;();&lt;br /&gt;        foreach (var user in users)&lt;br /&gt;        {&lt;br /&gt;            //Filter the names to avoid duplicates&lt;br /&gt;            if (!names.Contains(user.Element(&amp;quot;name&amp;quot;).Value))&lt;br /&gt;            {&lt;br /&gt;                names.Add(user.Element(&amp;quot;name&amp;quot;).Value);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        if (names.Count &gt; 0)&lt;br /&gt;        {&lt;br /&gt;            _onlineUsers = names.Count;&lt;br /&gt;            return names.Count;&lt;br /&gt;        }&lt;br /&gt;        _onlineUsers = 0;&lt;br /&gt;        return 0;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public List&lt; string&gt; GetMessagesHistory()&lt;br /&gt;    {&lt;br /&gt;        List&lt; string&gt; messages = new List&lt; string&gt;();&lt;br /&gt;        var users = (from o in _usersRoot.Elements(&amp;quot;user&amp;quot;)&lt;br /&gt;                     where o.Element(&amp;quot;message&amp;quot;).Value != string.Empty&lt;br /&gt;                     orderby DateTime.Parse(o.Element(&amp;quot;date&amp;quot;).Value) ascending&lt;br /&gt;                     select o).Distinct();&lt;br /&gt;        foreach (var user in users)&lt;br /&gt;        {&lt;br /&gt;            string fullString = user.Element(&amp;quot;name&amp;quot;).Value + &amp;quot; : &amp;quot; + user.Element(&amp;quot;message&amp;quot;).Value;&lt;br /&gt;            if (!messages.Contains(fullString))&lt;br /&gt;            {&lt;br /&gt;                messages.Add(fullString);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        return messages;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Well, now we are done with our class, we have the ability to get the online names, the number of them,&lt;br /&gt;and the messages history (this means if someone started the chat at x time and another one joined the chat&lt;br /&gt;after 30 minutes from x, the last one will get the messages history since the chat has been started..).&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Moving to ChatRoom.aspx&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;&lt;img alt="Design" src="http://www.codeproject.com/KB/ajax/ChatRoom/design.JPG" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In the Page_Load event, we are going to:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Register the page to the Anthem Manager to allow it to be called from client-side script.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Get an instance of the XHandle class.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Get the number of online chatters if there is.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Set a fixed time (may be 2 seconds) as the timer interval&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Subscribe to the Tick event&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Attach the refreshing controls methods to delegates, So we can invoke them asynchronously.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;public partial class ChatRoom : System.Web.UI.Page&lt;br /&gt;{&lt;br /&gt;    XHandle xmll;&lt;br /&gt;    &lt;br /&gt;    List&lt; string&gt; names;&lt;br /&gt;    List&lt; string&gt; msgs;&lt;br /&gt;&lt;br /&gt;    private delegate void AsyncCallingNames();&lt;br /&gt;    private delegate void AsyncCallingMessages();&lt;br /&gt;&lt;br /&gt;    AsyncCallingNames callerNames;&lt;br /&gt;    AsyncCallingMessages callerMessages;&lt;br /&gt;&lt;br /&gt;    protected void Page_Load(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        Anthem.Manager.Register(this);&lt;br /&gt;&lt;br /&gt;        xmll = new XHandle(Server.MapPath(&amp;quot;App_Data&amp;quot;), &amp;quot;FirstChatRoom&amp;quot;);&lt;br /&gt;        //Get chat room name from user or chat admin&lt;br /&gt;&lt;br /&gt;        int x = xmll.GetNumberOfOnlines();&lt;br /&gt;        if (Session[&amp;quot;userName&amp;quot;] != null)&lt;br /&gt;        {&lt;br /&gt;            LabelError.Text = &amp;quot;Online, Users Online: &amp;quot; + x.ToString();&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            LabelError.Text = &amp;quot;Offline, Users Online: &amp;quot; + x.ToString();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        Timer1.Interval = 2;&lt;br /&gt;        //I set it to 1 second, and it wroked well&lt;br /&gt;&lt;br /&gt;        Timer1.Tick += new EventHandler(Timer1_Tick);&lt;br /&gt;&lt;br /&gt;        callerNames = new AsyncCallingNames(this.RefreshListNames);&lt;br /&gt;        callerMessages = new AsyncCallingMessages(this.RefreshMessages);&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    .....&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now we have 2 jobs:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Join, say and leave, This is done by: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Join button click event handler&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Send button click event handler&lt;/li&gt;&lt;br /&gt;&lt;li&gt;onunload client-side script event handler&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    protected void ButtonJoin_Click(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        if (Session[&amp;quot;userName&amp;quot;] == null)&lt;br /&gt;        {&lt;br /&gt;            Session[&amp;quot;userName&amp;quot;] = TextBoxName.Text.ToString();&lt;br /&gt;            xmll.Join(Session[&amp;quot;userName&amp;quot;].ToString(), DateTime.Now);&lt;br /&gt;&lt;br /&gt;            TextBoxName.Enabled = false;&lt;br /&gt;&lt;br /&gt;            Timer1.StartTimer();&lt;br /&gt;&lt;br /&gt;            TextBoxType2.Focus(); &lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    protected void ButtonSend_Click(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        if (Session[&amp;quot;userName&amp;quot;] != null)&lt;br /&gt;        {&lt;br /&gt;            string name = (string)Session[&amp;quot;userName&amp;quot;];&lt;br /&gt;            string msg = TextBoxType2.Text.ToString();&lt;br /&gt;            xmll.Say(name, msg, DateTime.Now);&lt;br /&gt;            TextBoxType2.Text = &amp;quot;&amp;quot;;&lt;br /&gt;            TextBoxType2.Focus();&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            LabelError.Text = &amp;quot;You have to join with a name first..&amp;quot;;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [Anthem.Method]&lt;br /&gt;    public void Leave()&lt;br /&gt;    {&lt;br /&gt;        Timer1.StopTimer();&lt;br /&gt;&lt;br /&gt;        if (Session[&amp;quot;userName&amp;quot;] != null)&lt;br /&gt;        {&lt;br /&gt;            string name = (string)Session[&amp;quot;userName&amp;quot;];&lt;br /&gt;            xmll.Leave(name, DateTime.Now);&lt;br /&gt;&lt;br /&gt;            LabelError.Text = &amp;quot;Offline&amp;quot;;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Refresh our controls in timer tick event handler:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;ListBox of chatters names&lt;/li&gt;&lt;br /&gt;&lt;li&gt;ListBox of messages&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    void Timer1_Tick(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        if (Session[&amp;quot;userName&amp;quot;] != null)&lt;br /&gt;        {&lt;br /&gt;            IAsyncResult resultN = callerNames.BeginInvoke(null, null);&lt;br /&gt;            if (!resultN.IsCompleted)&lt;br /&gt;            {&lt;br /&gt;                callerNames.EndInvoke(resultN);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            IAsyncResult resultM = callerMessages.BeginInvoke(null, null);&lt;br /&gt;            if (!resultM.IsCompleted)&lt;br /&gt;            {&lt;br /&gt;                callerMessages.EndInvoke(resultM);&lt;br /&gt;            }&lt;br /&gt;            TextBoxType2.Focus();&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Timer1.StopTimer();&lt;br /&gt;            TextBoxType2.Text = &amp;quot;You have to join with a name first..&amp;quot;;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    private void RefreshListNames()&lt;br /&gt;    {&lt;br /&gt;        ListBox1.Items.Clear();&lt;br /&gt;        names = xmll.GetOnlineNames();&lt;br /&gt;        foreach (var name in names)&lt;br /&gt;        {&lt;br /&gt;            ListBox1.Items.Add(name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void RefreshMessages()&lt;br /&gt;    {&lt;br /&gt;        ListBox2.Items.Clear();&lt;br /&gt;        msgs = xmll.GetMessagesHistory();&lt;br /&gt;        foreach (var msg in msgs)&lt;br /&gt;        {&lt;br /&gt;            ListBox2.Items.Add(msg);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;code&gt;Leave()&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The last thing is how to call the &lt;code&gt;Leave()&lt;/code&gt; method from Client-side script&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;&lt; body  önunload=&amp;quot;Leave(); return false;&amp;quot;&gt;&lt;br /&gt;&lt; script type=&amp;quot;text/javascript&amp;quot;&gt;&lt;br /&gt;function Leave()&lt;br /&gt;{&lt;br /&gt;    Anthem_InvokePageMethod('Leave', null, null);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt; /script&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Reports&lt;/h3&gt;&lt;br /&gt;I'll really appreciate your try of this code and any problems you may get, to make this application better.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-3487564684236215797?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/3487564684236215797/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=3487564684236215797" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3487564684236215797?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3487564684236215797?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/03/aspnet-ajax-chat-web-application.html" title="ASP.NET Ajax Chat Web Application" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>4</thr:total></entry><entry gd:etag="W/&quot;CU8MRn8zfyp7ImA9WxZSFU8.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-3567483369830299927</id><published>2008-01-28T04:21:00.000-08:00</published><updated>2008-01-28T04:38:07.187-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-01-28T04:38:07.187-08:00</app:edited><title>WCF and Callbacks - How to generate proxy using svcutil tool</title><content type="html">Many of us tried to implement even a small simple of WCF service and a callback implementation, which (at least to me) I couldn't &lt;br /&gt;get it to work. I've looked &lt;a href="http://msdn.microsoft.com/msdnmag/issues/06/10/WCFEssentials/default.aspx"&gt;here&lt;/a&gt;, &lt;br /&gt;&lt;a href="http://www.c-sharpcorner.com/UploadFile/john_charles/CallbackoperationsinWindowsCommunicationFoundation06112007120551PM/CallbackoperationsinWindowsCommunicationFoundation.aspx"&gt;there&lt;/a&gt;,&lt;br /&gt;and some many others and I couldn't create a proxy which I use in my client.&lt;br /&gt;&lt;br /&gt;In order to make the WCF service able to make a Callback to clients (if some client fired some events.., or even if the service decides to&lt;br /&gt;because of an operation it monitors), you have to create a proxy (on service standards) so the client can be able to implement the ICallback interface.&lt;br /&gt;&lt;br /&gt;How can I create this proxy?&lt;br /&gt;There is two solutions for this,&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;First: Use a tool called SvcUtil.exe to generate a proxy.cs and app.config file from the service, so I can use both in my client.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Second: After making the service, start it, in the client add a service reference to thats you have just started.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;strong&gt;Generate proxy.cs and app.config files&lt;/strong&gt;&lt;br /&gt;To use the svcutil.exe tool follow this:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Start &gt; All Programs &gt; Visual Studio 200x &gt; Visual Studio Tools &gt; Visual Studio 200x Command Prompt&lt;/li&gt;&lt;br /&gt;&lt;li&gt;type &lt;code lang="cs"&gt;cd..&lt;/code&gt; and switch to this path C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin&lt;/li&gt;&lt;br /&gt;&lt;li&gt;type &lt;code lang="cs"&gt;sn.exe -Vr svcutil.exe&lt;/code&gt; &lt;img alt="Run svcutil tool" src="http://www.geocities.com/issy.issy/snWCF.JPG"/&gt; &lt;/li&gt;&lt;br /&gt;&lt;li&gt;now we can use svcutil, switch to the path where your service is &lt;img alt="Where is svcutil.exe" src="http://www.geocities.com/issy.issy/svcutilWCF.JPG" /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;if the service is .svc start it then type &lt;code lang="cs"&gt;svcutil http://localhost:8080/CallbackAppNAME/YOURSERIVCENAME.svc?wsdl &lt;/code&gt;&lt;br /&gt;&lt;img alt="Use svcutil tool" src="http://www.geocities.com/issy.issy/useSvcWCF.JPG" /&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;if the service is .exe type &lt;code lang="cs"&gt;svcutil YOURSERVICE.exe&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;there is gonna be file .wsdl and .xsd, type &lt;code lang="cs"&gt;svcutil fileName.wsdl filename.xsd /language:C# /out:Proxy.cs /config:app.config&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;The generated files can be found here C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin (this where the svcutil tool is).&lt;br /&gt;Note: There are more options you can use with svcutil tool like:&lt;br /&gt;merging new configuration file with a one already exists, use this &lt;code lang="cs"&gt;/mergeConfig&lt;/code&gt;.&lt;br /&gt;generating a proxy with asynchronous methods, use this &lt;code lang="cs"&gt;/a&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Add a service reference&lt;/strong&gt;&lt;br /&gt;You can just add a service reference from your client:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;With Visual Studio, start your ready .svc service.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;In the client solution right click to add a service reference and just point to the service.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;This will make a reference to call the service directly.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-3567483369830299927?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/3567483369830299927/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=3567483369830299927" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3567483369830299927?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3567483369830299927?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/01/wcf-and-callbacks-how-to-generate-proxy.html" title="WCF and Callbacks - How to generate proxy using svcutil tool" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>0</thr:total></entry><entry gd:etag="W/&quot;AkcNR38_eip7ImA9WxZSFUw.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-2881878104198952833</id><published>2008-01-24T16:50:00.001-08:00</published><updated>2008-01-28T03:01:36.142-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-01-28T03:01:36.142-08:00</app:edited><title>Design Patterns - Observer Pattern</title><content type="html">&lt;h5&gt;Introduction&lt;/h5&gt;&lt;br /&gt;This article explains the Observer patterns which is one of the C# Design Patterns, the article provides a very simple implementation so its complexity can be easily understood.&lt;br /&gt;&lt;br /&gt;The observer pattern makes an object that if its state changed somehow, other instances will be notified (or updated) automatically, In other words, it is used to keep track of many objects. &lt;br /&gt;&lt;img alt="observer" src="http://www.dofactory.com/Patterns/Diagrams/observer.gif" /&gt;&lt;br /&gt;&lt;h5&gt;Implementation&lt;/h5&gt;&lt;br /&gt;Imagine if we have cards game, some tables, and some players..&lt;br /&gt;On a table.., in the game context the suit of cards is changed time by time and we want to notify the players each time the&lt;br /&gt;suit is changed.&lt;br /&gt;&lt;br /&gt;Note* this is not a complete logic for a cards game, its an example.&lt;br /&gt;&lt;br /&gt;The player object is going to have a function &lt;code lang="cs"&gt;Update()&lt;/code&gt; which will be called by the notifier, and data:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Player Number (Player Identity) &lt;code lang="cs"&gt;int&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Current Suit &lt;code lang="cs"&gt;string&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Current Table Object &lt;code lang="cs"&gt;Table&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;How can the player be notified? we pass the (always changes) object of the table as a parameter in the Update() function,&lt;br /&gt;So the player (object) can see the new differences in the table (object).&lt;br /&gt;&lt;br /&gt;This is the Player object..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    interface IPlayer&lt;br /&gt;    {&lt;br /&gt;        void Update(Table _table);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class Player : IPlayer&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        public void Update(Table _table)&lt;br /&gt;        {&lt;br /&gt;            this._table = _table;&lt;br /&gt;            _currentSuit = _table.currentSuit;&lt;br /&gt;            Console.WriteLine("Player '" + _PlayerNo + "' notified that current suit is " + _currentSuit);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private int _PlayerNo;&lt;br /&gt;        private Table _table;&lt;br /&gt;        private string _currentSuit;&lt;br /&gt;&lt;br /&gt;        public Player(int _PlayerNo)&lt;br /&gt;        {&lt;br /&gt;            this._PlayerNo = _PlayerNo;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public Table CurrentTable&lt;br /&gt;        {&lt;br /&gt;            get { return _table; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In our table object you want to add players or remove players (or count them for some reasons..)&lt;br /&gt;So in the table object you'll have:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;An array list of the players objects &lt;code lang="cs"&gt;List&lt;&gt;&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Current Suit &lt;code lang="cs"&gt;string&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Table Number &lt;code lang="cs"&gt;int&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Add Player Function &lt;code lang="cs"&gt;AddPlayer()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Remove Player Function &lt;code lang="cs"&gt;RemovePlayer()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Notify Function &lt;code lang="cs"&gt;Notify()&lt;/code&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;The notify function is sending the updated object (table) to all players objects..&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    abstract class Table&lt;br /&gt;    {&lt;br /&gt;        private string _currentSuit;&lt;br /&gt;        private int _tableNo;&lt;br /&gt;        private List&lt;&gt; players = new List&lt;&gt;();&lt;br /&gt;&lt;br /&gt;        public Table(int _tableNo, string _currentSuit)&lt;br /&gt;        {&lt;br /&gt;            this._tableNo = _tableNo;&lt;br /&gt;            this._currentSuit = _currentSuit;&lt;br /&gt;        }&lt;br /&gt;        public void AddPlayer(Player _player)&lt;br /&gt;        {&lt;br /&gt;            players.Add(_player);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void RemovePlayer(Player _player)&lt;br /&gt;        {&lt;br /&gt;            players.Remove(_player);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string currentSuit&lt;br /&gt;        {&lt;br /&gt;            get { return _currentSuit; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _currentSuit = value;&lt;br /&gt;                Notify();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Notify()&lt;br /&gt;        {&lt;br /&gt;            foreach (Player _player in players)&lt;br /&gt;            {&lt;br /&gt;                _player.Update(this);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class ReadyTable : Table&lt;br /&gt;    {&lt;br /&gt;        public ReadyTable(int _tableNo, string _currentSuit) : base(_tableNo, _currentSuit)&lt;br /&gt;        { }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And the &lt;code lang="cs"&gt;Main()&lt;/code&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            //Create Table&lt;br /&gt;            ReadyTable table = new ReadyTable(1, "Spade");&lt;br /&gt;            Console.WriteLine("Starting table 1 with suit spades, suit will be changing in 3 seconds");&lt;br /&gt;&lt;br /&gt;            //Create Players&lt;br /&gt;            List&lt;player&gt; players = new List&lt;player&gt;(4);&lt;br /&gt;            for (int i = 0; i &lt; 4; i++)&lt;br /&gt;            {&lt;br /&gt;                players.Add(new Player(i));&lt;br /&gt;                table.AddPlayer(players[i]);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            Thread.Sleep(3000);&lt;br /&gt;            //Change the suit and all players will be notified&lt;br /&gt;            table.currentSuit = "Hearts";&lt;br /&gt;&lt;br /&gt;            Thread.Sleep(6000);&lt;br /&gt;            table.currentSuit = "Diamonds";&lt;br /&gt;&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-2881878104198952833?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/2881878104198952833/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=2881878104198952833" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/2881878104198952833?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/2881878104198952833?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/01/design-patterns-observer-pattern.html" title="Design Patterns - Observer Pattern" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>4</thr:total></entry><entry gd:etag="W/&quot;AkEFSHk4fSp7ImA9WxZSEUo.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-2869455916852912300</id><published>2008-01-24T03:44:00.000-08:00</published><updated>2008-01-24T04:43:39.735-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-01-24T04:43:39.735-08:00</app:edited><title>Design Patterns - The Factory Method</title><content type="html">&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;This article explains the Factory Method Pattern, which is one of the C# Design Patterns.&lt;br /&gt;&lt;br /&gt;This pattern gives you the ability to create a factory (instance) that will instantiate many relatedobjects.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;&lt;br /&gt;When to use the Factory Method?&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;A class can’t anticipate which kind of class of objects it must create.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;A class uses its subclasses to specify which objects it creates.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;You want to localize the knowledge of which class gets created.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p align="right"&gt;Cooper - Introduction to Design Patterns in C#&lt;/p&gt;&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;You can think of this like if you have some different implementation for 1 parent object, and&lt;br /&gt;then you have some other different creators for these instances.., so we will have a factory&lt;br /&gt;that decides what creators and decide what instances does every creator instantiate.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Pattern&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Imagine we have a class called Message that sends some contents through the Send() function.&lt;br /&gt;&lt;br /&gt;And we have some types of messages (Email, sms, .. etc.) each of which has a special implementation&lt;br /&gt;of the send() function.&lt;br /&gt;&lt;br /&gt;Now how to decide which type (instance) of message we will send if using a cell phone or a PC?&lt;br /&gt;&lt;br /&gt;So, this means we have different machines (cell, PC, Laptop..), and each machine will instantiate &lt;br /&gt;specific types of messages.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Message&lt;/h4&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The best way is to make an abstract class called Message and include an abstract method called Send(), So&lt;br /&gt;we can easily implement it.&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    abstract class Message&lt;br /&gt;    {&lt;br /&gt;        abstract public void Send();&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Example of different implementations..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class Email : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class VoiceMail : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class SMS : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class MMS : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Machine&lt;/h4&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Now to make the machine.. Its the the factory that will decide which instances (types) of messages to instantiate,&lt;br /&gt;so if we have more than 1 machine, we can inherit from the machine and decide in the concrete factory.&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    abstract class Machine&lt;br /&gt;    {&lt;br /&gt;        //The array of objects&lt;br /&gt;        private List&lt; Message &gt; _messages = new List&lt; Message &gt;();&lt;br /&gt;        public Machine()&lt;br /&gt;        {&lt;br /&gt;            CreateMachines();&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        //The function that each machine will override&lt;br /&gt;        abstract public void CreateMachines();&lt;br /&gt;        &lt;br /&gt;        public List&lt; Message &gt; Messaages &lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                return _messages;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Cell Phone and PC example..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class CellPhone : Machine&lt;br /&gt;    {&lt;br /&gt;        public override void CreateMachines()&lt;br /&gt;        {&lt;br /&gt;            //Instantiating objects&lt;br /&gt;            Messaages.Add(new SMS());&lt;br /&gt;            Messaages.Add(new MMS());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class PC : Machine&lt;br /&gt;    {&lt;br /&gt;        public override void CreateMachines()&lt;br /&gt;        {&lt;br /&gt;            //Instantiating objects&lt;br /&gt;            Messaages.Add(new Email());&lt;br /&gt;            Messaages.Add(new VoiceMail());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;And this how we can use the factory..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Machine[] machines = new Machine[2];&lt;br /&gt;            //The constructor is the one who calls CreateMachine()&lt;br /&gt;            machines[0] = new CellPhone();//A machine&lt;br /&gt;            machines[1] = new PC();//Another machine..&lt;br /&gt;&lt;br /&gt;            foreach (Machine _machine in machines)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine("--" + _machine.GetType().Name);&lt;br /&gt;                foreach (Message _message in _machine.Messaages)&lt;br /&gt;                {&lt;br /&gt;                    _message.Send();&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;namespace Factory_Method&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Machine[] machines = new Machine[3];&lt;br /&gt;            machines[0] = new CellPhone();&lt;br /&gt;            machines[1] = new PC();&lt;br /&gt;            machines[2] = new Laptop();&lt;br /&gt;&lt;br /&gt;            foreach (Machine _machine in machines)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine("--" + _machine.GetType().Name);&lt;br /&gt;                foreach (Message _message in _machine.Messaages)&lt;br /&gt;                {&lt;br /&gt;                    _message.Send();&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    abstract class Message&lt;br /&gt;    {&lt;br /&gt;        abstract public void Send();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class Email : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class VoiceMail : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class SMS : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    class MMS : Message&lt;br /&gt;    {&lt;br /&gt;        public override void Send()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(this.GetType().Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    abstract class Machine&lt;br /&gt;    {&lt;br /&gt;        private List&lt; Message &gt; _messages = new List&lt; Message &gt;();&lt;br /&gt;        public Machine()&lt;br /&gt;        {&lt;br /&gt;            CreateMachines();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        abstract public void CreateMachines();&lt;br /&gt;        public List&lt; Message &gt; Messaages &lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                return _messages;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class CellPhone : Machine&lt;br /&gt;    {&lt;br /&gt;        public override void CreateMachines()&lt;br /&gt;        {&lt;br /&gt;            Messaages.Add(new SMS());&lt;br /&gt;            Messaages.Add(new MMS());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class PC : Machine&lt;br /&gt;    {&lt;br /&gt;        public override void CreateMachines()&lt;br /&gt;        {&lt;br /&gt;            Messaages.Add(new Email());&lt;br /&gt;            Messaages.Add(new VoiceMail());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class Laptop : Machine&lt;br /&gt;    {&lt;br /&gt;        public override void CreateMachines()&lt;br /&gt;        {&lt;br /&gt;            Messaages.Add(new Email());&lt;br /&gt;            Messaages.Add(new VoiceMail());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-2869455916852912300?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/2869455916852912300/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=2869455916852912300" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/2869455916852912300?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/2869455916852912300?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/01/design-patterns-factory-method.html" title="Design Patterns - The Factory Method" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>2</thr:total></entry><entry gd:etag="W/&quot;D0QCRnkzeyp7ImA9WxZSEU0.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-3371624793144023674</id><published>2008-01-23T07:42:00.000-08:00</published><updated>2008-01-23T08:22:47.783-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-01-23T08:22:47.783-08:00</app:edited><title>Design Patterns - Singleton</title><content type="html">&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;This article explains the Sngileton Pattern which is one of The C# Design Patterns.&lt;br /&gt;&lt;br /&gt;The singleton pattern is used to make a class that has always only one instance, how can this be useful?&lt;br /&gt;&lt;br /&gt;There is times that you want to have only one instance of a specific class like for example a chat window,&lt;br /&gt;you want to allow each chatter to have only one opened chat window.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;This can be easily done by returning one instance of the class and allow a global access to it. How?&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;make the constructor private (or protected if you plan to inherit this class before instantiating it).&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class ChatWindow&lt;br /&gt;    {&lt;br /&gt;        private ChatWindow() { }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Second make a static refrence to the class&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class ChatWindow&lt;br /&gt;    {&lt;br /&gt;        //this is static so we can access it&lt;br /&gt;        //in the next point&lt;br /&gt;        private static ChatWindow chatObject;&lt;br /&gt;&lt;br /&gt;        private ChatWindow() { }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Third make a static function that will check if the object has been instantiated or not,&lt;br /&gt;if not, it will instantiate a new one and assign it to &lt;code lang="cs"&gt;chatObject&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class ChatWindow&lt;br /&gt;    {&lt;br /&gt;        private static ChatWindow chatObject;&lt;br /&gt;        private static object syncLock = new object();&lt;br /&gt;&lt;br /&gt;        private ChatWindow() { }&lt;br /&gt;&lt;br /&gt;        public static ChatWindow GetObject()&lt;br /&gt;        {&lt;br /&gt;            if (chatObject == null)&lt;br /&gt;            {&lt;br /&gt;                lock (syncLock)&lt;br /&gt;                {&lt;br /&gt;                    if (chatObject == null)&lt;br /&gt;                    {&lt;br /&gt;                        chatObject = new ChatWindow();&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            return chatObject;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;So I can always get only the same instance,&lt;br /&gt;&lt;br /&gt;this is the Main..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            ChatWindow TheOnlyChatObject = ChatWindow.GetObject();&lt;br /&gt;            if (TheOnlyChatObject != null)&lt;br /&gt;            { Console.WriteLine("Object instantiated"); }&lt;br /&gt;            ChatWindow sameObject = ChatWindow.GetObject();&lt;br /&gt;            if (sameObject == TheOnlyChatObject)&lt;br /&gt;            { Console.WriteLine("A new object is the same object"); }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-3371624793144023674?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/3371624793144023674/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=3371624793144023674" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3371624793144023674?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3371624793144023674?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/01/design-patterns-singleton.html" title="Design Patterns - Singleton" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>0</thr:total></entry><entry gd:etag="W/&quot;CEMARXg7cSp7ImA9WxZSEU0.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-3490115995430508176</id><published>2008-01-23T05:54:00.000-08:00</published><updated>2008-01-23T07:34:04.609-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-01-23T07:34:04.609-08:00</app:edited><title>Design Patterns - Abstract Factory</title><content type="html">&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/abstract_pattern.zip"&gt;Download Abstract Factory Pattern Source Code - 28 KB&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h3&gt;Introduction:&lt;/h3&gt;&lt;br /&gt;This article explains the Abstract Factory pattern of the Design Patterns, and implements an example.&lt;br /&gt;The Abstract Pattern is used to give you the ability to return one of related (grouped) objects of classes&lt;br /&gt;through a factory object, The factory object can return one of a family classes and can also instantiate objects of &lt;br /&gt;another family classes.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;We are going to explain this on Investments, There is types of investment like stocks and bonds.&lt;br /&gt;The investment itself can be raised and can fall, then the stocks investment for example can be raised and can fall.&lt;br /&gt;This is done through the investment object (which is the factory).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The investment class is abstract, and has two abstract (not implemented) methods: CreateRaise(), and CreateFall() , each of which is type of&lt;br /&gt;raiseInvestment and fallInvestment respectively.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    abstract class invsetment&lt;br /&gt;    {&lt;br /&gt;        public abstract raiseInvestment CreateRaise();&lt;br /&gt;        public abstract fallInvestment CreateFall();&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    abstract class fallInvestment&lt;br /&gt;    {&lt;br /&gt;        public abstract int Minus(int current);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    abstract class raiseInvestment&lt;br /&gt;    {&lt;br /&gt;        public abstract int Plus(int current);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;So what I need now is to implement fallInvestment and raiseInvestment classes..&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    /// Beside Fall and Raise classes we can add &lt;br /&gt;    /// new class to calculate the interest related&lt;br /&gt;    /// changes for example, with a static method&lt;br /&gt;    /// to directly calculate the interest.&lt;br /&gt;    &lt;br /&gt;    class Fall : fallInvestment&lt;br /&gt;    {&lt;br /&gt;        public override int Minus(int current)&lt;br /&gt;        {&lt;br /&gt;            return current - 1;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class Raise : raiseInvestment&lt;br /&gt;    {&lt;br /&gt;        public override int Plus(int current)&lt;br /&gt;        {&lt;br /&gt;            return current + 1;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Well, Now you have to decide what types of investments you want to make..&lt;br /&gt;&lt;br /&gt;There can be Stocks and Bonds, each is an investment so each can inherits investment class.&lt;br /&gt;&lt;br /&gt;To inherit investment class you have to override the CreateRaise() and CreateFall abstract&lt;br /&gt;methods (which are in the investment class) and return a new instance of Raise and Fall classes.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class stocks : invsetment&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        public override raiseInvestment CreateRaise()&lt;br /&gt;        {&lt;br /&gt;            return new Raise();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public override fallInvestment CreateFall()&lt;br /&gt;        {&lt;br /&gt;            return new Fall();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class bonds : invsetment&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;        public override raiseInvestment CreateRaise()&lt;br /&gt;        {&lt;br /&gt;            return new Raise();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public override fallInvestment CreateFall()&lt;br /&gt;        {&lt;br /&gt;            return new Fall();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Because here I have instantiated Raise and Fall classes they will be the most derived in the instantiated object class&lt;br /&gt;thats inherited from fallInvestment or raiseInvestment, and the compiler will take the most derived (when overriding).&lt;br /&gt;&lt;br /&gt;And actually here we have implemented fallInvestment and raiseInvestment (abstract classes) by the Fall and Raise &lt;br /&gt;(concrete classes), inside stocks and\or bonds classes.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In my client level, the client is the class thats instantiates objects, call functions,..&lt;br /&gt;&lt;br /&gt;In my client I want to make instances of raiseInvestment and fallInvestment by calling &lt;br /&gt;investment.CreateRaise() or investment.CreateFall().&lt;br /&gt;&lt;br /&gt;But how can I get the refrence of the decided investment?.. it can be passed as a parameter to the constructor&lt;br /&gt;of the client when instantiating the client.&lt;br /&gt;&lt;br /&gt;when i get these two instances of raiseInvestment and  fallInvestment i can then call these fucntions&lt;br /&gt;raiseInvestment.Plus() and fallInvestment.Minus() and I'll getthe overrided functions because they&lt;br /&gt;have been the most derived.&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class clientOnInvestment&lt;br /&gt;    {&lt;br /&gt;        private fallInvestment _fallInvestment;&lt;br /&gt;        private raiseInvestment _raiseInvestment;&lt;br /&gt;        private int currentBalance;&lt;br /&gt;&lt;br /&gt;        public clientOnInvestment(invsetment _investment, int currentBalance)&lt;br /&gt;        {&lt;br /&gt;            _fallInvestment = _investment.CreateFall();&lt;br /&gt;            _raiseInvestment = _investment.CreateRaise();&lt;br /&gt;            this.currentBalance = currentBalance;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void doFall()&lt;br /&gt;        {&lt;br /&gt;            currentBalance = _fallInvestment.Minus(currentBalance);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void doRaise()&lt;br /&gt;        {&lt;br /&gt;            currentBalance = _raiseInvestment.Plus(currentBalance);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public int Balance &lt;br /&gt;        {&lt;br /&gt;            get &lt;br /&gt;            {&lt;br /&gt;                return currentBalance;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;and Finally, the Main&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine("Welcome to Investments");&lt;br /&gt;            &lt;br /&gt;            Console.WriteLine("Creating Stocks............................");&lt;br /&gt;&lt;br /&gt;            invsetment myStocks = new stocks();&lt;br /&gt;            clientOnInvestment myClientS = new&lt;br /&gt;                clientOnInvestment(myStocks, 0);//set starting balance to 0&lt;br /&gt;            &lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientS.Balance);&lt;br /&gt;            Console.WriteLine("Raising balance.........");&lt;br /&gt;            &lt;br /&gt;            myClientS.doRaise();&lt;br /&gt;            &lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientS.Balance);&lt;br /&gt;            Console.WriteLine("Falling balance.........");&lt;br /&gt;            &lt;br /&gt;            myClientS.doFall();&lt;br /&gt;            &lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientS.Balance);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Creating Bonds.............................");&lt;br /&gt;&lt;br /&gt;            invsetment myBonds = new bonds();&lt;br /&gt;            clientOnInvestment myClientB = new &lt;br /&gt;                clientOnInvestment(myBonds, 0);//set starting balance to 0&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientB.Balance);&lt;br /&gt;            Console.WriteLine("Raising balance.........");&lt;br /&gt;&lt;br /&gt;            myClientB.doRaise();&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientB.Balance);&lt;br /&gt;            Console.WriteLine("Falling balance.........");&lt;br /&gt;&lt;br /&gt;            myClientB.doFall();&lt;br /&gt;&lt;br /&gt;            Console.WriteLine("Current Balance = {0}", myClientB.Balance);&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-3490115995430508176?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/3490115995430508176/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=3490115995430508176" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3490115995430508176?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/3490115995430508176?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2008/01/design-patterns-abstract-factory.html" title="Design Patterns - Abstract Factory" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>2</thr:total></entry><entry gd:etag="W/&quot;DU4BQXo7fyp7ImA9WB9UFUo.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-8667200305872527148</id><published>2007-12-13T12:27:00.000-08:00</published><updated>2007-12-13T12:32:30.407-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-12-13T12:32:30.407-08:00</app:edited><title>Linq to SQL Vs. ADO.NET</title><content type="html">&lt;p&gt;The article shows a simple comparison between Linq to SQL and ADO.NET for the excution time of Selecting data from SQL Server Database.&lt;/P&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.codeproject.com/KB/dotnet/linqVsADO.aspx"&gt;View the article on Code Project for better reading..&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul class="Download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.codeproject.com/KB/dotnet/linqVsADO/LinqvsADO.zip"&gt;Download LinqVsADO Source Code - 94,038 KB&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-8667200305872527148?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/8667200305872527148/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=8667200305872527148" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/8667200305872527148?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/8667200305872527148?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2007/12/linq-to-sql-vs-adonet.html" title="Linq to SQL Vs. ADO.NET" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>0</thr:total></entry><entry gd:etag="W/&quot;DkcNQH04eip7ImA9WB9UFEo.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-5430233212881379268</id><published>2007-11-30T11:11:00.001-08:00</published><updated>2007-12-12T07:41:31.332-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-12-12T07:41:31.332-08:00</app:edited><title>CreateUserWizard Ajax-Enabled using Anthem .NET</title><content type="html">&lt;ul class="download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/CreateUserAjax.zip"&gt;Download CreateUserAjax.zip - 127.8 KB&lt;/a&gt; &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;img height="281" alt="Screenshot - CreateUserAjax.jpg" src="http://www.geocities.com/issy.issy/CreateUserAjax.bmp" width="600" /&gt; &lt;br /&gt;&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;This is a Web User Control to create a new user in the SQL Membership in ajax way.&lt;br /&gt;&lt;strong&gt;The Problem&lt;/strong&gt;: When i click register the page do a postback to the server.&lt;br /&gt;&lt;strong&gt;The Goal&lt;/strong&gt;: Click register without loading or postback.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Background&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;I decided to use Anthem .NET Ajax Framework to get the AJAX functionality because: &lt;br /&gt;- You won't write any javascript &lt;br /&gt;- Control the VIEWSTATE &lt;br /&gt;- Anthem Controls&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Lets begin with the button, If you see the picture (this is good :D) then you can see the 'run it' button which is 2 gif images. &lt;br /&gt;When you click it: &lt;br /&gt;- It displays another image. &lt;br /&gt;- Calls a server method! (asynchronously) &lt;br /&gt;- In the method, do something useful. &lt;br /&gt;- Displays the original image.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;But what if I dont want to use the image button and just use a normal button? &lt;br /&gt;Well this is the story of a normal button and this is exactly what the article talks about: &lt;br /&gt;- The button calls a client javascript function. &lt;br /&gt;- This function (using anthem) calls a server method, passing it parameters like UserName, Pass, Email.. etc. &lt;br /&gt;- When the server method completes, a callBack comes to the client with the result calling a client javascript function passing it this result object.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Using the code&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Starting with the normal button (ASP.NET Button Control) Client-Side Code:&lt;/strong&gt; &lt;br /&gt;&lt;strong&gt;Small Example:&lt;/strong&gt; &lt;br /&gt;Dont forget to add a reference to Anthem &lt;a href="http://anthem-dot-net.sourceforge.net/"&gt;dll&lt;/a&gt; &lt;br /&gt;&lt;strong&gt;Client-Side Code:&lt;/strong&gt; &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="html"&gt;//&lt;br /&gt;//&amp;lt;asp:Button ID="Button2" runat="server" Text="Register" OnClientClick="call(); return false;"/&amp;gt;&lt;br /&gt;//&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="jscript"&gt;&amp;lt;script type="text/javascript"&amp;gt;&lt;br /&gt;    function call()&lt;br /&gt;    {&lt;br /&gt;        Anthem_InvokePageMethod(&lt;br /&gt;            'AddOne',&lt;br /&gt;            [6, 4],&lt;br /&gt;            CallBack(result)&lt;br /&gt;            );&lt;br /&gt;    }&lt;br /&gt;    function CallBack(result)&lt;br /&gt;    {&lt;br /&gt;        alert(result.value.ToString());&lt;br /&gt;    }&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is how to call a server method in aspx page, &lt;code lang="jscript"&gt;Anthem_InvokePageMethod('param1', [param2], param3(result));&lt;/code&gt; &lt;br /&gt;The first parameter is the method name &lt;code lang="jscript"&gt;Anthem_InvokePageMethod('Add', [param2], param3(result));&lt;/code&gt; &lt;br /&gt;The second parameter is the parameters you want to pass to the server method &lt;code lang="jscript"&gt;Anthem_InvokePageMethod('Add', [6, 4], param3(result));&lt;/code&gt; &lt;br /&gt;The third parameter is the callBack client javascript function &lt;code lang="jscript"&gt;Anthem_InvokePageMethod('Add', [6, 4], CallBack(result));&lt;/code&gt; &lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Server-Side Code:&lt;/strong&gt; &lt;br /&gt;So what is the server method that we want to invoke from the client-side? &lt;br /&gt;Its a public method in the same aspx page, with this attribute &lt;code lang="cs"&gt;[Anthem.Method]&lt;/code&gt;, so to use it we have to register the page to the Anthem Manager. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;public partial class CreateUser : System.Web.UI.Page&lt;br /&gt;{&lt;br /&gt;    protected void Page_Load(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        Anthem.Manager.Register(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [Anthem.Method]&lt;br /&gt;    public int Add(int param1, int param2)&lt;br /&gt;    {&lt;br /&gt;        return param1 + param2;//this is an example&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I think you got it, so lets see how to do it.. &lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Client-Side Code:&lt;/strong&gt; &lt;br /&gt;Add HTML inputs of type text (for username, password and email for example) and a button &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="html"&gt;&amp;lt;asp:Button ID="Button2" runat="server" Text="Register" OnClientClick="register(); return false;"/&amp;gt;&lt;br /&gt;&amp;lt;input id="NameTextInput" type="text" /&amp;gt;&lt;br /&gt;&amp;lt;input id="PassTextInput" type="text" /&amp;gt;&lt;br /&gt;&amp;lt;input id="EmailTextInput" type="text" /&amp;gt;&lt;br /&gt;&amp;lt;input id="resultTextInput" type="text" /&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="jscript"&gt;&amp;lt;script type="text/javascript"&amp;gt;&lt;br /&gt;    function register()&lt;br /&gt;    {&lt;br /&gt;        Anthem_InvokePageMethod(&lt;br /&gt;            'CreateUserOnTheFly',&lt;br /&gt;            [document.getElementById('NameTextInput').value, document.getElementById('PassTextInput').value, document.getElementById('EmailTextInput').value],&lt;br /&gt;            function(result) &lt;br /&gt;            {&lt;br /&gt;                document.getElementById('resultTextInput').value = result.value;&lt;br /&gt;            }&lt;br /&gt;            );&lt;br /&gt;    }&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Server-Side Code:&lt;/strong&gt; &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;protected void Page_Load(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    Anthem.Manager.Register(this);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Simply Create User with .NET Membership class&lt;br /&gt;[Anthem.Method]&lt;br /&gt;public string CreateUserOnTheFly(string name, string pass, string email)&lt;br /&gt;{&lt;br /&gt;    string theReturn = "";&lt;br /&gt;    try&lt;br /&gt;    {&lt;br /&gt;        if (!string.IsNullOrEmpty(name))//I recommend using validation as the control does&lt;br /&gt;        {&lt;br /&gt;            MembershipCreateStatus status;&lt;br /&gt;            MembershipUser user = Membership.CreateUser(name, pass, email, "question", "answer", true, out status);&lt;br /&gt;            #region statusIs&lt;br /&gt;            switch (status)&lt;br /&gt;            {&lt;br /&gt;                case MembershipCreateStatus.DuplicateEmail:&lt;br /&gt;                    theReturn = "DuplicateEmail";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.DuplicateProviderUserKey:&lt;br /&gt;                    theReturn = "DuplicateProviderUserKey";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.DuplicateUserName:&lt;br /&gt;                    theReturn = "DuplicateUserName";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidAnswer:&lt;br /&gt;                    theReturn = "InvalidAnswer";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidEmail:&lt;br /&gt;                    theReturn = "InvalidEmail";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidPassword:&lt;br /&gt;                    theReturn = "InvalidPassword";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidProviderUserKey:&lt;br /&gt;                    theReturn = "InvalidProviderUserKey";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidQuestion:&lt;br /&gt;                    theReturn = "InvalidQuestion";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidUserName:&lt;br /&gt;                    theReturn = "InvalidUserName";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.ProviderError:&lt;br /&gt;                    theReturn = "ProviderError";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.Success:&lt;br /&gt;                    theReturn = "Success, User: '" + user.UserName;&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.UserRejected:&lt;br /&gt;                    theReturn = "UserRejected";&lt;br /&gt;                    break;&lt;br /&gt;            }&lt;br /&gt;            #endregion&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    catch (Exception ex)&lt;br /&gt;    {&lt;br /&gt;        theReturn = ex.Message.ToString();&lt;br /&gt;    }&lt;br /&gt;    return theReturn;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Well, this was the normal button (normal functions calling) code, lets see the Image Button Anthem Control&lt;/strong&gt; &lt;br /&gt;The image button control click event is a server event &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which brings you directly to the server-side code and handle the client-side itself, then how can you get the result? &lt;br /&gt;Actuallty Anthem provides you with this bool property with every Anthem control (UpdateAfterCallBack), then we can make this: &lt;br /&gt;(Add an Anthem label control) &lt;br /&gt;&lt;pre lang="cs"&gt;        resultLabelAnthem.Text = theReturn;&lt;br /&gt;&lt;br /&gt;        resultLabelAnthem.UpdateAfterCallBack = true;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;What you exactly do here is assign a value to the text property and ask the control to update itself after the callBack so the client can see the assigned value. &lt;br /&gt;And this is our simple Control! &lt;br /&gt;&lt;pre lang="cs"&gt;public partial class CreateUserAjax : System.Web.UI.UserControl&lt;br /&gt;{&lt;br /&gt;    protected void Page_Load(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        string theReturn = "";&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            MembershipCreateStatus status;&lt;br /&gt;            MembershipUser user = Membership.CreateUser(TextBoxName.Text, TextBoxPass.Text, TextBoxEmail.Text, TextBoxQuestion.Text, TextBoxAnswer.Text, true, out status);&lt;br /&gt;            #region statusIs&lt;br /&gt;            switch (status)&lt;br /&gt;            {&lt;br /&gt;                case MembershipCreateStatus.DuplicateEmail:&lt;br /&gt;                    theReturn = "DuplicateEmail";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.DuplicateProviderUserKey:&lt;br /&gt;                    theReturn = "DuplicateProviderUserKey";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.DuplicateUserName:&lt;br /&gt;                    theReturn = "DuplicateUserName";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidAnswer:&lt;br /&gt;                    theReturn = "InvalidAnswer";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidEmail:&lt;br /&gt;                    theReturn = "InvalidEmail";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidPassword:&lt;br /&gt;                    theReturn = "InvalidPassword";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidProviderUserKey:&lt;br /&gt;                    theReturn = "InvalidProviderUserKey";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidQuestion:&lt;br /&gt;                    theReturn = "InvalidQuestion";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.InvalidUserName:&lt;br /&gt;                    theReturn = "InvalidUserName";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.ProviderError:&lt;br /&gt;                    theReturn = "ProviderError";&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.Success:&lt;br /&gt;                    theReturn = "Success, UserName: " + user.UserName;&lt;br /&gt;                    break;&lt;br /&gt;                case MembershipCreateStatus.UserRejected:&lt;br /&gt;                    theReturn = "UserRejected";&lt;br /&gt;                    break;&lt;br /&gt;            }&lt;br /&gt;            #endregion&lt;br /&gt;        }&lt;br /&gt;        catch (Exception ex)&lt;br /&gt;        {&lt;br /&gt;            theReturn = ex.Message.ToString();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        resultLabelAnthem.Text = theReturn;&lt;br /&gt;&lt;br /&gt;        resultLabelAnthem.UpdateAfterCallBack = true;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Points of Interest&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;I think this is very simple, invoking server methods asynchronously and CallBacks are the way to put your code in an ajax way. Well not everything! I tried to make an Ajax File Uploader control, typed many scripts, ActiveX.. but finally the security system stopped the stream to read the files on the client computer and I noticed I'm trying to upload any file from the client wihtout his permission asynchronously in ajax way!. &lt;br /&gt;Some developers say they made it with the FileUpload Control and iFrames.. I tried this too but I failed. &lt;br /&gt;Please tell me your experience. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;History&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Expecting an Ajax Validation Control&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-5430233212881379268?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/5430233212881379268/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=5430233212881379268" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/5430233212881379268?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/5430233212881379268?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2007/11/createuserwizard-ajax-enabled-using.html" title="CreateUserWizard Ajax-Enabled using Anthem .NET" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>0</thr:total></entry><entry gd:etag="W/&quot;DkUHQXw4fSp7ImA9WB9UFEo.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-6631528560560166908</id><published>2007-11-30T11:01:00.000-08:00</published><updated>2007-12-12T07:43:50.235-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-12-12T07:43:50.235-08:00</app:edited><title>Video Uploader to SQL Server WebUserControl</title><content type="html">&lt;ul class="download"&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.geocities.com/issy.issy/VideoUploaderControl.zip"&gt;Download VideoUploaderControl.zip - 4.9 KB&lt;/a&gt; &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;This article will explain how to upload and insert files into sql server (specially audio, video, images files) using C# and ADO.NET, and then how to show the video file in asp.net page with a player control&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Background&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Before we start I don't know what is better, uploading files to a database or uploading files to server system and store only their path in the database, well I think if those files are small size (like images) I'd prefer to store them in the database, but if their size was large (I dont have a number) then I think this will take time with the stream while reading, writing binary data.. (I'd like to know your experience).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Tools:&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;- Create a table in a sql server database that will store the file data, file name, file size&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;table&gt;&lt;br /&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;ID&lt;/td&gt;&lt;td&gt;int&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Video&lt;/td&gt;&lt;td&gt;varbinary(MAX)&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Video_Name&lt;/td&gt;&lt;td&gt;nvarchar(50)&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Video_Size&lt;/td&gt;&lt;td&gt;bigint&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;- In the control add a FileUpload control, a button, a label&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;- Add the control to your page&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Using the code&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The idea to upload a file to a database is to convert it to bytes, converting the file to bytes is easy getting the HTTPPostedFile and read it with the stream to bytes, then insert them in a varbinary column in sql server (in case of video or audio files) or image column (in case of images)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;using System.IO;&lt;br /&gt;using System.Data.SqlClient;&lt;br /&gt;&lt;br /&gt;public partial class UploadVideo : System.Web.UI.UserControl&lt;br /&gt;{&lt;br /&gt;    protected void Page_Load(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;    byte[] buffer;//this is the array of bytes which will hold the data (file)&lt;br /&gt;    SqlConnection connection;&lt;br /&gt;    protected void ButtonUpload_Click(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        //check the file&lt;br /&gt;        if (FileUpload1.HasFile &amp;&amp; FileUpload1.PostedFile != null &amp;&amp; FileUpload1.PostedFile.FileName != "")&lt;br /&gt;        {&lt;br /&gt;            HttpPostedFile file = FileUpload1.PostedFile;//retrieve the HttpPostedFile object&lt;br /&gt;            buffer = new byte[file.ContentLength];&lt;br /&gt;            int bytesReaded = file.InputStream.Read(buffer, 0, FileUpload1.PostedFile.ContentLength);&lt;br /&gt;            //the HttpPostedFile has InputStream porperty (using System.IO;)&lt;br /&gt;            //which can read the stream to the buffer object,&lt;br /&gt;            //the first parameter is the array of bytes to store in,&lt;br /&gt;            //the second parameter is the zero index (of specific byte) where to start storing in the buffer,&lt;br /&gt;            //the third parameter is the number of bytes you want to read (do u care about this?)&lt;br /&gt;            if (bytesReaded &amp;gt; 0)&lt;br /&gt;            {&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    string connectionString = ConfigurationManager.ConnectionStrings["uploadConnectionString"].ConnectionString;&lt;br /&gt;                    connection = new SqlConnection(connectionString);&lt;br /&gt;                    SqlCommand cmd = new SqlCommand&lt;br /&gt;                    ("INSERT INTO Videos (Video, Video_Name, Video_Size) VALUES (@video, @videoName, @videoSize)", connection);&lt;br /&gt;                    cmd.Parameters.Add("@video", SqlDbType.VarBinary, buffer.Length).Value = buffer;&lt;br /&gt;                    cmd.Parameters.Add("@videoName", SqlDbType.NVarChar).Value = FileUpload1.FileName;&lt;br /&gt;                    cmd.Parameters.Add("@videoSize", SqlDbType.BigInt).Value = file.ContentLength;&lt;br /&gt;                    using (connection)&lt;br /&gt;                    {&lt;br /&gt;                        connection.Open();&lt;br /&gt;                        int i = cmd.ExecuteNonQuery();&lt;br /&gt;                        Label1.Text = "uploaded, " + i.ToString() + " rows affected";&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;                catch (Exception ex)&lt;br /&gt;                {&lt;br /&gt;                    Label1.Text = ex.Message.ToString();&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Label1.Text = "Choose a valid video file";&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;        //create a sqlcommand object passing the query and the sqlconnection object&lt;br /&gt;        //when declaring the parameters you have to be sure u have set the type of video column to varbinary(MAX)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;How to select the data and show it on your page:&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The problem here is that we have to set the src property of the player control, but our file exists in a database, so we need a handler to read the bytes in the database.. the handler idea is awesome! u can call it this way "Handler.ashx?ID=1", and in the handler code read the video column where the ID column = QueryString["id"].&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Web;&lt;br /&gt;using System.Data.SqlClient;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Configuration;&lt;br /&gt;&lt;br /&gt;public class VideoHandler : IHttpHandler &lt;br /&gt;{&lt;br /&gt;    &lt;br /&gt;    public void ProcessRequest (HttpContext context) &lt;br /&gt;    {&lt;br /&gt;        string connectionString = ConfigurationManager.ConnectionStrings["uploadConnectionString"].ConnectionString;&lt;br /&gt;&lt;br /&gt;        SqlConnection connection = new SqlConnection(connectionString);&lt;br /&gt;        SqlCommand cmd = new SqlCommand("SELECT Video, Video_Name FROM Videos WHERE ID = @id", connection);&lt;br /&gt;        cmd.Parameters.Add("@id", SqlDbType.Int).Value = context.Request.QueryString["id"];&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            connection.Open();&lt;br /&gt;            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);&lt;br /&gt;            if (reader.HasRows)&lt;br /&gt;            {&lt;br /&gt;                while (reader.Read())&lt;br /&gt;                {&lt;br /&gt;                    context.Response.ContentType = reader["Video_Name"].ToString();&lt;br /&gt;                    context.Response.BinaryWrite((byte[])reader["Video"]);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        finally&lt;br /&gt;        {&lt;br /&gt;            connection.Close();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    public bool IsReusable &lt;br /&gt;    {&lt;br /&gt;        get {&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Ok.. how to show the video?!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You can show the video in ASP.NET Data Control, well i made an example on the Repeter Control.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You have to read the data from the sql server with a sql adapter and bind the datasource to the repeater control, well here u can specifiy which videos to select in the datasource..&lt;br /&gt;&lt;pre lang="cs"&gt;&lt;br /&gt;    private DataTable GetSpecificVideo(object i)//pass the id of the video&lt;br /&gt;    {&lt;br /&gt;        string connectionString = ConfigurationManager.ConnectionStrings["uploadConnectionString"].ConnectionString;&lt;br /&gt;        SqlDataAdapter adapter = new SqlDataAdapter("SELECT Video, ID FROM Videos WHERE ID = @id", connectionString);&lt;br /&gt;        adapter.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = (int)i;&lt;br /&gt;        DataTable table = new DataTable();&lt;br /&gt;        adapter.Fill(table);&lt;br /&gt;        return table;&lt;br /&gt;    }&lt;br /&gt;    protected void ButtonShowVideo_Click(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        Repeater1.DataSource = GetSpecificVideo(2);//the video id (2 is example)&lt;br /&gt;        Repeater1.DataBind();&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now its time for the player control..&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In the repeater (source view) add an ItemTemplate, set the url value parameter of the player control to &lt;code&gt;&amp;lt;'%# "VideoHandler.ashx?id=" + Eval("ID") %'&amp;gt;&lt;/code&gt; the ID is the name of the ID column of the datasource that the repeater binded.&lt;br /&gt;&lt;pre lang="html"&gt;&lt;br /&gt;    &amp;lt;asp:Button ID="ButtonShowVideo" runat="server" onclick="ButtonShowVideo_Click" &lt;br /&gt;        Text="Show Video" /&gt;&lt;br /&gt;    &lt;br /&gt;&lt;br /&gt;    &amp;lt;asp:Repeater ID="Repeater1" runat="server"&gt;&lt;br /&gt;        &lt;ItemTemplate&gt;&lt;br /&gt;            &amp;lt;object id="player" classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" &lt;br /&gt;                        height="170" width="300"&gt;&lt;br /&gt;                        &lt;param name="url" value='&amp;lt;%# "VideoHandler.ashx?id=" + Eval("ID") %&amp;gt;'/&gt;&lt;br /&gt;                        &lt;param name="showcontrols" value="true" /&gt;&lt;br /&gt;                        &lt;param name="autostart" value="true" /&gt;&lt;br /&gt;                    &amp;lt;/object&gt;&lt;br /&gt;        &lt;/ItemTemplate&gt;&lt;br /&gt;    &amp;lt;/asp:Repeater&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Hope you found this useful.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-6631528560560166908?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/6631528560560166908/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=6631528560560166908" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/6631528560560166908?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/6631528560560166908?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2007/11/video-uploader-to-sql-server.html" title="Video Uploader to SQL Server WebUserControl" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>9</thr:total></entry><entry gd:etag="W/&quot;DkUBRnY6fyp7ImA9WB9REE8.&quot;"><id>tag:blogger.com,1999:blog-9065209590602593347.post-4717423901103086629</id><published>2007-10-10T06:31:00.000-07:00</published><updated>2007-10-10T06:50:57.817-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-10-10T06:50:57.817-07:00</app:edited><title>Hello World!</title><content type="html">This is my first post on my blog, Welcome all..&lt;br /&gt;Actually I've made this blog to share my work, ideas, codes, controls, and tools in my Programming World,&lt;br /&gt;If you are interested on what you see, then communicate with me through this blog or IM&lt;br /&gt;Your feedback and comments are very important to me.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9065209590602593347-4717423901103086629?l=islameldemery.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://islameldemery.blogspot.com/feeds/4717423901103086629/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=9065209590602593347&amp;postID=4717423901103086629" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/4717423901103086629?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/9065209590602593347/posts/default/4717423901103086629?v=2" /><link rel="alternate" type="text/html" href="http://islameldemery.blogspot.com/2007/10/hello-world.html" title="Hello World!" /><author><name>Islam Eldemery</name><uri>http://www.blogger.com/profile/15038541116668653086</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="31" height="25" src="http://bp3.blogger.com/_BdiycLss6Ws/SEANuS08cnI/AAAAAAAAACI/ZdnDMXxv11w/S220/n520640460_1584430_1099.jpg" /></author><thr:total>3</thr:total></entry></feed>

