uncategorized comments edit

I have been in IT industry for fifteen years and for last three and half years I been in consulting firm. I really like the type of work I usually do as a consultant. Issues that we have to deal with are usually different and more challenging. Systems we have to build requires more focus and special architecture and extra care. In this industry I do meet new people and a really like to pair with others, teach and of-course learn new things.

Last week, I started working for a new company called Readify. Programmers in Australia, specially Microsoft stack programmers, would probably know Readify. But for those who don't know, Readify is the best Microsoft Consulting company in Australia which has offices across major states in Australia (NSW, VIC, QLD, Perth and SA). I’ve been interested to work for Reaidfy since I came to Australia. But it happened for me after four and half years. Many thanks to my good friend Hadi Eskandari who mentored me during last year when I was studying so hard to get through.

Anyway, If you want a challenging workplace, pairing with smart and knowledgeable developers and using bleeding edge technologies, probably Readify is one of places you might want to consider to work in Australia. During past few years great developers have been working for Readify. To name a couple of them, Damien Edwards who is currently program manager at Microsoft at ASP.net team and Paul Stovell creator of famous deployment tool called Octopus Deploy. And many others who still work for Readify.

Its an opportunity to work in challenging environment with high quality expectation. When a client choose Readify, most likely there is a challenging issue or project. I as a consultant have the opportunity to work with highly skilled and smart people in different project.

Now, let me tell you about first impressions I’ve got since I’ve started with them. I signed the contract nearly six weeks ago and immediately a couple of days after, I got access to my corporate email and other documents so I got myself familiarized with the processes and introduced myself to the team before actually starting new job. Everything was surprisingly well organised and open.

I got my allowance to buy gears and get ready for my new position at Readify. The allowance is enough to buy a decent ultrabook or mac book pro which gets renewed every two years. I decided to buy a Surface pro 3 which I will blog about that later. Anyway, I had a chance to get everything ready before the very first day.

Day one when I went to Readify’s nice office in the city everybody were welcoming to me and helping me to get started. There is is buddy system at Readify which helps new Readifarian get through all induction stuff faster. My buddy Jorge helped me to get through all the stuff quickly. I had a chance to have a chat with one of the principal consultants (Richard Banks). Although principal consultants are busy but they are available to help developers and other consultants. Basically we can reach them quite easily. During past week I had a change to meet other principal consultants and senior consultant and catch up with them.

At Readify everybody gets number of days annually to work on professional development, we can self study new technologies, prepare for exam, write an article or get ready for presentation. First few days I had a chance to look at new interesting changes in mobile area with Xamarin products. Xamarin has gained a lot of attention recently especially in enterprise. I will write more about them later.

So far it has been great experience working at Readify and I have just started my first gig this week which is going to be awesome.

Stay tuned I’ll blog more to share technical and non-technical stuff.

blog comments edit

AutoMapper is a great library helps developer to almost get rid of left hand right hand assignment between different types. In real world C# .net applications there are lots of scenarios developer wants to map different types of objects to each other. Normally it happens in system boundaries, like between UI and services or between ViewModel and Model. Without AutoMapper you have to do it for all properties every time you want to map to objects. This task is cumbersome, hard to test and bug prone. Automapper with does this for you with minimum cost. It has its own conventiones to facilitate type mapping. On top of built in defaults you as developer can teach Automapper new tricks.

You can find lots of blogs and articles of how to use AutoMapper. In fact this, this and this can help you.

Following is also an example of rather complex mapping between Source and Destination types.

In this example I’ve used xUnit to test and AutoFixture to generate random data. Then in constructor of test class I have created mapping by using static method Mapper.CreateMap. this creates mapping at application domain context and you just need to set this up once and will be available across your application. After that in our test we created a source type and then mapped that to destination type finally checked the destination properties.

This post is not about normal scenario of using Automapper. When you are working with database you’d normally use repositories (arguably you might not need repository). in simple case of repository you would have following code

This is a simple interface for repository. Implementation of this doesn't even need mapping (you might do the mapping in other layers, though). However if we want to separate domain model from persistence model we could introduce another interface like following:

In this interface we have to generic types TI and TO. TI is our domain model and TO is our persistence model. For example we pass Source object to Add method but repository implementation would save that in Destination model (See bellow example as Add implementation)

This is possible if we map Source object to Destination object. Automapper does that for us.

Now, the real issue is when we want to implement Find method which accepts Expression<Func<Source, bool. Mapping an expression of func of type source to expression of func of type destination is more difficult as Jimmy Bogard main author of Automapper stated in this mailing list. Anyway, with a quick search I’ve found this question where somebody asked in stackoverflow about AutoMapper for Func’s between selector types. Person how answered this question updated the answer later with answer to Expression mapping with Automapper. The first class which does this magic is an implementation of ExpressionVisitor. This class can traverese an expression tree and replace a single parameter with an arbitrary expression

The second piece that comes into play is an extension method for Expression<Func<Z,Y>> called “Compose”  and it returns a new Expression<Func<X, Y>>.

With this extension method and ExpressionVisitor Class I can complete the repository class for. This repository class is implementing SQL Serve implementation. Later on we will implement another repository class for MongoDB as well.

This is the Entity Framework implementation of our repository. Interesting point is “Find” Method which is taking advantage of Mapper.Engine.CreateMapExpression and Compose extension method. CreateMapExpression in AutoMapper creates an expression for mapping between Source to Destination. In the next line we use the mapper expression and pass this to Compose extension method to build a new expression. And finally we call Where method on Users DBSet and it returns IQueriable of type Destination. I have written a Unit Test to test this.

This test successfully passes. As you see I used Source type to add records and query the records. The repository maps the add part to destination and also map predicates expression.

When I debug the code I can see entity framework successfully constructed the query. This is using Destination type.

Well this is really good, although there is a down side to this approach. This is good and pretty mych abstracted the Destination class and I just work with Source type. However, if I want to join results of two different IQueriables I have to mention the property name of the Model.

Anyway it worked reasonably good with SQL server and EntityFramework. Let see if it works with MongoDB. In order to connect to MongoDB I use mongo csharp driver and on top of that I’m using MongoRepository. Now let see if the same scenario works for Repository Implemented for MongoDb.

In following code I have implemented the IRepository for MongoDB.

