... all I'm offering is the truth. Nothing more. RSS 2.0
# Saturday, August 21, 2010

This post is really just a design addendum to my previous post, an opportunity to revisit and redress the solution I presented for the problem of converting GPS data directly into US based Zip Code and while technically correct, I really did spend much time discussing or considering the the nature and architecture of the Windows Phone. In fact part of my solution would lead directly to poor phone performance, and so I wanted to take a couple of moments and discuss one of the fundamental differences in the approach of using and consuming services for WP7.

Lets consider the archetypal example where a button calls a service and that service returns some simple result. There are several ways to accomplish this using the WP7, however, you are guided toward a “pit of success” by being subtlety pushed toward the event driven model. In the traditional service call model you make a call and literally wait for the service to return some kind of result.

Waiting for the service to return the result with a potentially unreliable internet connection could lead to long wait times which in turn could produce a very inconsistent and unresponsive UI experience. Also note that this version of WP is a single threaded environment (it may change in the future) so we cannot offload this work to some background thread. What we can do is some simple event driven programming (you remember “call backs” from back in the day single proc PC days, same concept) which would look like this:

private void StartLocationButton_Click(object sender, RoutedEventArgs e)
{
  // The watcher variable was previously declared as type GeoCoordinateWatcher. 
  if (watcher == null)
  {
    watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Use high accuracy.
    watcher.MovementThreshold = 20; // Plus or Minus 20m, helps ignore noise in the signal.
    watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged); //Define delegate
  }
  watcher.Start();
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
  Dispatcher.BeginInvoke(() => MyStatusChanged(e)); //Call BeginInvoke as discussed below…
}
void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
{
  if (e.Status == GeoPositionStatus.Ready)
      // Use the Position property of the GeoCoordinateWatcher object to get the current location.
      GeoCoordinate co = watcher.Position.Location;
      LatitudeTextBlock.Text = e.Position.Location.Latitude.ToString("0.000");
      LongitudeTextBlock.Text = e.Position.Location.Longitude.ToString("0.000");
      //Stop the Location Service to conserve battery power.
      watcher.Stop();
  }
}

For those of us coming from the Web world there is a subtle “hoop” that is easily forgotten that is critical to Windows GUI programming i.e. only the thread that created a control can subsequently access and/or modify its contents (there are a couple of exceptions). Any attempts to update controls from other threads will result in unpredictable behavior and downright weird UI results. Whenever you need to update a control from a thread that did not initially create it, you need to wrap the call within a BeginInvoke call as show above (see Line 14).

 

Related Posts:

Saturday, August 21, 2010 12:26:11 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C# | Phones
# Wednesday, August 18, 2010

I am currently working on a Windows Phone 7 (WP7) app and I essentially needed to get two pieces of information for the idea to get off the ground. First I need a way to get the the current GPS coordinates from the phone and secondarily I needed to be able to translate that GPS coordinate into a zip code.

As of this writing there are very few physical WP7 devices available to test with, and while Microsoft have done a great job in sending these phones to the press and the big players in the smart phone industry that does not help people like me. I am aware that the Visual Studio Express tool contains a good Emulator, however, it does not provide you access to the GPS backbone, as a result I will wait to offer suggestions on the code.

Get Zip Code (Postal Code) information from the longitude and latitude

Once we have the GPS data from the phone we can pull the zip code information from GPS (reverse geocode) using the Bing Maps API, specifically the Geocode Service. In order to access this service you will need to sign up at the Bing Maps Account Center (requires a Live ID), and subsequently get a Bing Maps key for authentication (review the terms of use carefully).

private void MakeReverseGeocodeRequest(double latitude, double longitude)
{
	string Results = "";
	try
	{

		// Set up you Bing Maps key here...
	        string key = "....."; 

                GeocodeService.ReverseGeocodeRequest reverseGeocodeRequest = new GeocodeService.ReverseGeocodeRequest();
                reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
                reverseGeocodeRequest.Credentials.ApplicationId = key; //apply the key

                // Set the long and lat
                GeocodeService.Location point = new GeocodeService.Location();
       	        point.Latitude = latitude;
                point.Longitude = longitude;

                reverseGeocodeRequest.Location = point;

                // Make the reverse geocode request
                GeocodeService.GeocodeServiceClient geocodeService =
                	new GeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
                GeocodeService.GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
	                
		//Postal Code is one of the properties of the Address
		Results = geocodeResponse.Results[0].Address.PostalCode;
	}
      	catch (Exception ex)
	{
		Results = "An exception occurred: " + ex.Message;
	}
}

UPDATE: This is not the code I would use in a Windows Phone environment, I would probably perform some form of callback. My next post will explain further.

Wednesday, August 18, 2010 10:46:56 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Thursday, May 27, 2010

I have recently been fortunate enough to venture back into the world of math, specifically dealing with the idea of complex numbers. I am not sure how many developers are really into math so I will recap some concepts of complex numbers.

One of the main properties of a real number is that it square is nonnegative. For example, there is no real number x for which the following equation is true:

x² = -1

To help solve this kind of problem, a number called the imaginary unit was introduced (i).  The imaginary unit is the number whose square is –1, that is

i² = -1

The system that results from introducing the number i is called the complex number system. Complex numbers are numbers of the form a + bi, where a and b are real numbers . The real number a is referred to as the real part of the number a + bi, while the real number b is called the imaginary part of a + bi. For example the complex number -2 + 3i has the real part of -2 and the imaginary part of 3.

Now there are some basic rules for adding, subtracting and multiplying complex numbers as follows:

  • (a + bi) + (c + di) = (a + c) + (c + d)i
  • (a + bi) -  (c + di) = (a - c) + (c - d)i
  • (a + bi) * (c + di) = (ac - db) + (ad - bc)i

In .NET 4.0 we saw the introduction of a new struct designed to represent the complex number called Complex. With this new type the complex number addition, and multiplication patterns become really easy.

            using System.Numerics;

            Complex cpx1 = new Complex(2, 3);
            Complex cpx2 = new Complex(4, 6);
            Complex cpx3 = new Complex(1, 5);

            Complex cpxsum = cpx1 + cpx2 - cpx3; // produces 5 + 4i
            Complex cpxsum2 = cpx1 * cpx3; // produces -13 + 13i

