June 2004 - Posts
When checking if an enum that is a flags enum has a value set, you may wish to use either of two methods:
if ((ve & ValuesEnum.One) != 0)
or
if ((ve & ValuesEnum.One) == ValuesEnum.One)
I always use the first version. It seems faster. I did, however, mean to check it for a while now. This is what I came up with:
Method 1:
Tested code:
ValuesEnum ve = ValuesEnum.One;
if ((ve & ValuesEnum.One) != 0)
{
ve = ValuesEnum.Two;
}
Output IL:
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: and
IL_0005: brfalse.s IL_0009
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: ret
Time for 200,000,000 runs: 4.3963216 seconds.
Method 2:
Tested code:
ValuesEnum ve = ValuesEnum.One;
if ((ve & ValuesEnum.One) == ValuesEnum.One)
{
ve = ValuesEnum.Two;
}
Output IL:
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: and
IL_0005: ldc.i4.1
IL_0006: bne.un.s IL_000a
IL_0008: ldc.i4.2
IL_0009: stloc.0
IL_000a: ret
Time for 200,000,000 runs: 4.8970416 seconds.
Conclusions:
- My computer sucks, as Ido keeps reminding me.
- We get two commands with the second version. One to load ValuesEnum.One again and the other to compare the result of the And operation. The first version has only one that compares it to zero (it's a build in command).
- The first version is faster by a very very very very very small amount.
A while ago, I was in an infrastructure team for a project that used the User Interface Process Application Block (version 1.0) for working with Windows Forms applications.
I was required to create an application that would manage the obese configuration file the application block required and was given a free pass to create what kind of GUI I liked.
I worked for about five weeks and produced something that resembled Longhorn's Aero style interface, but only in Hebrew. I used icons I found online (there is no commercial value for this application, mind you) and the grid and combo box controls created by Janus Systems that were already being used in the project. The rest of the controls and the design are my handiwork.
Now for what it means to you. If you want to use this application (it's designed specifically for using with Windows Forms applications, but can be easily used for Web Forms applications), I am working on re-creating this application (in English) and will distribute it openly.
In the meantime, you can take a look at a few screen shots I took of the original application (blurred out the application specific details since of an NDA I signed). The original application is in Hebrew, so I included translation for the screen captures. They are in an article here.
[ Update: If anyone knows of a good library that could replace the grid and combobox (Janus's aren't free), please drop me a line. ]
Phil Haack's words "Do not store user settings in an application configuration file!" reminded me of something I made a while back, in order to store user settings in an application. I used the Object Model Generator to create an object oriented representation of my configuration and wrote a wrapper for it to load from, and persist back to, an Xml based format.
Here's some code for you:
using System;
using System.IO;
using System.IO.IsolatedStorage;
namespace Utilities.Configuration
{
public class ConfigurationFile
{
private static IsolatedStorageFile m_IsolatedStorage = null;
private static ConfigurationElement m_Element = null;
// This is the name of the configuration file I will use in isolated storage.
private const string ConfigurationFileName = "configuration.xml";
// This class can not be inherited.
private ConfigurationFile()
{
}
// The static constructor loads the file and creates the document object
// model out of it, then stores it in memory for manipulations.
static ConfigurationFile()
{
// Load the configuration file's contents.
string configurationFile = LoadConfigurationFile();
if (configurationFile != null)
{
// If the configuration file existed, create the object grid from it.
ConfigurationDocument document = new ConfigurationDocument();
document.LoadXml(configurationFile);
m_Element = document.CreateDOM();
}
else
{
// If the configuration file has not been found,
// create a new object grid.
m_Element = new ConfigurationElement();
}
}
// Using this property, we can access the configuration settings.
public static ConfigurationElement DOM
{
get
{
return m_Element;
}
}
// This method is called when the application is closed,
// causing it to commit all the changes made to the object
// grid back to the configuration file in the isolated storage.
public static void Close()
{
// Save the configuration file.
SaveConfigurationFile(ConfigurationDocument.FromDOM(m_Element).OuterXml);
// Dispose of the isolates storage file.
if (m_IsolatedStorage != null)
{
m_IsolatedStorage.Dispose();
}
}
private static string LoadConfigurationFile()
{
if (m_IsolatedStorage == null)
{
// This gets storage isolated for this user using this application.
m_IsolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();
}
// This looks for the file. If it is found,
// it reads its contents and returns that.
if (m_IsolatedStorage.GetFileNames(ConfigurationFileName).Length == 1)
{
using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream(ConfigurationFileName, FileMode.Open, FileAccess.Read, FileShare.Read, m_IsolatedStorage)))
{
return sr.ReadToEnd();
}
}
else
{
return null;
}
}
private static void SaveConfigurationFile(string fileData)
{
// Store the data to its original file location.
using (StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(ConfigurationFileName, FileMode.Create, FileAccess.Write, FileShare.None, m_IsolatedStorage)))
{
sw.Write(fileData);
}
}
}
}
I've been using files for a long time and at times I stumble across this kind of code before:
public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
System.IO.StreamReader reader = new System.IO.StreamReader(fileName);
string data = reader.ReadToEnd();
// Work with the data.
reader.Close();
}
Let's fix this code up a bit:
public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
System.IO.StreamReader reader = null;
try
{
reader = System.IO.File.OpenText(fileName);
string data = reader.ReadToEnd();
// Work with the data.
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
So what else is there to do? How would you like this?
public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
using (System.IO.StreamReader reader = System.IO.File.OpenText(fileName))
{
string data = reader.ReadToEnd();
// Work with the data.
}
}
So what I wanted to talk about was C#'s using statement.
What it does is take the variable that sits between the parenthesis and disposes of it (using IDisposable.Dispose) at the end of the code structure, whether an exception has been thrown or not. The variable's type must implement IDisposable. What it means in the third code segment is that the file is closed for you and you don't have to take care of it.
I've been using using for things like files, GDI+ objects, etc. It's quite useful.
using isn't part of the IL, so the second and third code segments come out very close to each other in the final IL.
More about using, here and here.
I was at the TDD Workshop today and got my perspective adjusted on the matter of Unit Testing.
As I was trying to attack the method in my mind from different angles on my way back home, I came to the question of using Unit Tests on methods marked as Obsolete.
After all, Unit Tests are supposed to check that your code is all right whenever you run them. If your code uses Obsolete methods, this means that soon enough, it might not run and even not compile. Using nightly builds with unit tests will not reveal this matter, since using an Obsolete method raises only a faint warning.
Consider the following:
The Red Team is the infrastructure team for The Blue Team at Gulch inc.
The reds decide one day that they are going to refactor their code and decide to kick some methods out the door. Like every other polite team, they decide to keep the old methods, but place an ObsoleteAttribute on them.
The blues get the new set of assemblies and run all of their unit tests on them to see that their code is still all right. It is, since the Obsolete methods still run, but it's not okay to use them.
I think that if the unit tests would warn in a way (or even fail), that the code uses an Obsolete method, nightmares like the ones Raymond has would just not occur (yes, only for people who use Unit Tests, you cynics ;).
What do you say?
[ Please read the original post before reading this post ]
Bill McCarthy talks about the Eloquence of Language. I wanted to reply to his post, but it was just getting too long, so I decided to post this here.
"Are C# languages really only used because of outdated Computer Science courses, and are those students who use C style languages exhibiting signs of inability to evolve?"
Why is C# so popular?
Yeah, it might actually also be the fact that I learned C style languages when I was at school, but you know what? The first compiler I ever used was QBasic.
When I started working, I was assigned to a VB6 project. I had so much fun with it because it was a RAD tool and a good one at that. When I switched to .NET, I checked both languages and decided to use C#.
One of the reasons was that when using it, you have the ability to clearly identify code constructs, since they use different symbol types. It's not plainly obvious from a quick look where the "Begin" and "End" are, because they are made of letters, like almost everything else in VB. Syntax highlighting just isn't good enough to overcome this, in my opinion. "{" and "}" are easily found, since they 'jump out of the code at you'.
"So perhaps they should be asking why is it that fortune 500 companies choose VB over C style languages, that VB is so strong yet is not part of the Computer Science curriculum."
VB6 was one of the best RAD tools prior to the coming of .NET. VB.NET is used by many companies because they usually have the people who know VB and mistake the upgrade to simple language changes. It's not always like that. I don't have the statistics to claim I know how often it happens. I am sorry to say that I am witnessing another one of those, in my opinion, poor decisions.
VB might be the best choice for some developers, the same way C# is the best choice for others.
Heck, there are some languages out there I have no idea why people still use to code.
But I don't go around calling their language primitive and that they should evolve to use my language. I don't like people telling me I'm too thick to evolve.
Last night we had the blogger dinner at El Gaucho in Tel Aviv.
There were six of us there and we talked about anything from weblogs to writing device drivers. I tried talking about .NET, I really did, but the conversation flowed in different directions and turned out even better.
I had a blast! :D If you didn't come, you missed out!
There were talks around the table to make this into a monthly thing.
Roy took pictures and he'll post them later, I guess. Can't believe I'm the first to post about this.
I can just sum this up with Roy's words, when he said "This is the best conversation I've had in a long long time!"
 |  |
