Ian (Fluxtah) Warwick's blog RSS 2.0
# Wednesday, November 11, 2009

It comes to that point in time when you need a country table in your database and you do not have a list to import at hand, after scouring the web a bit, everything seemed to be out of date, so I wrote a little script to scrape the details from a wikipedia page for the ISO 3166-1 standard for country codes.

I wrote and ran the following quick & dirty JQuery script on that page.

if($('#output_textarea').length == 0){
    $(document.body).append($('<textarea rows="128" id="output_textarea"></textarea>'));
}

document.output_textarea_val = "";

$('#sortable_table_id_0 tr').each(function(idx){

    if(idx > 0){
        document.output_textarea_val += "INSERT INTO country (name, code_alpha_2, code_alpha_3, code_numeric) VALUES(";
        var cells = $('td', this), cellLen = cells.length;
        cells.each(function(cellIdx){
            if(cellIdx < 4){
            document.output_textarea_val += "\"" + $(this).text().trim() + "\"";
            if(cellIdx < cellLen - 2){
            document.output_textarea_val += ", ";
            }
            }
        });
        document.output_textarea_val += ');\n';
    }
});

$('#output_textarea').val(document.output_textarea_val);

This script creates insert statements for mySQL and inserts the results into a text box at the foot of the page, in order for it to work you need to inject jQuery into the document, you can do this with the jQueryify Bookmarklet.

I have tested this script and it qualifies for the "works on my machine" certification programme.

The script produces the following output.

Wednesday, November 11, 2009 1:07:31 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Javascript | SQL
# Tuesday, September 15, 2009

Whilst working on my network engine I came across a problem that I initially solved with an interface, but it turned out that the class that implemented this interface exposed public methods that I really wanted to be private, an example will explain the problem.

public interface IMessageReceiver
{
    void Receive(string message);
}

public interface IMessageProvider
{
    IMessageReceiver MessageReceiver;
    void Update();
}

public class ConcreteReceiver: IMessageReceiver
{
    private IMessageProvider _MessageProvider;

    public ConcreteReciever(IMessageProvider messageProvider)
    {
        _MessageProvider = messageProvider;
        _MessageProvider.MessageReceiver = this;
    }
    public void Receive(string message)
    {
        Console.WriteLine(message);
    }

    public void Update()
    {
        MessageProvider.Update();
    }
}

When calling ConcreteReceiver.Update(), this will call MessageProvider.Update(), then, the concrete implementation of IMessageProvider should call IMessageReceiver.Receive, effectively like a callback.

Now the issue in my case was that I did not want the Receive method of ConcreteReceiver to be public, but of course any concrete type that implements an interface must implement those methods as public, after pondering a while I realised the design was actually flawed anyway, what I really wanted was a callback, so I changed my design as follows.

public interface IMessageProvider
{
    Action<string> ReceiveAction;
    void Update();
}

public class ConcreteReceiver
{
    private IMessageProvider _MessageProvider;

    public ConcreteReciever(IMessageProvider messageProvider)
    {
        _MessageProvider = messageProvider;
        _MessageProvider.ReceiveAction = Receive;
    }
    private void Receive(string message)
    {
        Console.WriteLine(message);
    }

    public void Update()
    {
        MessageProvider.Update();
    }
}

So now my Receive method on my ConcreteReceiver can be private, since I am now using a generic Action<T> delegate, this prevents my public API exposing methods that are really meant to be only used internally.

Tuesday, September 15, 2009 3:50:00 AM (GMT Daylight Time, UTC+01:00)  #    Comments [1] -
C#
# Wednesday, September 09, 2009

The Available property of the System.Net.Sockets class will tell you how much data is available to read.

With UDP sockets, one thing to remember is that Socket.Available will give the total size of all the datagrams ready to read, so to the only way to know how many datagrams are waiting to be read is to call ReceiveFrom repeatedly until all data is read, for instance:-

while(Socket.Available > 0)
{
   int datagramSize = Socket.ReceiveFrom(buffer, ref endPoint);
} 

The datagramSize variable will give the size of the datagram that was read, this can be troublesome to manage since you do not know what you are going to get, until you get it, so you would need to initialize a large enough buffer to hold the datagram.

In the networking framework I am currently writing, the application has a configurable MaxPacketSize option so I can initialize my buffer to this size, but this wont help in the event that a bum packet is sent that breaches this constraint so some error handling would also need to be in place to compensate for this issue.

Wednesday, September 09, 2009 5:26:00 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
C#
# Sunday, March 08, 2009

A cool thing, did not realise this, you can use a @MasterType directive in an ASP.NET page to strongly type the Master property, quite cool.

<%@ MasterType TypeName="BaseMaster" %>
Sunday, March 08, 2009 3:59:00 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
General | ASP.NET

This is cool, if you write your own http module by implementing IHttpModule you can subscribe to any events that it raises in the Global.asax, just like you would with Application_Start, Application_End, etc you can do the same with your own events with the signature ModuleName_EventName.

So if you had a IHttpModule, say, StatsModule with an event, Start, you can subscribe to the start event with StatsModule_Start.

Its described on this MSDN Docs page for ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0.

Very cool!

Sunday, March 08, 2009 1:00:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
ASP.NET
# Saturday, March 07, 2009

It can be quite handy to use the ~ with ResolveUrl or for url properties of server controls, however, it does not work for ordinary markup, for instance: 

<a href="~/Foo/Bar.aspx"></a>

would not work since you have to add the runat="server". You can work around this with the following if you happen to have access to Page:

<a href="<%=ResolveUrl("~/Foo/Bar.aspx") %>"></a>

But what if you do not have access to Page? Well, there is the option of rolling your own ResolveUrl, which is the approach I have taken many times.