Related Links:

Thursday, May 27, 2010 9:38:59 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Sunday, May 23, 2010

I stopped doing meaningful Windows development many moons ago, however, I was recently attempting to setup a simple test application that would send and receive data via a URI. I was taking advantage of existing code and missed the opportunity to do it the right way so I am taking the opportunity to do it the right way here. In this example (inspired by Scott Gu) I am using the WebClient class and the Twitter API. I am using DownloadString*, however, there is also a DownloadData* which returns a byte array for processing.

WebClient mytweets = new WebClient();
mytweets.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mytweets_DownloadStringCompleted);
mytweets.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + _name));


I am primarily using .NET 1.1 at work and so my options would be limited in terms of processing the response. As I am currently testing out Visual Studio 2010 Express, we can and will use LINQ to SQL to process the XML response.

void mytweets_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
        return;

    XElement tweets = XElement.Parse(e.Result);
    var sometweets = from twt in tweets.Descendants("status")
                     select new Tweet
                     {
                         ImageSource = twt.Element("user").Element("profile_image_url").Value,
                         Message = twt.Element("text").Value,
                         UserName = twt.Element("user").Element("screen_name").Value
                     };
}
public class Tweet
{
    public string UserName { get; set; }
    public string Message { get; set; }
    public string ImageSource { get; set; }
}

 

That is it really, if you need to pull string or binary data from a URI in the Windows world WebClient is your class in the world of .NET. An opportunity missed but I feel better for having got it off my chest here.

Related Links:

Sunday, May 23, 2010 9:34:56 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Tuesday, February 09, 2010

As always my posts are usually based on experiencing some travesty of code that required me either to change or endure it. In this case I was looking at a web page who’s only purpose was to return data … for the more seasoned among us the preceding sentence should scream murder. The truth is a web page has a metric ton of overhead and simply using them as conduits for the delivery of raw unformatted non html information (jpeg, text,xml, etc) is a pure waste of resources. The following is an example of what not to do when you trying to return data:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class WebPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details

        Response.Write(xml);

    }

}

This example takes advantage of the generic handler, which has all the flexibility of a web page but none of the overhead of the web page life cycle. While I am returning text/xml this could be any of your defined MIME types.

<%@ WebHandler Language="C#" Class="SomeHandler" %>

using System;
using System.Web;
using System.Text;

public class SomeHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/xml";
        context.Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details
        context.Response.Write(xml);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

In my humble opinion the above concept should be known to all senior asp.net developers, in fact this is one of the first interview questions I ask.

Technorati Tags: ,
Tuesday, February 09, 2010 12:16:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET | C#
# Wednesday, January 06, 2010

I have been reviewing some code where a clear appreciation of the difference between ‘&’ and ‘&&’ is not fully realized. The humble ‘&’ provides a distinct way to provide a logical ‘AND’. Let us take this simple class with a single string array associated with it. Lets ignore the obvious lack of properties for a moment…

public class SimpleClass
{
    public string[] SimpleString;
}

Now when we go to use this class we would want to ensure that the SimpleString array is not null before actually performing any operations on it. One way could be to nest the if statement as follows:

if (foo.SimpleProperty != null)
{
    if (foo.SimpleProperty.Count() > 0)
    {
        MessageBox.Show("Success");
    }
}

This might negatively effect your Cyclomatic Complexity and we could not have such an offense ;) So a simple AND (‘&’) would be useful but as mentioned before this is a logical AND, as a result both values are always evaluated. So the following code would actually fail in the event of a SimplyProperty actually being null.

if (foo.SimpleProperty != null & foo.SimpleProperty.Count() > 0) //this could give you a null exception!!
{
    MessageBox.Show("Success");
}

So to the use of ‘&&’. With this technique the JIT compiler always checks the validity of the first expression and if it is false will not even evaluate the second (or subsequent) expressions in the if statement.

if (foo.SimpleString != null && foo.SimpleString.Count() > 0) //this is safe from null exceptions!! 
{
    MessageBox.Show("Success");
}

Simple, basic and true!!

Wednesday, January 06, 2010 7:59:56 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
C# | Programming Note to Self
# Wednesday, December 09, 2009

On a recent project I was asked to provide a real easy way to zip multiple files and while I have seen this problem solved many moons ago in VB6 I have never really thought about this question from a managed framework standpoint. While navigating MSDN I came across GZipStream but this did not explicitly provide an interface for adding files to a zip archive. Several Bings later I came across a highly rated project on CodePlex called DotNetZip.

I must say this got straight to the point, with a intuitive API that was well documented and explained. Here is a code sample:

using (ZipFile zip = newZipFile()
{
    // add this map file into the "images" directory in the zip archive
   
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
    // add the report into a different directory in the archive
   
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
    zip.AddFile("ReadMe.txt");
   zip.Save("MyZipFile.zip");
}

DotNetZip is packaged as a single DLL, a single assembly. It is fully managed code, written in C#, and provides support for reading and writing Zip archive files and streams. The main type is ZipFile, featuring methods like Add(), Extract() and Save(). There are string and int indexers for the entries of the ZipFile. There are properties for things like password protection, unicode and codepage support, and ZIP64 behavior. And there are progress events for Reading, Saving, and Extracting.

Technorati Tags:
Wednesday, December 09, 2009 9:53:09 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
C#
# Sunday, December 06, 2009

This is the first in a series of posts that I wanted to dedicate to my own coding errors, the situations where I forget some fundamental programming concept and it has me confused for minutes, hours and\or days. So I will attempt to lay bare my own gaffs and hope that this blog serves as a permanent reminder that I remain irrevocably human.

So my latest brain freeze involved an attempt to filter an Array List  based on its content (using .NET 1.1), the basic premise was as follows…

ArrayList ls = new ArrayList();
ls.Add("This");
ls.Add("is");
ls.Add("a");
ls.Add("Test");

foreach (string s in ls)
{
    if(s == "is")
        ls.Remove(s);
} 

The more discerning programmers among us will immediately realize that this for each loop will keep iterating right up until we actually remove something and then we will get this error…

System.InvalidOperationException was unhandled
  Message="Collection was modified; enumeration operation may not execute."

Simply put we cannot modify collection while iterating through it, pretty obvious when you actually take the time to read the exception ;) There are several ways to resolve this, we could create a new ArrayList that we simply add to, however, I preferred using for loops, feels closer to C.

