ILearnable .Net

May 20, 2009

params T[] vs IEnumerable<T>

Filed under: Uncategorized — andreakn @ 07:34

Just got bitten by a fascinating little gem.

I have extracted the essentials in the code below. What do you think the output is?

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            Console.WriteLine(p.DoStuff(5, 6, 7));
        }

        public string DoStuff(IEnumerable<int> ints)
        {
            Console.WriteLine("ienum");
            return "avg = "+ints.Average();
        }
        public string DoStuff(params int[] ints)
        {
            Console.WriteLine("params");
            return DoStuff(ints);
        }
    }

It prints “params” like its nobodys business before it crashes on a stackoverflow

The intent was of course to provide two methods with slightly different signatures that does the same, one calling the other under the hood. so if you have many ints you stuff them into a list, but if you have few you can call DoStuff with the ints directly. (no, my code didn’t calculate averages of ints, the ints are just for illustration)

Turns out that given an array of type T, the params method gets precedense. If you cast to an IEnumerable of type T, the other one gets preference

May 19, 2009

Shameless bid to get a licence for TypeMock

Filed under: Uncategorized — andreakn @ 12:46

I tried getting my hands on a trial version of TypeMock way back when it was first announced.

But as the license model back then was “either pay up or use it for open source”, and I didn’t want to pay up and wasn’t involved in any open source I couldn’t be bothered getting my hands on it. Since then I probably could have had a use for it at several clients’ but as I didn’t know pros/cons we have ended up using other stuff.

In order to get to try it out, here’s the shameless advert for typemock as stolen from typemock.com:

—-
Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle – and for the launch will be giving out FREE licenses to bloggers and their readers.

The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

Go ahead, click the following link for more information on how to get your free license.

—-

Can I get my copy of Typemock now ? 🙂

May 13, 2009

EPiServer convenience Extensions

Filed under: Uncategorized — andreakn @ 08:36

We have had a great time extending the API in EPiServer to provide conveniences that are easy to use.

extensions on pagedata relating to property values:

 public static bool HasProperty(this PageData pageData, string propertyName)
{
    if (pageData == null)
        throw new ArgumentNullException("pageData");
    
    if (string.IsNullOrEmpty(propertyName))
        throw new ArgumentNullException("propertyName", "propertyName is null or empty");
   
    var propertyData = pageData.Property[propertyName];

    return propertyData != null;
}

public static bool HasValue(this PageData pageData, string propertyName)
{
    if (!HasProperty(pageData, propertyName))
        return false;

    var propertyData = pageData.Property[propertyName];

    return !propertyData.IsNull;
}

public static T  GetValue<T>(this PageData pageData, string propertyName)
{
  return GetValue<T>(pageData, propertyName, default(t) );
}

public static T GetValue<T>(this PageData pageData, string propertyName, T defaultValue)
{
   if(!HasValue(pageData, propertyName))
       return defaultValue

    var propertyData = pageData.Property[propertyName];

    try
    {
        return (T)propertyData.Value;
    }
    catch (InvalidCastException)
    {
        throw new InvalidCastException(string.Format(
                                           "Property '{0}' on page {1} is not compatible with {2}. Property type is {3} ({4}).",
                                           propertyName,
                                           pageData.DebugString(), typeof(T).Name,
                                           propertyData.Value.GetType().Name, propertyData.Type));
    }
}

Extensions relating to childpages


public static PageDataCollection GetChildren(this PageData pageData)
{
    if (pageData == null)
    {
        throw new ArgumentNullException("pageData");
    }
    return pageData.PageLink.GetChildren();
}

public static PageDataCollection GetChildren(this PageReference pageReference)
{
    if (pageReference == null)
    {
        throw new ArgumentNullException("pageReference");
    }
    return DataFactory.Instance.GetChildren(pageReference);
}

public static IList<PageReference> GetDescendents(this PageReference pageReference)
{
    if (pageReference == null)
    {
        throw new ArgumentNullException("pageReference");
    }

    return DataFactory.Instance.GetDescendents(pageReference);
}
public static PageData GetPage(this PageReference pageReference)
{
    if (pageReference == null)
    {
        throw new ArgumentNullException("pageReference");
    }
    return DataFactory.Instance.GetPage(pageReference);
}


naturallty, (for me at least) all these extension method reside in the same namespace as the classes they are extending. It makes the API super-easy to use, and we don’t have to remeber special namespaces

May 12, 2009

EPiServer R2: TemplatePage.CurrentPage never null

Filed under: Uncategorized — andreakn @ 14:11

In the good old days (4.5) you could rely on the CurrentPage property to be set if the page you were looking at was in fact a fully populated EPiServer page, or more importantly: You could rely on it *not* being set if the page you were on was *not* a fully populated EPiServer page. Nowadays the CurrentPage property is *always* set, either to a page as ordered or to the start page if nothing else, but with a bool: this.IsDefaultPageLink  set to true if it sorta shouldn’t be there.

I’d have called the bool this.IsNotReallyHere

but what do I know….

Setting a cookie from within iframe on different site

Filed under: Uncategorized — andreakn @ 11:14

The site I’m working on is accessed through partners’ sites through iframes. ie: users log in to the partner, the partner opens an iframe to our site, (with encrypted url params (shared timestamp) ) letting us know who the user is, and in effect logging the user into our site. We could have used cookieless sessions to store the users info (you end up with a kind of GUID in the urls) but that would not be very safe, any haXor between the user and our web servers could read the request url, containing the sessionId and spoof the user, even if we are running under https. And as we are handling monetary transactions, safety is kind of important.

This means we need to fall back to using a cookie based session management, where the sessionId will be safely encrypted inside the https request. For most browsers saving cookies emitted by a site within an iframe is no big deal. but Internet Explorer (!) is a bit more picky. If the iframe is directed at a different site (which it is in our case) then cookies are ignored by default. There are two ways around this:

  • Get all your users to set their privacy settings in IE to their lowest setting. (obviously not a viable solution)
  • Use the P3P protocol to inform IE that you’re not a criminal.

the p3p protocol is thoroughly documented here and boils down to the following:

<META xmlns="http://www.w3.org/2002/01/P3Pv1">
<POLICY-REFERENCES>
 <POLICY-REF about="/w3c/mysite.p3p#mysite">
 <INCLUDE>/*</INCLUDE>
 <COOKIE-INCLUDE/>
 </POLICY-REF>

</POLICY-REFERENCES>
</META>

if you need different policies for different parts of your site you specify paths with the include element

  • Add a .p3p file on the location specified (with relative url) in the p3p.xml (this file can be generated by the p3peditor) ( when using the p3peditor you can check to see if the policy you are defining will be accepted by IE on the default trust level (medium), check the “HTML Policy” tab.  => “Policy Evaluation”
  • make sure IIS outputs the .p3p file (you might have to setup mime-type) (through management console in IIS5/IIS6 or config file in IIS7):

<system.webServer>
 <staticContent>
 <mimeMap fileExtension=".p3p" mimeType="text/xml" />
 </staticContent>
</system.webServer>

  • add a response header containing a compact version of your policy (replace the *REPLACE_ME* in the example below with your policy settings. The compact form can be generated using the p3peditor.(through management console in IIS5/IIS6 or config file in IIS7):
<system.webServer>
<httpProtocol>
 <customHeaders>
 <add name="P3P" value="policyref=&quot;/w3c/p3p.xml&quot;, CP=&quot;*REPLACE_ME*&quot;" />
 </customHeaders>
 </httpProtocol>
</system.webServer>

That should do the trick.

The free p3peditor isn’t exactly the most intuitive piece of software in the world, so there is an alternative that’ll set you back about $39. Supposedly, it’s easier to use.

May 7, 2009

Getting Win7 into Acer Aspire 1

Filed under: Uncategorized — andreakn @ 05:51

I got my ridiculously small netbook in the mail yesterday, and spent a short while figuring out hot to get win7 onto it as it doesn’t have any dvd-rom.

I ended up making a bootable USB thumb drive (Kingston data traveller 8GB).
Making it bootableusing vistas GUI didn’t work for me, so I used diskpart.exe

after installing win7 I noticed the fan was really starting to bug me. the internal fan and the HDD is just similer enough in their frequency that intereference patterns are created. pretty annoying.

Anyway, I googled for a bit and discovered a nifty little tool specially designed for the Aspire 1: AA1FanControl. http://www.computentsystems.de/aceraspireonefancontrol/

I started it up, and I haven’t heard the fan since. NICE!

May 6, 2009

jQuery fires global methods when dispatching events

Filed under: Uncategorized — andreakn @ 07:20

Just found a bug in our app that had me flabbergasted a bit. Turns out the problem was that we had a global javascript function called showCongratulations(){…} that would display a congratulation message to a user who had just won a prize, and we had a jQuery event called ‘showCongratulations’ (which together with the event ‘hideCongratulations’ would control whether these messages were displayed at all, the user could choose to fit his need). So whenever a user chose that he wanted these messages when he won, he would get one immediately. because jQuery would call our global showCongratulations() method when we triggered the ‘showCongratulations’ event.

I don’t exactly know why jQuery does this, as it has a perfectly capable event pub/sub model, might be thought of as a nifty shortcut to have a function auto-subscribe to the events.

anyway: beware that you don’t name the jQuery events things that correlate to global functions, or if you do so that it is a really hacky way (IMHO) to autosubscribe to the correlating event.

Create a free website or blog at WordPress.com.