<?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>Coded - Web Development and Programming Blog &#187; C#</title>
	<atom:link href="http://www.codedblog.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codedblog.com</link>
	<description>C#, ASP.NET, Google, Remoting, AJAX, Silverlight, Web Development</description>
	<lastBuildDate>Wed, 16 Jul 2008 13:15:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Automatically adding ValidatorCalloutExtenders to your validators</title>
		<link>http://www.codedblog.com/2008/07/16/automatically-adding-validatorcalloutextenders-to-your-validators/</link>
		<comments>http://www.codedblog.com/2008/07/16/automatically-adding-validatorcalloutextenders-to-your-validators/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 13:05:01 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Web Programming]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/2008/07/16/automatically-adding-validatorcalloutextenders-to-your-validators/</guid>
		<description><![CDATA[	I recently had to work on a pretty big ASP.NET page with lots of fields that needed to be validated.
	 We thought it would be cool if we used the AJAX Toolkit ValidatorCalloutExtender control on the validators to keep the validation inline and concise.
	To quote from the AJAX Toolkit page: 
ValidatorCallout is an ASP.NET AJAX [...]]]></description>
			<content:encoded><![CDATA[	<p>I recently had to work on a pretty big ASP.NET page with lots of fields that needed to be validated.</p>
	<p><img src='http://www.codedblog.com/wp-content/uploads/2008/07/requiredfieldvalidator.png' style="padding: 3px" align="right" alt='requiredfieldvalidator.png' /> We thought it would be cool if we used the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/">AJAX Toolkit</a> <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx">ValidatorCalloutExtender</a> control on the validators to keep the validation inline and concise.</p>
	<p>To quote from the AJAX Toolkit page: </p>
<blockquote>ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an input field and a validator control as you normally would. Then add the ValidatorCallout and set its TargetControlID property to reference the validator control. </blockquote>
	<p>Because we had over 30 text fields, it would have been really tiresome to add extenders manually to each of the validators. So a way to attach them dynamically was needed.</p>
	<p>Fortunately, this is pretty easy to do by iterating through the Page.Validators collection, dynamically creating ValidatorCalloutExtender controls and adding them to the Page.</p>
	<h2>Challenges</h2>
	<ul>
		<li>The first problem I had was an error that occured when trying to dynamically add controls to the Page.Controls collection:</li>
	</ul>
	<p><span id="more-23"></span></p>
	<p><code>The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).</code></p>
	<p>
The error probably occurred because of the way I had the MasterPage set up. The solution, although more of a hack, was to add a PlaceHolder to the page and add my controls to it instead of the Page.Controls collection. I named it <strong>ValidatorsPlaceHolder</strong> (see below)</p>
	<ul>
		<li>Another problem was that the extender was being dynamically added to a different naming container than the target control, so it wouldn&#8217;t find it. </li>
	</ul>
	<p>This lead to the following error:</p>
	<p><code>Target control with ID &#039;XYZ&#039; could not be found for extender...</code></p>
	<p>The error is described in the <a href="http://forums.asp.net/t/992919.aspx">AJAX Control Toolkit FAQ</a> and the solution is to handle the <strong>ResolveControlID</strong> event and help it find the control it needs.</p>
	<p>For this to work I needed to create an <strong>Extension method</strong> for the <strong>Page</strong> class that would find a control by ID by looking recursively through all of its children.</p>
	<h3>Here it is below:</h3>
	<p><textarea name="code" class="csharp">namespace ExtensionMethods 
 {
    public static class ExtensionMethods
    {
        public static Control FindControlRecursive(this Control root, string id)
        {
            if (root.ID == id)
            {
                return root;
            }
            foreach (Control c in root.Controls)
            {
                Control t = FindControlRecursive(c, id);
                if (t != null)
                {
                    return t;
                }
            }
            return null;
        }
    }
 } </textarea></p>
	<p>Usage: <code>var myControl = Page.FindControlRecursive(&quot;MyControlsName1&quot;);</code></p>
	<p>Now that this we got this out of the way, here&#8217;s the full code listing for the method that adds ValidatorCalloutExtenders to all of the validators.</p>
	<h2>Code Listing</h2>
	<p><textarea name="code" class="csharp">    protected void ExtendValidators()
    {
        ValidatorsPlaceHolder.Controls.Clear();
        foreach (Control ctl in Page.Validators)
        {
            if (ctl is RequiredFieldValidator)
            {
                var validatorCtl = (RequiredFieldValidator)ctl;
                validatorCtl.Display = ValidatorDisplay.None;
                validatorCtl.SetFocusOnError = true;
            }
            else if (ctl is CompareValidator)
            {
                var validatorCtl = (CompareValidator)ctl;
                validatorCtl.Display = ValidatorDisplay.None;
                validatorCtl.SetFocusOnError = true;
            }
            else if (ctl is RegularExpressionValidator)
            {
                var validatorCtl = (RegularExpressionValidator)ctl;
                validatorCtl.Display = ValidatorDisplay.None;
                validatorCtl.SetFocusOnError = true;
            }
            if (!String.IsNullOrEmpty(ctl.ID))
            {
                var valExtender = new ValidatorCalloutExtender();
                valExtender.TargetControlID = ctl.ID;
                valExtender.ID = ctl.ID + &#8221;_ValExtender&#8221;;
                valExtender.ResolveControlID +=
                    ((sender, e) => e.Control = Page.FindControlRecursive(e.ControlID));
                ValidatorsPlaceHolder.Controls.Add(valExtender);
            }
        }
    }</textarea></p>
	<p>Notice the .ResolveControlID event handler written as a lambda. It uses the FindControlRecursive extension method shown above to help the Extender find the target control, because it will not be able to do it by itself.</p>


 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2008/07/16/automatically-adding-validatorcalloutextenders-to-your-validators/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Owner-drawing a Windows.Forms TextBox</title>
		<link>http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/</link>
		<comments>http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/#comments</comments>
		<pubDate>Mon, 17 Sep 2007 12:23:20 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SharpSpell]]></category>
		<category><![CDATA[User Interface]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/</guid>
		<description><![CDATA[	This article describes how SharpSpell is able to modify existing TextBox controls to display wavy red underlines below misspelled words.
	Here&#8217;s an image to demonstrate what I mean:
	
(This image is borrowed from SharpSpell, but you get the point)
	Overview
	The .NET framework provides means to subclass native Win32 windows and controls by inheriting from the NativeWindow class. 
	This [...]]]></description>
			<content:encoded><![CDATA[	<p>This article describes how <a href="http://www.tachyon-labs.com/sharpspell.aspx">SharpSpell</a> is able to modify existing TextBox controls to display wavy red underlines below misspelled words.</p>
	<p>Here&#8217;s an image to demonstrate what I mean:</p>
	<p><img src="http://www.tachyon-labs.com/Portals/0/winspellasyoutype.png" alt="SharpSpell - ASP.NET spell checker"/><br />
(This image is borrowed from <a href="http://www.tachyon-labs.com/sharpspell.aspx">SharpSpell</a>, but you get the point)<span id="more-17"></span></p>
	<h3>Overview</h3>
	<p>The .NET framework provides means to subclass native Win32 windows and controls by inheriting from the <a href="http://msdn2.microsoft.com/en-us/library/system.windows.forms.nativewindow.aspx">NativeWindow</a> class. </p>
	<p>This is exactly what we need to do, and here is the basic outline of our inherited class:</p>
	<p><textarea name="code" class="csharp">
 using System;
 using System.Collections.Generic;
 using System.Text;
 using System.Windows.Forms;
 using System.Drawing;
 namespace CodedBlog
 {
    public class CustomPaintTextBox : NativeWindow
    {
        private TextBox parentTextBox;
        private Bitmap bitmap;
        private Graphics textBoxGraphics;
        private Graphics bufferGraphics;
        // this is where we intercept the Paint event for the TextBox at the OS level
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 15: // this is the WM_PAINT message
                    // invalidate the TextBox so that it gets refreshed properly
                    parentTextBox.Invalidate();
                    // call the default win32 Paint method for the TextBox first
                    base.WndProc(ref m);
                    // now use our code to draw extra stuff over the TextBox
                    this.CustomPaint();
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        public CustomPaintTextBox(TextBox textBox)
        {
            this.parentTextBox = textBox;
            this.bitmap = new Bitmap(textBox.Width, textBox.Height);
            this.bufferGraphics = Graphics.FromImage(this.bitmap);
            this.bufferGraphics.Clip = new Region(textBox.ClientRectangle);
            this.textBoxGraphics = Graphics.FromHwnd(textBox.Handle);
            // Start receiving messages (make sure you call ReleaseHandle on Dispose):
            this.AssignHandle(textBox.Handle);
        }
        private void CustomPaint()
        {
            // code goes here, see below
        }
    }
 }</textarea></p>
	<p>Now we need to write the custom paint routine. In order to draw underlines underneath words, we need to know where these words are in the first place. We can get these values using Win32 API functions.</p>
	<p>I will not go into detail with these API functions because the code is pretty long and doesn&#8217;t make the object of this article. You can download the support class here: <a href='http://www.codedblog.com/wp-content/uploads/2007/09/nativemethods.zip' title='SharpSpell Native Win32 Methods for measuring text inside a TextBox'>Native Win32 Methods for measuring text inside a TextBox (nativemethods.zip)</a></p>
	<h3>The custom paint method</h3>
	<p>This is the <strong>CustomPaint()</strong> method: </p>
	<p><textarea name="code" class="csharp">
 private void CustomPaint()
 {
     // get the index of the first visible line in the TextBox
     int curPos = TextBoxAPIHelper.GetFirstVisibleLine(textBox);
     curPos = TextBoxAPIHelper.GetLineIndex(textBox, curPos);
     // clear the graphics buffer
     bufferGraphics.Clear(Color.Transparent);
     // * Here&#8217;s where the magic happens
     // For simplicity we&#8217;ll just draw a line underneath a character range.
     // This will be from character 1 to character 5 in this sample.
     // You can of course modify this to underline specific words.
     Point start = TextBoxAPIHelper.PosFromChar(textBox, 1);
     Point end = TextBoxAPIHelper.PosFromChar(textBox, 5);
     // The position above now points to the top left corner of the character.
     // We need to account for the character height so the underlines go
     // to the right place.
     end.X += 1;
     start.Y += TextBoxAPIHelper.GetBaselineOffsetAtCharIndex(textBox, 1);
     end.Y += TextBoxAPIHelper.GetBaselineOffsetAtCharIndex(textBox, 5);
     // Draw the wavy underline.
     DrawWave(start, end);
     // Now we just draw our internal buffer on top of the TextBox.
     // Everything should be at the right place.
     textBoxGraphics.DrawImageUnscaled(bitmap, 0, 0);
 }</textarea></p>
	<p>We use the <strong>DrawWave()</strong> method to draw a wavy line (zig-zag) from one point to another &#8211; you can customize it to your needs:</p>
	<p><textarea name="code" class="csharp">
 private void DrawWave(Point start, Point end)
 {
     Pen pen = Pens.Red;
     if ((end.X &#8211; start.X) > 4)
     {
         ArrayList pl = new ArrayList();
         for (int i = start.X; i <= (end.X &#8211; 2); i += 4)
         {
             pl.Add(new Point(i, start.Y));
             pl.Add(new Point(i + 2, start.Y + 2));
         }
         Point [] p = (Point[])pl.ToArray(typeof(Point));
         bufferGraphics.DrawLines(pen, p);
     }
     else 
     {
         bufferGraphics.DrawLine(pen, start, end);
     }
 }</textarea></p>
	<p>Now to use this class, you just need to instantiate it by passing a TextBox control to the constructor. Make sure you keep a reference to it at the module level so it doesn&#8217;t get eaten by the Garbage Collector.</p>
	<p><code>CustomPaintTextBox customUnderlines = new CustomPaintTextBox(textBox1);</code></p>
	<p>I haven&#8217;t really tested this stripped out version of the class, but it should work. Most of it is taken directly from the <a href="http://www.tachyon-labs.com/sharpspell.aspx">SharpSpell</a> source code.</p>
	<p>I hope this article helps you understand how to owner draw native Win32 controls using the .NET framework. If you have any questions please leave a comment.</p>
	<p>[tags]Windows.Forms, C#, User Interface, .NET Framework, Win32[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Calling a Windows Service from ASP.NET via Remoting &amp; IpcChannel</title>
		<link>http://www.codedblog.com/2007/09/01/calling-a-windows-service-from-aspnet-via-remoting-ipcchannel/</link>
		<comments>http://www.codedblog.com/2007/09/01/calling-a-windows-service-from-aspnet-via-remoting-ipcchannel/#comments</comments>
		<pubDate>Sat, 01 Sep 2007 17:23:44 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/2007/09/01/calling-a-windows-service-from-aspnet-via-remoting-ipcchannel/</guid>
		<description><![CDATA[	I recently had to design a Windows Service that connects to several game servers via UDP, gathers stats, and then updates a MSSQL database.
	These stats were then made available in real-time on a web-site written in C# and ASP.NET.
	Before Remoting
	For the first version of the application, the web-site and Windows Service were completely independent. The [...]]]></description>
			<content:encoded><![CDATA[	<p>I recently had to design a <a href="http://en.wikipedia.org/wiki/Windows_service">Windows Service</a> that connects to several game servers via UDP, gathers stats, and then updates a MSSQL database.</p>
	<p>These stats were then made available in real-time on a web-site written in C# and ASP.NET.</p>
	<h3>Before Remoting</h3>
	<p>For the first version of the application, the web-site and Windows Service were completely independent. The web-site would just query the database and determine, or make a best guess about what was going on inside the Windows Service at that exact time. This worked pretty good, and although the database is now about 1GB in size and growing fast, I optimized it good enough for this to work in real-time without a hitch.</p>
	<p>There was some caching going on, thanks to the <a href="http://msdn2.microsoft.com/en-us/library/hdxfb6cy.aspx">OutputCache</a> directive in ASP.NET, but surprisingly enough there were no performance issues.</p>
	<h3>After Remoting</h3>
	<p>All right, so because I needed to display some extra information about ‘online’ users, that the Windows Service knew about, but the database didn’t, I decided to have a look at <a href="http://msdn2.microsoft.com/en-us/webservices/aa740645.aspx">.NET Remoting</a>. This was my first time working with it.</p>
	<p>These were the issues I experienced (as a Remoting newbie) when rewriting the Windows Service to be accessible via .NET Remoting:<span id="more-10"></span><br />
<ol><li><strong>The actual functionality of the Windows Service had to be moved to a separate Class Library (.DLL).</strong> <br />
If you wrote your Windows Service all in one .EXE you will have to move it out to DLLs. Ideally you would have a DLL for the actual functionality &#8211; let’s call this <strong>Business.dll</strong> -, and another DLL for the Remoting methods and objects &#8211; <strong>Remoting.dll</strong>. You then create wrapper methods and objects in Remoting.dll which delegate work to Business.dll.</p>
	<p>The reason you have to do this is that the ASP.NET web-site will need to know which methods and objects are available via Remoting, and how to access them. All you have to do now is <strong>add a reference to Remoting.dll</strong> inside the ASP.NET web-site.</p>
	<p>This would have actually been a good design decision in the first place, because the <strong>Firewall</strong> on the server that was running the Windows Service kept complaining about changes to the Service’s .EXE each time I updated and restarted it. After moving the code out to a DLL, the complaints stopped because the .EXE was just a wrapper and it wasn’t changed any more.<br />
</li><br />
<li><strong>The Remoting Wrapper</strong>.<br />
Now you can create wrapper methods around Business.dll in the Remoting.dll Class Library. To enable remoting, you will need to create a class that inherits from <a href="http://msdn2.microsoft.com/en-us/library/system.marshalbyrefobject(VS.71).aspx">MarshalByRefObject</a> . I&#8217;ll supply a code sample for clarity:</p>
	<p><textarea style="width:500px; height: 300px;" name="code" class="csharp">
    public class FragRankRemoting : MarshalByRefObject
    {
        public List<PlayerData> GetOnlinePlayers()
        {
            List<PlayerData> list = new List<PlayerData>();
            foreach (Server s in ServerController.Servers.Values)
            {
                foreach (Player p in s.Players.Values)
                {
                    list.Add(p.PlayerData);
                }
            }
            return list;
        }
    }</textarea></p>
	<p>This is actual code from a real application, but it should help you get started.</p>
	<p></li><br />
<li><strong>Using IpcChannel for Remoting.</strong><br />
Because the Windows Service and Web Site were hosted on the same computer, I decided that the best Remoting channel to use is <strong>IpcChannel</strong> (Inter-Process Communication channel via Named Pipes). The alternatives are TcpChannel and HttpChannel, which I would recommend for situations where the service and web site are not on the same computer.</p>
	<p>The problem with <strong>IpcChannel</strong> is that it requires both the Windows User Account that is running the Windows Service, and the User Account that is running ASP.NET to be under the same User Group, otherwise you will get the following error:<br />
<code>RemotingException: Failed to connect to an IPC Port: Access is denied.</code></p>
      If you have complete control over the system and are certain that no other applications can interact with your service, you can work around this security measure by allowing users in the <strong>&#8220;Everyone&#8221;</strong> Group to access the IpcChannel. Here’s how to do it:
	<p><textarea style="width:500px; height: 300px;" name="code" class="csharp">
            Dictionary<string, string> props = new Dictionary<string, string>();
            props.Add(&#8220;authorizedGroup&#8221;, &#8220;Everyone&#8221;);
            props.Add(&#8220;portName&#8221;, &#8220;FragRankChannel&#8221;);
            props.Add(&#8220;exclusiveAddressUse&#8221;, &#8220;false&#8221;);
            IpcChannel channel;
            try
            {
                channel = new IpcChannel(props, null, null);
                ChannelServices.RegisterChannel(channel, false);
            }
            catch
            {
            }</textarea><br />
Notice the <strong>exclusiveAddressUse</strong> property. I needed to add this due to intermittent problems which occured when the service crashed during debugging, and the Remoting channel didn’t get properly closed.<br />
</li><br />
<li><strong>Connecting to the Service from ASP.NET</strong><br />
In order to connect to the service in ASP.NET via Remoting you will have to create an .XML file with the following contents (this can also go in your <strong>Web.config</strong> if you want):</p>
	<p><textarea style="width:500px; height: 300px;" name="code" class="csharp">
 <?xml version="1.0"?>
 <configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown
        type=&#8221;fragrank.FragRankRemoting,FragRankLogic&#8221;
        url=&#8221;ipc://FragRankChannel/FragRank&#8221;
        />
      </client>
      <channels>
        <channel ref="ipc" authorizedGroup="Everyone">
          <clientProviders>
           <formatter ref="binary"/>
          </clientProviders>
        </channel>
      </channels>
    </application>
  </system.runtime.remoting>
 </configuration></textarea></p>
	<p>All you have to do now is let the Remoting class know about your configuration file and you can start using it! It&#8217;s as easy as:</p>
	<p><textarea style="width:500px; height: 300px;" name="code" class="csharp">
        try
        {
            // you only need to call this once for the whole life-time 
            // of your application, any subsequent calls will result in an error
            //
            // please replace this try/catch block with a more 
            // elegant solution in your application
            RemotingConfiguration.Configure(Server.MapPath(&#8221;.&#8221;) + &#8221;\\web.config&#8221;, false);
        }
        catch { }</p>
        // now just instantiate your remote class
        FragRankRemoting r = new FragRankRemoting(); 
        // and you can use it just like any other class, even if it is hosted remotely
        List<PlayerData> playersAll = r.GetOnlinePlayers();
</textarea>
</li></ol>
	<p>That&#8217;s it, the Windows Service and ASP.NET web-site are now communicating through Named Pipes.</p>
	<p>[tags]Windows Service, Remoting, .NET, C#, IpcChannel, Named Pipes, ASP.NET, IPC[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/09/01/calling-a-windows-service-from-aspnet-via-remoting-ipcchannel/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Google Web Toolkit and ASP.NET?</title>
		<link>http://www.codedblog.com/2007/08/29/google-web-toolkit-and-c/</link>
		<comments>http://www.codedblog.com/2007/08/29/google-web-toolkit-and-c/#comments</comments>
		<pubDate>Thu, 30 Aug 2007 03:42:29 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[User Interface]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/2007/08/29/google-web-toolkit-and-c/</guid>
		<description><![CDATA[	Now that Google&#8217;s Web Toolkit is out of beta, I&#8217;m looking at ways of integrating it somehow with C# and ASP.NET.
	First of all, if you don&#8217;t know what Google Web Toolkit is, here&#8217;s a quickie: it is a framework for creating Web 2.0 AJAX Web Applications using the Java language, preferably inside an Integrated Development [...]]]></description>
			<content:encoded><![CDATA[	<p>Now that <a href="http://code.google.com/webtoolkit/">Google&#8217;s Web Toolkit</a> is <a href="http://google-code-updates.blogspot.com/2007/08/google-web-toolkit-out-of-beta-as-of-14.html">out of beta</a>, I&#8217;m looking at ways of integrating it somehow with C# and ASP.NET.</p>
	<p>First of all, if you don&#8217;t know what <strong>Google Web Toolkit</strong> is, here&#8217;s a quickie: it is a framework for creating Web 2.0 AJAX Web Applications using the Java language, preferably inside an Integrated Development Environment (IDE) such as <a href="http://www.eclipse.org/">Eclipse.</a> You then compile this from Java to HTML/JavaScript using the provided tools, and you have a <em>desktop application</em>-like web-page without knowing anything about the W3C DOM, HTML or JavaScript.</p>
	<h3>What does this have to do with C#?</h3>
	<p>Well, don&#8217;t get me wrong, the <a href="http://ajax.asp.net">ASP.NET AJAX Toolkit</a> is amazing, but being able to visually design a page and use JavaScript behaviors and AJAX from inside an IDE is a step forward.</p>
	<p>It seems that <a href="http://www.nikhilk.net/" title="Nikhil Kothari's Blog">Nikhil Kothari</a> from Microsoft is working on a <strong>C# to JavaScript compiler</strong>, called <a href="http://www.nikhilk.net/ScriptSharpIntro.aspx">Script#</a>, as a side project of his. Unfortunately, <strong>Script#</strong> is not currently supported by Microsoft, and they are really losing ground on the AJAX field because of this. They should promote this to a corporate project, I would love having that same power that <strong>GWT</strong> has, but directly in the Visual Studio IDE.<br />
<span id="more-9"></span><br />
Most would argue that <strong>AJAX.NET</strong> is enough, and they are right, it&#8217;s ok for most sites, but for a fully interactive Web application that doesn&#8217;t have to postback to the server for every single user interaction &#8211; it isn&#8217;t. Not if you don&#8217;t want to mess with JavaScript anyway.</p>
	<p><strong>Script#</strong> helps in this regard, but <strong>GWT</strong> is much more powerful, and writing a RPC web-service in C#/ASP.NET that <strong>Google Web Toolkit</strong> can use shouldn&#8217;t be too hard. I&#8217;ll post my findings on this topic in a future post.</p>
	<p>Stay tuned!</p>
	<p>[tags]Google, Google Web Toolkit, C#, ASP.NET, Script#[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/08/29/google-web-toolkit-and-c/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Generating a transparent GIF image using C#</title>
		<link>http://www.codedblog.com/2007/08/28/generating-a-transparent-gif-image-using-c/</link>
		<comments>http://www.codedblog.com/2007/08/28/generating-a-transparent-gif-image-using-c/#comments</comments>
		<pubDate>Tue, 28 Aug 2007 13:31:06 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Web Programming]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/?p=5</guid>
		<description><![CDATA[	Problem:
	There is apparently no easy way to generate a transparent GIF image using the .NET framework. Microsoft provided a method in the Bitmap class called MakeTransparent() but it doesn&#8217;t work for GIFs, it only seems to work for PNGs.
	To create a transparent GIF you need to recreate the color table of the image using Imaging [...]]]></description>
			<content:encoded><![CDATA[	<h3>Problem:</h3>
	<p>There is apparently no easy way to generate a transparent GIF image using the .NET framework. Microsoft provided a method in the Bitmap class called <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.bitmap.maketransparent.aspx">MakeTransparent()</a> but it doesn&#8217;t work for GIFs, it only seems to work for PNGs.</p>
	<p>To create a transparent GIF you need to recreate the color table of the image using Imaging APIs, as detailed in <a href="http://support.microsoft.com/default.aspx?scid=kb%3bEN-US%3bQ319061">this KB article</a> . Unfortunately, this can be pretty slow for an ASP.NET Web application, and it has a lot of overhead, so I needed an alternative.<span id="more-5"></span></p>
	<h3>Solution:</h3>
	<p>The alternative is to alter the color table directly using the GIF specification. To implement this, I needed to save the non-transparent GIF to a MemoryStream, and then go through the binary data, updating the color table with the new transparency bits.</p>
	<p><em>The original code for this function is not my own, I have found it somewhere on the Internet and modified it. Unfortunately I can&#8217;t remember where I found it, so I can&#8217;t give credit, but if you know the original author please add a comment.</em></p>
	<h3>Source:</h3>
	<p><textarea name="code" class="csharp">
    /// <summary>
    /// Returns a transparent background GIF image from the specified Bitmap.
    /// </summary>
    /// <param name="bitmap">The Bitmap to make transparent.</param>
    /// <param name="color">The Color to make transparent.</param>
    /// <returns>New Bitmap containing a transparent background gif.</returns>
    public Bitmap MakeTransparentGif(Bitmap bitmap, Color color)
    {
        byte R = color.R;
        byte G = color.G;
        byte B = color.B;</p>
        MemoryStream fin = new MemoryStream();
        bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif);
        MemoryStream fout = new MemoryStream((int)fin.Length);
        int count = 0;
        byte[] buf = new byte[256];
        byte transparentIdx = 0;
        fin.Seek(0, SeekOrigin.Begin);
        //header
        count = fin.Read(buf, 0, 13);
        if ((buf[0] != 71) || (buf[1] != 73) || (buf[2] != 70)) return null; //GIF
        fout.Write(buf, 0, 13);
        int i = 0;
        if ((buf[10] &#38; 0&#215;80) > 0)
        {
            i = 1 << ((buf[10] &#38; 7) + 1) == 256 ? 256 : 0;
        }
        for (; i != 0; i&#8212;)
        {
            fin.Read(buf, 0, 3);
            if ((buf[0] == R) &#38;&#38; (buf[1] == G) &#38;&#38; (buf[2] == B))
            {
                transparentIdx = (byte)(256 &#8211; i);
            }
            fout.Write(buf, 0, 3);
        }
        bool gcePresent = false;
        while (true)
        {
            fin.Read(buf, 0, 1);
            fout.Write(buf, 0, 1);
            if (buf[0] != 0&#215;21) break;
            fin.Read(buf, 0, 1);
            fout.Write(buf, 0, 1);
            gcePresent = (buf[0] == 0xf9);
            while (true)
            {
                fin.Read(buf, 0, 1);
                fout.Write(buf, 0, 1);
                if (buf[0] == 0) break;
                count = buf[0];
                if (fin.Read(buf, 0, count) != count) return null;
                if (gcePresent)
                {
                    if (count == 4)
                    {
                        buf[0] |= 0&#215;01;
                        buf[3] = transparentIdx;
                    }
                }
                fout.Write(buf, 0, count);
            }
        }
        while (count > 0)
        {
            count = fin.Read(buf, 0, 1);
            fout.Write(buf, 0, 1);
        }
        fin.Close();
        fout.Flush();
        return new Bitmap(fout);
    }</textarea>
	<p><a href="http://www.codedblog.com/wp-content/uploads/2007/08/giftransparencydemo.zip">Download ASP.NET GIF Transparency Demo WebForm</a><br />
[tags]C#, GIF, Transparent GIF, ASP.NET, Bitmap, System.Graphics[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/08/28/generating-a-transparent-gif-image-using-c/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