for (int i = 0; i < ls.Count; i++)
{
    if((string)ls[i] == "is")
        ls.RemoveAt(i);
}

I will keep going with a list of embarrassing Faux Pas until I stop committing them, that is to say, until I stop programming ;)

Technorati Tags:

Sunday, December 06, 2009 9:09:01 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, August 14, 2009

This topic has been done to death but I see the occasional errors in code that are directly related to a misunderstanding of “shallow” vs “deep” copies of reference types. Putting it here provides an outlet for my thoughts and a link I can point developers to so I do not have to repeat myself.

A shallow copy is best illustrated by the following diagram. Effectively both variables A and B are pointing at the same memory address, so any updates to A are reflected in B and vice versa:

Here is some code that performs a shallow copy:

MyClass c1 = new MyClass();
MyClass c2 = c1; // A shallow copy is performed here

c1.SC.SomeValue = "25";
c1.ST = "45";

//c2 will reflect the changes made to c1 above, trust me.
MessageBox.Show(String.Format("SomeValue: {0} : ST: {1}",c2.SC.SomeValue,c2.ST));

In C# shallow copies can explicitly performed by a MemberWiseClone and can be completed as follows:

MyClass c2 = c1.MemberWiseClone();

In contrast a deep copy creates and entirely new memory space from which the variables are referenced as show:

In order to provide deep copy capabilities you can use the ICloneable interface and make your class Serializable (I am sure there are other ways to do this).

public object Clone()
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, this);
    ms.Position = 0;
    object o = bf.Deserialize(ms);
    ms.Close();
    return o;
}

So now the code for completing a deep copy would look something like this…

MyClass c1 = new MyClass();
MyClass c2 = (MyClass)c1.Clone();

c1.SC.SomeValue = "25";
c1.ST = "45";

//the message below will have empty strings as c2 was never initialized.
MessageBox.Show(String.Format("SomeValue: {0} : ST: {1}",c2.SC.SomeValue,c2.ST));

Please do not make the assumption that all ICloneable implementations are deep, Framework design guidelines were very vague and developers are notoriously inconsistent. You have been warned.

Technorati Tags: ,
Friday, August 14, 2009 12:03:00 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Monday, June 22, 2009

In a quest to get to know the .NET library just a little bit I wanted to push on into the System.Math class just a little further. Having done quite a lot of math in my college days most of the methods in Math were pretty obvious and so I will forgo going over the obvious ones (cos, tan, etc) here.

There were several that were not immediately recognizable to me for a variety of reasons, it has after all been 10 or more years since I have had any serious mathematic problems to deal with. Also the names of the methods were not as intuitive as they might have been if not for the constraints of method naming.

System.Math.IEEERemainder(x, y) – Gives the remainder of the division as defined by IEEE.
System.Math.BigMul(a, b) – Gives the full product of two 32 bit numbers as Int64 (long).
System.Math.Pow(x,y) – Raises one number to the power of another. Not sure why they did not use the full “Power” word, I probably would have known it right away.
System.Math.E – This is simply a natural log, again I would have figured this out but the natural log is usually represented by a lower case “e” in Math.

What class or namespace should I look at next … I think System.Text … I reread the Joel on Software article on Unicode.

 

Technorati Tags: ,
Monday, June 22, 2009 9:00:44 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Thursday, June 11, 2009

I was doing some rudimentary math solutions in C# the other day and was looking at the System.Math namespace in the hope of finding a MOD (modulo) method but came up blank. I started down the C programming path of using % but then realized that System.Math.DivRem was the new name for what I needed.

int remainder,result;
result = Math.DivRem(10, 3, out remainder);
Console.WriteLine(result.ToString()); //gives 3
Console.WriteLine(remainder.ToString()); //gives the remainder of 1

I need to make a concerted effort to have a more in depth look at the various .NET name spaces and the shortcuts they provide to common problems. Most of my opinions on programming are heavily informed by the functional programming construct of C and to a lesser extent VB … may be that is not such a bad thing?

Technorati Tags:

Thursday, June 11, 2009 1:22:56 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Thursday, March 12, 2009

I was investigating and en error recently with DateTime.ToString() that gave produced the following call stack:

System.FormatException: Input string was not in a correct format.

at System.DateTimeFormat.GetRealFormat(String format, DateTimeFormatInfo dtfi)

at System.DateTimeFormat.ExpandPredefinedFormat(String format, DateTime& dateTime, DateTimeFormatInfo& dtfi)

at System.DateTimeFormat.Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi)

at System.DateTime.ToString(String format, IFormatProvider provider)

at MyWork.NewMethod(string a, string b)

I was doing the following…

DateTime.ToString(“o”)

…which is a valid input string for 2.0 and above but not 1.1. This would not have been issue but the test PC I ran the offending assembly on had both 1.1 and 2.0. The ToString() method took the path of least resistance and used the framework dependencies under 2.0 and not 1.1. Of course the real problem arises when you try to rerun the assembly on a machine that only has .NET 1.1, at this point the “o” option is invalid.

 

Took me a few moments to track down, and reminded me never to trust MSDN (defaults to .NET 3.x) without verifying the backward compatibility of the options.

 

 

Thursday, March 12, 2009 5:16:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, January 23, 2009

It has been a while since I have done significant UI work for a Windows application, however, the last product I remember developing we broke almost every rule in the book with regards to storing local data on the PC. The main reason for this level of contravention was that Windows NT, and subsequently, Windows 2000 never complained. Couple that with the fact that everyone basically ran as administrator led to programmer apathy and a lack of Windows compatibility.

With the advent of Vista and the persistence of UAC we have been forced to collectively understand what we should and should not do when it comes to reading and writing application specific data, and trust me this will not go away in Windows 7. Here are my top 3 bad data storage decisions for Windows:

  • Storing User and Application data in the Program Files – Now I am not talking about installation type data, but I am referring to user specific information that probably will not be shared.
  • Reading and Writing from System32 – There may be a few edge cases where a read is needed but a write?
  • Writing to Global registry settings – enough said…