I am still on a mission brushing up on my ASP.NET and found a community comment on the MSDN Docs for ASP.NET Web Site Paths that has a out-of-the-box way of doing this as follows:

<a href="<%=System.Web.VirtualPathUtility.ToAbsolute("~/Foo/Bar.aspx")%>"></a>

 Very handy! and its been in since .NET 2.0 so it shows how much I am missing out on by not thumbing through the ASP.NET docs.

Saturday, March 07, 2009 3:31:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
ASP.NET
# Friday, March 06, 2009

According to the ASP.NET Docs on XHTML Conformance if you try to validate an ASP.NET page with the W3C XHTML validation service it might not report it as valid XHTML simply because the W3C validation service does not report itself as a browser that ASP.NET recognises.

You can get around this problem by creating a browser definition in a .browser file that you put into your App_Browsers folder of your ASP.NET website.

Yoinked directly from the docs:

<browsers>
  <browser id="W3C_Validator" parentID="default">
    <identification>
        <userAgent match="^W3C_Validator" />
    </identification>
    <capabilities>
      <capability name="browser"              value="W3C Validator" />
      <capability name="ecmaScriptVersion"    value="1.2" />
      <capability name="javascript"           value="true" />
      <capability name="supportsCss"          value="true" />
      <capability name="tables"               value="true" />
      <capability name="tagWriter"
         value="System.Web.UI.HtmlTextWriter" />
      <capability name="w3cdomversion"        value="1.0" />
    </capabilities>
  </browser>
</browsers>

This might just be handy to know at some point, although most good browser based web dev tool suites offer the ability to validate XHTML, and I believe they send the content to validate from rendered markup in your browser.

Friday, March 06, 2009 6:21:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
ASP.NET

Yesterday, I thumbed through the C# Docs looking for stuff I might not know yet, and today I am doing the same thing for ASP.NET in hope to fill in some gaps that might help me with a technical interview I have coming up on tuesday.

This is something I did not know, in the web.config you can add a tag to define what level of XHTML compliance to render.

<system.web>
<!-- other elements here -->
    <xhtmlConformance
        mode="Legacy" />
</system.web>

Where mode could be one of 3 values (taken directly from the MSDN How to page for XHTML Conformance):

Legacy (which is similar to how markup was rendered in previous versions of ASP.NET)

Transitional (XHTML 1.0 Transitional)

Strict (XHTML 1.0 Strict)

Friday, March 06, 2009 6:03:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
ASP.NET
# Thursday, March 05, 2009

Another keyword I have not used much is the new modifer, the MSDN docs for the new Modifer open up with the following:-

When used as a modifier, the new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.

The new modifier has an interesting but important effect when casting, as the following example demonstrates. 

class Program
 {
     public class Animal
     {
         public void Say()
         {
             Console.WriteLine("I am an animal!");
         }
     }
     public class Cat : Animal
     {
         public new void Say()
         {
             Console.WriteLine("Meeeoooooww!");
         }
     } 
     public class WildCat : Cat
     {
         public new void Say()
         {
             Console.WriteLine("ROAR!");
         }
     } 

     static void Main()
     {
         WildCat wildCat = new WildCat();
         Cat cat = wildCat;
         Animal animal = cat; 

         wildCat.Say();
         cat.Say();
         animal.Say();
     }
 }

The code outputs the following.

ROAR!
Meeeoooooww!
I am an animal! 

The code demonstrates when downcasting, WildCat and Cat use their own implementations of Say(), I am not sure I would want that type of behaviour, since it could be rather dangerous if its not used intentionally, but its interesting to know anyway.

Thursday, March 05, 2009 11:28:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
    public abstract class Animal{}
    public class Cat : Animal
    {}
    public class Ornament
    {
        public static explicit operator Ornament(Cat cat)
        {
            return new Ornament();
        }
    } 

    class Program
    {
        static void Main()
        {
            Cat cat = new Cat(); 

            // This line fails to compile
            Ornament jug = cat as Ornament; 

            // this works with our explicit operator defined for Ornament
            Ornament anotherJug = (Ornament)cat;        
        }
    }

Well the holes in my C# knowledge never cease to amaze me, I mean, I knew what I could do with the as keyword but I did not know the subtle difference it has to a direct cast.

By using the as keyword to cast from one type to another, if the cast is not possible it will result in a null, however using a direct cast will throw an exception.

An example demonstrates the use of the as keyword.

    public abstract class Animal{}
    public class Cat : Animal{}
    public class Ornament{} 

    class Program
    {
        static void Main()
        {
            object cat = new Cat(); 

            // jug will be null after this conversion since
            // cat is not an Ornament
            Ornament jug = cat as Ornament;

            // this throws an InvalidCastException
            jug = (Ornament) cat; 

            // This works since Cat is an Animal, animal will not
            // have a reference to cat
            Animal animal = cat as Animal; 

        }
    }

Quite handy really, but there is one thing to note, notice that we say object cat = new Cat();? This is because we get a compilation error if we had used Cat cat = new Cat();

Cannot convert type 'ConsoleApplication1.Cat' to 'ConsoleApplication1.Ornament' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

The reason for this (I believe) is because of the limitation described in the MSDN Docs for the as keyword.

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

An example below shows this, it has been slightly modified by adding an explicit cast operator to Ornament so we can use a cast expression for anotherJug to show the difference between a cast and a conversion with the as keyword, so as the docs say:- user-defined conversions do not work with the as keyword.

kick it on DotNetKicks.com
Thursday, March 05, 2009 6:01:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
Archive
<November 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Ian Warwick
Sign In
Statistics
Total Posts: 33
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2012, Ian Warwick
DasBlog theme 'Business' created by Christoph De Baene (delarou)