Archive for the ‘C#’ Category

ASP.NET GridView with an ObjectDataSource

Monday, October 26th, 2009

Just a quick tip:

I got the following exception today:

If a data source does not return ICollection and cannot return the total row count, it cannot be used by the GridView to implement server-side paging.

If you’re trying to return an IEnumerable from your select method, try changing it to a List or an array. That should clear the problem right up.

Configuring webHttpBinding When Using WCF with JQuery

Thursday, June 25th, 2009

Firstly, a disclaimer: I don’t have a lot of experience working with AJAX enabled WCF services, and from reading some of Rick Strahl’s posts on using JQuery with ASP.NET, I’m doing things in a really hackish and terrible manner. Hopefully my mistakes won’t impact the usefulness of this short tip.

When working with JQuery and AJAX enabled WCF services, I recently encountered the following error, through Firebug and Fiddler:

The maximum string content length quota (8192) has been exceeded while reading XML data.
This quota may be increased by changing the
MaxStringContentLength property on the XmlDictionaryReaderQuotas
object used when creating the XML reader.

This is caused by WCF webHttpBinding default having fairly draconion limitations on XML message length and depth. This thread on MSDN helped diagnose the problem, however it didn’t do much to help me solve my particular problem. Ultimately, I stumbled upon the solution quite accidentally.

Firstly, as per the MSDN thread, you need to add the custom binding configuration underneath the configuration section:

<system.serviceModel>
  <bindings>
    <webHttpBinding>
      <binding name="bindingConfiguration">
        <readerQuotas maxDepth="32" maxStringContentLength="2048000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      </binding>
    </webHttpBinding>
  </bindings>
  ..
</system.serviceModel>

At first I thought this was a custom binding, and tried to replace the service endpoint binding to the custom binding defined above, however this was causing an “System.ServiceModel.ServiceActivationException” exception.

The above binding declaration is actually a configuration for the webHttpBinding. As such, you need to add the BindingConfiguration property onto your service endpoint, along side your binding declaration. This is as follows:

<service behaviorConfiguration="Your.Service.Behavior"
      name="Your.Service.Name">
    <endpoint address="" behaviorConfiguration="Your.Behavior.Configuration"
     binding="webHttpBinding" bindingConfiguration="bindingConfiguration" contract="Your.Service.Contract" />
</service>

This will allow you to send larger messages to your WCF services via AJAX, and get on with creating applications.

Visual Studio 2008 Deletes LINQ DBML Designer File

Wednesday, April 1st, 2009

Do you spend hours wrangling with your “Interactive” Development Environment, trying to prevent it from deleting your boiler plate .designer file for your LINQ DBML? Do you get baffled watching Visual Studio delete said file from your software version control system, and then struggle to get the two back into sync?

Then you might be encountering this bug right here. The reason for this post is because this bug seems very hard to find information on in Google. So hopefully I can raise some awareness, and at least have it pop up on a Google search.

Typical symptoms are the designer file for the DBML being deleted when the DBML is updated. If you’re also using source control, Visual Studio will attempt to delete it from your source control at the same time. Renaming the DBML file will cause it to regenerate, however it can cause major headaches when combined with source control, removing it, adding it, pending delete actions hidden in a project you thought you had unchecked out.

The solution is the suitably moronic action of moving all your using statements inside your namespace declaration. A co-worker found this solution in this MSDN forum thread. Once you move your usings, Visual Studio happily stops deleting your designer file, and you can finally get back to work programming instead of fighting your tools.

Parsing ASP.NET pages with SGMLParser

Monday, March 9th, 2009

I’m going to take a short break in my Ruby CMS series to post something I encountered at work.

During my development of the CMS at work, I’ve had to deal with parsing HTML content in order to compile page content into tags. This involves being able to replace certain elements of a page with other elements. At first I tried to do this with regular expressions, however this didn’t turn out too well when it came to dealing with the inconsistencies in legacy sites running on the current, older CMS. Next, I tried parsing the pages as XDocuments, which worked ok as long as I was parsing well formed pages. As soon as it hit a malformed page, however, it died in a fiery burst of exceptions.

Then I looked at SGMLParser, and it seemed like it was my savior. It parsed SGML, of which HTML is a subset, and it auto corrected malformed content, and would handle all the inconsistencies of life, in use HTML, and it would allow me to parse it into an XDocument so I can manipulate nodes. However, even SGMLParser had it’s own problems: it wouldn’t handle ASP.NET server tags very well, which was a problem.

We provide “plug in” functionality to CMS sites by the way of ASP.NET server controls. You build your functionality, stick the server control files into your site, drop the binary into the bin folder and insert the server control tags into your page. Fire it up, and it will appear and function. However, when running pages with server control tags through the SGMLParser, it wouldn’t recognise the namespaces, and would strip them, completely breaking them.