.NET Framework has a really convenient enumerated type, Environment.SpecialFolder, which is used in Environment.GetFolderPath

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData + “\AppName”)

Member Name Description
MyDocuments The "My Documents" folder.
MyComputer The "My Computer" folder.
MyMusic The "My Music" folder. 
MyPictures The "My Pictures" folder.
ApplicationData The directory that serves as a common repository for application-specific data for the current roaming user. 
CommonApplicationData The directory that serves as a common repository for application-specific data that is used by all users. 
LocalApplicationData The directory that serves as a common repository for application-specific data that is used by the current, non-roaming user. 
Cookies The directory that serves as a common repository for Internet cookies. 
Desktop The logical Desktop rather than the physical file system location. 
Favorites The directory that serves as a common repository for the user's favorite items.
History The directory that serves as a common repository for Internet history items. 
InternetCache The directory that serves as a common repository for temporary Internet files.
Programs The directory that contains the user's program groups.
Recent The directory that contains the user's most recently used documents.
SendTo The directory that contains the Send To menu items. 
StartMenu The directory that contains the Start menu items. 
Startup The directory that corresponds to the user's Startup program group.
System The System directory.
Templates The directory that serves as a common repository for document templates.
DesktopDirectory The directory used to physically store file objects on the desktop.
Personal  The directory that serves as a common repository for documents.
ProgramFiles The program files directory.
CommonProgramFiles The directory for components that are shared across applications.



Here are a list of the members that will get you quick access to various locations on your PC, I find the top 7 or so the most useful and UAC appropriate. Here are a couple of links on Windows Compatibility and Configuring User Access Control.

Technorati tags: ,
Friday, January 23, 2009 5:22:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, October 31, 2008

I am a huge fan of extension methods and in a past post I have described how one could add useful methods to existing types within the .NET framework. This idea is sound, however, I remember almost within a week of the post Jeff Atwood posted a critique of the extension methods that bordered on hostile (I believe the timing was a complete coincidence).

Upon reading both posts again I realized that there should be additional discussion on Extension Methods within the scope of Interface design. What both posts did not look at was the potential impact of extension methods on the fundamental idea of interfaces in C#, vis-a-vis, having abstract method signatures with implementation code.

So lets look at a simple interface:

    public interface ITalk
    {
        void Shout(string words, bool whisper);
        void Shout(string words);                 //whisper is supposed to be false but an
                                                  //interface cannot implement this solution
    }

So if I am the architect of the interface and want to ensure that when developers use the ITalk.Shout(string words) signature, that the bool whisper parameter is always false, I would be forced to redesign this as a base class because this default value constraint is traditionally only enforceable in a base class.

However, with extension methods another options is made available to me, I can actually spot weld an implementation that forces default values to be used as follows:

    public interface ITalk
    {
        void Shout(string words, bool whisper);
        //I remove the Shout(string words) implementation
    }

    public static class ITalkExtensions
    {
        public static void Shout(this ITalk talk, string words)
        {
            talk.Shout(words, false);
        }
    }

So with the above example we actually solve the issue of using an interface while simultaneously providing a pseudo implementation that will provide default values. This technique also enables us to modify an interface without requiring wholesale updates to users of the the Interface. Our code using ITalk would look like this.

    public class Test1 : ITalk
    {

        #region ITalk Members

        public void Shout(string words, bool whisper)
        {
            throw new NotImplementedException();
        }

        #endregion

    }

In the following example, Test1 inherited ITalk and as you can see there is an extension method available to you.
image

Technorati tags: ,
Friday, October 31, 2008 10:49:40 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
C#
# Wednesday, September 24, 2008

A few weeks back I took the opportunity to write about the Singleton Pattern, however, 'The Don' found what I consider to be a really comprehensive set of articles on common patterns (by Granville Barnett) that include:

Technorati tags:

Wednesday, September 24, 2008 10:55:40 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Thursday, September 18, 2008

If you do any significant web development you will have probably seen this error messages, which generally means you will be able to open the project.

image

After seeing this error message this generally means that the VSWebCache (a folder that is found in C:\Documents and Settings\user.name\VSWebCache) is out of synch and the best thing to do is simply delete it. After going to this folder I simply could not find VSWebCache.

Up until today I thought this folder was found in documents and settings by default but this is actually controlled by the following Web Settings.

image

Technorati tags:
Thursday, September 18, 2008 10:04:21 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, September 05, 2008

This week I was asked a question regarding the singleton pattern and I went blank, it has been a while since I have even thought about the concept, this was extremely embarrassing considering how fundamental the pattern is for computer science. So as always this blog serves as a public way of reminding myself that there is always something to learn and even more to remember.

So the concept of a singleton revolves around the idea that you want to ensure that an object should be restricted to one instance of itself . This may be because you are trying to create an object that manages other objects on a global basis within your project.

There a two main principles that go into the singleton. First, we need some mechanism by which we ensure that there is a single object created. Secondly, you have to control the constructor (using private/protected keywords) so at no point after the initial creation of the object can someone perform a create new instances of your class.

The following is the most rudimentary form of the singleton pattern that I could come up with, the 'public static readonly' keywords ensure that when we create an object the uno member is only created once (readonly). While this solves the problem, there are those engineers among us who would complain that the design of the class forces the immediate creation of a static MySingleton object because the 'new' function is not restricted to a method call or the constructor.

    public class MySingleton
    {
        public static readonly MySingleton uno = new MySingleton();

        private MySingleton()
        {

        }
    }

The following example builds upon the weakness of the first in that the instantiation of the object does not occur until requested in the Instance method, as a result the public static singleton object has become private. The Instance method now verifies if uno is null and returns it accordingly.

    public class My2ndSingleton
    {
        private static My2ndSingleton uno;

        private My2ndSingleton()
        {

        }

        public My2ndSingleton Instance()
        {
            if (uno == null)
                uno = new My2ndSingleton();

            return uno; 
        }
    }