The target is to test Find(Expression<Func<Source, bool>> predicate) and see if it works, however, I have added another Find with Find(Expression<Func<Destination, bool>> predicate) signature and I will describe why I added that method.

Now the unit test to test this implementation.

This test fails!. This complains about full name not having serialization information

Additional information: Unable to determine the serialization information for the expression: <MemberInitExpression>.FullName.

This approach doesn't work for MongoDB (probably Mongo CSharp driver could not handle that). I have written another method that accepts Expression<Func<Destination, bool>> predicate, If you uncomment this method call and comment the other in unit test it’ll work.

Having looked at transformed expression shows that this approach does not completely re-write the expression.

This is just wrapper around another lambda that does the mapping. Interestingly EntityFramework handles that very well but MongoDB CSharp Driver not.

On option it to find a way to rewrite the whole expression based on the mapping configuration. But as Jimmy mentioned it could be quite hard to implement.

You can find the full implementation and tests here

blog comments edit

I think developers are a bit confused about the concept of ValueTypes and Reference Type. Often I hear that all primitive data types and value types are in stack. First of all it is thread’s stack and it is not a single stack for application. Secondly, when we say value types are in stack it doesn't include field members of the class. Only method parameters and local variable which are value type will be in the thread’s stat. Field members, even if they are value type, will be in heap. Consider following example:

using System;

namespace ClassLibrary
{
    public class Foo
    {
    public int number = 0;
        public int Bar(int x, int y)
        {
            int sum = x + y + number
        return sum;
        }
    }
}

In this example, only x, y, sum and return value are in thread's stack and number variable will be held in heap as part of object instance and is accessible using this keyword (which compiler let you omit that). In other word when we say object instance is created in the heap, what does really stored there? Field members are object state that needs to be stored in object instance.

blog comments edit

In .net world you can choose your language and write your application with best language which matches your requirements. Different languages has different paradigm. For example C# started with static/strongly type paragoge  but over years it has been evolved and now it does support functional programming as well as dynamic. There are many other languages like F#, Visual Basic and fortran.

It is compiler responsibility to generate assembly with proper intermediate language so that CLR (Common Language Runtime) would be able to generate native code (using JIT) and run at run time. Each compilers support subset if intermediate language and provide its flavour using syntactic sugars in the language.

.Net Languages

CLR allows language integration as long as written code comply with Common Language Specification. It means because of differences between languages, if you want to use types generated by other languages, you need to use certain feature of language that are guaranteed to be available in other languages. CLS is the lowest common denominator of language features provided by Microsoft.

However, today I don't want to highlight CLS, instead I want to mentions that Intermediate Language in some cases has more features which languages like C# didn't bother to implement.

For example we all know about access modifiers in C#. There is public, private, internal and protected

Access Modifiers Description
public public access is the most permissive access level. There is no restrictions on accessing public members
private private access is the least permissive access level, private members are accessible only within the body of the class or the struct in which they are declared
internal internal types or members are accessible only within files in the same assembly
protected A protected member is accessible within its class and by derived class instances
protected internal visible to derived classes and those of the same assembly

 

OK, now lets have a look on access modifiers in IL

IL Access Modifier Description C# equivalent
Private The member is accessible only by other members in the same class or struct private
Family The member is accessible by derived types. protected
famandassem The member is accessible by derived types, but only if the derived type is defined in the same assembly. N/A
Assembly The member is accessible by any code in the same assembly internal
famorassem The member is accessible by derived types in any assembly and also by any types within same assembly protected internal
Public The member is accessible by any code in any assembly public

 

As you might have noticed there is no C# equivalent for family or assembly although IL has this keyword. there is not such a thing in VB.Net as well. Now lets have a closer look on a simple sample and generated IL code.

Assume we have two simple project in a solution. A Console Application and a Class Library which console application referenced that. In the Class Library we have a simple class called Super and in console application, beside Program class we have a class derived from Super class called Sub. Lets have a look on their codes.

 

Super class source code

using System;

namespace ClassLibrary
{
    public class Super
    {
        protected internal void Foo()
        {
            Console.WriteLine("Foo");
        }

        internal void Method()
        {

        }
    }
}

Other class in ClassLibrary Project

namespace ClassLibrary
{
    public class Other
    {
        public void Test()
        {
            var super = new Super();
            super.Foo();
        }

    }
}

Sub class in ConsoleApplication

using System;
using ClassLibrary;

namespace ConsoleApplication
{
    public class Sub : Super
    {
        public void Bar()
        {
            Foo();
            Console.WriteLine("Bar");
        }
    }
}

Program.cs class in ConsoleApplication

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var sub = new Sub();
            sub.Bar();
            Console.ReadLine();

        }
    }
}

Sub class simply calls Foo method which is defined as “protected internal” which in C# means family *or *assembly in IL. If you build and run application you’ll see that Sub class successfully accesses because although it is not in the same assembly but But sub is actually derived from Super class. the output will be

Foo 
Bar

Cool, now let mess around with the IL and see that would happen if we change that.

If you want to dump the IL of an assembly you can simply open a Visual Studio Command and then go to the folder your assembly exist and run ildasm with following parameters

ildasm ConsoleApplication.exe /out:ConsoleApplication.il

ildasm ClassLibrary.dll /out:ClassLibrary.il

Now, you can open ClassLibrary.il and have a look into generated code. Actually it is a bit long so I just copied part that I’m interested in which is Foo method

  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      &quot;Foo&quot;
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

You see that protected internal compiled to famorassem. What would happen if we change this to famandassem and assemble this IL again? Answer is CLR will prevent calling this method and will raise MethodAccessException exception when we call this from console application. But let put this into action and actually test this. So, change the famorassem to famandassem and save the file and use ilasm.exe from Visual Studio Command to assemble this code again. Before assembling this you can delete current ClassLibrary.Dll. To assemble use following command parameters:

ilasm ClassLibrary.il /out:ClassLibrary.dll /dll

If you get Operation completed successfully at the end new class library is generated. If you run ConsoleApplication.exe you’ll get following exception because of violating the access level defined in the IL

Unhandled Exception: System.MethodAccessException: Attempt by method 'ConsoleApp
lication.Sub.Bar()' to access method 'ClassLibrary.Super.Foo()' failed.
   at ConsoleApplication.Sub.Bar() in f:\Users\ara\Documents\Visual Studio 2013\
