Archive for the 'Visual Studio' Category
Visual Studio 2008 Class Diagram
I’ll be returning to my series on “Upgrading your C# skills” next week. For now, though, I wanted to share with you a cool new option in VS2008: Class Diagrams.
Class Diagrams
A Class Diagram is a new file type that allows you to visually create, edit, and manage Classes, Structs, Enums, Interfaces, Delegates, and more. It is a quick and easy way to add Property and Method stubs to existing Classes or to create entire class shells. You can even manage Events and Fields. The interface is immediately familiar and intuitive. Diagrams can even be exported to Images.
To begin, open a project in Visual Studio and follow these steps:
- In the Solution Explorer window, right click the project and select “Add -> New Item”.
- From the Add New Item dialog box, highlight “Class Diagram” and give it a name.
- Press the Add button. The Class Diagram file will be added to your project and the designer will open.
You will now have a Blank Diagram to work with in the designer. To add an existing class to the diagram, simply drag and drop it from the Solution Explorer window onto the design surface. To create a new Class (or Struct, Enum, etc.), right click in the designer and expand the “Add ->” menu item. Select the appropriate type and follow the instructions. Easy as pie.
Once you have an item in the designer, it will look something like this (Click on Screen Shot for Full Size):
I moved the Class Details window to the right, but the default will have it on the bottom. Just like working with a Control in a Form, you will need to select the class in the designer window in order for its details to show in the Class Detail window. And you can have multiple classes in a diagram.
When you create a new item, you will be prompted to either create a new file or append to an existing file. As you can see, the Class Detail window allows you to easily add Methods, Properties, Fields, and Events to a class. You can edit the Name of an element, the Type, the Access Modifier, and the Summary. The Summary column is the XML Comments description: if you leave it blank, then there will be no XML comments at all. If you supply a Summary, it will be added to the source code. You can also elect to “Hide” an element, which only means that it will be not listed in the Class Diagram itself.
So let’s talk about what code the IDE generates from this designer. Consider the Person class listed above: this class already existed and was dropped into the Class Diagram designer. I then added the DOB, MaritalStatus, and IsMilitaryVeteran properties using the Class Detail window. Now the code looks like this:
{
public Person()
{
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
/// <summary>
/// Date Of Birth
/// </summary>
public string DOB
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Marital Status Code
/// </summary>
public char MaritalStatus
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Exposes whether or not this Person ever served in the Armed Forces
/// </summary>
public bool IsMilitaryVeteran
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
}
The properties were created, but not as I would have expected. I would have expected these to be default Automatic Property stubs. Instead, they are classic property stubs, and the getter throws a NotImplementedException. The good news is that this will compile as is. The bad news is that it is surely not the behavior you want, so you will have to do some work to implement the details. And you cannot simply remove the NotImplementedException because the getter must have a return path. Of course, a simple copy and paste can quickly convert these to Automatic Properties, but it is unfortunate that this isn’t the default behavior.
Which brings up another good point: the Property is created, but with no corresponding variable, and yet it still compiles. This tells me that the Automatic Property mechanism is still in play here, but it causes a problem when you go to implement the details: there is no variable to return, so you must create one. A pretty minor point, but worth noting none-the-less. And again, I think this issue could have been avoided if the standard Automatic Property stub had been implemented (or at least optional).
So let’s make this a little more robust and add some other goodies. First, since I have to implement the details anyway, I’m going to add fields to support my new properties. Next, I’m going to add a GetFullName method, and I’m going to override the ToString method. Finally, I’m going to add a MaritalStatusChangedEvent Event Handler. Now let’s look at the results:
{
private string _dob;
private bool _isMilitaryVeteran;
private char _maritalStatus;
public event EventHandler MaritalStatusChangedEvent;
public Person()
{
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
/// <summary>
/// Date Of Birth
/// </summary>
public string DOB
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Marital Status Code
/// </summary>
public char MaritalStatus
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Exposes whether or not this Person ever served in the Armed Forces
/// </summary>
public bool IsMilitaryVeteran
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Retrieves the Full Name of the Person formatted as "Last, First".
/// </summary>
public string GetFullName()
{
throw new System.NotImplementedException();
}
public string ToString()
{
throw new System.NotImplementedException();
}
}
Much as expected, the fields are simple fields, the Event is declared, and the methods are stubbed but all throw a NotImplementedException. This all compiles right out of the box, but if you want to really override ToString(), you’ll need to add the keyword yourself. Again, it would be nice if the tool detected that for you and prompted you to select the desired behavior, but it is not that big of a deal.
Finally, the Class Diagram tool has some options. When you open one, VS2008 will include a new Menu and a new Toolbar. Explore these options a little and you’ll find some other helpful items. In this last screen shot, representing the completed class above, I have elected to show full signature detail in the Designer. (Click on Screen Shot for Full Size).
So I encourage you to explore this feature. For rapid stubbing, I think you’ll find this a very handy and useful tool.
8 commentsChanging Visual Studio Shortcuts
OK, so I’ve been playing with VS2008 for a few days now, and I had a minor annoyance. At first, I was inclined to blame the designers, but it turns out it was my own fault, or rather, my own lack of knowledge.
My complaint was that in VS2005, “F6″ is the Shortcut Key for “Build Solution”, but in VS2008 it had been returned to “Ctrl+Shift+B” (like VS2003). At first, I was upset by this, but I did a little digging and was chagrined to find that my VS2005 Keyboard Settings had been changed from “Default” to “Visual C# 2005″. I checked in VS2008, and sure enough when I changed the Mapping Scheme to “Visual C# 2005″, my beloved F6 had been restored. There are several options here (none of which is C# 2008).
In the process, I also found that you can set these Shortcuts yourself. If you do not want to switch, but instead wish to customize the Default settings (which can always be restored later), follow these steps:
- Go to Tools -> Options -> Keyboard.
- In “Show Commands Containing”, type “Window.NextSplitPane” (this is what F6 points to now – I found this out by first by skipping all the other steps and going directly to #8 below).
- The Current Shortcut “F6″ for “Window.NextSplitPane” will be shown in the “Shortcuts for Selected Command Box”.
- Press the “Remove” button.
- Go back to the “Show Commands Containing” and type “Build Solution”.
- The Current Shortcut “Ctrl+Shift+B” for “Build.BuildSolution” will be shown in the “Shortcuts for Selected Command Box”.
- You do NOT need to Remove this, but you can if you wish. To do so, press the “Remove” button again.
- Put your cursor in the “Press shortcutkeys” textbox and press the “F6″ function key.
- Press the “Assign” button.
- Press the “OK” button to save your changes.
Changes to the Keyboard Mapping Scheme should show immediately in the IDE. You can have multiple shortcuts for a given function, but naturally a shortcut can only be assigned once.
Now, obviously, I had changed the Keyboard Mapping Scheme in VS2005, I just don’t remember doing it. Visual Studio is just such an incredible tool with so many options: I’ll bet that most of us don’t know the half of it. And something like this you may do once, to tweak your setup, and then never think about again. At any rate, I hope this helps someone out there.
6 commentsUpgrade your C# Skills part 2 – Compiler Inference, Object Initializers, and Anonymous Types
Well, that Title sure is a mouthful! “Compiler Inference”, “Object Initializers”, “Anonymous Types”: as fancy as these items sound, they are among some of the more mundane changes to C# 3.0. Don’t get me wrong: these changes lay the groundwork for all the really cool stuff going on in C#, especially LINQ. Truthfully, I should have covered these first, but I had actually been dreaming about Extension Methods, so I hope you’ll understand if I had to get that out of my system!
Compiler Inference
It probably isn’t fair for me to say this is “mundane”, but look at the two examples below:
Person p = new Person();
string name = p.LastName + " " + p.FirstName;
// New Way
var p = new Person();
var name = p.LastName + " " + p.FirstName;
Doesn’t seem like much, does it? All we did was replace the explicit Type with a new keyword called var. When you see var, what you are seeing is an instruction to the compiler to figure out for itself what Type the resulting variable will be. This is NOT var like in PHP or other loosely typed languages. Once assigned by the compiler, all the Strongly Typed rules still apply. And var can only be used for local variables, so it won’t be replacing all type references any time soon.
In the example above, “var p = new Person();”, the compiler will infer from the return type that variable “p” should be of type “Person”. Granted, in this simple example it doesn’t really mean much. It does mean less typing, especially when looping through generic collections, but where it will really come into play is with Anonymous Types and LINQ. In fact, without Compiler Inference, Anonymous Types could not function, but more on that later in the article.
There is some debate going on as to when to use Compiler Inference. Some feel that using var whenever possible is just lazy and leads to less readable code. These people think that you should use it only when it is really needed. In other words, if I know p is going to be a Person, then why not say so explicitly? Personally, I don’t have an opinion. I’ll use it when it seems convenient and of course where it is required. It certainly makes looping through Collections nicer to write:
foreach (var person in people)
{
Console.WriteLine("{0} {1} is {2} years old.", person.FirstName, person.LastName, person.Age);
}
I have to think that if Person is later subclassed, fewer changes would be required to make this code continue to function. Is it lazy? Perhaps, but we all know that a good programmer is a lazy thief!
Object Initializers
Another cool feature are Object Initializers. Initializers allow you to set a series of Property variables when you create the object. How many times have you coded something like this:
p.FirstName = "John";
p.LastName = "Smith";
p.Age = 32;
Now, you can shorten this considerably. Sort of like Array Initializers, which I’m sure we’ve all used, the syntax is a list of property=value pairs inside curly braces immediately following a constructor:
Person p = new Person() {FirstName = "John", LastName = "Smith", Age = 32};
An interesting side note about IntelliSense: naturally, inside the initializer block, IntelliSense will show you the list of properties available for the Person object. As you use Properties in the Initializer block, you will notice that they disappear from IntelliSense. This is a quick way to make sure you set every property (if you need to), and should help prevent listing duplicate properties (which, incidentally, throws a compiler error).
Now, for some extra coolness, you can embed Object Initialization inside a Collection’s Object Initializing block, so that this:
Person p = new Person();
p.FirstName = "John";
p.LastName = "Smith";
p.Age = 32;
people.Add(p);
Person p2 = new Person()
p2.FirstName = "Jimmy";
p2.LastName = "Crackcorn";
p2.Age = 57;
people.Add(p2);
Person p3 = new Person();
p3.FirstName = "Mary";
p3.LastName = "Contrary";
p3.Age = 44;
people.Add(p3);
Can now be done like this:
{new Person() {FirstName = "John", LastName = "Smith", Age = 32},
new Person() {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57},
new Person() {FirstName = "Mary", LastName = "Contrary", Age = 44}};
As you can see, this is very concise and readable code. Less Typing = More Cool!
Automatic Properties
Since we are talking about properties, at least in a round about way, I want to throw in a quick item you may not be aware of called Automatic Properties. We all know that we are supposed to be exposing access to our variables via properties, but a lot of the time all we want to do is to be able to read and write the variable data. As such, we end up with a lot of code that looks like this:
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
Now, there is nothing wrong with this approach, but it feels a little verbose. To address this, you can now use an Automatic Property:
The two main differences are that you do not define the variable, and you do not have to write the getter and setter logic. In fact, you’ll notice there aren’t even curly braces for get or set. The upside is that it is again less code for a common function. The downside is that you do not have an internal variable to access: you must use the Property name, even internally. Also, the Property must contain both the get and the set, so you cannot have a read-only Automatic Property. You also cannot add custom logic: get and set default behaviors are it.
The plus, though, is that if you start with an Automatic Property and need to add any of this functionality, you simply create the variable and update the Property as you would have before. There is nothing magic about Automatic Properties, this is just another example of the Compiler doing menial work for you. One last tidbit: in VS2008, if you use the “prop” code snippet, you will get the format of an Automatic Property by default. It really replaces the need for my Property Builder tool.
Anonymous Types
When I first learned about Anonymous Types, I didn’t think it would be all that big of a deal. The more I think about it though, the more I can see a use for it. And when I saw how they are used with LINQ, I was sold. Basically, you can define a Type without naming it or creating a separate class definition. Let’s revisit our Person and People class from before, only this time I am not going to define the Person Class:
var p2 = new {FirstName = "Jimmy", LastName = "Crackcorn", Age = 57};
var p3 = new {FirstName = "Mary", LastName = "Contrary", Age = 44};
Here I have created three instances of my new Type, but I have not explicitly defined the type definition. Instead, the compiler has created a class for me and given it the Properties I listed (using our new friend, Compiler Inference). All of the properties are read-only, so once created, the values cannot be changed. Since the three objects above are all identical in their property names, all three objects are of the same (unknown) type. And IntelliSense still works as well: Typing “p1.” will reveal a list of the properties. I said earlier in the article that Anonymous Types could not function without Compiler Inference: hopefully it is obvious now what is happening above. “var” is the only option here, because the Type of the variable does not exist at design time. The Compiler must infer the Type to be of whatever class the Compiler creates, otherwise, you could not have Anonymous Types in a language like C# because of its strong typing.
Of course, there is a catch: as of yet, I have not figured out a way to use these in a list. You cannot use a Generic list, because there is no Type for strong typing. You can store them as Objects, but then you cannot cast them back out because there is no type. So what does this particular method buy you? In my opinion, not much. There could be an argument for using this method to replace the use of temporary Structs, a method I use frequently to store grouped information. But since I can’t store them in a list or pass these objects around, it would be a very limited approach.
There is, however, a necessary use for Anonymous Types: LINQ requires them to be able to create custom query results as a Collection. We’ll explore that more later this week, so be sure to check back.
7 commentsUpgrade your C# Skills part 1 – Extension Methods
DOWNLOAD the Code!
Now that I have VS2008 and .NET 3.5 installed, I am going to begin a series of articles on some of the new features you can use in C#. My hope is to add one new article a day for the rest of this week. Along the way, we’ll explore some of the new language features for C# 3.0. Truthfully, they aren’t all that new since C# 3.0 has been around for about a year, but support for them is now built in to Visual Studio, so using them is now realistic. Also, with the release of VS208, I’m sure this will be the first time most developers will be exposed to them. I’m going to start by introducing one of my favorite enhancements: Extension Methods.
Extension Methods
Extension methods offer us a way to expand class functionality even if we do not have access to the code for those classes (including sealed classes). In other words, we can add our own functionality to any object type. Have you ever looked at the String class and said “why can’t I do {fill in the blank} with a String?” If so, you probably created your own method, passed it the string in question, and consumed the return value:
string z = Reverse(s);
If you’ve ever written code like this, then Extension Methods are for you. In the case above, it should be obvious that Reverse is a static method, since it is not attached to an instance. Wouldn’t it be nice instead to write this?
string z = s.Reverse();
I know it is a subtle difference, and in this case not a terribly functional one, but hopefully you can see the difference. Instead of passing the string variable to a static method, you can treat your methods as though they belong to the string class. And these new methods are available in Intellisense: when I type “s.”, I will see my extension methods right alongside all the native methods, which makes finding and using them much more palatable. And you will find in the new Intellisense that Microsoft itself is making heavy use of Extension Methods. You can tell in two ways: first, the icon for extension methods is the familiar purple box but accented with a blue down arrow. Secondly, when the method description pops up in Intellisense, the description is preceded by “(extension)”.
Let’s look at a more reasonable example. Using the Regex class, you can determine whether or not string matches a Regular Expression pattern by passing a string and a pattern to the Regex.IsMatch() method:
if (Regex.IsMatch(s, "awe"))
{
Console.WriteLine("Yep, this is a match!");
}
else
{
Console.WriteLine("Sorry, no match.");
}
I think it would be handy on occasion to simply “ask” the string itself if it matches a certain pattern:
if (s.IsRegexMatch("awe"))
{
Console.WriteLine("Yep, this is a match!");
}
else
{
Console.WriteLine("Sorry, no match.");
}
Pretty neat, huh? OK, I admit it doesn’t appear to lessen your code, but to me it can make your code make more syntactic sense. And given a more complex example, it could do a lot for you. Richard Hale Shaw showed us an example of a .ForEach extension for IEnumerable<T> collections that would knock your socks off! Imagine being able to loop through an entire Collection and perform some action on each item in a single line of code, without passing the Collection off to a method? It would look something like this:
FileInfo[] files = dir.GetFiles();
files.ForEach<fileinfo>(f => Console.WriteLine("{0} {1}", f.FullName, f.Length));
For now, ignore the code between the () – that’s a Lambda Expression, and we’ll get to those later in the week. Just understand that with this sample above, each FileInfo object in the array will have the passed Action applied to it. How many foreach loops do you think this little nugget could eliminate?
Now, I hope this will get you interested in Extension methods: it didn’t take me too long to think these are very cool! To get you started, I’m adding a new project called DevelopingForDotNet.Extensions to the Free Code page . My take on Richard’s method(s) are included, along with a handful of String and Numeric operations. Nothing too fancy, but hopefully enough to help get you started.
Enough already, how do I do it?
Creating Extension Methods is very simple. First, you must follow these simple rules:
- Extension Methods must be static, defined in a static class
- Extension Methods must be public
- The this keyword precedes the first parameter
We’ll take these one at a time. First, the method must be static because of how the compiler handles extensions. Behind the scenes, whenever an Extension Method is employed, the compiler actually generates code to call the static method. The idea of the Extension Method is just a visual layer for the developer: behind the scenes the actual static method is being called. Also, these methods can be called in a static fashion, rather than as methods attached to an instance. Which brings up another good point: the class name the Extension Methods are in is essentially irrelevant (unless you are going to call them explicitly). I put all my extensions in a single static class (imaginatively called “ExtensionMethods”).
Second, they probably do not absolutely have to be public, but if they aren’t then you are severely limiting the functional scope, so what’s the point?
Finally, preceding the first parameter with “this” is what tells the compiler that this is an Extension Method. It is also probably going to be the main source of initial confusion, because you do not pass this parameter (unless you are calling the method explicitly).
Overall, these are fairly simple rules to follow. Here is a handy method I’ve used for a while:
{
string ch = FillCharacter.ToString();
if (s.Length > Size)
{
throw new ArgumentException("Size of Value larger than Requested Size.");
}
while (s.Length < Size)
{
s = ch + s;
}
return s;
}
This method receives a string and right adjusts it to the given size, filling the leading characters in with the passed char. Calling it looks like this:
s = RightAdjust(s, 7, ’0′);
// Value of s is now "0001234"
Now, let’s convert this to an Extended Method:
{
string ch = FillCharacter.ToString();
if (s.Length > Size)
{
throw new ArgumentException("Size of Value larger than Requested Size.");
}
while (s.Length < Size)
{
s = ch + s;
}
return s;
}
All we did was add “this” before the first parameter. Now we can call it like so:
s = s.RightAdjust(7, ’0′);
// Value of s is now "0001234"
Naturally, you will need to add a reference to the DLL that contains your Extension Methods in order to find and use them.
Overloading Extension Methods:
Just like other methods, Extension Methods can be easily overloaded. My approach for overloading has always been to put all the functionality in the method that requires the most parameters. I then simply have my overloading method signatures call the primary method, sending it the appropriate parameter values. Looking at the RightAdjust method above, I want to establish a method that will use a blank character as the default fill character if one is not supplied. What’s different about overloading extension methods, is that I actually employ the primary extension method in my overloading methods:
{
return s.RightAdjust(Size, ‘ ‘);
}
So now I can call this method passing it just the Size parameter, and that method then calls the primary method using the Extension Method mechanism.
Conclusion:
Extension Methods can be as simple or complex as you like. They are a nice syntactical enhancement to the language that lets you enhance other objects and use them how you would like. But beware: you could easily go overboard. I mean, there is no reason to create a MakeDirectory method for a TimeStamp instance, but you could. Just use common sense and make sure that the extensions you create apply to the object type and way that you would use them.
9 commentsInstalling VS2008
FINALLY! After 5 hours and 45 minutes of downloading, the ISO file is here! I also downloaded Microsoft’s VirtualCD software, mounted the ISO file, and began the Install process at 3:01pm EST.
First, after mindlessly bypassing the EULA, I saved 1.6 GB of install space on my machine by not installing C++ or Crystal Reports. I’ve had C++ since I first installed VS2003 Pro and have never once used it, same for Crystal Reports, so why bother? I could have saved more but not installing SQL Server, but I figured better safe than sorry.
A few things about this machine while the installer runs:
- IBM ThinkPad G41, about two years old, with some kind of Pentium IV Mobile processor.
- Running Windows XP Pro SP2.
- It had a little over 8 GB free when I started.
- 1 GB RAM.
- Already installed are VS2005, Mobile 5.0 SDK, .NET 3.0 (and 2.0 and 1.1)
4:18pm -
The install is finished. I had to reboot, which meant remounting the Virtual CD image. Also, I cannot install the MSDN Documentation: the installer will not recognize the ISO image as the correct disc. Perhaps there is a separate download from MSDN for the docs.
At any rate, it seems I am up and running. I opened the IDE for the first time and selected C# as my primary environment. The software configured and opened a few minutes later.
So all in all, the installation was a breeze (except for the waiting for the download part). Now on to Blend!
No comments

