Tuesday, March 25, 2008

The Controls collection cannot be modified because the control contains code blocks (i.e. <% %>)

This one hit me some time ago but was easy to work around. Today I had to face it in a ListView's LayoutTemplate:

<LayoutTemplate>
    <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
    <% if ( ApplicationUser.IsCurrentUserTheAdmin )
       { %>
    <hr />
    <asp:ImageButton ID="SwitchAddSectionButton" runat="server" OnClick="SwitchAddSectionButton_Click"
        ImageUrl="~/Resources/item_add.gif" />
    <% } %>
</LayoutTemplate>

As you can see there is a dynamic part of the template which is available to users with sufficient priviledges.


Although google provides a lot of articles referening the issue, the solution I've came up is amazingly simple:



<LayoutTemplate>
    <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
    <div runat="server">
        <% if ( ApplicationUser.IsCurrentUserTheAdmin )
           { %>
        <hr />
        <asp:ImageButton ID="SwitchAddSectionButton" runat="server" 
            OnClick="SwitchAddSectionButton_Click"
            ImageUrl="~/Resources/item_add.gif" />
        <% } %>
    </div>
</LayoutTemplate>
Note that the only difference is the <div ... runat="server"> tag which contains all other additional controls in a control tree.

Monday, March 17, 2008

WebServices, 302 Object moved and "Client found response content type of 'text/html', but expected 'text/xml'" exception

The issue

This article focuses on the issue of WebServices intentionally redirecting requests to other locations. Please first make sure that the exception is not caused unintentionally, for example by incorrect authorization policy in web.config.

In general, Web Browsers handle redirects with no issues. If "302 Object moved" is sent to indicate a redirect, the web browser happily checks new location and retrieves the data.

However, while web browsers automatically handle redirects regarding requests to WebServices, it seems that client proxy classes do not automatically handle such redirects. This is quite annoying - my WebBrowser automatically redirects 302s, the HttpWebRequest also does but the WebService proxy inheriting from SoapHttpClientProtocol does not!

I am not going to answer a general question "why do you need to redirect a web service call". I just assume you need, just as I do.

General solution

My first attempt to find the solution was to use Google. I've came upon nice article by Matt Powell, Using ASP.NET Session State in a Web Service (look for the "Cookieless Sessions" section).

In short, Matt's solution is to wrap each invocation in a try-catch clause which tries to remap original WebService's Uri to the new one. This solves the issue, however is not practical since you'd end up with wrapping each single WebService method with a bloating try-catch clause.

The nice thing in Matt's approach is that it's general - if any subsequent WebService call causes 302 to be sent to the client, it is handled on the client side.

Specific solution - single redirect

The case of my application is not as general as to require the remapping to be handled for every request. I need to remap the url just once during the first call, however an additional cookie is appended to this first request. Instead of wrapping each single method, I've just wrote a simple proxy class which inherit from the SoapHttpClientProtocol class.

using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
using System.Net;
using System.IO;
 
namespace Vulcan.Web.WebServices
{
    public class SoapHttpClientProtocol302 : 
        System.Web.Services.Protocols.SoapHttpClientProtocol
    {
        protected override System.Net.WebRequest GetWebRequest( Uri uri )
        {
            if ( !_302Fixed )
            {
                Fix302( new Uri( this.Url ) );
                _302Fixed = true;
 
                return base.GetWebRequest( new Uri( this.Url ) );
            }
 
            return base.GetWebRequest( uri );
        }
 
        private bool _302Fixed    = false;
        private void Fix302( Uri uri )
        {
            HttpWebRequest request    = (HttpWebRequest)HttpWebRequest.Create( uri );
            request.CookieContainer   = new CookieContainer();
            request.AllowAutoRedirect = false;
            HttpWebResponse response  = (HttpWebResponse)request.GetResponse();
 
            if ( response.StatusCode == HttpStatusCode.Redirect )
            {
                this.Url = new Uri( uri, response.Headers["Location"] ).ToString();
                this.CookieContainer.Add( response.Cookies );
            }
        }
    }
}

As you can see, the first request is handled in a special way: a new request is made to the application server and if the response code is 302 the Url of the proxy class is remapped to the new location returned by the appliaction server.


What I then need to do is to move my client proxy classes in the class hierarchy from SoapHttpClientProtocol to SoapHttpClientProtocol302.

Friday, February 29, 2008

Linq to Object vs Linq to SQL and custom predicates

One of the most interesting issues of Linq is the ability to use arbitrarily complicated predicates inside linq expressions. You are also aware of the fact that the there are two equivalent syntax possibilities:

List<int> l = new List<int> { 1, 2, 3, 4, 5 };
 