Projects\ConsoleApplication3\ConsoleApplication3\Sub.cs:line 10
   at ConsoleApplication.Program.Main() in f:\Users\ara\Documents\Visual Studio
2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 10

famandassem means that only derived class within same assembly will have access to that member. Just for the sake of testing lets Super to the ConsoleApplication and see if it works.

Open ClassLIbrary.il in a text editor. Copy following IL code which is Super class il code

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit ClassLibrary.Other
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          Test() cil managed
  {
    // Code size       15 (0xf)
    .maxstack  1
    .locals init ([0] class ClassLibrary.Super super)
    IL_0000:  nop
    IL_0001:  newobj     instance void ClassLibrary.Super::.ctor()
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  callvirt   instance void ClassLibrary.Super::Foo()
    IL_000d:  nop
    IL_000e:  ret
  } // end of method Other::Test

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Other::.ctor

} // end of class ClassLibrary.Other

.class public auto ansi beforefieldinit ClassLibrary.Super
       extends [mscorlib]System.Object
{
  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Foo"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

  .method assembly hidebysig instance void 
          Method() cil managed
  {
    // Code size       2 (0x2)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ret
  } // end of method Super::Method

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Super::.ctor

} // end of class ClassLibrary.Super


// =============================================================

Now open ConsoleApplication.il and paste this code at the end after end of Class ConsoleApplication.Sub.

We need to do one more thing and get rid off reference to ClassLibrary.il which we don't need anymore. So right in the beginning there is some code for that. Delete that piece of code and save the file.

.assembly extern ClassLibrary
{
  .ver 1:0:0:0
}

One more thing to do and it is replacing all [ClassLibrary] with empty string.

Delete console application and assemble the il to make new ConsoleApplication.exe using following command

ilasm ConsoleApplication.il /exe /out:ConsoleApplication.exe

Now we have new ConsoleApplication which doesn't have reference to ClassLibrary. Run ConsoleApplication.exe you see it runs successfully.

blog comments edit

Imagine you have multiple instances of SQL server on your server and one of them is using almost all of available memory and second one is facing memory shortage. What are possible Cause for this symptom. Does one of application have memory leak?

The answer is NO, When you install multiple instances of SQL server on a single server you have to consider memory allocation for each instances because windows does not balance memory across applications with the memory notification.

The first instance with a work load will  used huge portion of memory (Especially when you have actual data - not testing - on that instance).

Three approaches are available for Server Memory Option documented in the section "Sunning Multiple Instances of SQL server" and if you have selected third one which is "Do nothing", you might have same problem.

  • Do nothing (not recommended). The first instances presented with a workload will tend to allocate all of memory. Idle instances or instances started later may end up running with only a minimal amount of memory available. SQL Server makes no attempt to balance memory usage across instances. All instances will, however, respond to Windows Memory Notification signals to adjust the size of their buffer pools. As of Windows Server 2003 SP1, Windows does not balance memory across applications with the Memory Notification API. It merely provides global feedback as to the availability of memory on the system.

blog comments edit

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I'm going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate
    Note: Making a browser enabled application as full trust according to this method is not completely secured. This can be used for testing purposes in testing environments. Please select proper certificates and known trusted root certification authorities.
    Before starting I think its better to have same understanding of file extension that we are going to talk about.

*.cer file: *Apublic key which is given by Certificate Authority

*.pvk file: *This file is your private key and should keep it confidential

*.pfx file: *This is a Personal Information Exchange file and again you should keep it confidential because it contains

We have created a simple WPF Browser application and a simple windows application which is hosted inside the XBAP application. When we created WPF application Visual Studio automatically create a .pfx (Which is used for signing ClickOnce manifest).

To create your own certificate you need to follow these steps:

Step 1: Creating your key pairs (Public and Private)

open Visual Studio Command Prompt (2010) and then goto your application path and type following command

[sourcecode language="Text"]

makecert -n "CN=Your Company Name" -r -sv Key.pvk Key.cer

[/sourcecode]

A password dialog box will be displayed and you set your own password. This command creates two files one private key and one certificate.

Step2: Then you need to create PFX file which is used for signing ClickOnce manifest and contains both private and public key.

[sourcecode language="Text"]

pvk2pfx.exe -pvk Key.pvk -spc Key.cer -pfx KeyPFX.pfx -po [password]

[/sourcecode]

Put your own password as [password] and this command will create a PFX file

Step 3: Back to the solution explorer delete "SimpleBrowserApplication_TemporaryKey.pfx" and goto Application property page and select signing tab. Click on "Select from file" and select the PFX file you have just created.

*Step 4: *Just like before  publish it to you server.

*Step 5: *Give certificate to the client and register the certificate on the client machine. To do this double-clicking on .cer file. You will see following window. Click on Install Certificate button.

Follow installation wizard and click Next on the first window.

In this window select "Place all certificates in the following store"  and then select "Browse..." button.

**In this window select "Trusted Publishers" and then click Ok. Select "Next" previous windows and then select finish.

*Step 6: *Redo the step 5 but this time select "Trusted Root Certification Authorities" as the certificate store.

Now you have enabled your client to accept this XBAP application as full-trust application.

blog comments edit

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I'm going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate
    Imagine we have an existing windows form application or you are developing a windows form application. The question is how you can make your windows application browser enabled. The answer is Browser Enabled WPF application. But usually when we create a WPF application we have to use WPF elements inside Xaml. "WindowsFormsIntegration" will help you to host your windows form application inside your WPF.
    For rest of this post I consider you already have previous post sample, because I'm going to update the same project. Lets open the SimpleBrowserApplication and add a reference to "WindowsFormsIntegration". As the second step I want to add new project to our solution of type "Windows Form Application" and I call it "WinFormSample".
    *Note: *Make sure when you are creating windows form application you selected .Net 3.5 because we are going to reference this project inside WPF project and they should be compatible.
    That is how our solution looks like after adding windows form application and couple of simple controls on it. Next step we have to reference WinFormSample in SimpleBrowser application. Now our WPF application has got two more references which are "WindowsFormsIntegrations" and "WinFormSample". Now we have to change Page1.xaml and put the following StackPanel instead of previous <Grid>
    [sourcecode language="xml"] <StackPanel x:Name="stackPanel"> </StackPanel> [/sourcecode]