The final Singleton scenario accounts for multithreaded applications and provides a standard lock() with a double check to create a critical section around the uno instance. We actually have two verifications (double check) for uno being null, the first check ensures that we do not use the lock unnecessarily , the  second check is conducted after the lock is created to ensure that no other thread snuck in just before the lock.

    public class My3rdSingleton
    {
        private static My3rdSingleton uno;
        private static object sync = new object();

        private My3rdSingleton() { }

        public My3rdSingleton Instance()
        {
            if (uno == null)
            {
                lock (sync)
                {
                    if (uno == null)
                    {
                        uno = new My3rdSingleton();
                    }
                }
            }

            return uno;
        }
    }

May I never forget this again...

Technorati tags: ,
Friday, September 05, 2008 6:42:44 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Tuesday, June 24, 2008

I have written a couple of app's that use LINQ, however, I realized that in order to talk about LINQ I would really have to have a brief look at the ICollections pattern and extension methods.

So extension methods are a really neat way to spot weld additional methods to existing classes in the .NET Framework. So for example, I recently talked about the HttpUtility.UrlEncode being buried in the System.Web namespace. Let us say that I wanted the UrlEncode method to be available where ever I use the String type, then I could do the the following:

    public static class MDUtilities
    {
        //Indicates that this method should be associated string
        public static string EncodeMyUrl(this string s) 
        {
            return System.Web.HttpUtility.UrlEncode(s);
        }
    }

So by including the above class definition you now have a supercharged version of the string type as shown below.

extension method

Extension methods are littered throughout .NET 3.5 Framework and specifically in the ICollections pattern. These extension give us all the access to the LINQ goodness that we are starting to enjoy. So you can imagine somewhere in the .NET Framework would be a definition above that spot welds the new LINQ methods to ICollections.

Tuesday, June 24, 2008 7:31:31 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Sunday, June 08, 2008

I like poking fun at code only because I hope to help highlight simple errors and make our programming world a better place ;) I am sure there is a trail of awful code littered behind my career, however, I am grateful for the fact that I do not have to look at it.

So the latest faux pas was seen in a piece of code that required a string to undergo URL encoding. This is a simple process that requires one to remove all the illegal characters from a URL. The following are considered illegal (reserved) characters:

! * ' ( ) ; : @ & = + $ , / ? % # [ ]

This led to the following code snippet...

String HttpPost = GetRawHttpString();
HttpPost = HttpPost.Replace("%","%25");
HttpPost = HttpPost.Replace("|", "%7C");
HttpPost = HttpPost.Replace("/", "%2F");

Now the basic concept is to identify the reserved characters and replace them with their percentage encoded equivalent. This is not wrong just a little off ... It is the kind of thing you do when you are, for example, an expert C programmer converting to the .NET Framework. It is really easy to fall into traps of how to solve the problem verses the idea of learning the more about .NET Framework. This is probably what I would have done:

String HttpPost = GetRawHttpPostString();
HttpPost = HttpUtility.UrlEncode(HttpPost);

I think the real reason why HttpUtility was not used was because this was not a Web application and in that scenario you are required to import System.Web.dll as a reference manually.

Technorati tags:
Sunday, June 08, 2008 10:33:31 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Friday, May 30, 2008

Reading source code should be the aim of every serious software developer. I am constantly looking for patterns that are interesting and potentially useful for future projects. Anyway, I was reviewing some code over the weekend and there was a pattern that I have not seen for a while.

So below is a basic abstract Mammal class, you have two constructors differentiated by the method signature (of course),

    public abstract class Mammal
    {
        public Mammal()
        {
            Console.WriteLine("A");
        }
        public Mammal(bool asf)
        {
            Console.WriteLine("B");
        }
    }
So the MyDog class inherits from from Mammal and provides an opportunity to access the either of the base class constructors.

    public class MyDog : Mammal
    {
        public MyDog() : base()
        {
            Console.WriteLine("1");
        }
        public MyDog(bool asf) : base(asf)
        {
            Console.WriteLine("2");
        }
    }

You can explicitly select which base class constructor gets called by using ": base()" pattern after the constructor. Simple but nice!

Technorati tags: ,

Friday, May 30, 2008 12:05:09 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Monday, May 19, 2008

I saw this little test over at the site of Visual Stuart. Please do not compile it until you have really thought about it ... a small clue ... take note of the nested 'try/ catch' statement.

            try
            {
                try
                {
                    throw new ApplicationException();
                }
                finally
                {
                    throw new SystemException();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType().Name);
            }
Technorati tags:
Monday, May 19, 2008 11:42:07 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Saturday, April 26, 2008

When .NET 2.0 hit the streets I never paid much attention to the partial class, the concept being that you can define a class over multiple source locations. For example I could have a source file with the following definition of MyDog:

    public partial class MyDog
    {
        public MyDog(int eyes)
        {
            Eyes = eyes;
        }

        private int Eyes;

        public int NumberofEyes
        {
            get { return Eyes; }
            set { Eyes = value; }
        }

    }

... then within another source file complete the definition of MyDog as follows (within the same namespace of course).

    public partial class MyDog
    {
        public string Vocalize()
        {
            return string.Empty;
        }
    }

For all intents and purposes this is the same as just creating one big "public class MyDog", you intellisense features are none the wiser and ILDASM does not appear to be able to discern the difference either.

image 

I had overlooked the features of the partial class, up until now, because I could not envision why I would need to spread a class over multiple source files. Surely spreading the definition of a class over multiple files was a singular waste of time ... except when you have automatic source file generation.

Fast forward to LINQ to SQL when it suddenly became trendy to allow Visual Studio to define your database connections and you will see that the auto generated files are replete with partial class definitions. This allows us, the humble LINQ to SQL consumer, to modify the auto generated class without actually modifying the source file in which it was so carefully created ... now *that* makes all the sense in the world!

Technorati tags: ,
Saturday, April 26, 2008 4:37:14 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C#
# Friday, March 21, 2008

In the CommonRSS application I am creating I started looking at using the Microsoft Feeds API. This API will allow me to check whether any new feeds are available within the Windows RSS platform.

using Microsoft.Feeds.Interop;

public
static int TotalUnreadItemCount() { try { FeedsManager fm = new FeedsManager(); IFeedFolder rootfolder = (IFeedFolder)fm.RootFolder; return rootfolder.TotalUnreadItemCount; } catch { return 0; } }
Technorati Tags:
Friday, March 21, 2008 7:02:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
C#
# Wednesday, March 19, 2008

