Bookmark and Share

Missing a Section Declaration After Upgrade

by KodefuGuru 27. August 2010 00:02

In the process of installing Orchard tonight, I encountered the following error.

The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration.

The web.config clearly had an empty system.web.extension section.

<system.web.extensions/>

But there was no corresponding section declaration, just like the error said. However, Orchard runs fine on my local machine, and I’ve deployed it to my server before. What could be going on?

It turns out that it’s quite a simple issue, and probably a common problem. If you upgrade a site to .NET 4, and don’t upgrade the application pool to use .NET 4, you will get this. The machine.config file for .NET 4 declares this section, and earlier version did not have it (unless you manually added it).

In IIS 7, with the site select, choose Basic Settings in the right pane. This will bring up a dialog that contains the name of your application pool. Then select the application pools tree node and the application pool from the list that shows up. Choose Basic Settings from the right pane here, and you can change the framework version.

Bookmark and Share

Continuation-Passing Style Overload

by KodefuGuru 25. August 2010 01:23

I wrote about continuation-passing style in a post a couple of months ago, and I’ve had time to ruminate over it since. One consideration I had is whether to return a type or not. This is easily handled by overloading the method.

static void Main()
{
    var result = Div(16, 3, (q, r) => new { Quotient = q, Remainder = r });
    Console.WriteLine("quotient: {0}", result.Quotient);
    Console.WriteLine("remainder: {0}", result.Remainder);

    Div(20, 3, (q, r) => Console.WriteLine("\nquotient: {0} \nremainder: {1}", q, r));
}

public static T Div<T>(int dividend, int divisor, Func<int, int, T> func)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(func != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    return func(quotient, remainder);
}

public static void Div(int dividend, int divisor, Action<int, int> action)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(action != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    action(quotient, remainder);
}

The first block of code inside of the Main method returns an anonymous type with Quotient and Remainder properties that are then printed to the screen. The second block passes the continuation action to the method. The purpose of the second version is create side-effect, in this case I’m writing to the screen, but in C# world this is sometimes necessary and beats the uglier code you will end up with if you attempt to do it with the function type.

But is the action really necessary? In my mind, Action<int, int> should be the same thing as Func<int, int, void>. I posted a message about this on twitter, and received a response that return type can’t be nothing. But here’s the rub… void isn’t nothing. The void keyword actually refers to the System.Void type. When you define a void method and return out of it, it returns a Void. This is object-oriented land, everything is an object; even void.

It would be neat if this could work as there would be no need for an action overload. If the lambda performed an action, void would be returned automatically. Basically, with void functions the second block of code in Main would make the second call have the following calling signature (with T replaced):

public static void Div<void>(int dividend, int divisor, Func<int, int, void> func)

This works great for generic continuation-passing methods. This actually works fine for any type of generic method with a tail function (a tail function is at the end). Upon further thought, I realized it’s terrible when the function wasn’t the tail.

If this were to exist, what would you do if someone were to assign a variable within the method?

public static void WriteDiv<T>(int dividend, int divisor, Func<int, int, T> func)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(func != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    var ret = func(quotient, remainder);

    Console.WriteLine(ret);
}

I suppose ret would be an instance of System.Void, but what does it mean to write a void, which is nothing? It’s not the same as null… is more nothing than null. In fact, it can’t even be null because, well, it’s a struct.

Despite the fact it’s probably a bad idea, I attempted the impossible anyway. The C# compiler does not like you using System.Void, and it will not allow you to define void inside of generic parameters. So, I modded some IL!

Download the files

It assembles fine, and you can see it in reflector. However, I receive a runtime error when running it.

Unhandled Exception: System.TypeLoadException: The generic type 'System.Func`2' was used with an invalid instantiation in assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. at VoidFuncs.Program.Main()

It’s probably for the best that it doesn’t work. Any suggestions on how to make it work? I’m particularly looking for semantics as I believe that this could help promote functions to be first class citizens in C#.

Bookmark and Share

My First LightSwitch Failure

by KodefuGuru 18. August 2010 19:14

I used the prerequisite installer to make sure LightSwitch would be happy, then I installed the real thing. I then spun out a simple contact manager in a couple of minutes. It was amazingly easy to build an application that allows you to search contacts, add new contacts, and edit contacts. Unfortunately, I built the solution to encounter errors (without any code)!