/* linq-style syntax */
foreach ( int v in
    from i in l
    where i > 2
    orderby -i
    select i )
    Console.Write( v );
 
/* is translated to method invocation sequence */
foreach ( int v in l.Where( i => i > 2 ).OrderBy( i => -i ) )
    Console.Write( v );

No matter what syntax you prefer, sooner or later you will realize that expressing filtering and ordering clauses in an explicit form inside linq expression is not a good way to write reusable code.


What if you actually have defined some filtering/sorting clauses in the business logic of the application and you wish to be able to use them both in application logic and in linq expressions?


Let's write a predicate and try to use it in linq-style syntax and method-invocation-sequence syntax.

static Func<int, bool> NumberIsGreaterThan( int K )
{
    return i => i > K;
}


The latter is easy:

foreach ( int v in l.Where( NumberIsGreaterThan( 2 ) ).OrderBy( i => -i ) )
    Console.Write( v );


The former can be expressed in two different ways, using method invocation inside linq-style expression:

foreach ( int v in
    from i in l.Where( NumberIsGreaterThan( 2 ) )
    orderby -i
    select i )
    Console.Write( v );


or the application of the predicate to the parameter:

foreach ( int v in
    from i in l
    where NumberIsGreaterThan( 2 )(i)
    orderby -i
    select i )
    Console.Write( v );


It is interesting to explain the last example. Well, the NumberIsGreaterThan predicate is of type Func<int,bool> and in the where part of linq expression the compiler expects bool expression which I create by applying the parameter to the predicate.

The bubble breaks when you realize that predicates in the way we express them above do not work in Linq to Sql. You'll just end with the nice exception saying that the "method WhateverYouCallIt has no supported translation to SQL".

Why this is so? You see, there are in fact two different linq approaches.

First one is built into the .NET, works on IEnumerable collections and you know it as Linq to Objects. The other one has few example implementations built into the .NET but rather operates on IQueryable collections.

In the latter case, instead of executing a sequence of methods, the compiler rather builds the expression tree for the whole linq expression and passes the tree to the IQueryable implementation saying: "do whatever you like with this expression tree, it's up to you".

(one specific implementation known as Linq to SQL just traverses the expression tree and builds a sql clause that correspond to the tree)

What's the relation of this to our example with custom predicates in linq expressions?

Well, it seems that if instead of passing Func<T, bool>  as a filtering predicate you'll pass it's expression tree, Linq to SQL will be able to step into this tree and build a SQL clause for it.

And how do you build an expression tree from the function? Well, you'll be surprised:



static Expression<Func<int, bool>> NumberIsGreaterThan( int K )
{
    return i => i > K;
}


Compare it with the former definition:



static Func<int, bool> NumberIsGreaterThan( int K )
{
    return i => i > K;
}


Is that all? Does it really make such a huge difference to put Expression<...> over the method's signature?

Well, yes, it does. By putting Expression<...> over method's signature you inform the compiler to automatically build the expression tree of the method rather than just to return the method body.

