<?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</title>
	<atom:link href="http://www.codedblog.com/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>4</slash:comments>
		</item>
		<item>
		<title>How to auto zoom and auto center Google Maps</title>
		<link>http://www.codedblog.com/2007/09/28/how-to-auto-zoom-and-auto-center-google-maps/</link>
		<comments>http://www.codedblog.com/2007/09/28/how-to-auto-zoom-and-auto-center-google-maps/#comments</comments>
		<pubDate>Fri, 28 Sep 2007 16:03:45 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[User Interface]]></category>
		<category><![CDATA[Web Programming]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/2007/09/28/how-to-auto-zoom-and-auto-center-google-maps/</guid>
		<description><![CDATA[	This post discusses how to auto center and auto zoom a Google Map to display all of the markers optimally.
	In order to get accomplish this, you have to calculate the center point and zoom level manually via code. Fortunately this is pretty easy to do, you just need to calculate the minimum and maximum latitude/longitude [...]]]></description>
			<content:encoded><![CDATA[	<p>This post discusses how to auto center and auto zoom a <a href="http://www.google.com/apis/maps/">Google Map</a> to display all of the markers optimally.</p>
	<p>In order to get accomplish this, you have to calculate the center point and zoom level manually via code. Fortunately this is pretty easy to do, you just need to calculate the minimum and maximum latitude/longitude of all of your markers and then get the center point of the resulting area (which will be a rectangle).<span id="more-22"></span></p>
	<p>I&#8217;m using the <a href="http://en.googlemaps.subgurim.net/">Google Maps for ASP.NET control by Subgurim</a>, but this method should apply to any other control, and should even work with plain JavaScript.</p>
	<h3>Auto center</h3>
	<p>First, you will need to find out the min/max latitude and longitude for your markers, this can usually be done in one pass at the same time as you add them. Here&#8217;s some Visual Basic.NET code to help you out (I&#8217;m using VB.NET for this project at the request of my collaborator, but it should be easy to convert to C# &#8211; think of it as pseudo code):</p>
	<p><textarea name="code" class="vb">
        Dim minLongitude As Single = Nothing
        Dim maxLongitude As Single = Nothing
        Dim minLatitude As Single = Nothing
        Dim maxLatitude As Single = Nothing
        &#8217;
        &#8217; add markers 
        For i As Integer = 0 To dataSet.Tables(0).Rows.Count &#8211; 1
            Dim glatlng As New GLatLng
            glatlng.lat = dataSet.Tables(0).Rows(i).Item(&#8220;latitude&#8221;)
            glatlng.lng = dataSet.Tables(0).Rows(i).Item(&#8220;longitude&#8221;)
            &#8217;
            &#8217; First time initialization of the variables
            If minLongitude = Nothing Then minLongitude = glatlng.lng
            If maxLongitude = Nothing Then maxLongitude = glatlng.lng
            If minLatitude = Nothing Then minLatitude = glatlng.lat
            If maxLatitude = Nothing Then maxLatitude = glatlng.lat
            &#8217;
            minLongitude = Math.Min(minLongitude, glatlng.lng)
            maxLongitude = Math.Max(maxLongitude, glatlng.lng)
            minLatitude = Math.Min(minLatitude, glatlng.lat)
            maxLatitude = Math.Max(maxLatitude, glatlng.lat)
            &#8217;
            &#8217; Other code here&#8230;
        Next</textarea></p>
	<p>You then just need to calculate the center point of the resulting area. This is as easy as:</p>
	<p><textarea name="code" class="vb">
        centerLatitude = minLatitude + (maxLatitude &#8211; minLatitude) / 2
        centerLongitude = minLongitude + (maxLongitude &#8211; minLongitude) / 2</textarea></p>
	<p>You can now center your map widget to these coordinates.</p>
	<h3>Auto zoom</h3>
	<p>The auto zoom part is where it gets a little tricky. In my application I&#8217;m calculating the distance in miles from the minLatitude, minLongitude coordinate to the maxLatitude, maxLongitude coordinate.</p>
	<p>The formula for calculating the distance in miles between two coordinates is:</p>
	<p><pre><code>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;miles = (3958.75 * Math.Acos(Math.Sin(latitude1 / 57.2958) * Math.Sin(latitude2 / 57.2958) + Math.Cos(latitude1 / 57.2958) * Math.Cos(latitude2 / 57.2958) * Math.Cos(longitude2 / 57.2958 - longitude1 / 57.2958)))
</code></pre></p>
	<p>By calculating how many miles your markers span, you can make an informed guess on which zoom level to use. For instance, if the distance between the furthest two markers is less than 0.2 miles, then you could use the maximum zoom level available&#8212;which is <strong>16</strong> by the way&#8212;; if the distance is more than 0.2 miles and less than 0.5 miles&#8212;use zoom level 15, and so on.</p>
	<p>Here&#8217;s a list of zoom levels for distances up to 15 miles:</p>
	<p><textarea name="code" class="vb">
        Select Case miles
            Case Is < 0.2
                GMap1.GZoom = 16
            Case Is < 0.5
                GMap1.GZoom = 15
            Case Is < 1
                GMap1.GZoom = 14
            Case Is < 2
                GMap1.GZoom = 13
            Case Is < 3
                GMap1.GZoom = 12
            Case Is < 7
                GMap1.GZoom = 11
            Case Is < 15
                GMap1.GZoom = 10
            Case Else
                GMap1.GZoom = 9
        End Select</textarea></p>
	<p>That&#8217;s it, your map should now be able to auto zoom and auto center itself on your markers!</p>
	<p>[tags]Google Maps API, Visual Basic.NET[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/09/28/how-to-auto-zoom-and-auto-center-google-maps/feed/</wfw:commentRss>
		<slash:comments>7</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>8</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>8</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>Green Marinee Wide WordPress Theme</title>
		<link>http://www.codedblog.com/2007/08/28/green-marinee-wide-wordpress-theme/</link>
		<comments>http://www.codedblog.com/2007/08/28/green-marinee-wide-wordpress-theme/#comments</comments>
		<pubDate>Tue, 28 Aug 2007 20:19:07 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[User Interface]]></category>
		<category><![CDATA[Web Design]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/?p=7</guid>
		<description><![CDATA[	While looking around trying to find a theme for this blog I came across the great Green Marinee Theme theme by Ian Main .
	The theme has one flaw:
	While I&#8217;m pretty sure that back in 2005 screen resolutions such as 800&#215;600 were still common, in today&#8217;s world the theme is just too narrow for a big [...]]]></description>
			<content:encoded><![CDATA[	<p>While looking around trying to find a theme for this blog I came across the great <a href="http://e-lusion.com/greenmarinee/">Green Marinee Theme</a> theme by <a href="http://e-lusion.com">Ian Main</a> .</p>
	<h3>The theme has one flaw:</h3>
	<p>While I&#8217;m pretty sure that back in 2005 screen resolutions such as 800&#215;600 were still common, in today&#8217;s world the theme is just too narrow for a big screen display, and too much space is lost.</p>
	<p>This is especially a problem with a blog such as mine because I frequently use code samples, and lines can get pretty long.</p>
	<h3>My update:</h3>
	<p>So, I decided to keep the theme, but I modified it to make it exactly 200 pixels wider. I also added a <strong>Latest Posts</strong> display to the right navigation bar to improve the overall usability, and more importantly: <strong>Widget Support</strong><br />
<span id="more-7"></span></p>
	<h3>Downloading the theme:</h3>
	<p>If you want to use the theme you can download it from here: <a href="http://www.codedblog.com/wp-content/uploads/2007/08/greenmarineewide.zip" title="Green Marinee Wide WordPress Theme">Green Marinee Wide WordPress Theme</a></p>
	<p>[tags]WordPress, WordPress Theme, Green Marinee[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/08/28/green-marinee-wide-wordpress-theme/feed/</wfw:commentRss>
		<slash:comments>1</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>10</slash:comments>
		</item>
		<item>
		<title>How does SharpSpell work?</title>
		<link>http://www.codedblog.com/2007/08/23/how-does-sharpspell-work/</link>
		<comments>http://www.codedblog.com/2007/08/23/how-does-sharpspell-work/#comments</comments>
		<pubDate>Thu, 23 Aug 2007 17:17:59 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[SharpSpell]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/?p=4</guid>
		<description><![CDATA[	Many people are wondering how SharpSpell is able to provide wavy underline spell checking for regular HTML TEXTAREA elements. Other competitors replace TEXTAREAs with editable IFRAMEs to provide the same functionality, but this is an invasive method that we strongly discourage.
	The trick is to try to replicate the content of the TextArea as best as [...]]]></description>
			<content:encoded><![CDATA[	<p>Many people are wondering how <a href="http://www.tachyon-labs.com/sharpspell.aspx" title="Real time ASP.NET AJAX spell checker">SharpSpell</a> is able to provide wavy underline spell checking for regular HTML TEXTAREA elements. Other competitors replace TEXTAREAs with editable IFRAMEs to provide the same functionality, but this is an invasive method that we strongly discourage.</p>
	<p>The trick is to try to replicate the content of the TextArea as best as possible using a DIV that is positioned directly underneath the textbox. The TextArea&#8217;s background is then set to transparent, and the DIV shows up through it.</p>
	<p>We then send the text in the TEXTAREA to the server using AJAX calls, retrieve misspellings and suggestions, and we  then recreate the DIV on the client using CSS to display the underlines.</p>
	<p>[tags]SharpSpell, Spell Checker, JavaScript, AJAX[/tags]</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/08/23/how-does-sharpspell-work/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>First Blog Post</title>
		<link>http://www.codedblog.com/2007/08/23/first-blog-post/</link>
		<comments>http://www.codedblog.com/2007/08/23/first-blog-post/#comments</comments>
		<pubDate>Thu, 23 Aug 2007 16:49:41 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[SharpSpell]]></category>

		<guid isPermaLink="false">http://www.codedblog.com/?p=3</guid>
		<description><![CDATA[	Howdy,
	Since everyone seems to be doing it 1, I decided to start my own blog to write about my day to day experiences with web development and programming.
	1. yes, I realize that I&#8217;m starting way too late on the blogging phenomenon timeline, but better late than never right 2 ?
2. what better way to start [...]]]></description>
			<content:encoded><![CDATA[	<h3>Howdy,</h3>
	<p>Since everyone seems to be doing it <sup>1</sup>, I decided to start my own blog to write about my day to day experiences with web development and programming.</p>
	<p><sup>1</sup>. yes, I realize that I&#8217;m starting way too late on the blogging phenomenon timeline, but better late than never right <sup>2</sup> ?<br />
<sup>2</sup>. what better way to start a blog than with a cliché?</p>
	<h3>Who am I?</h3>
	<p>My name is Andrei Alecu and I&#8217;m a C# developer with over 5 years of experience in .NET, owner and lead developer of <a href="http://www.tachyon-labs.com/">Tachyon Labs</a>, a company that started as an outsourcing studio but later developed as a .NET component developer and web development company. Tachyon Labs is also the company behind SharpSpell, a real-time spell checker control for ASP.NET and WinForms.<span id="more-3"></span></p>
	<p>We <sup>3</sup> first launched <strong><a href="http://www.tachyon-labs.com/sharpspell.aspx" title="Real time ASP.NET AJAX spell checker">SharpSpell</a></strong> back in 2004, and I was the sole developer of my company back then. The thing about SharpSpell was that it was the first real-time wavy underline spell checker for the Web.</p>
	<p>This amazing <sup>4</sup> functionality was actually implemented by chance. I was approached by <a href="http://www.davefrank.com/" title="Dave Frank's Blog">Dave Frank</a> of the <a href="http://www.botw.org" title="Best of the Web directory">Best of the Web</a> directory, looking to buy a spell check product for their administrative back-end. He eventually suggested that a real-time spell check function like in Microsoft Word would add huge value to the product, but in my own mind I thought something like that would never be possible using pure HTML and JavaScript in a web-browser. Flash maybe, but pure HTML never.</p>
	<p>After a couple of months of work, I managed to get the first working version of a wavy underline spell checker using JavaScript and Internet Explorer&#8217;s DOM model. The code was really messy, but the tech demo made a great impact on the community and I received many words of praise from both interested parties and random people thinking how cool it was.</p>
	<p>Since then the component was rewritten several times, and is now at a state where I could safely say, without false modesty, that it is the most technologically advanced spell check component on the market.</p>
	<p>Over the following blog posts I&#8217;ll describe how I managed to overcome the obstacles I came across when first writing SharpSpell, and other development experiences and setbacks I came across.</p>
	<p><sup>3</sup>. I<br />
<sup>4</sup>. It was definitely &#8220;amazing&#8221; back then, when AJAX was just a term you heard about in technology news feeds, but there weren&#8217;t many concrete examples of what it was and did.</p>

 ]]></content:encoded>
			<wfw:commentRss>http://www.codedblog.com/2007/08/23/first-blog-post/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