Error 2 The type or namespace name 'RoundtripOriginalAttribute' does not exist in the namespace 'System.ComponentModel.DataAnnotations' (are you missing an assembly reference?) 56 c:\Projects\Application1\Application1\ClientGenerated\GeneratedArtifacts\DataClientImplementation.cs 34 ClientGenerated

Along with several other errors related to references. I could not find an add reference button, so I added it to the project manually (I verified the assembly was in the GAC). It still did not work.

I uninstalled WCF RIA Services for Visual Studio 2010 (installed by the prerequisite installer), then used the installer from Silverlight.net. That fixed the problem. I don’t know if it was a fluke with my system or if others will encounter this problem, but it’s easy enough to correct.

*UPDATE*

The correct dll (System.ServiceModel.DomainServices.Server.dll) isn't in the GAC. I was looking at the wrong assembly. WCF RIA Services for Visual Studio 2010 was installed at the time, however, and there didn't appear to be any problems with it. I don't want to dig deeper when it was likely something wrong with the installation, so if you experience the problem, just reinstall RIA Services.

*UPDATE 2*

This isn’t limited to my machine, and there is another invalid state you can reach. I posted this issue in the Lightswitch forums and Kris Langhor responded.

Thanks for the information. This is an issue that we are currently working to address for a future release.  The issue is related to the install order of the components. The Lightswitch prerequisites are specifically designed for provisioning a server that will not have the Lightswitch IDE installed on it. They install the WCF Ria Services bits in a Server-only mode that does not contain all of the assemblies. For a development machine you need only run the Lightswitch Web Install or setup from the CD.  That will install the full WCF Ria Services stack that is required by the designer.

When you follow the install steps that you have outlined you will get 1 of 2 results:

1) You end up in the state the you arrived at where Lightswitch installs but has compile errors. To work around that you need to uninstall WCF Ria Services and reinstall as you outlined.

OR

2) The Lightswitch install will report an install error and report it failed to install WCF Ria Services. In this case you should uninstall the version of Ria Services that is installed on your machine and then re-run the Lightswitch installer.

Hopefully this helps clarify the issue and provides folks wiht sufficient infromation to help workaround the issue.

This is a Beta, so don’t expect everything to work perfectly! I put this on my blog and posted to the forums to help others out who may run into the same problem.

Bookmark and Share

Visual Studio LightSwitch Resources

by KodefuGuru 18. August 2010 17:52

To celebrate the release of Visual Studio LightSwitch on MSDN, I am posting the resources of which I am aware. This is a list for you lucky few with an MSDN subscription who can download LightSwitch Beta 1 today. More resources and information will be released on Monday, August 23rd, along with the public beta.

LightSwitch Developer Center
LightSwitch Beta 1 Documentation on MSDN
Vision Clinic Application Walkthrough and Sample
LightSwitch Forum

I’m sure everyone will start posting basic LightSwitch articles soon. Instead of adding to the echo chamber, I intend on finding interesting tidbits within LightSwitch. I’m sure there’s more to be gleaned from this than merely scaling applications quickly. I am curious how to build addins for it, and what kind of problems the LigthSwitch team solved. A LightSwitch application looks pretty slick, and if I think there are things to learn from its internal infrastructure.

Bookmark and Share

Int32 + String = String

by KodefuGuru 16. August 2010 19:18

This past weekend, we were throwing around C# trivia at a bar in Baton Rouge after SQL Saturday #28. Another speaker asked me one that he used in his session that day: what happens if you call Console.WriteLine(5 + “5”). I nonchalantly replied, “the number 55 written to the console.”

It really never occurred to me to attempt to add an int to a string, so I encountered this behavior in the context of something a little more bizarre: creating LINQ to Object. Here’s the extension method I used.

public static TResult SelectMany<TSource, TCollection, TResult>(this TSource source, 
    Func<TSource, TCollection> collectionSelector, 
Func<TSource, TCollection, TResult> resultSelector) { return resultSelector(source, collectionSelector(source)); }

There’s nothing particularly special about this extension method, but it allows you to combine two objects in a query expression. My first test was with types of the same kind.

[TestMethod]
public void SelectMany()
{
    var result = from x in 2
                 from y in 3
                 select x + y;

    Assert.AreEqual(5, result);
}