I was working on some code that would provide a means to quickly tell if the application that you are starting is actually already running, actually it was for the CommonRSS application that I am working. I have done similar things in Visual Basic 6 but I do not remember ever trying this in C#. I am wondering if there is a much cleaner way of doing this ... any thoughts?

using System.Diagnostics;

private const string APPLICATION_NAME = "CommonRSS";

public static bool IsAppAlreadyRunning
{
    get
    {
        bool isAlreadyRunning = false;
        Process currentProcess = Process.GetCurrentProcess();
        Process[] processes = Process.GetProcesses();
        foreach (Process process in processes)
        {
            if (currentProcess.Id != process.Id)
            {
                if (APPLICATION_NAME == process.ProcessName)
                {
                    isAlreadyRunning = true;
                    break;
                }
            }
        }
        return isAlreadyRunning;
    }
}

Technorati Tags:

Wednesday, March 19, 2008 9:31:51 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, February 29, 2008

I was doing some coding and created a derived class today and realized that the compiler was giving a me a silent warning message. Consider the following case where my base class (FirstFloor) has a virtual method which, by definition when a class is derived from it, is permitted to override it. As below I had inadvertently forgot to include the override method in the derived class but things seemed to work as required (against my better understanding).

    public class FirstFloor
    {
        public virtual void Foo()
        {
            Console.WriteLine("FirstFloor.Foo");
        }
    }

    public class SecondFloor : FirstFloor
    {
        public void Foo() //missing the override keyword
        {
            Console.WriteLine("SecondFloor.Foo");
        }
    }

Below is the silent warning that occurred, and unfortunately the compiler is really forgiving and hides the inherited member for you:
image

This is really picking at the details, but in this case you should always use the keyword override even if the compiler is soft on this kind of crime.

    public class SecondFloor : FirstFloor
    {
        public override Foo()
        {
            Console.WriteLine("SecondFloor.Foo");
        }
    }   

One other thing I am doing is starting to setup my compiler to treat warnings as errors, now that is going to catch a whole bunch of other things going on in your code, but that is another blog entry.
image 

Technorati tags: , , ,

 

Friday, February 29, 2008 10:32:41 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
C#
# Saturday, February 23, 2008

I have been struggling with why LINQ (Language Integrated Query) was even useful for the last few weeks, and then finally the penny dropped. While I could go into an elaborate explanation of it inner wonders, I would prefer to share with you the source of my epiphany. I stumbled across a great video from Charlie Calvert that includes a interview with Anders Hejlsberg (Chief architect of C#).

At first I was looking into LINQ as a replacement for direct SQL query access, or just another way to write or access XML, however, LINQ is much more. It is a common way to link (pardon the pun) all of the above and more. I was able to really grok the concept as I listened to Anders speak. It really figures to join our various data sources and the programming world in a very intuitive way. It has a very specific nomenclature to describe data relationships much the same way SQL does (select, where, group by, etc).

Technorati tags: ,

Saturday, February 23, 2008 7:11:18 PM (Eastern Standard Time, UTC-05:00)  #    Comments [2] - Trackback
.NET | C#
# Wednesday, February 13, 2008

I was proposing a solution to a problem today and realized that I had an invalid assumption about the nature of the Array.BinaySearch function so I ran a quick test to confirm and verify my ignorance. So I defined the following test:

            string _mystring = "8,2,3,4,5,6,7,1"; //notice that 1 is not in numerical order
            string [] myarray = _mystring.Split(',');
            
            int result;

            for (int i=1; i < 9; i++)
            {
                result = Array.BinarySearch(myarray, i.ToString());
                Console.WriteLine(string.Format("The value of {0} has been found at {1}.",i,result.ToString()));
            }

            Console.ReadLine();

This resulted in the following output, clearly it could not find "1" or "8" even though they are at the beginning and the end of the array ... herein my fundamental floor was ultimately expressed and the anomaly revealed.

image

The simple problem here is that BinarySearch only works on arrays that are sorted! How did I forget that?!?!?

So this serves as an official note to self, when you are using BinarySearch on an unsorted array perform an Array.Sort:

            string _mystring = "8,2,3,4,5,6,7,1"; //notice that 1 is not in numerical order       
            string [] myarray = _mystring.Split(',');
            Array.Sort(myarray);

Doh!

Technorati tags:

Wednesday, February 13, 2008 10:00:09 PM (Eastern Standard Time, UTC-05:00)  #    Comments [2] - Trackback
.NET | C#
# Sunday, February 10, 2008

I love using enumerators! API developers should do all they can do to include them in method signatures so the API consumer can take advantage of all the wonders of intellisense.

I have recently found a pitfall that API developers have fallen into repeatedly when it comes to the use and type safety of enumerators in method signatures. If we consider the following enumerator and also a method that uses it, we can assume that the developer intended to use Direction and only have 4 valid values associated with it.

        public enum Direction
        {
            North,
            South,
            East,
            West
        }
        public static void WhichDirection(Direction number)
        {
            //Here we need to process values 0,1,2,3 as defined by 'Direction' 
            //anything else is not valid
        }

What I have noticed is that in this scenario API developers can assumes that the WhichDirection method requires no additional type checking as they have a defined enumerator. However, the following examples shows how the API consumer can abuse the method and its expected input.

  WhichDirection(Direction.North);    //expected input
  WhichDirection(Direction.South);    //expected input
  WhichDirection(Direction.East);     //expected input
  WhichDirection(Direction.West);     //expected input
  WhichDirection((Direction)59);      //a little skulduggery, that the compiler will not catch!

Clearly WhichDirection needs to be able to detect this scenario and react appropriately. If you have defined only 4 enumerated values and that is literally all that should be passed then the following is one way to safely check for that.

        public static void WhichDirection(Direction number)
        {
            if (Enum.IsDefined(typeof(Direction), number))
            {
                //
            }
            else 
            {
                throw new ArgumentOutOfRangeException();
            }
        }

The key here is not assume enumerators just keep you safe from the outside world, enumerators provide API consumers with a great pattern to follow. API developers need to assume that there is malicious (or ignorant) intent when developers consume their API.

n.b. IsDefined may not always be the best way to solve this problem, I believe it uses reflection and is notoriously slow.

Technorati tags: ,
Sunday, February 10, 2008 8:30:17 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Monday, January 14, 2008

My plan with CommonRSS was to have it run as a regular application (not a service, just did not want to be bothered yet). So one of the first problems that occurred to me was how you go about starting an application when the OS started. I also wanted to enable\disable that functionality through the registry so this is the class I came up with to support that. 

using Microsoft.Win32;
using System.Reflection;

static class UtilityFuncs
{
    private const string APP_NAME = "CommonRSS"; //replace this with the name of your application
    private const string REG_ENTRY = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";

    /// <summary>
    /// Enables auto start
    /// </summary>
    public static void EnableAutoStart()
    {
        RegistryKey key = Registry.CurrentUser.CreateSubKey(REG_ENTRY);
        key.SetValue(APP_NAME, Assembly.GetExecutingAssembly().Location);
    }

 

    /// <summary>
    /// Disables autostart.
    /// </summary>
    public static void DisableAutoStart()
    {
        RegistryKey key = Registry.CurrentUser.OpenSubKey(REG_ENTRY);
        if (key != null)
        {
            string val = (string)key.GetValue(APP_NAME);
            if (val != null)
                key.DeleteValue(APP_NAME);
        }
    }

 

    /// <summary>
    /// Checks if auto start is enabled.
    /// </summary>
    public static bool IsAutoStartEnabled
    {
        get
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(REG_ENTRY);
            if (key == null)
            {
                return false;
            }

            string val = (string)key.GetValue(APP_NAME);
            if (val == null)
                return false;

 

            return (val == Assembly.GetExecutingAssembly().Location);
        }
    }

}

