• About
  • Contact

Sam Moreira's Blog

~ What's Happening Out There?

Tag Archives: .Net Framework

How To Use Custom Objects as Hashtable Keys Without Getting Duplicated Keys in Your Collection

13 Friday Mar 2009

Posted by Sam Moreira in Development

≈ Leave a comment

Tags

.Net Framework, C#, Collection, Development, Microsoft, OOP

Have you ever faced an issue of having duplicated key objects in your Hashtable even though the objects represent the same entity? In this post I’ll show a way to circumvent the Hashtable behavior.

Sometimes we have a need to use objects as Hashtable keys instead of strings. At least for me, most of the time, Hashtables are used as standard dictionaries such as in the sample below:

Hashtable Sample with String Keys

The code above produces the following outcome:

Hashtable with strings results

In the sample above, the value of “key2” key has been updated as expected. Also notice that the Hash value of key2 is the same on both DisplayResults() executions.

Now, what happens if instead of using a string as the key, we use an object? Here’s the updated code after we change the key from string to a custom object:

Hashtable class with Objects as keys

And here’s the outcome:

Hashtable with objects as keys results

As you can see by the resulting outcome above, when I tried to update the instance of User 123, the Hashtable actually added the object as a new item to the collection and updated its value instead.

Why does this happen? Actually, the results of the second test are the ones we should expect when working with Hashtables as each newly created object receives a new hashcode value, and the Hashtable uses the hashcode value to search for keys in the collection. So, when the new user was created to update the value of the existing one, the new hashcode value given to the new object was used to search for an existing item in the collection; and as it could not be found, the object was added as a new item in the collection.

But, why doesn’t this happen with strings? They’re also objects, correct? String objects have a different behavior as they override object class methods to always consider equal two strings holding the same values even if they are actually different instances. On the first code sample, Let’s change the statement that updates the value of key2 to the following:

Hashtable Statement with string case changed

After running the program, we’ll get the following results:

Hashtable with different case strings used as keys

This result looks like the second test results when a custom object was used as the key; only at this time, we used a string. Why didn’t we get the same results as our first test? Notice that I have updated the “k” (lowercase) to “K” (uppercase) to make the values of each string object different. So, if you look at the resulting outcome, the “Key2” string has a different hashcode value than the “key2” one, what means that the overridden GetHashCode() string method didn’t come into play and the Hashtable behaved as it should.

Now that we have covered the basics, how do I make my custom object behave like the string object to prevent duplication of objects representing the same entity in my collection? Simple, we’ll have to update our User class to override two methods of the object class: GetHashCode() and Equals().

Here’s the new User class with the overridden methods:

Custom User class with overridden object methods

In case you’re lost, we’re doing two things here: first, we’re overriding the GetHashCode() method to return the hashcode of the UserCode property value (a string) instead of the hascode of the User instance itself. This way, two User instances with the same UserCode value will have the same hashcode value. And second, we’re overriding the Equals() method to use the value of the UserCode property for comparison; this way the class can identify whether or not two instances of the User class represent the same entity.

Here is the outcome of our program after the two object methods have been overridden:

User class with overridden methods results

It’s nice isn’t it? Now we can easily update the value part of User keys in the collection without worrying that duplicated User keys will be added to the collection.

Enjoy!

How to Monitor File System Changes in C#

27 Friday Feb 2009

Posted by Sam Moreira in Development

≈ Leave a comment

Tags

.Net Framework, C#, Development, Events, File System, Microsoft, Monitoring, OOP

Have you ever needed to monitor a specific directory or file for changes? .Net Framework has a class called FileSystemWatcher within System.IO namespace that allows developers to take action when a specific event occurs in the File System. In this posting, I’ll show you how you can use the FileSystemWatcher class to monitor your files or directories.

For our sample, let’s use the following hypothetical scenario: your company hosts its own website and for months, without success, you have been asking content editors not to store their image files within the folder reserved for web pages only. So, you decide to monitor the folder and take action if any violation happens.