(you can also build Expressions directly in the code but it's beyond the scope of this post).

This tiny change has significant difference for the Linq to SQL and other Linq to IQueryable implementations - now, as the expression tree is placed in linq expression, the tree walker will likely correctly handle the tree structure for the predicate (even though the predicate body is defined outside of the linq expression).

Is it all?

Unfortunately, no. Defining predicates as Expression<...>  helps the Linq to IQueryable but confuses Linq to Objects!

Why?! Well, Linq to Objects expects predicates to be defined as Func<T,bool> not Expression<Func<T,bool>>! Is there a way to fix it?

Fortunately, yes, there is. You can "deexpression" the expression tree by compiling it using the Compile() method:



static Expression<Func<int, bool>> NumberIsGreaterThan( int K )
{
     return i => i > K;
}
 
...
 
/* all three syntax possibilities */
 
foreach ( int v in
     from i in l
     where NumberIsGreaterThan( 2 ).Compile()(i)
     orderby -i
     select i )
     Console.Write( v );
 
 foreach ( int v in
     from i in l.Where( NumberIsGreaterThan( 2 ).Compile() )
     orderby -i
     select i )
     Console.Write( v );
 
 foreach ( int v in l.Where( NumberIsGreaterThan( 2 ).Compile() ).OrderBy( i => -i ) )
     Console.Write( v );


Be aware of these differences between Linq to Objects and Linq to something-implementing-IQueryable and remember that in both cases you can use clauses defined as methods or properties in the business logic layer of your application.

Friday, February 22, 2008

Using LinQ to find largest group of anagrams in a given set of words

A friend of mine, Paweł R., who is an academic lecturer once gave following task to his students:

Two words are anagrams if they contain the exactly same number of the same letters. Write a program which, for given a set of words, will find a largest group of anagrams from this set. If more than one set exists with the same number of words, write the contents of each set.

A large set of words to play with this problem can be downloaded from my friend's page.

The task is not difficult at all - you just have to group words which are anagrams and then find the largest group. The easiest way to group is to split each word, sort letters ascending to get the hash key that uniquely identifies the word and then store the word in a hashtable using the key.

For example, having "leaf", "flea", "shore" and "horse", you split each word, sort letters and you get two distinct hash keys "aefl" and "ehors" and each hash group containst exactly two words. Let's call such hash a norm of a word.

It is easy to write a program in C# just few dozens of lines long but if are you a LinQ guy you would probably love to try to solve this task using LinQ.

I strongly recommend to stop reading now. Try to solve this task by yourself. You can start with sligtly simplified version: do not find all largest groups of anagrams, find just any largest group.

Are you ready:

// from the collection of words
( from slowo in File.ReadAllLines( "slowa.txt", Encoding.GetEncoding( "iso-8859-2" ) )
      group slowo by
          // group by the anagram "norm"  
          new string(
                // split the word into letters
              ( from letter in slowo.ToLower().ToCharArray()
                // and sort letters
                orderby letter
                select letter ).ToArray() )
          // so we have groups indexed by "norm"
          into anagramy
      // order this groups so the largest group is the first  
      orderby anagramy.Count() descending
      select anagramy.ToArray()
    ).First()

You probably came up with something similar to this. When I test it on the large set of words from the link given above, I get a group of seven words, just foreach the result and you will see them.


Now something more complicated - let's find all largest groups, not just the first one. To accomplish this we just group these groups of words by the size of the group and take the first groupped group of words. Sounds funny? Well, take a look:



foreach ( string[] tablicaanagramow in
    // tablica is a list of groups of words
    ( from tablica in
        // return list of groups
        ( from slowo in File.ReadAllLines(
                        "slowa.txt", Encoding.GetEncoding( "iso-8859-2" ) )
          group slowo by
              new string(
                  ( from letter in slowo.ToLower().ToCharArray()
                    orderby letter
                    select letter ).ToArray() )
              into anagramy
              // we do not have to orderby anagramy.Count() descending
              // since groups of anagrams are groupped
              select anagramy.ToArray()
        )
     // group by the group size
     group tablica by tablica.Count() into tablicatablic
     // and order by the size of any group from the group :)
     orderby tablicatablic.First().Count() descending
     select tablicatablic.ToArray()
     ).First() )
 {
        foreach ( string slowo in tablicaanagramow )
            Console.Write( slowo + "," );
        Console.WriteLine();
 }

Isn't LinQ amazing?

Thursday, February 21, 2008

Unable to cast object of type 'iTextSharp.text.Paragraph' to type 'iTextSharp.text.Table'

If you dig around the issue you will quickly discover that there are two possible solutions:

  • use <ignore> attribute
  • delete whitespaces between iTextXML tags

Luckily, another simple solution exists: the Parse method of ITextHandler accepts XmlTextReader as a parameter. You just use this feature:

XmlTextReader xmlTemplateReader = new XmlTextReader( source );
/* 
 *  this is crucial for iText to work correctly 
 *  WITHOUT <ignore> and
 *  WITH whitespaces
 *  since whitespaces are automatically removed from the xml
 *
 *  remove the line to see the exception
 */
xmlTemplateReader.WhitespaceHandling = WhitespaceHandling.None;
 
/* iTextSharp stuff follows */
ITextHandler xmlHandler = new ITextHandler( document );
xmlHandler.Parse( xmlTemplateReader );

There is also another possibility that leads to this exception - it is when the XML document contains table data that do not match the schema. For example if you have:



<itext author="Bruno Lowagie" title="curriculum vitae">
  <chapter numberdepth="0">
    <section numberdepth="0">
      <title font="Times New Roman" encoding="CP1250" size="13" align="Center" 
       leading="13">Title</title>
      <table width="100%" widths="70;70;70" cellspacing="0" cellpadding="2" columns="3" 
       borderwidth="1" left="true" right="true" top="true" bottom="true" >
        <row>
          <cell borderwidth="1" left="true" right="true" top="true" bottom="true" horizontalalign="Center" verticalalign="Default" colspan="3" grayfill="0.65">
            <phrase font="Times New Roman" encoding="CP1250" size="12" style="bold"></phrase >
          </cell>
        </row>
        SOMETEXTHERE
      </table>
    </section>
  </chapter>
</itext>
Note the misplaced "SOMETEXTHERE".