I know, that’s a really long-hand way to write 2 + 3. However, it proved that the SelectMany extension method worked. I then attempted it with an integer and a double. By all the rules, it should return a double.

[TestMethod]
public void SelectManyDifferentTypes()
{
    var result = from x in 2
                 from y in 3.1
                 select x + y;

    Assert.AreEqual(5.1, result);
}

Again, this was worked as I thought it would. But as I played with modifying the test to do an integer and a string, I noticed that it still compiled without any modifications to the select clause. Here’s the final test.

[TestMethod]
public void SelectManyIntAndString()
{
    var result = from x in 4
                 from y in "2"
                 select x + y;

    Assert.AreEqual("42", result);
}

I was dumbfounded. Was the act of passing the types through functions working magic with the types? I had to test it out on straight code to find out.

[TestMethod]
public void IntAndString()
{
    var result = 4 + "2";

    Assert.AreEqual("42", result);
}

There is no magic, unless you believe the compiler is a mystical force that binds all your code together. This is one of the compiler rules I had not encountered simply because it never occurred to me to add an int and a string together. I was expecting a type mismatch, but I missed one simple rule about strings buried deep in the C# specifications.

Whenever you use the + operator with a string, a string concatenation is performed. With a type that isn’t a string, this ends up calling String.Concat(object, object), which will use the ToString method of the object. If the parameter is null, String.Empty is used. You know all those places where you see “Hello “ + World.ToString() + “!!!”; completely unnecessary call to ToString().

Just because you know this works doesn’t mean you should do it. Readability of code is more important that doing tricks with strings. I would recommend calling ToString() when concatenating, prefering String.Format over concatenation, and using StringBuilder with large amounts of strings. But hey, it makes a great trivia question.

Tags:

Kodefu

Bookmark and Share

Is That Closure or Inheritance?

by KodefuGuru 10. August 2010 19:09

In response to my previous story, a commenter asked if the code I posted works due to a closure relationship rather than inheritance. The argument is that the field can be accessed by a nested class, and it wasn’t actually passed as a member to the other class. The reader of the story states that the field would still be accessed in Java even if Employee didn’t inherit from Person. Then, the question is asked if it’s different in C#.

I’m not familiar enough with Java to speak about how it works, but I can discuss what is happening in C#. First, let’s take a look at the code in question.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Person CreateEmployee()
    {
        return new Employee();
    }

    class Employee : Person
    {
        public Employee()
        {
            this.message = "I inherit private members!";
        }
    }
}

The reason you can be sure the constructor of Employee modifies the member named message on the instance of employee is because of the ‘this’ keyword. This keyword refers to the current instance, and this is the reason I don’t bother with underscores or funky names in my fields. If I need to scope to a member field, using the ‘this’ keyword is clearer than semantic customs… plus it has compiler support! Using ‘this’ within a nested type only refers to members of that type, and not the outer type

Of course, I use the keyword for convention, it oftentimes isn’t necessary. What happens If I remove the ‘this.’ from ‘this.message’?

public Employee()
{
    message = "I inherit private members!";
}

It still compiles, but whereas the answer was clearly “it’s inheritance” before, the lack of the keyword brings lack of clarity. So what’s happening? We could bring it up in reflector, but it would be more fun to modify the code. Let’s actually strip the inheritance hierarchy. This will require a few other modifications.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Employee CreateEmployee()
    {
        return new Employee();
    }

    public class Employee
    {
        public Employee()
        {
            message = "I inherit private members!";
        }
    }
}

And we find out quickly enough that this is will not work. Despite the lack of ‘this’, message was referring to the private member on Employee. Since Employee no longer inherits from Person, it is trying to access the field in the outer class. This gives us a rare error message.

Cannot access a non-static member of outer type 'Person' via nested type 'Person.Employee'

There’s a very simple explanation for this. Employee has been nested inside of Person. Just because you have an instance of the nested type does not mean you will have an instance of the outer type. Nesting allows for interesting accessibility scenarios, but there is no other special relationship defined.

The accessibility relationship works like this. I can create a method inside of Employee to access a private member of Person.

public class Employee
{
    public void Demo()
    {
        var person = new Person();
        person.message = "accessed";
    }
}

In the original version, it is possible to access the message field of Person from Employee if the message field is static as no instance is required.

I am not sure how this all works in Java, but my original example demonstrated inheritance with private accessibility. Try it out for yourself!

Bookmark and Share

Are Private Members Inherited?

by KodefuGuru 9. August 2010 17:30

When I interview someone, I start the question phase with simple object-oriented questions to get a feel for the person. Am I interviewing someone who writes rote procedural code or do I have someone in front of me who thinks in terms of objects and relationships. Even more intriguing, am I talking to a functional wunderkind who will enlighten me in my own journey through code? I start off with the simplest of questions: what’s the difference between a class and an object? Of course, the topics usually end up deep into their own experience as I use technical questions for the response factor more than right or wrong answers. I’m more interested in the fact that someone is thoughtful, into programming, and able to learn rather than whether they memorized a textbook or interview prep site.

A person came to me today to ask me a question they had recently in an interview for a C# position: are private members inherited? The answer given was no, and the interviewee was promptly informed that answer was incorrect.

On one level, it would appear that classes don’t inherit private members. Public and protected members are accessible by the subclass, but those pesky privates seemingly can’t be accessed. Of course, they’re there, otherwise calls to the exposed methods would not work. Then, there’s always reflection to access them. But I’m not really concerned about reflection or lower-level activities such as memory access; I’m more interested in the higher level concept of inheritance. Is the private member passed on to the subclass?

The problem with the private member isn’t actually one of inheritance, it’s one of accessibility. Being a private member means it’s only accessible within its defining type. To discover if the private members are inherited, we can set up a simple test: define the subclass within its parent.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Person CreateEmployee()
    {
        return new Employee();
    }

    class Employee : Person
    {
        public Employee()
        {
            this.message = "I inherit private members!";
        }
    }
}

Run this within a Console application, and it will print the message on the screen: “I inherit private members!”

class Program
{
    static void Main()
    {
        Console.WriteLine(Person.CreateEmployee());
    }
}

Proof positive that private members are actually inherited. Remember, modifiers such as public, protected, private, and internal are all accessibility modifiers. These modifiers affect encapsulation rather than inheritance.

A class takes everything from its parent class; its instantiation will have every member. In most situations, those marked private are hidden from from the subclass. Using reflection follows this same behavior: with the example above, message will not be returned through type.GetMembers(BindingFlags.NonPublic|BindingFlags.Instance) despite the fact that it has been exposed.

I do, however, feel that the concept of encapsulation and inheritance coexist and are intertwined. Certainly, at a physical level, the instance of the object has the same memory, and therefore can access the functionality that has been hidden from it through the interface its parent has given it. But conceptually, one does not look at a class and consider members that have been hidden from view as being part of it. Instead, we think of a class as inheriting an interface and behavior, not the entire template. I may inherit my parents’ features, but their secrets are theirs to keep.

I did demonstrate a way to break the way many think about inheritance in C#. Some languages don’t allow access beyond the public interface even to their subclasses. In those languages, inheritance doesn’t break encapsulation, and I believe the case is stronger that encapsulation makes our conceptual view more valid. Don’t get me wrong though, the accessibility modifiers in C# are very useful, and I wouldn’t trade them for a more “pure” language.

If I were the one asking the interview question, I would not be interested if the candidate got the question right with a simple yes or no answer. I would ask why in either case. Most people probably would respond that “objects can’t access private members of the parent class,” despite the fact that I’ve proven it can be done. Does that make the person a bad developer? No, because that is true in nearly all situations, and it describes, without being too technical, encapsulation. That would be a good time for me to follow up with encapsulation. What if instead the person knew how to access the parent’s private members through inheritance, then proceeded to provide more information about encapsulation and inheritance? Well, kudos, maybe you read my blog? In all seriousness though, if someone came back to me with that information I would be impressed simply because they care enough about their craft to learn it, just as I am impressed when someone cares enough to discuss these topics at conferences because they are truly interested in learning.

Bookmark and Share

Remove Generic Parameter Refactoring

by KodefuGuru 6. August 2010 12:30

I needed to remove an extraneous generic parameter from two classes in a 2008 project. One of the classes was BusinessObjectList<TList, TItem>, and TList wasn’t used and it ended up junking up the code throughout the solution. I was tired of looking at it and its bizarre subclasses like EmployeeList : BusinessObjectList<EmployeeList, Employee>.