Actually this is a place holder for WindowsFormsHost that we are going to place in main form. For next step we need add System.Windows.Froms reference to WBP project. Then  we have to change page1.xaml code as follow.

[sourcecode language="csharp"] public partial class Page1 : Page { private readonly Form1 mainForm = new Form1(); WindowsFormsHost windowsFormsHost;

public Page1()
{
    InitializeComponent();
    AddWindowsForm();
}
private void AddWindowsForm()
{
    windowsFormsHost = new WindowsFormsHost();

    stackPanel.Children.Add(windowsFormsHost);

    // If you don't write this line you'll get &quot;The child control cannot be a top-level form&quot; exception
    mainForm.TopLevel = false;
    windowsFormsHost.Child = mainForm;
}

} [/sourcecode]

We created a WindowsFormHost and added this control into stackPanel Child list and set the child property of windowsFormsMost to mainForm which is already instantiated of Form1.

One of important thing is setting mainForm.TopLevel to false. Because if you don't do that you will get an exception and if you dive into innerexeptions you will find out that main reason is System.ArgumentException: The child control cannot be a top-level form.

If you run this application you'll see following browser window which hosts Form1.

The point is when you run this application from visual studio it runs in My Computer Zone so there is no problem for security. According Microsoft document "WPF Partial Trust Security" section "Partial Trust Programming" when you run WPF application which requires full trust and current zone is "My Computer" behavior is "Automatic full trust" and for getting full trust no action is required.

But if you publish this project and try to browse this application you will get Trust Not Granted error. Because application will request for full trust and it fails with "Trust Not Granted". In order to get full trust is signing XBAP with certificate.

In the next post we will see how to sign XBAP with your own certificate and make it work.

The source code of this application is also available you can download it here

blog comments edit

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I'm going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate Firstly run Visual Studio 2010 and select new project from file menu

To create simple WPF browser application you need to select "WPF Browser Application" template from project templates. Once project template is created open Page1.xaml Xaml code and change Grid into following code

[sourcecode language="XML"] <Grid> <Rectangle Fill="#33CC66" Width="2in" Height="1in" Canvas.Top="25" Canvas.Left="50" StrokeThickness="6px" Stroke="Orange" /> </Grid> [/sourcecode]

This Xaml code will create a simple rectangle with border and if you run this application, It will show following shape inside your browser.

Deploying a WPF application

There are multiple ways to do that. Simply you can publish your application using visual studio. Right-click on project and select publish menu. Publish wizard is displayed. Follow the steps until the end of publish steps.

You must follow Microsoft instruction for How to: Configure IIS 5.0 and IIS 6.0 to Deploy WPF Applications to configure your server and client requires Internet Explorer plus .Net Framework to run this application.

Basically internet application which runs inside the browsers should have restricted access to critical resources. It means WPF browser application -By default- should respect to these restrictions so that client can make sure there is no harm to execute this application. Browser Enabled application by default is marked as partially trusted and ClickOnce security setting is set to Internet Zone so that your application will be running on the client browser without any problem.

As you see "Enable ClickOnce security settings" and "This is a partial trust application" are ticked by default and and ClickOnce manifests is signed by a temporary key. Which means on one your application will be restricted to security permission which is fully described in this document. On the other hand your application will be executed on client browser without any other additional configuration.

Above picture shows that you can run This simple WPF Browser Enabled application in "Internet Zone".

The main reason of writing this post series for me is hosting windows form application inside XBAP application and running inside browser. In next post we will see how to host an existing windows form application within a WPF Browser application.

Sample project is also available you can download it here

blog comments edit

I was working on a project to write a wrapper on a COM component in WCF. The COM object needs impersonation in some levels to provide certain functionalities to impersonated user. Basically impersonation in .Net application doesn't propagate COM calls. I’ve seen following sentence in How To: Use Impersonation and Delegation in ASP.NET 2.0

The impersonation token does not propagate across threads if you use COM interop with components that have incompatible threading models, or if you use unmanaged techniques to create new threads

Actually I have a COM component and I want to use this component in my WCF Services. One of classes in COM object has got a property which returns current user. I wrote a console application to test impersonation and see if impersonation does propagate to COM object or not. I wrote a class for impersonation and  it has a method called “ImpersonateUser” that impersonates to passed username and password.  Following code returns different username for .net and COM object. It means it doesn’t propagate to COM object.

static void Main(string[] args)
{
    DoWork();
    Console.ReadLine();
}

private static void DoWork()
{
    ImpersonateClass impersonate = new ImpersonateClass();
    using (impersonate.ImpersonateUser("AnotherUser",
                    "Domain",
                    "passw0rd"))
    {
        COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
        Console.WriteLine(string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
            System.Security.Principal.WindowsIdentity.GetCurrent().Name));
    }
}
//Returns:COM:DOMAIN\CurrentUser .Net:DOMAIN\AnotherUser&lt;/pre&gt;

But I used CoInitializeSecurity to initialize security with impersonation and cloaking. CoInitializeSecurity should be called before any marshalling so I called CoInitializeSecurity as first function call.

[DllImport("ole32.dll")]
public static extern int CoInitializeSecurity(IntPtr pVoid, int
cAuthSvc, IntPtr asAuthSvc, IntPtr pReserved1, RpcAuthnLevel level,
RpcImpLevel impers, IntPtr pAuthList, int dwCapabilities, IntPtr
pReserved3);

static void Main(string[] args)
{
    int result = CoInitializeSecurity(IntPtr.Zero, -1,
    IntPtr.Zero, IntPtr.Zero,
    RpcAuthnLevel.Connect, RpcImpLevel.Impersonate,
    IntPtr.Zero, Convert.ToInt32(EoAuthnCap.DynamicCloaking), IntPtr.Zero);

    DoWork();
    Console.ReadLine();
}

private static void DoWork()
{
    ImpersonateClass impersonate = new ImpersonateClass();
    using (impersonate.ImpersonateUser("AnotherUser",
                    "domain",
                    "passw0rd"))
    {
        COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
        Console.WriteLine(string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
            System.Security.Principal.WindowsIdentity.GetCurrent().Name));
    }
}
//Returns:COM:DOMAIN\AnotherUser .Net:DOMAIN\AnotherUser&lt;/pre&gt;

