Feeds:
Posts
Comments

Posts Tagged ‘windows7’

Howdy folks,

Here we are back again with an introduction of the new features of the upcoming Visual Studio 2010. Its release has been postponed to the 12th of April, so in the meantime we’ll have to stick to the Beta 2, which is pretty stable already. There are so many improvements that we’ll have to divide it into multiple parts. Let’s dive right in!

1. UI: WPF-Based

The UI is now WPF based, which means a better usability and more extensibility options for us developers. Clearly, introducing VS2010 as a WPF-based application is a big push in the direction of visualization and diagramming. We’ll see later how this can be performed using the new IDE.

The editor, for example, is now WPF-based. Cool, but what does that mean for us? Here are the advantages:

Change font size w/ mouse only, or better: No more Options->Change font size during presentations!

Extension Manager allows easy-to-install-and-use add-ins: Also from online galleries – Single click install and enabling!

Highlighting of related variable/method names (Figure 1)

clip_image002

Figure 1: Highlighting related variable. Note that the highlighter correctly references only the name variable passed as a parameter

You can navigate between the highlighted elements using CTRL + SHIFT and the ARROW keys!

2. Intellisense – Improvements:

Method Matching: When VS2010 brings up the list of available methods (after you typed something), it performs not a simple .StartsWith name comparison, but a .Contains. This leads to the results shown on the next screenshots:

Filtered list is gone: When typing letters, the auto completion list that pops up won’t give you all objects/methods/variables that start with the same letter, but only those who are truly related. Consider Figure 3: We typed IF. In the old version, VS would have brought up not only the items shown in the completion list, but possibly many many more, all starting with I (but not containing or continuing with F). Now the IntelliSense search is narrowed, which makes it a lot easier for the developer to select the correct entry.

clip_image004

Figure 2: Highlighting the related object/variable/method.

Case sensitivity: Another nice feature highlighted in figure 2 is the Pascal-Case typing of the capital letters IF, which brings correctly up our method, since its signature contains both I and F as of the method name. Try typing If (f is lowercase), and you won’t find the IsFasterThan method in the auto completion list anymore.

3. References dialog improvements

Remember the Add References dialog in figure 3?

clip_image006

Figure 3: Add references underwent some perception changes.

First of all, Microsoft realized that most people are using it to reference other projects, so they brought up the Projects tab by default. But that’s not all: We all LOVED to wait 30 seconds for the list of .NET or COM objects to appear, right? Because of that, while we are browsing by default the projects, VS2010 is asynchronously loading the available assemblies already. Saves time and nerves.

4. Search and Navigation

Let’s press CTRL + , anywhere in the editor. The window Navigate To will appear, providing us a very powerful search across the entire solution. The search results are updated as we type. From here, we can navigate directly to the found item. Figure 4 shows the dialog.

clip_image008

Figure 4: The Navigate To dialog is a powerful search and navigation mechanism, providing also essential information about the found items. Big improvement over the VS2008 style’s CTRL+SHIFT+F (and subsequent find results crawling without navigation to the desired item)!

5. Call Hierarchy

Remember the Find All References option in the editor’s context menu? It provided us information about where a method/variable has been used. Tell you what. We have a much more powerful way of doing this now: The Call Hierarchy option (Figure 5).

clip_image010

Figure 5: Context menu for the IsFasterThan method, highlighting the new View Call Hierarchy option.

This is the result: A list of all callers (“Calls To”) and callees (“Calls From”) of IsFasterThan (Figure 6). Every caller/callee can be expanded into its own callers/callees. As of figure 6, e.g. Main. This is a really expressive feature which outperforms Find All References by far. However, a possible drawback might be that you could expand the list to infinity by alternating the caller/callee relationship. Figure 6 shows the resulting

image

Figure 6: The View Call Hierarchy window, showing callers/callees of IsFasterThan.

6. Project dialog with search and .NET version selection