How do you get this done using FileSystemWatcher? In the code sample below, you will notice that you just need to create an instance of FileSystemWatcher, add event handlers for the events you want to monitor, and tell your object to watch for events. It’s that simple!

FileSystemWatcher Class Implementation

In the implementation of the Created event handler above, I am just checking for extensions of image files explicitly. The FileSystemWatcher has a property called “Filter”, which allows you to define a mask of the type of files to watch (“*.jpg”, “doc*.*”, etc), but I couldn’t get more than one file extension associated with this property (if you know of another way, let me know).

So, still in the implementation sample, if an image file is created or copied into the monitored folder, an e-mail is fired to alert of the violation and the file is automatically deleted from the folder. Also, just to play nice and prevent any problems if the only copy of the file is deleted, the e-mail will also have a copy of the file attached to it. Another option would be to automatically move the file to the correct directory instead of just deleting it; however, if you take that approach, you’ll also have to check for crashes on the filename, at minimum.

Besides the Created event illustrated in our sample, you can also monitor the File System for the following events: Changed, Deleted, and Renamed. In our sample, we could also have implemented the Renamed event handler to prevent a user from bypassing the monitoring system by copying an image into the folder without an extension and renaming it later. And finally, if you are also looking for events in subdirectories, you can just set the FileSystemWatcher.IncludeSubdirectories property to true.

One thing to keep in mind is that, I have used a Console Application just to illustrate the implementation of the FileSystemWatcher class. However, if you decide to implement something similar that should run constantly, instead of a Console Application, you’ll probably want to look into creating a Windows Service and get your monitoring application running in the background.

Have Fun!

How to Implement Automated Properties in C#

25 Wednesday Feb 2009

Posted by Sam Moreira in Development

≈ Leave a comment

Tags

.Net Framework, C#, Development, Microsoft, OOP

C# 3.0 and later versions give developers the ability to have underlying property structures automatically taken care by the compiler, which behind the scenes, creates the private members and implements the get and set inner workings. In this posting, I’ll cover how to create regular and automated properties in C#.

Before automated properties became available, the only way to create properties was to write code for each property we wanted to make available through our class. The snapshot below displays a Person class being consumed by the Program class. The Person class has three properties: FirstName, LastName, and DateOfBirth. In order to implement these properties in the correct encapsulated way, we needed three private members (declared at the top) that will only be accessible through the public properties.

autoproperty01

Now, let’s see what changes when using automated properties. After modifying the Person class above to use automated properties, we have the following code:

autoproperty02

The differences are clear. We basically replaced a regular block property declaration with a single line declaration by adding {get; set; } to the member declaration. The compiler will automatically create basic get and set blocks and the result will be transparent to other classes consuming your class. In addition to make it easier to create properties, we have also saved about 18 lines of code by switching just three properties to auto mode. Imagine not having to type several lines of code for classes requiring lots of properties.

You can also make one or more of your properties immutable by declaring the set accessor private. For instance, in our Person class, a Person might get married and need to change the Last Name, but the Date of Birth will never change. The code below displays how we can make DateOfBirth immutable using automated properties:

Immutable Property Implementation

As we can see from the snapshot above, we just needed to declare the set accessor as private during the member declaration to prevent users from changing property values once the object has been created. The downside of this approach is that a constructor needs to be implemented in order to populate the immutable property at the time the class is instantiated.

Have Fun!

Subscribe

  • RSS - Posts
  • RSS - Comments

Categories

  • Android (1)
  • Applications (7)
  • Business Process (2)
  • DBMS (1)
  • Development (5)
  • General (4)
  • Mobile (3)
  • Off-Topic (2)
  • Operating System (1)
  • Training (1)

Archives

  • April 2010
  • July 2009
  • March 2009
  • February 2009
  • September 2007

Create a free website or blog at WordPress.com.

Cancel
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy