Far Away Developer

Sebastien Lachance

Archive for the '.NET' Category

.NET

System.Data.Linq.ChangeConflictException: Row not found or changed

Posted by Sebastien Lachance on July 8, 2008

Hummm, gotta love this unclear exception message. I just can’t believe there is not a condition somewhere to return whether the row was not found or just changed. It would be a lot easier to diagnose problems.

Anyway, after reading several article on concurrency in Linq to SQL and making sure the date was sent correctly (like advised everywhere). I had not pin-pointed the problem until I remembered that I changed a NOT NULL column to a NULL column. Et voila. Problem solved!

Posted in .NET, Linq | No Comments »

WCF : Problems and Solutions

Posted by Sebastien Lachance on May 22, 2008

This is a list of various errors you may encounter when working with WCF (Windows Communication Foundation).

Could not find a base address that matches scheme http for the endpoint with binding BasicHttpBinding. Registered base address schemes are [].

Add to your service :

<host>
     <baseAddresses>
          <add baseAddress="http://localhost/MyService"/>
     </baseAddresses>
</host>

 

No set method for property ‘Message’ in type ‘MyProject.MyType.

A DataContract can’t have a property with no set method (http://msdn.microsoft.com/en-us/library/ms733127.aspx). However, you can use a private set accessor if allowing modification of the property is prohibited. :

[DataMember]
public object Message
{
    get { return _message; }
    private set { _message = value; }
}

 

HTTP could not register URL http://+:80/MyService/ because TCP port 80 is being used by another application.

Happen if IIS is running (very likely!). Change the port to another one. Example :

<host>
     <baseAddresses>
         <add baseAddress="http://localhost:8080/MyService"/>
     </baseAddresses>
</host>

 

The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

You have an error, but you don’t get all the details. To get them :

<behaviors>
    <serviceBehaviors>
       <behavior name="BasicBehaviorConfiguration">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
       </behavior>
    </serviceBehaviors>
</behaviors>

 

Technorati Tags: ,

Posted in .NET, WCF | No Comments »

Type Sharing in Visual Studio 2008

Posted by Sebastien Lachance on May 22, 2008

On a previous post called Reality of type sharing in WCF. I talked about a way to use existing types for a WCF service instead of the generated proxies. Previously, we were unable to do that in Visual Studio 2005, but it’s doable Visual Studio 2008.

Start by adding the library you would use for type sharing on the project you will add a service reference.

When you add a service reference, click on the Advanced… button.

addservicereference

 

Then, make sure the Reuse types in referenced assemblies checkbox is checked.

reusestypes

You can fine tune further, if you do not want to use some assemblies for type sharing.

And you are done!

Technorati Tags: ,

Posted in .NET, Visual Studio, WCF | No Comments »

Visual Studio 2008 - WCF Templates

Posted by Sebastien Lachance on May 21, 2008

When you want to create a new WCF project, you are presented with 4 different templates to use :

  • Sequential Workflow Service Library
  • Syndication Service Library
  • State Machine Workflow Service Library
  • WCF Service Library

Each one has it’s own particularities. It’s important to know which one to choose but you should know that the template only generate things you need to get started. You can always start from an empty WCF Service Library and build on top of it. Anyway, here is an explanation for each one.

 

Sequential Workflow Service Library

You basically create a sequential workflow project that made operations available by WCF. I have no experience with Workflow Foundation so I will not go further into details.

 

Syndication Service Library

This template is great. It present you a way to expose an RSS or Atom feed via a WCF Service contract. This is built-in stuff already present in the framework.

To expose a feed, you need an operation that return a  SyndicationFeedFormatter (in the System.ServiceModel.Syndication namespace). Then create a SyndicationFeed and add SyndicationItem to it. Finally, create a Atom10FeedFormatter or Rss20FeedFormatter and return it.

SyndicationFeed feed = new SyndicationFeed("Feed Title", "A WCF Syndication Feed", null);
List<SyndicationItem> items = new List<SyndicationItem>();

// Create a new Syndication Item.
SyndicationItem item = new SyndicationItem("An item", "Item content", null);
items.Add(item);
feed.Items = items;

// Return ATOM or RSS based on query string
// rss -> http://localhost:8731/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
// atom -> http://localhost:8731/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/?format=atom
string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
SyndicationFeedFormatter formatter = null;
if (query == "atom")
{
   formatter = new Atom10FeedFormatter(feed);
}
else
{
   formatter = new Rss20FeedFormatter(feed);
}

return formatter;

 

State Machine Workflow Service Library

Another template that expose a Windows Workflow as a Service. This time the type of Workflow is a State Machine. A state machine workflow contrary to a sequential workflow is driven by external events. Transition between states are based on certain events until it reach the final state.

 

WCF Service Library

The most basic project to create a WCF service. You can use it to do everything you want with the most control.

 

Technorati Tags:

Posted in .NET, Programming, WCF | No Comments »

Ohhh, that’s why I should make a TestRepository…

Posted by Sebastien Lachance on May 14, 2008

Listening to the last screencast of Rob Conery (MVC Storefront) made me realize something that I haven’t really understood before.

Suppose you have the interface of a repository, let’s say IEntryRepository. Then you have the actual SqlEntryRepository and TestEntryRepository. When I am doing TDD, I am testing the TestEntryRepository. But it will not be used in production. Why bothering with testing it then?

Because TDD is a design process. Even if I am testing my code, I am also designing it. The SqlEntryRepository will benefits from the actual design of the repository we use for testing.

 

Technorati Tags: ,,

Posted in ASP.NET MVC, Agile, Design, Learning, Tests | 2 Comments »

New code drop to the ASP.NET project on Codeplex

Posted by Sebastien Lachance on May 13, 2008

  • 05/12 Source code release of the ASP.NET AJAX Script Profiler helper control: To support the ASP.NET AJAX script combining feature which shipped in the .NET Framework 3.5 SP1 Beta release, we’ve added the ASP.NET AJAX Script Profiler helper control source and binaries to this project. This control helps you to identify the scriptreferences used in your ASP.NET AJAX page to use with ASP.NET AJAX script combining. You can find this release here: ScriptReferenceProfiler Source and Binary Release. In addition this control is used in a Screencast for ASP.NET AJAX script combining on the ASP.NET site.
  • 05/12 Release of the ADO Data Service AJAX Client : The ADO Data Service AJAX Client Library enables you to consume an ADO.NET Data Service from client script in an ASP.NET AJAX Web page.

Read more here.

I am really wondering how I can keep up with all these new things to try. Well, I guess we will really need a pill to stop sleeping one day.

Posted in .NET, ASP.NET | 1 Comment »

My solution node does not appear in Visual Studio 2005 or Visual Studio 2008

Posted by Sebastien Lachance on May 13, 2008

A reader asked me how we can display the solution node in Visual Studio when you have only one project. This feature is turned off by default. What you need to do is to go in your Tools/Options menu and click on Projects and Solutions. Then you need to check the Always Show Solution checkbox.

AlwaysShowSolution

Feel free to ask me any questions.

Posted in .NET, Visual Studio | No Comments »

Mocking the HttpRequest in ASP.NET MVC (April build)

Posted by Sebastien Lachance on May 12, 2008

Like promised, on a previous post, I will show you how to mock HttpRequest. I will use Rhino Mock but you can use the one you want (moq, typemock, etc).

On you controller base class, a property called Request is exposed. Behind the scene you are accessing an HttpContextBase instance (this class is contained in the System.Web.Abstractions library), which is providing you the HttpRequest you want to mock.

So, let’s start by creating a mock of these two object.

var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();

 

The mockedHttpRequest will be provided by the mockedHttpContext. So we will setup the mocked HttpContextBase.Request property to return the mocked HttpRequestBase.

SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);

 

But, what would we do with a mocked HttpRequestBase? When you need to test an action on a controller that will retrieve values for the Request.Form property you could create a NameValueCollection and tell the Form property of the HttpRequestBase instance to return it.

NameValueCollection formParameters = new NameValueCollection();
formParameters.Add("txtUsername", "username");
formParameters.Add("txtPassword", "password1");

SetupResult.For(mockedHttpRequest.Form).Return(formParameters);

 

I really like playing with the ASP.NET MVC framework!!!

Posted in .NET, ASP.NET MVC, Learning, Tests | No Comments »

Mocking the HttpContext in ASP.NET MVC

Posted by Sebastien Lachance on May 8, 2008

I just got a hard time figuring how I could be mocking the HttpContext so that I would be able to mock HttpRequest. But once you understand the principle, it is fairly easy.

First thing we need to know is that the HttpContext is held inside a ControllerContext object. Once we have instantiated one, we can then put it inside our controller.

controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
 
Where mockedHttpContext is your mocked HttpContextBase object.
 
Inside the HttpContextBase object reside a lot of useful stuff that can replace with our mocks. By example, the HttpRequest, HttpServer, HttpApplication, etc, are all contained inside. So, getting familiar with this basic knowledge is a must to do testing usefully.
 
Next post : Mocking HttpRequest.Form to return what we want.

Posted in .NET, ASP.NET MVC, Learning, Tests | 1 Comment »

Testing controllers in ASP.NET MVC aka ActionResult

Posted by Sebastien Lachance on May 6, 2008

I haven’t really done any testing in ASP.NET MVC until now. I started the development of a more serious application and decided to do it TDD. My first test was to make sure the Index action render the Index view. So as an informed developer, I started reading some blog posts to discover that in order to test a controller you need to mock a lot of things. I followed the screencast of Scott Hanselman and implemented his MvcMockHelper. It didn’t worked. The ViewContext on the view engine remained null, resulting in an NullReferenceException. I downloaded the source of the last build to see for myself what was wrong. Surely I don’t understand, because nowhere in the source they are setting the ViewContext on the ViewEngine. They just fill a RenderViewResult object and return it back.

This is how I figured out how we can now test controllers. With the new Interim build of the 04/16, we don’t have to mock the HttpContext, HttpRequest and so on anymore. No need to do a fake view engine and no more mocking needed to test the RenderView method.

[Test]
public void Index_Should_Set_The_Index_View()
{
    EntryController controller = new EntryController();
    var result = (RenderViewResult)controller.Index();

    Assert.That(result.ViewName, Is.EqualTo("Index"));
}

So if you have any other operations (RedirectToAction and Redirect for example), it will return an object of type ActionResult that you can cast to the appropriate inheritor (RenderViewResult, ActionRedirectResult, HttpRedirectResult) to get a lot of information that you would have to retrieve manually with a mock.

I really like the simplicity of it and can’t wait to see more improvement. This is an immense opportunity to learn a great deal of different things.

Posted in .NET, ASP.NET MVC, Learning | 1 Comment »

Quick Start with ASP.NET MVC 0406 MVC Interim Source Code Release

Posted by Sebastien Lachance on May 6, 2008

This is intended to be a quick start for anyone who want to start playing with the latest version of ASP.NET MVC without going through the origin and goals of the MVC pattern. I will use the ASP.NET 0416 MVC Interim Source Code Release for this. Keep in mind, that this will probably all change in a near future.

First step, download and build the source. You will need to have the Moq library (more about this mocking framework in a future post).

Second, download and install the Visual Studio MVC Templates (execute the vsi file).

Third, start an ASP.NET MVC project.

I have two useful resources to share with you. I believe they will give you a head start.

You have the Scott Hanselman’s screencast series on the ASP.NET web site. And you have the MVC Storefront series from Rob Conery.

Posted in .NET, ASP.NET MVC, Agile, Learning | No Comments »

var keyword (or Implicitly Typed Local Variables)

Posted by Sebastien Lachance on April 17, 2008

If you are like me and installed the nightly build of Resharper 4, you might have seen the recommendation it made to use the keyword “var” almost everywhere. But why?

Here is my answer :

First of all, you must know that the keyword var is not like “Variant”. It is not late-bound or loosely typed. The compiler will be able to infer the type from the right side of the expression. In many case, it’s optional, but sometime you don’t have a choice. It’s the case with Anonymous Types :

var customer = new {ID = 1, Name = "Sebastien", CreditCardNumber = "You can dream!"};
 
It is also often seen with LINQ.
 
Should you use it everywhere you can? Well, it’s a matter of preferences. Mine is to use it only when necessary. If the code is harder to understand when using var, then declare the variable explicitly.
 
Technorati Tags: ,,

Posted in .NET | No Comments »

Exploring Anonymous Methods

Posted by Sebastien Lachance on April 16, 2008

My desire to explore Delegates and Anonymous Methods came from my next exploration, which will be the the Lambda feature. So, I will probably do an article on it in a near future.

So, what exactly is an anonymous method? It’s a C# 2.0 feature. Whenever you encounter the need to pass something as a delegate parameter, you can use an anonymous method.

Example :

This class has a method that expect a delegate that has no parameter and no return value.

public class Action
{
    public delegate void MyActionDelegate();

    public void Execute(MyActionDelegate myActionDelegate)
    {
        myActionDelegate.Invoke();
    }
}

Previously, you would have declared a method that has no parameter and no return value and passed it to the Execute method. Like this :

public static void DoSomething()
{
    Console.WriteLine("This is not an anonymous method.");
}

static void Main(string[] args)
{
    Action action = new Action();

    action.Execute(DoSomething);
}

An the output would be :

DelegateOutput

With an anonymous method, we reduce the code and by the same occasion, augment code readability.

static void Main(string[] args)
{
    Action action = new Action();
    action.Execute(delegate() { Console.WriteLine("This is inside an anonymous method."); });
}

 

AnonymousOutput

If the delegate has expected a parameter you could have done it like :

action.Execute(delegate(string s) { Console.WriteLine(s); });

And if the delegate have an return value, make sure you return one of the correct type :

action.Execute(delegate(string s) { return s; });

 

Accessing variables located outside the anonymous block :

A feature of an anonymous method is the ability to access variables located outside the anonymous scope (anonymous-method-block). Those variables called “outer variables”. It is better explained by an example :

string myString = "Outside the anonymous method.";
action.Execute(delegate(string s) { Console.WriteLine(myString); });

AnonymousScope

The exception to this rule are the ref and out parameters, which cannot be accessed by the anonymous method. You also can’t put unsafe code in the anonymous method.

Real life example

Maybe not (it’s always hard to come with great example), but it illustrate how you can use an anonymous method to find all string matching “String5″ inside a collection of string. Just imagine doing the same thing in your collection of orders or products.

List<string> myListOfString = new List<string>();

for (int x = 0; x < 10; x++)
{
    myListOfString.Add("String" + x);
}

List<String> returnedStrings = myListOfString.FindAll(delegate(string s) { return s == "String5"; });

 

Conclusion

Mastering Anonymous Methods is a great skill to have in you toolbox. But be careful, if you need to reuse the same code again and again, you better have to create a method and put the code in it. Don’t try to impress your friends too much. :)

 

Posted in .NET | No Comments »

Refreshing my memory : Delegates in C#

Posted by Sebastien Lachance on April 9, 2008

I haven’t really used delegates since I was programming with the .NET Framework 1.0. Since I have some spare time left, I decided to ‘”refresh my memory”. I have prepared a little cheat-sheet that you can use as a reminder for the delegates functionalities in the .NET Framework 3.0.

 

1. What is a delegate?

A delegate is a data structure that refers to one or multiples static methods and/or instance methods. You can use this when you have a dynamic list of methods to be called that you don’t know ahead of time.

2. How to create a delegate?

public class TestClass
{
    private delegate void myDelegate(string name);
}

The signature of the declaration is very important! The methods that will be contained in the delegate must perfectly match the declaration. In this case, the methods that will be allowed must be void and take a single string as a parameter.

When using the delegate keyword, you are actually creating a System.MulticastDelegate.

 

3. How do I instantiate a delegate?

public void TestMethod()
{
    ClassTest test = new ClassTest();

    //Instantiating a delegate with an instance method
    var del1 = new myDelegate(test.InstanceMethod);

    //Instantiating a delegate with a static method
    var del2 = new myDelegate(ClassTest.StaticMethod)
}

 

4. How do I call the method contained in the delegate?

del1.Invoke("This is a test.");

The Invoke method will actually have the same signature as your delegate signature. So you benefit of a strongly-typed way to use the delegate feature. There is also a BeginInvoke and an EndInvoke method to program asynchronously.

 

5. But you said that you can have more than one method in the delegate?

Actually yes. There is several ways to add more methods, but the easiest way is :

del1 += ClassTest.StaticMethod;

When calling Invoke (or BeginInvoke) each one will be executed in the order that they were added to the delegate. If an exception occurs at any point, the execution is canceled and the remaining methods will not be called. And you will get an exception of course.

 

5. Anything else?

Yes, a delegate is immutable. Each time you add a method entry point, a new delegate is created for you.

Posted in .NET | No Comments »

Cannot have multiple items selected in a DropDownList.

Posted by Sebastien Lachance on March 8, 2008

Cannot have multiple items selected in a DropDownList.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
Source Error:

Line 253:            total = parseFloat(lblTotal.innerHTML.replace('$', '').replace(',', '.'));
Line 254:            fBudget = parseFloat(budget.replace('$', '').replace(',', '.'));
Line 255:            var lblWarningContract = document.getElementById('<%= lblWarningContract.ClientID %>');
Line 256:
Line 257:            if (total > fBudget)

I spent at least one hour figuring this out. The Source Error  does not contain any valid information. The solution is : you should never use the same item twice on two different dropdownlist.

ListItem item = new ListItem(" -- Select one -- ", "-1");

ddlLoadingContact.Items.Insert(0, item);
ddlUnloadingContact.Items.Insert(0, item);

A ListItem have a property called Selected that tells which one (the item) the dropdownlist should display as selected. If you use the same ListItem in more that one dropdownlist and you select this item in the DropDownA and a different item in DropDownB. The DropDownB will have two ListItem with the Selected property set to true. Since this is the same item in both dropdownlist.

ddlLoadingContact.SelectedValue = "-1"; //item will have the Selected property set to true
ddlUnloadingContact.SelectedValue = "John";  //another item will have the Selected property set to true. And both are contained in this dropdownlist.
 
 

Posted in .NET, ASP.NET | 4 Comments »