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:
I am a huge fan of WPF and more specifically Silverlight so when my wife took the opportunity to incorporate Expression Blend into a recent project I was eager for her to give the new Sketch Flow pattern a whirl. The Sketch Flow concept came across as the ability to mock up a complete application or website and transform that into a working production model. Effectively narrowing the gap between the client, designer and the developer. After working with my wife over the last couple of months it is clear that this particular idea was misrepresented. My wife had created a prototype using the Sketch Flow concept and put together a very compelling, and partially functional, application. Unfortunately that fact that project was in fact Sketch Flow means that you just cannot simply open this application up in Visual Studio and start doing the complex software engineering work. In fact there a bunch of hoops (albeit well documented in Blends User Guide) that need to be followed in order to make this happen: It is just clear to me that the role of the Devigner (Designer and Developer amalgam) is not a cohesive as advertised.
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: ArrayList
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.
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.
I have just completed 10 day attack on Windows Presentation Foundation and after repeated false starts I have concluded I need to buy a book. In the age of Google search this may seem absurd to the average developer, however, after 8 days of trying to recreate a Windows Forms App (the other 2 days were actually useful) I am realizing I need to have a paradigm shift in my current mindset. Let us take the humble ListBox for example, the XAML would look something like this: <ListBox>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
<ListBoxItem>Item 4</ListBoxItem>
</ListBox>
So I thought that was it I *know* List Boxes in WPF … WRONG! This is not even scratching the surface my friends! Our capable WPF designers have broken the ListBox into its simplest forms. For example let us trying creating a list of Rectangles
<ListBox>
<Rectangle Width="20" Height="20" Stroke="Yellow" StrokeThickness="4" ></Rectangle>
<Rectangle Width="20" Height="20" Stroke="Blue" StrokeThickness="4" ></Rectangle>
<Rectangle Width="20" Height="20" Stroke="Green" StrokeThickness="4" ></Rectangle>
</ListBox>
or ellipses…
<ListBox>
<Ellipse Width="20" Height="20" Stroke="Yellow" StrokeThickness="4" ></Ellipse>
<Ellipse Width="20" Height="20" Stroke="Blue" StrokeThickness="4" ></Ellipse>
<Ellipse Width="20" Height="20" Stroke="Green" StrokeThickness="4" ></Ellipse>
</ListBox>
…or any combination of the above. It is a type agnostic list of items you want to show. I can also orient the flow of list boxes as I see fit…
<ListBox VerticalAlignment="Top">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<Ellipse Width="20" Height="20" Stroke="Yellow" StrokeThickness="4" ></Ellipse>
<Ellipse Width="20" Height="20" Stroke="Blue" StrokeThickness="4" ></Ellipse>
<Ellipse Width="20" Height="20" Stroke="Green" StrokeThickness="4" ></Ellipse>
</ListBox>
Can you see why I need a book, at a casual glance I thought I really knew what was going on with a simple drag and drop, but on closer inspection it is clear that I am missing some underlying goodness through my own poor ignorance.
WPF rocks!!!
Technorati Tags: WPF, ListBox
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.
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.
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. 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.  Technorati tags: VSWebCache
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 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.
Automatic updates has really helped XP, and subsequently 2003 and Vista, stay on top of the mounting attacks directed against PC users. Whenever I am called upon by relatives and friends to fix their PC's this is the first gift I always give them. My windows workstation is still using XP I have opted not to update to Vista, even though I have a copy sitting in my cupboard, because there remains some continuing compatibility issues with some of the Music software I use. Due to the critical nature of this workstation I am strict about not letting it connect to the Internet on a regular basis. I try to conduct the updates once a month to ensure that everything is as it should be. I noticed that there have been several non critical updates that I have had queued for a while, and upon further investigation I realized that they have been failing. All the failures were related to the .NET framework and their associated service packs.  So I am thinking that there maybe an issue with the Automatic Updates delivery system and so I proceed to download the .NET Framework SP (1.1 and 2.0) in the hope to circumvent the problem. I end up being give this useless error message to the left which tells me absolutely nothing. Seriously what were they expecting me to glean from this, what is SL4.tmp? how does it relate to my problem? Is the file corrupted or missing? Where is it supposed to be? All the bits of useful information I was hoping for did not seem to be given when the failure occurred. At this point I am forced to perform a Google search on it but I come up with nothing! My next step is to try uninstalling the entire framework both 2.0 and 1.1, but unfortunately neither the remove or repair options for either framework appears to be functional. This new error appears related to DOTNETFX.MSI, which does not appear to exist on my machine ... aaargh!! I performed a series of searches on the topic of .NET installation errors and come across the blog of Aaron Stebner who has developed a tool for cleaning up installations of the .NET framework (called the Installation Cleanup Utility) . He clearly indicates on his blog that this should be considered a last resort, and that is certainly the position I found myself in, so I took the leap of faith and downloaded the tool. Well it worked! The Cleanup Utility is easy to use and allows you to select which framework you are having problems with, or select them all. It produces a log file indicating what changes were made (this may include registry updates so you will want to make a back up before proceeding). All in all it took about 20 seconds to fix the problem at which point all the Automatic updates started to run successfully! Another useful tool that is free!!  Before you decide to use this tool you should consider the following: There are a couple of very important caveats that you should read before using this tool to cleanup .NET Framework bits on your machine: - You should try to perform a standard uninstall first. This tool is not designed as a replacement for uninstall, but rather as a last resort for cases where uninstall or repair did not succeed for unusual reasons.
- This cleanup tool will delete shared files and registry keys used by other versions of the .NET Framework. So if you use it, be prepared to repair or reinstall any other versions of the .NET Framework that are on your computer to get them to work correctly afterwards
There are a great set of troubleshooting labs for .NET, seven in all, over at Tess' blog. It deals with different troubleshooting scenarios and provides step by step instructions for dealing with each of them. They do not take very long to set up and go through, and it really helps identify some of the core debugging issues. Tess is a Microsoft employee who has been blogging about .NET debugging for years and she really has a great talent for troubleshooting.
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: GetCurrentProcess
I am really trying to nail down my understanding of LINQ but with the current work load, MCP study (yes I am riding that train again) and trying to move into a new home, I am left with very little spare time. I would really love to get into the whole XNA development thing, however, it is tough to justify even more time in front of the PC that will ultimately result in my wanting to purchase an Xbox 360. This is a very cool demo of the process of creating PC\360 games using the XNA framework. Unfortunately this is as close as I will get. Video: 3D XNA From Scratch: 10 How To Access The Guitar Controller When I was much younger I had access to a ZX spectrum (PC from the 80's, not sure if this made it state side) and was able to hack into the code of a Soccer management game (written in some derivative of BASIC), it always fun to give my self limitless funds! I would love to be able reverse engineer some the games they have out there now!
Technorati tags: XNA, ZX Spectrum
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).
Over the last year or so I have been working predominantly with ASP.NET and for that reason alone I have tended to not have to deal directly with the GAC and some of its finer benefits (specifically side by side execution). So I thought I would go over one of the benefits of bindingRedirect. Obviously the prerequisite to installing assemblies in the GAC include creating strong name key file, associating it with the assembly and installing it in the GAC, and so I created two version of an assembly. In my test application I configured and tested against 1.1.0.0, and so based on that fact, the test application would call 1.1.0.0 . In order to ensure that I can use version 1.2 at will I needed to create and\or modify the App.Config file to use the bindingRedirect element as follows. <configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="TestLib" culture="" publicKeyToken="e5baad3d93d8778a"/>
<bindingRedirect oldVersion="1.1.0.0" newVersion="1.2.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
If you are dealing with multiple applications that need to be upgraded, or indeed downgraded, you should also consider using a Publisher Policy File or modifying the Machine Config File.
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.
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!
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: Enumerator, IsDefined
As I become more and more comfortable with Vista the number of unsigned software that I am using is starting to grate on my nerves. I am not sure if I am more annoyed with the developers or the OS that keeps reminding me (even when I tell it not to remind me). There is quite comprehensive article on signing of .NET applications, however, what the article does not go into is that getting a valid certificate from a 3rd party is not free. I can create a test certificate, but the application will have a test certificate that is not verifiable. What, pray tell, is the point of that!
 The perfect scenario for me is to use a Uri that I own as the point of verification, that way I can have and own a certificate that is publicly accessible! So as long as you believe that my site is mine, by extension you can trust that I own and control the certificate at that Uri! Please submit all ideas for this scenario here!
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); } } }
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).  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!  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: RSS, tools p.s. This tool is only useful in XP and below. There are sidebar gadgets that do the same thing for Vista!
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: DataSet, Copy, Clone
After a fielding a few questions about security in some recent projects, I was looking at couple of ways that security is handled within the .NET framework. I wanted to figure out how you could define, method by method, whether a user had permission to run a method within their security context.. The two methods I focused on are Windows Principal and Principal Permission. Windows Principal At a basic level we could implement code that verifies what role the current user is based upon. This method is clean and simple! Throw this at the front of each method and your golden ... but that is not very elegant. WindowsIdentity ident = WindowsIdentity.GetCurrent(); WindowsPrincipal user = new WindowsPrincipal(ident); if(user.IsInRole("Admin")){ //Do stuff here... } The Principal Permission In the following example we have applied PrincipalPermissionAttribute which declaratively requires the user running the code to belong to a specific role or to have already have been authenticated. I learned the hard way that you also need to explicitly set the Principal Policy before calling the method or class with a permission attribute. using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading; class Program
{
static void Main(string[] args)
{
try
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
MyTest mt = new MyTest();
Console.WriteLine(mt.GetMessage());
}
catch(SecurityException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class MyTest
{
public MyTest() {Console.WriteLine("Start MyTest"); }
[PrincipalPermissionAttribute(SecurityAction.Demand, Name = @"Domain\Admin")]
public string GetMessage()
{
return "My Message";
}
}
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: Generics
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: Nullable Types
Microsoft's online MSDN documentation has, for some time, offered a very intuitive way of discovering information about various classes and namespace via direct input into the URL. Effectively you can guess what the location of things you want to look up. I can for example type the following URL in my browser http://msdn2.microsoft.com/en-us/library/system.io, and get directed to the System.IO namespace documentation. Similarly I can get directly to information on classes by using the same technique. http://msdn2.microsoft.com/en-us/library/system.data.odbc.odbcerror, takes me directly to OdbcError class.
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: C#, switch
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!
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.
I was debugging some issues at work and we ended up discovering a compatibility issues with some the dll's. These issues were discovered primarily by looking at the Fusion logs. The fuslogvw.exe provides quick and easy access to the logs which in turn describe a variety of issues, however, I have found that binding errors are most common and easily determined. Fusion logs describe the probing paths used to find compatible dll's and the success or failure of the search. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/en-US/BlogExtension.Delicious.resources.DLL. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/en-US/BlogExtension.Delicious.resources/BlogExtension.Delicious.resources.DLL. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/plugins/en-US/BlogExtension.Delicious.resources.DLL. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/plugins/en-US/BlogExtension.Delicious.resources/BlogExtension.Delicious.resources.DLL. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/en-US/BlogExtension.Delicious.resources.EXE. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/en-US/BlogExtension.Delicious.resources/BlogExtension.Delicious.resources.EXE. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/plugins/en-US/BlogExtension.Delicious.resources.EXE. LOG: Attempting download of new URL file:///C:/Program Files/RssBandit/plugins/en-US/BlogExtension.Delicious.resources/BlogExtension.Delicious.resources.EXE. LOG: All probing URLs attempted and failed. The following registry location [HKLM\Software\Microsoft\Fusion\LogPath] will show you where the raw logs are stored. If you use Visual Studio.NET you will notice quite a few of your own applications have orphaned fusion logs as well as whatever .NET applications you use. If things are going drastically wrong with a complicated multi assembly installation, then take the time to look at the fusion log files.
I am doing a doing a fair share of work that makes use of automated and semi-automated builds using NAnt scripts. I am loving the convenience, however, I usually come into the project after all that stuff is set up. So while I am encouraged and able to make significant changes to NAnt build files, I am never really in on the ground floor construction. Don passed on this really useful series of posts from Jean-Paul S. Boodhoo. He successfully explains the steps and considerations when setting up a fully automated build with NAnt. I am pretty confident I could complete this quite quickly from scratch ... in theory!
Scott Gu is the man, and his latest post really nails the major Silverlight questions. As always his demo's are thorough and thought provoking. I have nothing to contribute here, just check out the videos! "Blessed is the man who, having nothing to say, abstains from giving wordy evidence of the fact." - George Eliot Technorati tags: Silverlight, Scott Gu
Mix 07 has done nothing but ensure that I have a bunch of speculation and no sound grasp of the future. I am currently referring to the advent of the cross platform Dynamic Language Runtime (DLR). The DLR will serve as the core engine for Silverlight and helps provide MS with an in road into the world of Mac\Linux\whatever ... I wonder what Mac users think of that? Jim Hugunins is a pioneer in the field of dynamic languages and was recruited by MS for that very reason. Here is his overview: The DLR is about giving you the best experience for your language - true to the language, excellent tools, performance and seamless integration with a wealth of libraries and platforms. The essential benefits of the DLR are about sharing. It lets language implementers share standard features rather than rebuilding them from scratch. This lets them focus on the features that make a given language unique rather than on reinventing yet another GC system. It lets developers share code regardless of the language the code is implemented in and to use whatever language they prefer regardless of the language preferred by the environment they want to run in. Coupled with the Silverlight 1.1 platform announced today, it even lets languages share a sandboxed security model and browser integration. This means that developers building browser-based applications can now use their preferred language even for client-side code. I must admit I am very impressed but I am forced to wonder if this just a precursor to CLR being used cross platform. If my wild speculation is indeed the case then the MONO project is as good as dead! "When I came back to Dublin I was courtmartialed in my absence and sentenced to death in my absence, so I said they could shoot me in my absence." - Brendan Behan
As I read more about Silverlight from Mix 07 I must admit that I am totally confused as to what this will now mean for AJAX. I thought AJAX was supposed to be the rich GUI that we have been waiting for with baited breath. Am I missing something or does Silverlight spell the end for AJAX? I have just finished downloading the ASP.NET futures which seems to plug the gap between AJAX and Silverlight but I am wondering why we need AJAX in the middle at all. I guess I will have to wait and see what the fall out for Mix 07 truly reveals!
Silverlight is a cross platform rich media experience from Microsoft (never thought I would be using the words cross platform and Microsoft in the same sentence!). What is intriguing about Silverlight is that the programming model is based upon and immersed within the .NET framework. Together with a choice of programming languages and the presentation model using XAML, Silverlight is set to change the game significantly. Silverlight serves as a direct competitor to technologies like Flash and while I believe that Silverlight is a great alternative to Flash I am wondering if this is too little too late. Flash is basically on every machine that I have ever sat down at, its market penetration is second to none. I am wondering if even MS can compete with that kind of distribution. Unless of course they bundle it as a priority update to your machine (approx 2Mb) then they would level the playing field quite quickly ... don't you just love monopolies! The Silverlight evangelists have put together a series of Screencasts that capture some the great features of this technology, Enjoy! "Knowledge is power, if you know it about the right person." - Ethel Mumford
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
Web based commerce is increasing exponentially and the companies, retailers, banks etc are responding to the diverse nature of its world wide clientele. In the US the main concerns are for english (en) and Spanish (es) speaking counterparts. I have been doing a lot of work recently with Satellite assemblies. By definition, satellite assemblies only contain resource files (.resx). They do not contain any application code. These assemblies are generally reserved for strings that can be used to support a particular culture or language. In the satellite assembly deployment model, you create an application with one default assembly (which is the main assembly) and several satellite assemblies (en, es, etc). Visual Studio (VS) has an implied strategy for creating satellite assemblies it looks for a specific naming scheme for .resx files. Strings.en.resx - Implies the need for a satellite assembly named strings.en.dll Strings.es.resx - Implies the need for a satellite assembly named strings.es.dll Strings.resx - Will not create a satellite assembly, this will be embedded in the default assembly based on the build action. Now in order for the default assembly to have knowledge of an associated satellite assembly there also needs to be an explicit reference applied during compilation as follows (VS does this for us). csc.exe /debug+ /reference:..\Bin\en\strings.en.dll;..\Bin\es\strings.es.dll/out:..\Bin\MyApp.exe 'syntax maybe a little off Updating information in a satellite assemblies is really a trivial task, and is certainly the way to go if you are in a hurry and need to avoid a full rebuild. So taking the case where you have existing a MainApp.exe and a Strings.en.dll associated with the main app. To update the Satellite assembly do the following: - Update the resx file as required (Please note you cannot add information here without recompiling the default assembly).
- run the following command (VS.NET cmd): resgen MyWeb/Resources/Strings.en.resx Strings.en.resources
- run the following command (VS.NET cmd): al /out:Strings.en.dll /c:en /embed:Strings.en.resources
"I have learned that success is to be measured not so much by the position that one has reached in life as by the obstacles which he has had to overcome while trying to succeed." - Booker T. Washington
This just up on Scott Gu's Blog ... AJAX is getting full support in ASP.NET\Visual Studio 2005. While there have been various plugins available for some time now, this represents a great commitment to the ground swell of AJAX wannabe's (me included). Microsoft's implementation of AJAX aka ATLAS has represented the Holy Grail of Web Development. It seeks to fill the gap between Postbacks and the Windows Programming model that we all would prefer.
There are many inconsistent explanations on the use and nature of ViewState in ASP.NET. Don found this rather detailed explanation of its existence ... the why's and the wherefore's. ViewState seems to be a staple question for ASP.NET interviews and understanding its nature is fundamental of the discipline! "The wise man does at once what the fool does finally." - Machiavelli
|