Vadim’s Weblog

Never stop learning.

Archive for the ‘.Net’ Category

Creating an “M” Project in VS 2010.

Posted by Vadim on June 1, 2009

When you install “Oslo”, installation also adds one “Oslo” template in your Visual Studio.  It’s “M” Project. 

oslo_vs_plug-in

However, if you try to create a new “M” Project or open an existing one you probably will get the following error:

This method uses CAS policy, which has been obsoleted by the .NET Framework.  In order to enable CAS policy for compatibility reasons, please use the legacyCasPolicy configuration switch. Please see http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.

English is not my first language, as you probably already realized that by reading my blog, but I thought that word obsolete is an adjective.  In this Microsoft error message it’s used like a verb “obsoleted”.

Well, enough about English.  I’m sure that you can take any of my posts and have a lot of fun criticizing my English.  If you want to do so, please do.  Your criticism probably will improve my English.

Let’s get back to the error.  You can follow the link in the message to read more about Security Changes in the .NET Framework 4.  One of the thing you can find there is that Code Access Security (CAS) policy got replaced by Windows Software Restriction Policies (SRP).

Historically, the .NET Framework has provided code access security (CAS) policy as a mechanism to tightly control and configure the capabilities of managed code. Although CAS policy is powerful, it can be complicated and restrictive. Furthermore, CAS policy does not apply to native applications, so its security guarantees are limited. System administrators should look to operating system-level solutions such as Windows Software Restriction Policies (SRP) as a replacement for CAS policy, because SRP policies provide simple trust mechanisms that apply to both managed and native code. As a security policy solution, SRP is simpler and provides better security guarantees than CAS.

However, it doesn’t tell us how we can fix our problem.  After some research, I got across documentation about legacyCasPolicy Element.

Next I open devenv.exe.config file that is in C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE folder and added following line:

   1: <legacyCasPolicy enabled="true"/>

You should add this line inside <runtime> element.

M_proj_error 

I understand that “Oslo” and VS 2010 are both Beta products so far.  I’m sure that Microsoft will resolve this problem in future releases. 

I realize that this is not the best solution.  However, it worked for me.  Please let me know if you can find a better solution.

kick it on DotNetKicks.com

Posted in Oslo, VS2010 CTP | Tagged: | Leave a Comment »

New May 2009 CTP for Microsoft “Oslo” is out.

Posted by Vadim on May 29, 2009

Oslo_installIf you don’t know what “Oslo” is, it’s set of future Microsoft modeling technologies.  You can find out more at “Oslo” Developer Center.

In this release Microsoft finally is going to include “Quadrant”, a GUI tool for “Oslo”.

As for previous CTPs you need .NET Framework 3.5 SP1, SQL Server 2008, and VS 2008 or higher.  New install for “Oslo” allows to to customize the installation.  If you select “Install Now” instead of “Customize” option, all of “Oslo” is going to be installed.  It includes: “Quadrant, “Oslo” repository, and “Oslo” SDK.  You must to have administrator privileges in order to run installation.  You can find more details by reading Release Notes.

In case you have  a previous CTP installed on your machine, you must uninstall it before installing new CTP.  Also you must drops the ‘Repository’ from your SQL 2008 database. 

Microsoft also provides us with May CTP Samples.

After installing “Oslo” you can find template for “M” Project in your Visual Studio:

oslo_vs_plug-in

“Oslo” installation also is going to create Repository in your SQL 2008.

oslo_sql

kick it on DotNetKicks.com

Posted in Oslo | Tagged: | Leave a Comment »

Keywords as variables/identifiers. Why?

Posted by Vadim on May 13, 2009

I use words variable and identifier interchangeably.

Have you ever tried to use a keyword as a name of your variable?  Until recently I thought it was impossible.  However, C# and VB.NET allow developers to use keywords as variables.

string string = '' '';
Dim String As String = '' ''

If you try to compile this code, compiler will generate three errors:

  • Error    1    Identifier expected; ’string’ is a keyword
  • Error    2    Identifier expected
  • Error    3    Invalid expression term ’string’ 