This was unsatisfactory, as we were planning on using a similar sort of set up to perform the same thing in the new CMS. So, I hit Google, looking for ways to get around this. There’s not a lot of information out there about it, other than “SGML parses SGML, not ASP.NET, which isn’t valid SGML” which was exceedingly unhelpful, because I already know.

I peeked into the source of SGMLReader to see if maybe I could remove the functionality that stripped out unknown namespaces. Sure, this would probably defeat the purpose of using SGMLParser, but it would help me out in this specific project. Unfortunately, the codebase is rather complicated and I really didn’t want to dig in and spend hours on something I wasn’t sure was even going to work.

I saw that the project has a custom HTML dtd, so I considered briefly writing a dtd for ASP.NET. However, while I was thinking of all the different permutations of server tags, especially when you can specify your own namespaces and tag names and attributes, I quickly decided that wasn’t suitable either.

In the end, and I believe this is honestly the only way to do it, I ended up pre-processing my content, wrapping ASP.NET server tags within <![CDATA[ ]]> tags. I noticed that SGMLParser was wrapping my older <% %> ASP style tags in this fashion, and leaving them unmolested. After I parse it into the XDocument, do my manipulations and pull it back out as the desired content, I run a post-process through it, removing the <![CDATA[ ]]> tags that were added in the pre-process. After, I’m left with my content as it went in, with the modifications done through the compiling process.

Of course, I do the pre-processing and post-processing with a regular expression:

</?[\w]+:[^>]*/?>

 
which I think is kind of funny, in a way. I can never seem to escape regular expressions.

C# Interface Method Gotcha When Inheriting

Tuesday, February 3rd, 2009

I noticed some interesting behavior from C# yesterday at work. Truth be told, I’ve noticed this in the past, but I’ve only figured out what’s causing it today.

The behavior is this: when you inherit from a class that implements an interface, calling a hidden/overriden method from an object of the inheriting class that has been upcast to the interface will result in a call the the inherited function.

Ok, so that probably made no sense at all, which is why I will explain it, but not before a warning. I’m not sure if this is intended behavior, and I’m not sure if this is something I’m doing wrong. If someone can point me in the direction of an explanation or a correction, I would be very grateful.

Computer Bugs

On to the explanation.

Take a sample, trivial application that has widgets. These widgets just print messages out to the console. We have an interface, IWidget, which forms the contract for all widgets:

interface IWidget
{
    void DoSomething();
    void DoSomethingElse();
}

Next, we have a generic widget class, which we use for most widgets. This is called GenericWidget:

class GenericWidget : IWidget
{
    public void DoSomething()
    {
        Console.WriteLine("Doing something in GenericWidget");
    }

    public void DoSomethingElse()
    {
        Console.WriteLine("Doing something else in GenericWidget");
    }
}

 
And finally, we have a specific type of widget that does something different, called SpecificWidget:

class SpecificWidget : GenericWidget
{
    public new void  DoSomething()
    {
        Console.WriteLine("Doing something in SpecificWidget");
    }
    public new void DoSomethingElse()
    {
    Console.WriteLine("Doing something else in SpecificWidget");
    }
}

Now, we want to run some tests on our widgets, to see what’s going on. First, we’ll test the widgets themselves. Running:

GenericWidget genericWidget = new GenericWidget();
genericWidget.DoSomething();
genericWidget.DoSomethingElse();

SpecificWidget specificWidget = new SpecificWidget();
specificWidget.DoSomething();
specificWidget.DoSomethingElse();

 
will output:

Doing something in GenericWidget
Doing something else in GenericWidget

Doing something in SpecificWidget
Doing something else in SpecificWidget 

 Which is exactly what we expected to see. Test has passed.

Next, lets say we have a function that we want to pass widgets to, but we don’t know what kind of widgets we will be passing, only that they are widgets. So we pass them as widgets, but upcast them to IWidget, and call the methods on them from the interface. For example:

IWidget genericUpcast = new GenericWidget();
genericUpcast.DoSomething();
genericUpcast.DoSomethingElse();

IWidget specificUpcast = new SpecificWidget();
specificUpcast.DoSomething();
specificUpcast.DoSomethingElse();

 
which will give the following output:

Doing something in GenericWidget
Doing something else in GenericWidget

Doing something in GenericWidget
Doing something else in GenericWidget

Wait, that’s not right. The specificUpcast should call the method on SpecificWidget, shouldn’t it? At least, that’s my expected behavior. Just to prove there’s not something wrong with our specificUpcast:

(specificUpcast as SpecificWidget).DoSomething();
(specificUpcast as SpecificWidget).DoSomethingElse();

 
will yield:

Doing something in SpecificWidget
Doing something else in SpecificWidget 

which is our expected output all along.

If someone can explain this to me, or point me to a better method to upcast, then please do so. I’m finding a lot of my code needs to check for specific types in order to call the proper method, and it seems clunky and awkward. I’m sure I’m doing something wrong, I’m just not sure what.