Left to Right: Shmulik Primes, Avner Kashtan, Yours Truly, Ido Samuelson, Ohad Israeli. Behind the camera: Roy Osherove. | Left to Right: Me, Ido Samuelson, Roy Osherove and Ohad Israeli. Behind the camera: The waitress. We didn't get her name. ;) |
Eliyahu Baker wrote an article about estimating the size of an object in memory. He asked what's wrong with the code he presented:
if (graph == null)
return 0;
return Serialize(graph).Length;
He used binary serialization, to get the best estimate.
So here are a few things that are wrong with using this to estimate an object's size:
- Serialization includes the type's full name and other rubbish unrelated to what's in memory.
- The object might not support serialization.
- It's not an estimate of an object, but of a graph. You might want to do just this, but #2 still looms around since one of the objects in the graph might not be serializable.
- Custom serialization might not write all the data held in the object, but only its state. A Customer object might represent a customer from the database. The only thing that is needed in that serialization is the customer's id. What is actually in memory might be cached properties, etc.
Eliyahu also wrote what his original intent was: Speed. When estimating the size of the object requires full serialization, it could take 'ages' to do it.
Cyrus hates them, Jay agrees, Ed thinks they're ugly.
That's plain castism, and in broad day light, too!
I like the C# casts. They help me avoid run-time errors, such as those that I would get in VB6. Remember those?
Dim georgeClooney As Actor
Dim anyMovie As Movie
Set georgeClooney = New Actor
...
Set anyMovie = georgeClooney
And I could actually do this, never mind the fact that trying to cast George Clooney into a movie would cause my system to crash! Did I mention how much I hated VB6?
Just look at these poor ol' moms, marching for casts:

Join the anti-castism march today!
for those of you who can't read 4px fonts, the signs say, from left to right: "I (heart) casts", "Leave the casts alone!" and "My son is in (a) cast!"
I logged on to MSN a couple of days ago and saw Roy has postfixed his display name with "Eureka!". I asked why and he sent me a link to his latest article.
First of all, I have to say this is both simple and excellent at the same time. Why haven't I thought of it first? ;P
I started pondering whether this method had any flaws that would keep me from using it on my tests. Then I remembered that through my experience with NUnit, I had found that it used to create one instance of every TestFixture I had, probably to see whether it could be instantiated. I don't know if this also happens with the current version. Back in the day, this caused me lots of grief over code I put in the constructor to call the SetUp method, so that I wouldn't have to call it manually when calling a test from driver code.
I started to think what would happen, in theory, if NUnit created an instance of the class, thus creating the COM+ Application and starting the transaction, but just released it without the writer being able to manually commit or abort the transaction. What would happen to that transaction? Rolled back? Aborted? Committed?
I asked Roy this question and he gave me the old "Try it out and tell me what happened *wink* *wink*", so I decided I'd go for it.
I wrote a little class inheriting from ServicedComponent, requiring a transaction and called it from some other assembly. The transaction wasn't manually closed at any point.
My results?
Each time the transaction was started, it committed. Yes, committed.
Now, this proves that the code Roy explained can not be hurt by this, but think of the consequences of this affecting your application. If the action you did was unsuccessful and you don't do ContextUtil.SetAbort, the transaction will get committed.
...and then we talked about this.
More Posts
Next page »