To fix this error in C# you just prefix your variable with an @ character.  In VB.NET you surround the variable with square brackets [].  A variable or identifier with an @ prefix is called a verbatim identifier.

string @string = '' '';
Dim [String] As String = '' ''

Why anybody would use keywords as variables?  To me it looks like a very BAD practice.  Variables/identifiers must be descriptive.  Can you think of any keyword that would be descriptive enough to use in your code as a variable?

I found in C# specification why Microsoft includes verbatim identifier in their languages:

The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix.

I still believe it’s a BAD idea.

I also understand that if today I don’t see any reason to use verbatim identifiers, tomorrow I might find a perfect application for it.

If you use it and have a good reason, please let me know.

kick it on DotNetKicks.com

Posted in .Net, C#, VB.NET | 5 Comments »

Stub HttpContext

Posted by Vadim on March 23, 2009

Have you ever tried to TDD objects that use HttpContext, HttpResponse, or HttpRequest?  If you did, you probably created wrappers for these classes.  No more.  With .NET 3.5 Microsoft gave us System.Web.Abstractions.dll that extends System.Web namespace.  In this post I’d like to show an example how to stub HttpContext.

Here’s the system under test:

    public class MyContext
    {
        private readonly HttpContextBase _context;

        // This constructor is called by production system.
        public MyContext() : this(new HttpContextWrapper(HttpContext.Current))
        {}

        // Test calls this constructor
        public MyContext(HttpContextBase context)
        {
            _context = context;
        }

        public bool IsItemCached(string item)
        {
            return _context.Cache[item] != null;
        }
    }

Here are the unit tests:

    [TestFixture]
    public class MyContextTester
    {
        private HttpContextBase _contextStub;
        private MyContext _myContext;

        [SetUp]
        public void StartTest()
        {
            _contextStub = MockRepository.GenerateMock<HttpContextBase>();
            _myContext = new MyContext(_contextStub);
        }

        [Test]
        public void IsItemCached_if_Cache_item_is_null_return_false()
        {
            _contextStub.Stub(x => x.Cache).Return(HttpRuntime.Cache);
            Assert.IsFalse(_myContext.IsItemCached("NotThere"), "False is expected.");
        }

        [Test]
        public void IsItemCached_if_Cache_item_is_NOT_null_return_true()
        {
            HttpRuntime.Cache.Insert("I am HERE", "value");
            _contextStub.Stub(x => x.Cache).Return(HttpRuntime.Cache);
            Assert.IsTrue(_myContext.IsItemCached("I am HERE"), "True is expected.");
        }
    }

kick it on DotNetKicks.com

Posted in .Net, TDD | Tagged: , , , , , | 2 Comments »

Fun with Empty String.

Posted by Vadim on February 23, 2009

I am faster.

Everyone uses pretty heavily  IsNullOrEmpty function that is a member of String class.  But sometimes we need to implement different behavior for an Empty value versus the null one.  There are multiple ways we can check for an Empty value.

Here are three different ways I come up with:

public bool IsEmpty_1(string text)
{
    return text == "";
}
public bool IsEmpty_2(string text)
{
    return text.Equals(string.Empty);
}
public bool IsEmpty_3(string text)
{
    return text.Length == 0;
}

After looking at these functions in Reflector, it was obvious that the method that uses Length should be the most efficient.  To prove it I created a little Console application that executes each comparison 100,000,000 times.  Here’s the code that does it:

equality code

Here’s the result:

equality output

The result above compares empty string “” to “text”.

"text" == ""
"text".Equals("")
"text".Length == 0

You can see that statement with equality operator (==) executes slower than the one with Equals function.  However if we compare empty string with empty string we would have different result.

"" == ""
"".Equals("")
"".Length == 0

Here’s the output when comparing empty string with empty string.

equal output

I am more readable.

Efficient code is important but I would chose the most readable code.  Unfortunately we cannot prove with numbers which code is more readable.   It can be very subjective which code is easier to read but in any case I’ll be brave enough and make my recommendations.

I would extend String class with extension method.

public static class StringUtils
{
    public static bool IsEmpty(this string text)
    {
        return text.Length == 0;
    }
}

Now we can write code like this:

"text".IsEmpty();