Somebody suggested using built-in impersonation method for WCF so I changed my service to following code by setting [OperationBehavior(Impersonation = ImpersonationOption.Required)] and some changes in Web.Congif to make it work.

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string GetUserNames()
{
    return DoWork();
}

private string DoWork()
{
    string result;

    COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
    result = string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
        System.Security.Principal.WindowsIdentity.GetCurrent().Name);

    return result;
}

I passed user credentials from client for impersonation.

static void Main(string[] args)
{
    ServiceReference.ServiceImpersonateClient client = new ServiceReference.ServiceImpersonateClient();
    client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
    client.ClientCredentials.Windows.ClientCredential.Domain = "Domain";
    client.ClientCredentials.Windows.ClientCredential.UserName = "AnotherUser";
    client.ClientCredentials.Windows.ClientCredential.Password = "Passw0rd";

    string str = client.GetUserNames();
    Console.WriteLine(str);
    Console.ReadLine();
    client.Close();
}
// Returns COM:DOMAIN\CurrentUser .Net:DOMAIN\AnotherUser

But it returns different usernames which means impersonation of WCF does not propagate to COM object.

Ok I posted this issue in WCF Forum and I’ve got a simple response but it gave me a good clue. Allen Chen (The moderator) suggested me to use self-hosting for WCF instead of IIS hosting.

Self-hosted WCF was great idea!  Actually it works on self-hosted. But my WCF service should be unattended so that I created a managed service for WCF hosting. To make it work I’ve created three projects. One WCF service library which is used in managed service application. And the third one is a console application for testing. I’ve called CoInitializeSecurity on constructor of my service class as following

private ServiceHost serviceHost;
 public WCFServiceHost()
 {
  int result = CoInitializeSecurity(IntPtr.Zero, -1,
  IntPtr.Zero, IntPtr.Zero,
  RpcAuthnLevel.Connect, RpcImpLevel.Impersonate,
  IntPtr.Zero, Convert.ToInt32(EoAuthnCap.DynamicCloaking), IntPtr.Zero);
  //EventLog.WriteEntry(result.ToString());
  InitializeComponent();
 }

 protected override void OnStart(string[] args)
 {
  if (serviceHost != null)
  {
  serviceHost.Close();
  }

  // Create a ServiceHost for the CalculatorService type and
  // provide the base address.
  serviceHost = new ServiceHost(typeof(ServiceImpersonate));

  // Open the ServiceHostBase to create listeners and start
  // listening for messages.

  serviceHost.Open();

 }

 protected override void OnStop()
 {
  if (serviceHost != null)
  {
  serviceHost.Close();
  serviceHost = null;
  }
 }

]It doesn’t work with built in WCF impersonation. But I used my impersonation class inside the service class to impersonate to desired user and it works.

public string GetUserNames()
 {
  ImpersonateClass impersonate = new ImpersonateClass();

  using (impersonate.ImpersonateUser("AnotherUser",
         "Domain",
          "passw0rd"))
  {
   return DoWork();
  }
 }

 private string DoWork()
 {
  string result;

   COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
   result = string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
       System.Security.Principal.WindowsIdentity.GetCurrent().Name);
  return result;
 }

In the console application I simply called my service like following code:

ServiceReference.ServiceImpersonateClient client = new ServiceReference.ServiceImpersonateClient();
  string str = client.GetUserNames();
  Console.WriteLine(str);
  client.Close();
  Console.ReadLine();
// Returns COM:DOMAIN\ AnotherUser .Net:DOMAIN\AnotherUser

When you host WCF in IIS the process is spawned by IIS and before your code running code managed by IIS will be run in the process, which is almost out of your control. CoInitializeSecurity thus might be called before you calling it.

blog comments edit

I didn't know about this sophisticated application so called “Windows Live Writer”. Actually quiet frequently I was looking for an HTML editor to write my blog post and then update my blog. Because HTML edit which comes with BlogEngine.Net is not easy to use – and its the same problem with all web based HTML editor-. To be honest windows live writer is something more than what I expected.

I was reading an article about AtomPub Using WCF Data, I came across Windows Live Writer which surprisingly supports BlogEngine.Net (Its better to say that BlogEnine.Net supports AtomPub which is protocol for publishing content).

Windows Live Writer easily installed on my machine. After installation completed you will be asked about your blog information and if your blog supports AtomPub then you can continue to enter login information of your blog. With a quick search I found in WiKithat Windows Live Writer supports BlogEngine.Net so I selected “other blog service” option in this form. What blog service do you use

In next step you’ll be asked about your blog address and username and password.

Add a blog account

For me as a developer it was surprising that Windows Live Writer supports plug-ins. first thing I looked for was SyntaxHighlighter. Yes! . I’s already been developed. there is a project in CodePlex named "SyntaxHighlighter for Windows Live Writer” you can easily download and set it up.

blog comments edit

Couple of days ago I came across a fantastic challenging application in Facebook which is called “click test”. This application measures your click per second and you have to click as much as you can in 10 seconds. For sure in my 130 friend there are many who can click more than me, but I had to do my bests especially a friend of mine (Kambiz) who is not only good at typing and clicking but also good programming. What should I do! should I left the battle or keep challenging? Of course I have to stay in this battle. I tried to score a good click per second but honestly the best I did was about 90 clicks per second which is lower than lots of my friends.

What is “click test” application? This is a simple but

ton that you have to click on with a countdown timer which runs inside browser. Ok, the first thing pops in mind is writing a simple application to simulate clicking on this button. Ohhh, you have to find browser windows handle then use SendMessage with appropriate (wParam, lParam) parameters to simulate clicking on specific area of window. That sounds great. But the fact is I’m more JavaScript and HTML guy than API guy. So let Keep It Simple Stupid (KISS).

If you view source of “test” application page you’ll face huge amount of complex source code which is really complicated. At the beginning I wanted to find the function which is responsible for counting down t from 10 to zero and then increase it but the code is really messy and it takes time to find the function you want. Should I inspect all HTML and Jscript source code? The answer is No

Recently browsers are delivered with quite sophisticated feature for developers. For example Internet Explorer 8 has got famous feature which is called “Developer Tools” and you can activate it by pressing F12. Having pressed F12, nice window will be displayed to help you debug your HTML and JavaScript.

Ok to find start button you can press Ctrl+B or select Find -> Select element by click.