Technorati Tags: ,
Monday, January 14, 2008 10:51:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, January 11, 2008

I am currently working on a small tool designed to access the Common RSS list found within the Windows OS. It helps me because I have grown accustomed to using Internet Explorer for my RSS fix, however, there is currently no system wide desktop alert that will let me know if there any new feeds (that I know of).

 image

This simple application is designed to check if any new feeds are available, give the user an indication within the system tray and then allow the user to launch IE, the user can the review the new feeds from the Favorites Center!

 image

While there are a plethora of great RSS tools out there (better than this one), it has been a couple of years since I have done any continuous Forms based Windows programming so I wanted to throw my hat into the ring and shake the rust off. This will also give me the chance to have a closer look at Microsoft Visual C# Express 2008.

Technorati Tags: ,

p.s. This tool is only useful in XP and below. There are sidebar gadgets that do the same thing for Vista!

Friday, January 11, 2008 3:39:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C# | Tools
# Tuesday, January 01, 2008

I was looking at the DataSet object the other day and realized that there is both a Copy and a Clone methods. They are designed to fulfil similar functions which the following code highlights.

The Clone method is designed to only copy the structure i.e. the schema, relations and constraints.

The Copy method is designed to replicate the structure and the associated data.

DataSet data1 = new DataSet();
DataSet data2 = new DataSet();

System.IO.FileStream fs = new System.IO.FileStream(@"C:\test\test.xml", System.IO.FileMode.Open);
data1.ReadXml(fs);

data2 = data1.Clone();
foreach (DataRow dr in data2.Tables[1].Rows)
{
    Console.WriteLine(dr[0].ToString()); // We called the Clone method
}

 

data2 = data1.Copy();
foreach (DataRow dr in data2.Tables[1].Rows)
{
    Console.WriteLine(dr[0].ToString());
}

 

Technorati tags: , ,
Tuesday, January 01, 2008 2:11:01 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Wednesday, December 05, 2007

The idea behind collections is concurrently convenient and fraught with potential conversion problems. Collections are designed to store all things given to them as objects and therefore filling a collection is cake.

 

For example:

ArrayList MyList = new ArrayList();

MyList.Add(8);

MyList.Add(9);

MyList.Add("10"); //wait this is a string ... but it is perfectly legal as everything is stored as an object.

 

The fundamental idea is you can place multiple variable types in a single collection conveniently, without regard for all that is type safe or type sane. The problem is ultimately revealed when we unwrap our collection and expose it to the real type safe world of .NET programming.

 

We end up with:

int int8 = (int)MyList[0];

int int9 = (int)MyList[1];

int int10 = (int)MyList[2]; //but wait this is a string!

…but the compiler can never know because collections are all objects and this will not become apparent until run time (usually in QA or worse yet in Production).

 

This simple example now requires the programmer to continually track what types are associated with which element of the ArrayList which invariably leads to complex and custom type checking solutions.

 

.NET 2.0 to the rescue:

Our friends at Microsoft have provided us with a Generic List (Systems.Collections.Generic) that can be type safe. Our code now becomes

List<int> MyNewList = new List<int>() //<int> tells the compiler that this is a generic collection of type int.

MyNewList.Add(8);

MyNewList.Add(9);

MyNewList.Add("10"); \\this is still a string but this can be caught immediately

The problematic line of code can now be caught safely by the compiler before ever going to QA, production, or even you own unit testing.

Technorati tags:
Wednesday, December 05, 2007 8:48:58 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Monday, December 03, 2007

After Robert mentioned that we will be moving to a newer version of the .NET framework, I wanted the opportunity to look at some of the language improvements of .NET 2.0 specifically the use of nullable types.

 

There are two main types that we generally deal with, reference and value types. These two types are treated and stored differently and as a result we have specific behaviors that go along with these types. The main difference I would like to highlight is the fact that value types cannot be null.

So for example:-

int x = 0; //legal
int x = null; // not so legal "Cannot convert null to 'int' because it is a value type"
string s = "hello"; //legal
string s = null; //legal

The surface response is that integers are never null ... but development with XSD and Sql Server allows  us to have nullable integers. So there are legitimate reasons to have a strong solution for this problem of null values.

 

The first way we could do this is to actually create a class that wraps round the integer type. This class would support a series of methods that would checks for Null values. I saw a great VB 6 developer do a similar thing. However, this approach is made redundant in .NET 2.0.

 

Nullable Template:
The more appropriate way to do this would be to use the new Nullable struct This gives us the following:

Nullable<int> i = null; //legal