Figure 7 shows the improved New Project dialog.

clip_image012

Figure 7: The NewProject dialog. Please note the search field in the right upper corner and the .NET framework dropdown list (center), where now also version 4 of the .NET framework is available.

7. Code Snippets

The code snippets are accessible via the Tools menu, or by pressing the shortcut CTRL + K, CTRL + B

Additional snippets are now available also for HTML, JavaScript and SQL. In sub-categories you can find the different snippets already provided by VS2010. Moreover, you can add your own snippets (as we already know from previous VS versions), as well as remove and import snippets. Figure 8 shows the Code Snippets dialog.

clip_image002[1]

Figure 8: The Code Snippets dialog, showing the newly available languages, as well as subcategories in the Code Snippets Manager.

8. Environment settings: Code Optimized

One more newly available feature is a new default environment setting (remember you had to choose which default settings you wanted to use when starting VS2010 for the first time?). There is one newly available feature which will simply allow you to reduce your viewport to only the code when developing (hence removing the designer). If you have already chosen your first-time-startup environment settings: Don’t worry! The next screenshot explain how you can access the new Web Development (Code Optimized) default environment setting. First, choose Tools –> Import and Export Settings.

image

Figure 9: Import and Export Settings wizard. Choose Reset all settings here. Then you will be prompted whether or not you want to save your current settings. Choose as you wish there. Then proceed.

image

Figure 10: Default environment settings. Note the Web Development (Code Optimized) option, which is new to VS2010. Choose it and VS will immediately switch to those settings, removing e.g. the designer buttons and providing you with a much more lightweight code editor window. Very handy for developers who want to only focus on the code.

9. Conclusion

So I’d say this is about it for this time. Of course there are a lot more features which need to be covered.

The next lessons will deal with creating customized startup pages for VS2010, and introduce the new language features and tools of Visual Studio 2010.

In the meantime, enjoy exploring VS’ new capabilities and features, and hang on till the next time!

Best regards,

Martin

Advertisements

Read Full Post »

Dear community,

It’s me once more with a small but handy hint that can make your coding and maintaining a bit easier.

When mapping columns to integral types, it certainly is possible that a field’s value is NULL, right? Now, let’s assume a hypothetical table ORDER that contains a field QUANTITY. Assume also that we have an existing mapping that looks like the one in snippet 1:

   1: <property name="Quantity" column="QUANTITY" type="System.Int32"/>

Snippet 1: Excerpt of a Order table HBM file