Then move your mouse to element that you want inside browse.

As soon as you move your mouse inside browse you’ll notice that browser mark current element by bordering it. So find start button and then click on it. Gotcha! Developer tools automatically scrolls to input tag related to selected element. You can also scroll horizontally to find “onmouseup” which is actually responsible for counting your clicks. Ok, double click inside onmouseup and then press Ctrl+A to select all body of onmouseup.

So I can copy this element into clipboard and then paste in notepad. You may also have somthing similar to following:

[sourcecode language="javascript"] fbjssandbox.instances.a130168443678744.bootstrap(); return fbjsdom.eventHandler.call([fbjsdom.getinstance(this,130168443678744),function(a130168443678744event) {a130168443678744game.update($FBJS.ref(this).getForm())},130168443678744],new fbjs_event(event)); [/sourcecode]

Actually this is an event handler and this code runs every time you click on your mouse button. But it’s rather complicated. It calls a function at first and then calls another function. So If I want to change this code I have to find these functions and then change body of them.

But what if I don’t change any code and just make this event handler to run multiple times per click. That is sound good idea. So let copy and paste event handler for couple of times. But I should notice that second function call has “return” and I have to remove it for my new copies, and just leave it for last one.

[sourcecode language="csharp"] fbjssandbox.instances.a130168443678744.bootstrap(); fbjsdom.eventHandler.call([fbjsdom.getinstance(this,130168443678744),function(a130168443678744event) {a130168443678744game.update($FBJS.ref(this).getForm())},130168443678744],new fbjsevent(event)); fbjssandbox.instances.a130168443678744.bootstrap(); fbjsdom.eventHandler.call([fbjsdom.getinstance(this,130168443678744),function(a130168443678744event) {a130168443678744game.update($FBJS.ref(this).getForm())},130168443678744],new fbjsevent(event)); fbjssandbox.instances.a130168443678744.bootstrap(); return fbjsdom.eventHandler.call([fbjsdom.getinstance(this,130168443678744), function(a130168443678744event) {a130168443678744game.update($FBJS.ref(this).getForm())},130168443678744],new fbjs_event(event)); [/sourcecode]

As you see I copied all code for three times and left return just for last call. It means my clicks will be tripled and I can register 150 clicks just for 50. It’s good. So let’s copy this code back to onmouseup element it is ready for testing.

Enjoy it!

blog comments edit

As first day continued Scott and James tried to demonstrate Microsoft ASP.net 4.0 and MVC 2. Same question about ASP.Net was asked and was answered. Fellows was worried about replacement of ASP.Net with MVC 2 and as it was answered and like before Scott and James defined that ASP.Net is not going to be replaced by MVC. It is just a new approach of implementing web applications and depending on website structure and content websites could either be implemented by ASP.Net 4.0 or MVC 2.

Couple of new project templates has been added to Visual Studio 2010 and in web. One of them is “ASP.NET Web Application”. When a new ASP.NET Web Application is created visual studio automatically creates folder and files which are needed for a simple application. This type of project unlike

previous web application is not an empty project and contains necessary files and folders to create a simpl

e application.

This template includes Microsoft ASP.NET Membership Provider and if SQL Server Express is installed on developer machine this type of project is automatically configured for ASP.NET Membership provider which connects to SQL Express. This type of Web application is similar to ASP.Net application because the theme and style looks like default theme of ASP.Net MVC Application. Good news is Micros

oft has added jQuery to ASP.Net web application and ASP.Net MVC 2 Web application templates.

I think one of best features of MVC is its testability and on top of that you can change test framework of testing if you want. I’ve find some good articles and posts about adding customized test framework for testing MVC 2 projects. How to: Add a Custom MVC Test Framework in Visual Studio and a post about NUnit Template for ASP.NET MVC 2 .

Presenters created a new MVC2 Web application and for beginning they created a project without database just to keep it simple. View, Mode was discussed in this session and they talked about partial views and templates. I wanted to describe creating templates in MVC 2 but I found a good sample in Microsoft that helps to understand how to create templates in MVC. Following is link to EditorFor extension method. On the bottom of page you can find a link to Template Helper Sample.

For describing model part of MVC a virtual project was defined named Plan My Night. It was a simple application to plan night. They described model and controller by creating a simple database and entity model to implement Plan My Night. During implementation o f Plan My Night they described partial views editor templates. For editor templates there is a good sample to create an editor template for datetime inputs called MVC2 Editor Template with date and time.

They combined sample with newly introduced feature called jQuery Templates Data Linking. You can find a complete sample in ScottGu’s Blog. Another cool feature of visual studio which is really useful is Dynamic JavaScript Intellisense in VS 2010. Not only client items in win form can be identified by intellisense of VS 2010 but also items which are being created by developer during development can be identified in VS 2010 like following picture. 1000 items with TestDev prefix is added to window object. Exactly after while command you all TestDiv0 to TestDiv1000 is added to suggestion list.

During the presentation Scott wanted to use a trick to cause a crash for visual studio 2010 (It was on purpose). He changed “while” condition to an infinite while condition and he expected VS to crash when suggestion list was being opened, but visual studio is clever enough and calculates list until certain amount of millisecond and if it’s going to be time consuming visual studio just ignores rest of computing and jump over next statement. There is a good post in ScottGu’s Blog about JS Intellisense and its improvements.

Other feature which was discussed in webcamps was about Web.config transformation and packaging and deployment of web application SQL server. There is a good clip about Web.Config transformation in channel9 about Web Deployment and Web.Config.

 Rest of presentation was about IIS extensions which are available on http://www.iis.net/download and can be downloaded and installed by Web Platform Installer. Among those extensions SEO Toolkit was fantastic which was shown by Scott.

At the end of presentation fellows were asked to pitch their ideas for next day. Following are some of projects and people voted for them

.

My Noisy Neighbour (I voted this project)

RaceDay Commander

MongoDB Management Studio

Due Date – lightweight task-tracking for uni students

Address Book Lookup

I voted for first project “My Noisy Neighbour” and in second day I had to join to a group of people to develop this web application based on what we’d learned in first day. In the next post I’m going to describe what was our project was and what had happened.

blog comments edit