I will note how it could be useful: if any of the methods on BusinessObjectList were returning the subclassed list as part of a fluent interface. But nothing like this exists. I’m not even a fan of defined list classes. Why should you limit yourself when there are other sequence possibilities? What if I had an array of the particular BusinessObject?  I think extension methods on IEnumerable<BusinessObject> are better and it plays better with LINQ (I don’t have to redefine every LINQ method to make it return the list). These are fluent by their nature anyway since you typically make the method yield out the objects creating an IEnumerable<T>.

But, the hard lists are there, and I believe the cost of removing them is too high at this point in time but it’s something I’ll have my eye on if the opportunity exists. Keeping the code tight by removing the extraneous generic is worth it though considering some other framework issues I will be tackling. The problem is that hundreds of classes inherited from this class and the other, and a manual edit would take forever. This refactoring should be quick.

I checked all of my tools, but none had a “remove generic parameter” refactoring. Would I have to do this by hand? Of course not, I’m a programmer. What tool do we have for matching stuff like a BusinessObjectList<X, Y>? How about RegEx?

I pop up the Find/Replace dialog, and immediately type a regex that should match everything I want to replace. It doesn’t work. Now, I’m not an expert in that sort of thing, but surely I can write something that simple? After a few minutes of trying it out, I start searching and discover Jeff Atwood has already talked about this oddity in Visual Studio.

After learning Visual Studio’s flavor of regex, I finally achieved a somewhat bizarre construct for removing a generic parameter. Find what: BusinessObjectList\<:i,:b{:i}\> and Replace with: BusinessObjectList\<\1\>.

clip_image002

The class everything was inheriting from was BusinessObjectList, so I wrote that in and escaped the < and >. :i marks a C/C++ identifier (which works great with C#!) and :b matches tab or space. I enclosed the second :i with curly braces so I could use it as an identifier in the replace regex with \1.

There may not have been a fancy tool to achieve this, but the results were the same and it didn’t take much time. It certainly beats replacing the code by hand.

Bookmark and Share

Free Programming Windows Phone 7 Ebook

by KodefuGuru 4. August 2010 10:28

Microsoft Press has announced that Charles Petzold’s Programming Windows Phone 7 will be released in time for PDC10 as a free download! I find this crazy, as this is easily a book I would pay good money for. How do I know? I’ve been browsing the 11 chapters they released as a download for VSLive! You can download the PDF, the XPS, and the source code.

Released Chapter List

Part I   The Basics

Chapter 1   Hello, Windows Phone 7

Chapter 2   Getting Oriented

Chapter 3   An Introduction to Touch

Chapter 4   Bitmaps, Also Known as Textures

Chapter 5   Sensors and Services

Chapter 6   Issues in Application Architecture

Part II   Silverlight

Chapter 7   XAML Power and Limitations

Chapter 8   Elements and Properties

Part III   XNA

Chapter 20   Principles of Movement

Chapter 21   Textures and Sprites

Chapter 22   Touch and Play

Bookmark and Share

Visual Studio LightSwitch 2010

by KodefuGuru 3. August 2010 15:36

I’m a hardcore coder who is into design patterns and best practices. But sometimes, you just need to crank out a simple little application for someone to manage a database of employees or orders… maybe both! Recently, some of use have turned to ASP.NET Dynamic Data for scaling websites, but websites aren’t always the best solution. What if your client really wants a desktop application with rich functionality like exporting to Excel? Introducing the next wave of application scaling: LightSwitch!

As I said, I’m really into patterns and practices. I wouldn’t use this to design an enterprise architecture, and it wasn’t meant for that. However, LightSwitch is really great at plugging into an existing enterprise infrastructure and generating a useful application. As I watched the demo (keynote from VSLive and parts available at the website), I noticed three sources of data you could choose from: SQL Server, SharePoint, and RIA Services. If you’re building a standalone application, you can design your tables from scratch as well.

After you select your data, you select an option to generate views from your data. It is quite a simple design experience, and when you’re done you have a fully functional application with full data validation. Since it’s built on Silverlight, it even looks good! There are even extensibility points if you need to add custom code (only VB or C# at this time).

I sometimes get requests to write little applications to access data sources in a different manner than the primary applications. With LightSwitch, I know I will be able to do so quickly and get back to more interesting challenges. The beta will be available on the website on August 23rd.

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
C# MVP, INETA Community Champion


MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er

I have joined Anti-IF Campaign


World Map

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010