We can also use HasValue to determine whether the current value is null as follows:

Nullable<int> i = null
if(i.HasValue)  //(also i==null would work)
{
    int j = (int)i;
}

This can be rewritten as follows:

int? i = null; // int ? => nullable int
int j = i ?? 0;

Check the last two snippets of code out in ILDASM. It really amounts to the same thing.

Technorati tags:
Monday, December 03, 2007 8:45:50 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, November 30, 2007

I am always interested in writing one or two lines less and I saw a technique employed quite a lot when using Switch statements in C#. Directly below is the way I have always written the statements. Basically the execution line of the first two statements are identical, however, the case line is quite different.

XmlTextReader xr = new XmlTextReader(@"C:\test\test.xml");
while (!xr.EOF)
{
    switch (xr.NodeType)
    {
        case XmlNodeType.EndElement:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Element:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Text:
            Console.WriteLine(xr.Value.ToString());
            break;
    }
    xr.Read();
}

As a short cut you can completely eliminate the first line of execution and it associated "break;" statement as follows. Now both lines will execute the same line of code:

XmlTextReader xr = new XmlTextReader(@"C:\test\test.xml");
while (!xr.EOF)
{
    switch (xr.NodeType)
    {
        case XmlNodeType.EndElement:
        case XmlNodeType.Element:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Text:
            Console.WriteLine(xr.Value.ToString());
            break;
    }
    xr.Read();
}

I did not like this shortcut for case statements at first, but I realized that it was due to a small portions of my mind that still thinks in VB6. I do not believe there is a "break;" necessary in VB6. In fact the Select Case statement in VB 6 executes only one of several statements based on the value of the expression.

Technorati tags: ,
Friday, November 30, 2007 8:41:38 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Wednesday, November 28, 2007

I have been messing with a few of the more basic principles of reflection recently. The main points include pulling out a list of types from a given assembly and then reviewing the members of those specific Types.

        public static void ReviewTypes()
        {
            // Checking out a specific assembly
            Assembly a = Assembly.Load("Mscorlib.dll");
            Type[] mytypes = a.GetTypes();
            foreach (Type ty in mytypes)
            {
                Console.WriteLine("Type is {0}", ty);
            }

            Console.WriteLine("{0} types have been located", mytypes.Length);
        }

        public static void ReviewMembers()
        {
            // examine a single type
            Type thisType = Type.GetType("System.Reflection.Assembly");
            Console.WriteLine("This Type is {0}", thisType);

            // get all the associated members
            MemberInfo[] mbrInfoAll = thisType.GetMembers();
            foreach (MemberInfo mbrInfoSelect in mbrInfoAll)
            {
                Console.WriteLine("{0} is a {1}", mbrInfoSelect, mbrInfoSelect.MemberType);
            }
            
        }

This type of granular interrogation of types\members at runtime can be very helpful!

 

Technorati tags: , ,
Wednesday, November 28, 2007 8:37:30 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
.NET | C#
# Friday, October 26, 2007

I have doing a little too much work with legacy code (Visual Basic 6) recently, I was actually a better than good VB6 developer at one point but suddenly my mind cannot get around the fact that Strings in VB6 just simply do not have all the trappings (.Length, .Trim, .Remove, .Split etc) of their C# equivalents.

Anyway, I was tackling an issue that required me to remove all the unprintable characters (specifically the ASCII range 0-31) from a string in VB6 and this is what I came up with:

Dim lIndex as Integer
Dim sParseThis as String

sParse = GetDataWithWierdCharacters

For lIndex = 0 to 31
     sParse = Replace(sParse, Chr(lIndex), "")
Next

When I started thinking about this code in terms of C# my immediate desire was to make sure I am taking advantage of the glorious spackle that is the .NET Framework. Simply put I did not want to copy the above code, line for line in C#. So I thought I could take advantage of regular expressions.

string sParse;
sParse = GetDataWithWierdCharacters();
sParse = Regex.Replace(sParse, "[\x01-\x1F]", "");

Much better!

Friday, October 26, 2007 8:30:14 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
C# | Programming | Visual Basic
# Thursday, September 13, 2007

Having developed in C and VB6 at the start of my career there is a definite habit of creating utility modules that help with the manipulation of strings or processing arrays. I have noted from time to time that this has made me neglect some of the in built language features of my primary language, C#.

My first instinct when dealing with an array in C# is to loop through it to create and find strings. I am placing both of these string\array examples here to remind me to stop reinventing the wheel!

Example 1 - Creating a comma (or whatever) separated list of strings from an array.

string[] values = new string[5];
values[0] = "1";
values[1] = "2";
values[2] = "3";
values[3] = "4";
values[4] = "5";
string val = String.Join(",", values); //val = "1,2,3,4,5" - I believe Join had a VB6 equivalent

Example 1 - Search an array for a specific value

string stringvals = "1,2,3,4,5";
string [] values;
int searchresult;

values = stringvals.Split(','); // again a VB 6 equivalent was available
searchresult = Array.BinarySearch(values,"4"); //returns a negative number if it cannot find the value.

Technorati tags: ,
Thursday, September 13, 2007 8:14:38 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
# Tuesday, May 01, 2007

When C# first came out I spent an absorbent amount of time checking the language reference and ensuring that my C++ and VB6 know how was appropriately ported to this new language. So I must admit to being a little annoyed that I just found out about the is operator today.

The is operator is used to check whether the run-time type of an object is compatible with a given type. The following example highlights it practical uses.

MyClass mc;
if(mc is MyClass){
    '... do stuff
}

How useful is that? Why did I think reflection was the best way to solve this problem? When I was in Portland a couple of years ago I distinctly remember someone asking how to solve a problem of this ilk. I proudly explained the beauty of reflection and sent a long winded sample ... I was so wrong ;(

"Look back, and smile on perils past." - Walter Scott

Technorati tags: ,
Tuesday, May 01, 2007 6:42:51 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
.NET | C#
Blogroll
Statistics
Total Posts: 334
This Year: 22
This Month: 0
This Week: 0
Comments: 32
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 2010
Mark Downie
Sign In
All Content © 2010, Mark Downie
DasBlog theme 'Business' created by Christoph De Baene (delarou)