WEBCAMP was a 2 days event that provides a chance to learn and build projects based on Microsoft Web Platform. WEBCAMPS is held in different cities around the word and I had chance to participate in Sydney WEBCAMP event in 28 and 29 of May 2010. Interesting point is performers of this event in Sydney were Scott Hanselman and James Senior who I really wanted

to be in one of their presentations specially Scott that you’ll never be tired in a conference in case Scott is one of presenters. http://www.asp.net/dynamicdata

These project types are useful for creating administration pages from scratch. All you need to do is create your database and relations. Create a project type either Entity of Linq to SQL and select entities you want. Suddenly you find that All CRUD (Create/Remove/Update/Delete) of your entities is created in user friendly URL by using “DynamicDataRoute” class.

Following is steps to create an administration web site for Northwind in less than 2 minutes:

  1. Create a new web project type Asp.net Dynamic Data Entities Web application.
  2. Copy Nothwind Database files (MDF and LDF) in APP_DATA folder.
  3. Right click on project and new data item type ADO.Net Entity Data Model.
  4. In wizard form select “Generate from database” item.
  5. And then select NORTWIND as data connection.
  6. Select tables you want to be added to Entity Data Mod and then click finish.
  7. Open Global.asax and then remark line starting with DefaultModel change this line as follow.
DefaultModel.RegisterContext(typeof(NorthwindEntities), new ContextConfiguration() { ScaffoldAllTables = true });

8.Press F5 and run the application.

Simple, Easy and beautiful, It’s a good solution for quick data administration generation. And the good thing is all templates are editable and you can change them.

blog comments edit

 

 

After 22 months our (me and my wife) Australian permanent visa is granted. These 22 months of my life was so hectic. This is a big break in my life and I'm looking forward for shiny future. My visa was issued on 18 of January and new level of my migration is started.

There are tons of things to do in order to settle in:

 

1.       Sell our stuff including my car

2.       Rent my apartment

3.       Open a bank account in Australia

4.       Transfer money to Australia

5.       Send our stuff to Australia by AIR shipment

6.       Move into temporary accommodation for one or two weeks in Sydney

7.       Receive the AIR shipment.

8.       Move into Mid-level temporary accommodation for couple of mount

9.       Get a mobile phone including device (Hopefully buy an HTC HD2)

 

And last by not least

10.   Finding a new job in Sydney

 

I think the last one is the most important thing to focus on. I have to improve my English abilities, Prepare a professional Resume and covering letter for each vacancy, which I apply, improving my technical abilities in various aspects.

 

 

 

blog comments edit

Two days ago a question was asked in StackOverflow.com and I found this question so good to prepare a post. I want to explain this question:

Petr asked: I do not understand why there is Control.padding.all which is int and according to hint there is set as well as get but I cannot set it (Control.Padding.All=5)? I would be grateful for explanation.

For example when you want to set

textBox1.Padding.All = 5;

You will get this compiling error: Cannot modify the return value of 'System.Windows.Forms.TextBoxBase.Padding' because it is not a variable

Error Value Property

Following example is an implementation of this error:

public class ARAControl 
{ 
    public ARAPadding Padding { get; set; } 
}
public struct ARAPadding 
{ 
    public int All { get; set; } 
}

If you use this you'll get mentioned error:

ARAControl control = new ARAControl();
control.Padding.All = 10;

And why this compiling error happens. It hapens because structure is a value type. By setting this property you first call get Method. "Property Get" will return a copy of ARAPadding, so it is a value type and C# will detect out mistake and prevent compiling.

blog comments edit

I was about to write a simple application deal with screen size in WPF. Previously in windows form applications we could get WorkingArea parameters from System.Windows.Forms.WorkingArea but in WPF application typically we don’t have this assembly (however this assembly could be added to project). In WPF applications screen size could be obtained from System.Windows.SystemParameters. Following code is an example of setting a form right-bottom aligned in screen.

Windows form application:

this.Top = Screen.PrimaryScreen.WorkingArea.Height - this.Height;
this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width; [/sourcecode]

WPF application:

this.Top = System.Windows.SystemParameters.WorkArea.Height - this.Height;
this.Left = System.Windows.SystemParameters.WorkArea.Width - this.Width; [/sourcecode]

P.S. 2009/11/30: A friend of mine just asked "Is it possible to get all screen size (in multiple screen) in WPF without refering to System.Windows.Forms". As far as I see, It seems it is not possible to get other screens than current workarea unless you Use System.Windows.Forms.

blog comments edit

Recently I founded that LINQ-To-SQL Uses magic ROWNUMBER() function. ROWNUMBER() function is a magic function which was added in SQL Server 2005. Microsoft put this function in version 2005 so that developers will not take it for granted and appreciate it. ROW_NUMBER " returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition".

ROW_NUMBER() Syntax:

ROW_NUMBER ( )     OVER ( [ ] <orderbyclause> )

For example following query add a number field which is partitioned by ProductID (reset on new ProductID) in descending order on UnitPrice * OrderQty.

SELECT ROW_NUMBER()
OVER (Partition by ProductID ORDER BY UnitPrice * OrderQty DESC) AS ROWNUM,*
FROM Sales.SalesOrderDetail

ROW_NUMBER() helps programmer to select specified amount of rows within a select command. This feature commonly used in paging. Following example returns @P1th to @P2th rows which list is ordered by ProductId.

SELECT * FROM
SELECT *, ROW_NUMBER() OVER (ORDER BY ProductID) AS ROWNUMBER
FROM Sales.SalesOrderDetail) AS ALLDATA
WHERE ALLDATA.ROWNUMBER  BETWEEN @P1 and @P2

Skip() and Take()LINQ-To-SQL functions generate ROW_NUMBER syntax in query result. I created a LINQ-TO-SQL dbml file on AdventureWorks. I selected SalesOrderDetail as Data Class.

AdventureWorksDataContext advDC = new AdventureWorksDataContext();

IQueryable orderDetails = advDC.SalesOrderDetails.OrderBy(f => f.SalesOrderDetailID)
                                                 .Skip(20).Take(10);

foreach (SalesOrderDetail orderDetail in orderDetails)
    Console.WriteLine(orderDetail.ProductID);
Console.ReadLine();

Above code generates following SQL for orderDetails:

SELECT [t1].[SalesOrderID], [t1].[SalesOrderDetailID], [t1].[CarrierTrackingNumber], [t1].[OrderQty], 
    [t1].[ProductID], [t1].[SpecialOfferID], [t1].[UnitPrice], [t1].[UnitPriceDiscount], 
    [t1].[LineTotal], [t1].[rowguid], [t1].[ModifiedDate]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [t0].[SalesOrderDetailID]) AS [ROW_NUMBER], 
            [t0].[SalesOrderID], [t0].[SalesOrderDetailID], [t0].[CarrierTrackingNumber], 
            [t0].[OrderQty], [t0].[ProductID], [t0].[SpecialOfferID], [t0].[UnitPrice], 
            [t0].[UnitPriceDiscount], [t0].[LineTotal], [t0].[rowguid], [t0].[ModifiedDate]
    FROM [Sales].[SalesOrderDetail] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
}

As you see, Skip and Take functions interpreted as ROW_NUMBER() function.

blog comments edit

Finally, I've decided to convert my weblog engine from Graffiti CMS to BlogEngine. Moving to BlogEngine doesn't mean weakness of Graffiti blogging engine or indicating any problem. But after surveying BlogEngine and comparing to current version of Graffity CMS I've found lots of features more sophisticated than Graffiti and in my opinion blogEngine is handier. Although you can full features here but in my opinion following features are cool and convincing to migrate:

  • Easy installation
  • Cool widgets
  • Advanced comment system (Supporting Nested reply)
  • Cool themes (more themes are available on web)
  • Supporting ping service
  • Static pages

blog comments edit

I downloaded code contracts from here. After installing code contract, I tried to create my first project with code contracts. I created new console project name CodeContractTest . I added reference to Microsoft.Contracts library which is appeared in .Net references after installation.

I wrote following code this is clearly compiled without any warning.

[sourcecode language="csharp"] using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; using System.Diagnostics;

namespace CodeContractTest { class Program { static void Main(string[] args) { Swap(new string[] { "Code", "Contract" }, 1, 4); } static void Swap(string[] arr, int item1, int item2) { string temp; temp = arr[item1]; arr[item1] = arr[item2]; arr[item2] = temp; }

}

}[/sourcecode]

 

However, after running this application we will encounter with IndexOutOfRangeException. This is occurred because illegal parameter in Swap method call.

Let take a look at new feature added to Visual Studio 2008. I open properties window of project. New tab is added named "Code Contracts". I checked "Perform Static Contract Checking" and "Implicit Array Bound Obligations". If I rebuild project new warnings and message will be appeared in Error window.

![](http://gkasoq.bay.livefilestore.com/y1pwEGUN0tRu6dxokdijnyldZr4WfWrx-nQi7pHU2mrIHyhTcbGo10ji8ayYdHYz-xNHOz73AGZuV8rXZPV428u5n_NWXjoc6Ht/SettingCodeContractOptions.png?psid=1)

Four warnings are about Array access and four suggestion message plus one summary message.

![](http://public.bay.livefilestore.com/y1pBs0IHM3468q69kDP_2J5RP29NNxZFXqQUBAVguOaynepL0KF5Jm2EKF2tqa8iZTOHcK9n5UKSWcFRux2i12O6w/ErrorAndWarnings.png?psid=1)

In order to improve code and get rid of warnings I should add preconditions in swap method. I added four line of precondition which assure item1 , item2 is in array boundary. I used Contract class and Requires static method which is used for preconditions it has two overloads first overload has a bool parameter. We can use this method to explicitly define the conditions of input parameters.

[sourcecode language="csharp"]
static void Swap(string[] arr, int item1, int item2)
{
    Contract.Requires(item1 < arr.Length);
    Contract.Requires(item1 >= 0);
    Contract.Requires(item2 < arr.Length);
    Contract.Requires(item2 >= 0);
    string temp;
    temp = arr[item1];
    arr[item1] = arr[item2];
    arr[item2] = temp;
}[/sourcecode]
After rebuilding project new warning is appeared. It shows that one of contract precondition rules is broken. ![](http://public.bay.livefilestore.com/y1poY9KdXrsIFuNilWTT3b8M9YpWysCGDo9xJh4uHlucvRPmvRt5GHbMZ0Tz68HCH1uszbFJtOq5_crrPxI6533qw/WarningAfterContracts.png?psid=1) If I change the swap with proper input parameters after rebuilding project warning messages will be disappeared.
[sourcecode language="csharp"]
Swap(new string[] { "Code", "Contract" }, 0, 1);[/sourcecode]
If I check "Implicit Non-Null Obligation" on code contracts tab of property window building application will be face with new warning "contracts: Possible use of a null array 'arr'" ![](http://public.bay.livefilestore.com/y1pw_b-tHzJKUiOjB0_Zqb3W59YOBjZGLmL9DSCXsYF-oEccgyBGQfrMVN2_nf_1tYszJM-WW6l_M0yfsr5x1-w5A/ImplicitNon-Null.png?psid=1) Swap method should be called with non-null array parameter. This is another contract that should be added to preconditions. So I changed Swap method as follow.
[sourcecode language="csharp"]
static void Swap(string[] arr, int item1, int item2)
 {
     Contract.Requires(arr != null);
     Contract.Requires(item1 < arr.Length);
     Contract.Requires(item1 >= 0);
     Contract.Requires(item2 < arr.Length);
     Contract.Requires(item2 >= 0);
     string temp;
     temp = arr[item1];
     arr[item1] = arr[item2];
     arr[item2] = temp;
 }[/sourcecode]

In this case developer of Swap method define contract for input parameters and there is no need to swap caller know all swap code in order to prevent bad parameter calling.

You can download code from here

kick it on DotNetKicks.com

blog comments edit

A few days ago I saw a clip of PDC 2008 about MVC .Net which is great concept. It was performed by Phil Haack. In this video Phil shows a trick of Visual studio which is very useful.

Most of the time during application development you want use a class which its name space has not been included. Guess what should you do? Oh yes ! You should type name space completely or leave current line and go to top of class adding appropriate "using" statement get back to your line of code. Surprisingly there is a trick in visual studio 2008 (I tested in visual studio 2008). If reference of class included in project you can Type class name completely at the same time a tooltip bar will be appeared under your class name. At the same time press Ctrl+. (dot). A menu will be appeared which offers you two options. First option will add using statement at the top of code class file. Second option will insert full class name including name space.

kick it on DotNetKicks.com