We can go further and create extension methods like IsNull and IsNullOrEmpty:

public static bool IsNullOrEmpty(this string text)
{
    return string.IsNullOrEmpty(text);
}

public static bool IsNull(this object obj)
{
    return obj == null;
}

You probably think why do we need to extend with  IsNullOrEmpty; it’s already part of String class.  You don’t but I think it’s more readable.  Look at two statements bellow. Which one makes more scenes to you?

string.IsNullOrEmpty(text);
text.IsNullOrEmpty();

One more note that IsNull extension method you can use with any object not just String.

List<int> numbers;
if (numbers.IsNull())
  ....

kick it on DotNetKicks.com

Posted in C# | 10 Comments »

ASP.NET MVC template for MbUnit tests needs to be fixed.

Posted by Vadim on February 18, 2009

There’re so many new technologies and tools appearing all the time that it’s impossible to keep up. 

First time I looked at ASP.NET MVC framework was more than a year ago when Microsoft just released the first Beta.  I really liked the new web framework for decoupling and testability. However, because I didn’t have any project where I could use it I left it alonge and started playing with some other toys like WPF and Silverlight.  Now my company is starting developing using ASP.NET MVC framework and it’s time for me get familiar with it again.

So I updated my ASP.NET MVC Beta with RC1.  As a next step I created a sample site using ASP.NET MVC Web Application template.

mvc template

When I was asked if I want to create unit tests, I couldn’t say NO.  As a unit test framework I chose MbUnit v3.

mvc mbUnit

After all the default files were generated by the template, I compiled the solution before making any modifications.  I was surprised when the solution failed to compile.   I got the following errors:

mvc errors

As soon as I look at these errors I realized that I’m missing the following using statements:

using System.Web.Mvc;
using MyNamespace.Controllers;

After adding the missing statements, the solution compiled without any problems.

It’s not a hard problem for a developer to correct but I hope that ASP.NET MVC team will fix the template before they ship the final “1.0″ release.

kick it on DotNetKicks.com

Posted in ASP.NET MVC, MbUnit | 3 Comments »

Shortcut Key to Comment code in VS and SQL Server Management Studio

Posted by Vadim on October 16, 2008

When we learn any programming language, one of the firsCtrl+Ct thing  we discover is the syntax how to comment our code.  Some of you probably already have been using this shortcut key for awhile.

Select multiple lines of code and press Ctrl+K,Ctrl+C, and you hard work is going to be ignored. To reverse just press Ctrl+K,Ctrl+U

These keystrokes will comment/uncomment your code only with line comment like // in C# or — in SQL.  I’m not aware how to comment code with block comment (/**/) without using a plug-in for VS.

One more thing.  If you need to comment/uncomment a single line, you don’t need to select the whole line.  Just move the cursor to any position on the line you want to comment, and let you fingers press the magic combination.

If you like me (there’s nothing wrong to be different from me) and use ReSharper, than you would like to use Ctrl+Alt+/ with line comment and Ctrl+Shift+/ with block comment.

kick it on DotNetKicks.com

Posted in .Net, Coding, ReSharper, Tips And Tricks, Visual Studio | Tagged: , , , | 2 Comments »

WPF Margin demystified.

Posted by Vadim on October 13, 2008

In my previous post I asked a question about this line of code:

<Button Margin="10 5" />

Question:

In XAML we can assign margin to a control three different ways:

<Button Margin="5" />
<Button Margin="10 5" />
<Button Margin="10 5 10 10" />
  • The first line assigns left, top, right, and bottom margins with value 5.
  • The second line assigns left and right margins with value 10 but top and bottom with value 5.
  • The last line assigns left, right, and bottom with value 10 and top would have value 5.

If we try to do the same in the code behind, it would look like this:

button.Margin = new Thickness(5);
button.Margin = new Thickness(10, 5, 10, 10);

You can see in the code above that we have code for line 1 & 3 only.  I couldn’t find the way to create code behind for second line because there’s no Thickness constructor with two parameters.

Thanks to Rune Jacobsen & Sam who provided some clues in comments to my previous article.

Answer:

After I read Sam’s comment:

The converter at work here is a ThicknessConverter which parses the input string and attempts to map the values given in the string to one of the Thickness object constructor overloads.

, I used .NET Reflector to analyze ThicknesseConverter class.

ThicknesseConveter has a public method ConvertFrom that calls internal method FromString.

public override object ConvertFrom(
    ITypeDescriptorContext typeDescriptorContext,
    CultureInfo cultureInfo,
    object source)
{
     . . .
    if (source is string)
    {
        return FromString((string) source, cultureInfo);
    }
     . . .
}

FromString method is responsible for parsing string values like “10, 5, 10, 10″ and converting them into Thickness.

It means that this code

<Button Margin="10 5" />

will be converted by FromString method into:

new Thickness(numArray[0], numArray[1], numArray[0], numArray[1]);

Bellow is a switch statement in FromString method that explains the magic.

internal static Thickness FromString(string s, CultureInfo cultureInfo)
{
     . . .
    switch (index)
    {
        case 1:
            return new Thickness(numArray[0]);
        case 2:
            return new Thickness(numArray[0], numArray[1], numArray[0], numArray[1]);
        case 4:
            return new Thickness(numArray[0], numArray[1], numArray[2], numArray[3]);
    }
     . . .
}

If you want to assign a margin with two doubles from the code behind, you can do it like this:

button.Margin =
    (Thickness)new ThicknessConverter()
        .ConvertFrom(null, CultureInfo.CurrentCulture, "5, 10");

Mystery is solved.

kick it on DotNetKicks.com

Posted in .Net, C#, WPF, XAML | Leave a Comment »

WPF Margin Property

Posted by Vadim on October 5, 2008

I finally decided to spend some time to learn WPF.  One of the thing I learned today is Margin property.

<Button Margin="10 0 10 5" />

Every control that derives from FrameworkElement class has this WPF_Margin property.

I’m not going to describe this property here. However, I want to share with you how I memorized the sequence of margin.  It goes like this: Left, Top, Right, Bottom.

The easiest way for me to remember is to start from Left and then go clock wise: Top, Right, Bottom.

There are two main reasons why I blog and both of them selfish.

First reason is because writing helps me remember and understand better new things I learn.

The second reason is that people who read my blog comment and correct any mistakes I make and that helps me to learn too.

I have a question for WPF gurus.  I understand that if all margins are the same (for example left, top, right, and bottom are equal to 5), it’s possible to assign margin like this:

<Button Margin="5" />

The both assignments with one number and four numbers make sense because Margin is of type Thickness  and this struct has two constructors:

public Thickness(double uniformLength)
public Thickness(double left, double top, double right, double bottom)

Here comes my question: I discovered that it’s possible to assign Margin declaratively with two numbers.

<Button Margin="10 5" />

How is it possible if Thickness doesn’t have a constructor with two parameters?
kick it on DotNetKicks.com

Posted in .Net, C#, WPF | 5 Comments »

How big is null in Nullable types?

Posted by Vadim on July 28, 2008

I use often Nullable types in my code.  However, when today I was debugging my code I was surprised to learn that the expression bellow equals to false:

   1: int? n1 = null;
   2: int? n2 = null;
   3: if (n1 <= n2)
   4:     Console.WriteLine("not going to happen");

I decided to dig deeper to see what the reason for this behavior.

I learned that when you have a Nullable type variable that is null (int? n1 = null) in relation comparison expression, the expression is always false.  By relation comparison I mean binary comparison with one of following operators: <, >, <= , =>.

Let me try to explain why this happens.   Let assume that we have two Nullable integers n1 and n2.  n1 is null and n2 has value of 5.  When you compare (n1 < n2), behind the scene the following comparison happens:

(
    (n1.GetValueOrDefault() < n2.GetValueOrDefault()) && 
    (n1.HasValue & n2.HasValue)
)

n1.GetValueOrDefault() will return 0.

n2.GetValueOrDefault() will return 5.

That means the first part of our expression will be true because 0 is less than 5.  However the second part of our expression will be translated into (false & true) which equals to false.  So the first expression is true and the second one is false that means that the whole expression is false too.

That explains why any relation comparison with null value will be false.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, Nullable Types | 1 Comment »