Assume also the class we’re mapping to, Order:

   1: public class Order

   2: {

   3:     Int32 Quantity;

   4: ...

Snippet 2: Excerpt of the Order class

Now, what happens to this property once we’re actually mapping values from the DB to it?

If the value is NULL, then the property will assume its default value, which in this case i 0.

So what’s wrong with that?

Simply put, this is correct, but not very effective. Imagine a scenario where we have both 0 and NULL values stored in the QUANTITY column. Once the values are mapped, they could not be distinguished from each other anymore, since they would both map to 0 in our property Order.Quantity.

Hence, we need to come up with a more elegant solution:

We simply use Nullable Types

All you have to do is to change the property Quantity into a Nullable Type, as shown in Snippet 3:

   1: public class Order

   2: {

   3:     Int32? Quantity;

   4: ...

Snippet 3: Excerpt of the changed Order class. Note that the Int32 has been turned into a Int32? Nullable Type.

What else do we have to change? Nothing. NHibernate automatically determines that the property is a nullable type and assigns Null to the property in case of a NULL value arriving from DB.

For the above mentioned scenario, now a 0 would be mapped to a 0 (in the class), and an NULL value from DB would be mapped to an actual Null value (in the class).

That’s it! Enjoy mapping with NHibernate!

Till next time & best regards,

Martin

Read Full Post »

Howdy all,

Here comes another post about Code Contracts. Remember my post First Steps with Code Contracts?

Let’s just recall which class we have been working on last time:

   1: namespace Vehicles

   2: {

   3:     class Car : IVehicle

   4:     {

   5:         string name;

   6:         int speed;

   7:

   8:         public Car(string name, int speed)

   9:         {

  10:             this.name = name.ToUpper();

  11:             this.speed = speed;

  12:         }

  13:

  14:         void IVehicle.Drive(int speed)

  15:         {

  16:             Console.WriteLine("Car " + name +

  17:             " is driving at a speed of " + speed);

  18:         }

  19:

  20:         public bool IsFasterThan(Car c2)

  21:         {

  22:             Console.WriteLine(name.ToUpper() +

  23:             " is faster than "

  24:             + c2.name.ToUpper());

  25:             if (this.speed > c2.speed)

  26:                 return true;

  27:             else return false;

  28:         }

  29:

  30:         [ContractInvariantMethod]

  31:         void ObjectInvariant()

  32:         {

  33:           Contract.Invariant(name != null);

  34:         }

  35:     }

  36: }

Snippet 1: The Car class from the First Steps with Code Contracts example.

After completing all the steps from that example, in the end we should have ended up with at least one warning generated by Code Contracts:

Code Contracts: Possibly calling a method on a null reference ‘c2.name’

with respect to line 24.

Now, if we review the usage of Object Invariants (First Steps with Code Contracts), we would see immediately that the purpose of Objects invariants is to provide us a mechanism to perform the checking in ObjectInvariant() in all instances (and instances of subclasses) of Car.

It seems there are no assumptions generated for the Objects Invariants of objects of the same type passed as a parameter (at least not yet, maybe it’ll come).

The workaround:

In order to avoid the warning, we can do 2 things:

  • Assumption:Contract.Assume(!String.IsNullOrEmpty(name)) or
  • Postcondition: Create a property w/ getter postcondition ensuring the result is not null

That should about do the trick!

Enjoy and see you next time!

Martin

Read Full Post »

Howdy,

The Code Contracts User Manual holds (besides detailed information about Code Contracts’ usage, advantages and drawbacks) a few nice lists of Code Snippets that ship with the Code Contracts and will ease your life. Find below the list of available Code Snippets for the C# language, as exactly taken from the User Manual (January 12th, 2010):

cr Contract.Requires(…);
ce Contract.Ensures(…);
ci Contract.Invariant(…);
crr Contract.Result<…>()
co Contract.OldValue(…)
cim [ContractInvariantMethod]

private ObjectInvariant()

{

Contract.Invariant(…);

}

crn Contract.Requires(… != null);
cen Contract.Ensures(Contracts.Result<…>() != null);
crsn Contract.Requires( !String.IsNullOrEmpty(…) );
cesn Contract.Ensures( !String.IsNullOrEmpty(Contracts.Result<string>()) );
cca Contract.Assert(…);
cam Contract.Assume(…);
cre Contract.Requires<E>(…);
cren Contract.Requires<ArgumentNullException>(… != null);
cresn Contract.Requires<ArgumentException>( !String.IsNullOrEmpty(…) );
cintf expands to an interface template and associated contract class

If you plan to use Code Contracts effectively, this list comes in very handy. I hope it’s of use for you. In the Code Contracts User Manual, you can find a similar list also for Visual Basic.

Best regards,

Martin

Read Full Post »

Howdy ladies and gents out there,

Here we go with another NHibernate common problem solved for you. Recently the question arose whether it is possible or not to execute a query with NHibernate that checks whether a property lies in a given range of values or not. Not much of a problem, we would say, since HQL can do it just directly using its SQL-like syntax. For example, if we recall our example DevJour1 from part 1 of the NHibernate noob series, we could define a query in the Book.hbm.xml file:

   1: <query name="GetAllBooksWithinRange">

   2:   <![CDATA[

   3:     select b from Book b where b.Title in ('It', 'Salem's Lot',                                                  'Langoliers');

   4:   ]]>

   5: </query>

Snippet 1: Excerpt from the Book.hbm.xml file: HQL query returning all books whose title lies within a certain range of values.

Problem solved? Not quite. Another requirement to this query was to provide custom sorting w/ a custom field and a custom sort direction. Sounds familiar, doesn’t it? Remember our first NHibernate troubles post: Custom Sorting. Simply put, using HQL, this is not possible. So we had to use Criteria queries. But how do we implement the range value check for a given property using Criteria queries? It’s simple, really:

   1: public static List<Book> GetAllBooksWithinRange()

   2: {

   3:     String[] titles = { "It", "Salem's Lot", "Langoliers" };

   4:     ISession session = Program.OpenSession();

   5:     List<Book> books = session.CreateCriteria(typeof(Book)).

   6:         Add(Restrictions.In("Title", titles)).

   7:         List<Book>().ToList<Book>();

   8:     return books;

   9: }

Snippet 2: Excerpt from the Book class.

BookGetAllBooksWithinRange()explained (line by line):

3: Definition of our range of values

4: Opening a session, recall from Program class of the Custom Sorting article.

5: Creating criteria for type Book .

6: Crucial part: Adding Restrictions.In (NHibernate.Criterion), passing the property that needs to be checked (Title) and the list of range values.

7-8: Calling the List() method(s) and returning the retrieved list

Important: This works also, when comparing a property of a property with a range of values. Example: Assuming, Book contains a class Author , which in turn contains a property Surname. Then we could formulate such a comparison statement like follows:

.Add(Restrictions.In(“Author.Surname”, names)).


Under the assumption that names is an array containing strings.

That’s it! I’m sure there are more problems to be solved!

See you later!

Best regards,

Martin

Read Full Post »

Hello all,

This time we’ll do a quick exploration of how we can apply Code Contracts to interfaces. As you know from our post First Steps with Code Contracts, the preconditions and postconditions (Contract.Requires and Contract.Ensures calls, respectively) must be placed inside a method body.

Therefore, when defining an interface, we run into a problem: We do not have method bodies there. Of course we could put such calls inside each effective implementation of the interface methods. Clearly, this is not what we want, since

  • We do not want to replicate code in x classes that implement our interface and
  • Future implementations of our interface would contain the conditions we need

Luckily, the Code Contracts provide us with a powerful mechanism that allows us to define a class which implements that interface and which will do the necessary checks.

The Contract Class

Let’s see how this is done, right? For this example, please recall our example from the First Steps with Code Contracts introductory article.

 

   1: namespace Vehicles

   2: {

   3:     interface IVehicle

   4:     {

   5:         void Drive(Int32 speed);        

   6:     }

   7: }

Snippet 1: The IVehicle interface

Also do recall that we did not define any pre- or postconditions for our interface (how could we? – there is no method body).

This is exactly the place, where we will put a so called Contract Class, that will implement our interface. Every time the interface is called, the conditions put into our Contract Class will be injected. This holds for every implementation of our interface.

We basically need two things:

1. A class that implements our interface IVehicle that is marked as Contract Class via an attribute:

 

   1: [ContractClassFor(typeof(IVehicle))]

   2: public class IVehicleContract : IVehicle

   3: {

   4: }

Snippet 2: Contract Class implementing the interface we want to fulfil requirements

2. Another class that links up our interface to the ContractClass

   1: [ContractClass(typeof(IVehicleContract))]

   2: public partial interface IVehicle

   3: {

   4: }

Snippet 3: The link between the interface and our Contract Class

Hint: Don’t worry: You do not have to implement these two classes from scratch: The Code Contracts come with a bunch of predefined snippets that can be executed right away. The following snippet will do the trick for generating the Contract Classes for an interface:

 

cintf ->(TAB – TAB)

The next step is to implement the interface for IVehicleContract.

clip_image002

Figure 1: Explicitly implementing the interface IVehicle for the IVehicleContract class.

The result is shown in Snippet 4:

   1: [ContractClassFor(typeof(IVehicle))]

   2: public class IVehicleContract : IVehicle

   3: {

   4:     void IVehicle.Drive(int speed)

   5:     {

   6:         throw new NotImplementedException();

   7:     }

   8: }

As a next step, we can implement our conditions in the method body of IVehicle.Drive method in IVehicleContract, like shown in Snippet 5:

   1: [ContractClassFor(typeof(IVehicle))]

   2: public class IVehicleContract : IVehicle

   3: {

   4:     void IVehicle.Drive(int speed)

   5:     {

   6:         Contract.Requires(speed >= 0);

   7:     }

   8: }

Snippet 5: precondition in interface method implementation.

What does this mean now? Well, for every implementation of the interface IVehicle , the code precondition will be injected. In other words:

 

The condition we define in the Contract Class must hold for all implementations of the interface.

 

That was it already (for this time)! It is as simple to use as it seems.

 

Enjoy and stay tuned for the next time!

Best regards,

Martin

Read Full Post »

Hello all,

Today we are going to talk about another exciting project from the Microsoft Research Labs: Code Contracts. It is a Design-By-Contract (DbC) system, that enables us as developers to formulate the expected behaviour of our code by directly putting it into the code.

The main tools of applying Code Contracts are:

  • Static checking (checks contracts at compile time)
  • Runtime checking (checks contracts at runtime)
  • Automated documentation generation (keeps code and docs in sync)

Prerequisites

Before we get started using Code Contracts. I used the following environment for carrying out the tests with Code Contracts:

  • Windows 7
  • Visual Studio 2010 Beta 2 Ultimate*
  • Code Contracts Tools*

Important: I used Visual Studio 2010 Beta 2, because it contains the .NET framework 4, which already includes the Code Contracts framework. You could also use them with VS2008, if you installed the .NET framework 4. The Code Contract Tools need to be downloaded separately. I highly recommend them, since they will add a new pane to your VS2010 which in turn lets you set various options, like enabling the static checker directly from the UI.

1.1 The Strengths of Code Contracts

Elevating assertions to the API level. At this point, the specification of code is not only somewhere deeply hidden in the method, but immediately visible to the caller (if, for example, a Contract is not fulfilled). On the other side, a caller now can know perfectly what to expect from a method.

1.2 Code Contracts for Methods

First, we are going to show how to implement Code Contracts on the method level.

We’ll start with the creation of a test project that will serve our purposes of showing Code Contracts’ capabilities:

image

Figure 1: Add a new console application and name it Vehicles

As a next step, we create a class and an interface, namely Car and IVehicle. Implement them as follows in the snippets 1 and 2. Leave the automatically generated Program class – we’ll need it later for running our examples.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:

   6: namespace Vehicles

   7: {

   8:     interface IVehicle

   9:     {

  10:         void Drive(Int32 speed);

  11:     }

  12: }

Snippet 1: Interface IVehicle, defining one method signature

   1: namespace Vehicles

   2: {

   3:     class Car : IVehicle

   4:     {

   5:         string name;

   6:         int speed;

   7:

   8:         public Car(string name, int speed)

   9:         {

  10:             this.name = name.ToUpper();

  11:             this.speed = speed;

  12:         }

  13:

  14:         void IVehicle.Drive(int speed)

  15:         {

  16:             Console.WriteLine("Car " + name +

  17:             " is driving at a speed of " + speed);

  18:         }

  19:

  20:         public bool IsFasterThan(Car c2)

  21:         {

  22:             Console.WriteLine(name.ToUpper() +

  23:             " is faster than "

  24:             + c2.name.ToUpper());

  25:

  26:             if (this.speed > c2.speed)

  27:                 return true;

  28:             else return false;

  29:         }

  30:     }

  31: }

Snippet 2: Class Car implementing IVehicle.

So far, so good, right? Nothing special there, and the code has got very simple “functionality”. A car that can drive, alright. And check whether it is faster than another car. Compiling the project reveals a succeeding build which at first sight contains no errors.

Before we take further steps, let’s activate the Static Checking feature of Code Contracts. In order to enable this, just right-click the project Vehicles -> Properties.

The last pane on the bottom of the Properties’ window is called Code Contracts. Go for it.

clip_image004

Figure 2: The Code Contracts’ configuration in Properties. Then proceed with Figure 3.

image

Figure 3: Enable static contract checking and the checking of implicit non-null obligations.

Compile again, and in the warning sections, we’ll receive a bunch of warnings generated by Code Contracts:

image

Figure 4: Warning list, generated by Code Contracts.

Those messages are suggestions of how we should change our code in order to be (more likely to be) safe from exceptions.

The warnings, line by line:

1-2: Tell us that we should add a pre-condition in order to be sure from NullReferenceExceptions when accessing the property name (1) or passing a parameter that could be possible equal to null (2). The cool thing is: Code Contracts even provide us with the correct code in order to achieve this.

3-5: These are the actual warnings, containing possible failures.

Preconditions

A precondition is simply added by using the following method:

Contract.Requires(condition)

When debugging, we can step over such a call and verify that it is actually executed. The call is made in the method body, at any desired position. Usually it is placed at the beginning.

Postconditions

A postcondition is simply added by using the following method:

Contract.Ensures(condition)

When debugging, we cannot step over such a call (to be precise: not at the position where we put it in the code), since it is not actually executed in the method body, but only afterwards. Once we stepped over the complete method, we arrive at the Contract.Ensures call. The following snippet show how pre- and postconditions can be applied to the methods of our class Car:

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5: using System.Diagnostics.Contracts;

   6:

   7: namespace Vehicles

   8: {

   9:     class Car : IVehicle

  10:     {

  11:         string name;

  12:         int speed;

  13:

  14:         public Car(string name, int speed)

  15:         {

  16:             Contract.Requires(name != null);

  17:             this.name = name.ToUpper();

  18:             this.speed = speed;

  19:         }

  20:

  21:         void IVehicle.Drive(int speed)

  22:         {

  23:             Console.WriteLine("Car " + name +

  24:             "is driving at a speed of " + speed);

  25:         }

  26:

  27:         public bool IsFasterThan(Car c2)

  28:         {

  29:             Contract.Requires(c2 != null);

  30:             Console.WriteLine(name.ToUpper() +

  31:             " is faster than " +

  32:             c2.name.ToUpper());

  33:

  34:             if (this.speed > c2.speed)

  35:                 return true;

  36:             else return false;

  37:         }

  38:     }

  39: }

Snippet 3: The Car class, using Code Contracts’ preconditions

After we added the Contract.Requires calls in IsFasterThan and in the Car ctor, we receive only 2 warnings from Code Contracts. Just compile to verify that.

Why still two warnings? We added preconditions to check that!

The reason: Only our method IsFasterThan in this particular class, Car, requires name to be non-null. But we could have for example a subclass inheriting from Car, which does not perform the same check. Hence, we need to take care for that. And in fact, Code Contracts provides us the necessary means in order to ensure that no object deriving from Car, can have name which is null:

   1: [ContractInvariantMethod]

   2: void ObjectInvariant()

   3: {

   4:     Contract.Invariant(name != null);

   5: }

Snippet 4: Object invariants

Calling again reveals that the warning concerning the name variable of class Car has gone. Good! It means, we are safe from accessing a null value – variable, and all other programmers subclassing our Car are safe, too!

This is it for now! Next time we’ll see how to deal with Code Contracts and interfaces.

Enjoy playing with Code Contracts and see you soon!

Best regards,

Martin

Read Full Post »

Older Posts »