As usual, you can find the source code here: Interface Upcasting Inherited Classes Gotcha

First Impressions Of Ruby

Saturday, December 20th, 2008

I like it.

A lot.

But I always knew I would. I’m so far impressed with how much effort Ruby goes to at making itself understood at a casual glance, and just how easy it is to write self documenting code. Writing code that’s free of braces and parenthesis is refreshing, and it’s nice to know the safety blanket is there (with regards to parenthesis for functions, conditional statements, etc) is there if I need it.

I started last night by flicking through Why’s (Poignant) Guide, and found it pretty good for the basics. I quickly picked up the general concepts and basic syntax fast, and Why’s Guide was pretty whimsical and kept things interesting. However I quickly bored of the absurdity in chapter 5 where the majority of its content is fluff.

I tried switching to SaphireSteel’s The Book of Ruby, however right at the start when the author stated:

if (subtotal < 0.0) then subtotal = 0.0 end

Putting everything on one line like this adds nothing to the clarity of the code, which is why I prefer to avoid it

I knew that this book would not help me. I already know many languages that require simple statements like that to be spread over multiple lines. I want a language to do this:

subtotal = 0.0 if subtotal < 0.0

Hi, Ruby.

Then I browsed over to Ruby in 20 Minutes and quickly flicked through the pages, and it concreted my knowledge. I like iterators, I like respond_to?, I like how everything seems to make sense. I also am pleased to see how many concepts map onto similar things in C#. Modules are like namespaces, but better. attr_accessor is like { get; set;}. attr_reader is like {get; private set;}.

I feel I’m ready to go find some code in the wild and attempt to read it. I’ll also see if I can come up with a post that maps Ruby concepts to C# concepts for other C# programmers interested in Ruby (and with IronRuby, there’s no reason why you shouldn’t be).

Compile a User Control as a DLL

Monday, December 8th, 2008

At work, I’m redeveloping the old, ASP 3.0 CMS application and replacing it with a shiny new .NET 3.5 implementation. The software is designed to be run as a virtual directory from all websites, and thus shares the same from installation to installation.

The old CMS is a mutant. It started as an ASP 3.0 application, and then had extra bits made of .NET 1.0 & .NET 2.0 tacked on to it, much in the same manner that Frankenstein’s monster was created. The core ASP 3.0 application handled the page/news creation and publishing, and served as the interface.

The additions were mostly in the form of user controls (.ascx files) that were placed in the content for a page that needed one. These user controls took care of things like random image rotators, contact forms, bread crumb menus, etc. Various sites used a various sub-section of a pool of controls.

The modus operandi with the current system is that each installation has it’s own collection of controls which are inserted into pages by us on behalf of the client, because it involves putting ASP.NET markup into the content areas.

I’ve decided this isn’t such a great idea, and as such, I’m centralising the user controls as a library, seperate from the CMS, so that each site accesses the single pool of controls, and if a client leaves, it will be relatively simple to recompile a new library with the controls they use.

Anyway, that’s the back story. Essentially what I need to do is compile a whole load of .ascx files into a dll, and load them into pages. I’ve spent all morning looking on Google for tips on how to do this. And frankly the results were less than helpful, however I have a history of not reading documentation properly.

What I found out you need to do, is to add a class library project to your solution, and add the .ascx file as per normal. However, you need to do several steps to get this working properly:

  • Go to the properties of your .ascx file and change the build action to Embedded Resource.
  • From your control declaration on the .ascx file, delete AutoEventWireup. We need to wire these things up ourselves. Personally I cleared it of everything except the language attribute.
  • In the old code behind (now unattached class file) for the .ascx, you need to override the OnLoad event handler, and put the following code:
    string content = String.Empty;
    Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), "example.ascx");
    using (StreamReader reader = new StreamReader(stream))
    {
    content = reader.ReadToEnd();
    }
    Control userControl = Page.ParseControl(content);
    this.Controls.Add(control);
    

    This source will use reflection to open the currently executing dll (in this case, our .ascx library) and find the content for the .ascx, parse it as a new control and add it to the currently executing context.

  • For every control on the .ascx, in our now orphaned .ascx.cs you need to declare a private/protected variable of the same time, with the same variable name as the ID on the control (for sanity’s sake). You need to find this control in our newly loaded .ascx and assign a reference:
    labelInAscx = (Label)control.FindControl("labelInAscx");
    
  • The above two steps is exactly what the AutoWireUp attribute on the control declaration does for you. We do it manually because we have to use reflection to extract the content of the ascx file, which is compiled into our dll.

After taking these steps, compile your project, and in another project, on a regular aspx page, register the assembly and use as you would any normal .ascx and hopefully the content will render out fine.

Compile .ascx as DLL solution for Visual Studio 2008