Ctrl+N, persisted viewstate, persisted pain

I can’t get into the exact details here, but suffice it to say, that when you stray out of the standard viewstate-sandbox (ie LoadPagestateFromPersistenceMediume & SavePageStateToPersistenceMedium), be very careful.  Once you get viewstate out of that page and you consider users who use multiple browser tabs (yet with the same application session, or worse, new windows launched with Ctrl+N) there are a few subtle design considerations.  This guy’s article provides one solution.   If you also deal with multiple nodes (like a Web Farm), just persist to a shared location (Network share, NAS, whatever).

J

Tsql rank can come in handy

OK, i had a scenario where the database contained data with non-unique names, but we wanted to force the names to appear unique.  For example, if you had “TheThing” and it was repeated 3 times, we’d want “TheThing(1)”, “TheThing(2)” and “TheThing(3)”.  I had to do this all in Tsql since its in a SSRS report and that’s the clearest way to do this for the given situation.

So, I’m sure there are lots of other ways to do this (feel free to supply those via comments), but I used a temp table, and the tsql RANK() function to do it: 

 

CREATE

TABLE #DuplicateNamesWorkAround(Id int, Name nvarchar(100),DuplicateExists bit,NameRank int)

INSERT
INTO#DuplicateNamesWorkAround
SELECT t.id, t.Name,
(SELECT CASE
WHEN COUNT(*) >1 THEN 1 ELSE 0 END
FROM TableWithDups t
WHERE t.Name=t.Name) AS DuplicateExists,
— We’re creating a rank partition made up of the name with a hard-coded suffix.
— By doing so, we can get a rank thats unique per partition, and not across the
— entire resultset (since we want to append rank numbers to the name to give
— unique names).
RANK() OVER(PARTITION BY(
SELECT CASE WHEN COUNT(*) >1 THEN t.Name + ‘DUPLICATE’ ELSE t.Name END
FROM
TableWithDups t
WHERE t.Name=t.Name group by t.Name

 

 

 UPDATE #DuplicateNamesWorkAround
   
SET Name=Name + ‘(‘ + CAST(NameRank AS VARCHAR(2)) + ‘)’ WHERE DuplicateExists=1

Nothing amazing, and perhaps there are better ways with counters and cursors, but this worked for me.

Extension methods are legal Crack!

Ok, so we know this feature will become horribly abused and nobody’s going to know where the hell methods are defined.  But, come on, you know you love this:

DropDownList cboProfiles;
int  selectedValue=
this.cboProfiles.SelectedValue.ToInt();

OR

int  selectedValue=  this.ViewState[“MyKey”].ToInt() ; Courtesy of these trivial extension methods: public static class TypeHelper
{
    public static int ToInt(this string value)
    {
        return Convert.ToInt32(value);
    }
    public static int ToInt(this object value)
    {
        return Convert.ToInt32(value);
    }
}
 

Admit it, your looking for a way for your next hit!J

WCF and HTTP request is unauthorized with client authentication scheme ‘Ntlm’

 This turned out to be “fun”, so I thought I’d share.  OK, i have a few WCF services that call each other, all on the same network.  I create dynamic proxies (not anything generated by svcutil) as i needed the flexibility, but still using straight up WCF stuff, nothing too fancy.   The consumers might be .net or java, or php, so to keep things open to all, I went with the httpBasicBinding, and figured I’d stick with Windows Authentication to keep things simple (we can always come back later and make things more custom/complicated as needed).   So, I set up the binding as follows, and this worked fine (for a while):

<binding name=ServiceBindingBasic sendTimeout=00:1:00 maxReceivedMessageSize=10000000>
<
readerQuotas maxArrayLength=10000000 maxStringContentLength=10000000/>
<
security mode=TransportCredentialOnly>
<
transport clientCredentialType=Windows />
</
security>
</
binding>

Then, after a few months, I started seeing this message on my [somewhat new] XP machine:
The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘Negotiate,NTLM’.
Yet, when these services were installed on Windows Server 2003 sp1, no issues.  At the end of the day, the credentials were’nt flowing correctly from one machine to another, and when I finally found a small article that had one tidbit that worked,  I got past this thing.  I needed to set this on my dynamic proxy:
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
So, if you ever see this error message, or a derivative of it, don’t go chasing down things like this crap until you’ve ensure your TokenImpersonationLevel meets whatever your requirements are.

I must admit, WCF security is a huge topic, and I certainly don’t lay claim to expertise in this area, so also consult others!

J

 

Asp.net ajax (3.5) serialization and extension methods

ok, so the IDE is much slower when designing web forms, but other than that VS 2008, the 3.5 flavor of Asp.Net Ajax, and .net 3.5 in general rock the casbah big time.

For example, today I had to whip up a little code to serialize a small object graph to the client, so that I can allow users to interact with a couple UI controls, whose combined selection displays a result.  It would be crazy to do a postback, and even silly to do an async ajax retrieval, as simply caching the object graph yields the very best user experience.

The new System.Runtime.Serialization.Json.DataContractContractJsonSerializer rocks.  Combine that with a tiny extension method (see this article)  and the serialization is easy.  On the client-side, just use the Sys.Serialization.JavaScriptSerializer.deserialize(‘[your JSON here]’) and you are off and running.  Very clean, very simple, very nice job Microsoft!

 OH, by the way, i’m using the ajax slider, very slick as well! 

 J

Tips for preparing text files (for later use by BCP)….

Naturally, the first choice is to just use BCP itself:

bcp “SELECT * MyDataBaseNameHere.MySchemaNameHere.MyTableNameHere”  queryout c:\blah.csv  -S ServerNameHere -T -t “|” -c

 Or, for those little times where you just need a delimited bunch of rows of the data in a table, do the following to leverage Sql Server Management Studio:

  1. Open a new query window.
  2. Set the Query\Results To\Results to Text
  3. Go to Query\Query Options \Results\Text and make the following settings:
    • Output format:  Custom Delimiter
    • Specify the custom delimiter
    • Turn off “Include column headers in the result set”
    • Expand the Maximum number of characters displayed ( set to the highest of 8192)
  4. Run your query, copy the text into your text file.

Ok, kind of a lame post.

 J

c# 3.5 Automatic properties….sweeeeeet….

So, in c# 3.5, this code:
public int Property1 { get; set; }

gets compiled by csc.exe into:

[CompilerGenerated] private int <Property1>k__BackingField;

public int Property1
{
    [CompilerGenerated]
    get
    {
        return this.<Property1>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        this.<Property1>k__BackingField = value;
    }
}

 Nice!

Ajax mashup (and technie goodness)

I finished that ajax book a few weeks ago.  Of course, reading never gets me too far, I always have to have my hands on the ‘ol keyboard for this stuff to actually sink in a bit more.  So, i’ve been creating a mashup that is similar in spirit to some of the examples in the book, and using a number of new or emerging technologies to do it (which is great).  Its a really simple little 1-pager app that pulls a few concepts together using the asp.net ajax library from Microsoft (and no, i’m not using the simple [but handy] update panel in any of this). 

 One thing I really noticed while reading the book was how little I’ve leveraged javascript (turns out there’s more to it than getElementById), or used it in a more traditional programming sense (um, except that whole strong-typing thing). 

 So, i set forth to create a little application that had nothing but a single javascript option instantiated, which internally, did everything from creating the UI, to making all the Ajax calls, to responding to user interaction, etc.

 I’ll swing back later and give more details and probably push the javascript goop up here soon, but basically the application brings together a custom database of people and addresses, allows for searching for items, drilling down on more detail on an item, including loading that info into Google maps, and brining in the location’s weather data (from the Weather Channel’s weather feed), and never submits the page.

Again, its really simple (the javascript object which is the workhorse has barely over 230 lines of code), but it does help solidify some of the concepts and features of some of the technologies.

Quick rundown of technologies used for this mashup:
– C# 3.5
– asp.net ajax using the native JSON support
– LINQ to SQL (minor tweaks to the sqlmetal.exe-generated code to work with the JSON serializer though, because the generated code had cyclic references, which that serializer chokes on.  Simply comment out an entitie’s parent relationship to avoid that explosion).
– WCF (the new WCF Web programming model in .net 3.5, which is how asp.net ajax can use a WCF service as an <asp:ServiceReference  />)
– Google Maps (love google)
– The Weather Channel’s weather feed (very nice, and pretty imagery too!)
– A bunch of CSS positioning, some animated gifs, and a whole lotta fun

I’ll post the code if anyone [reads this blog or…] wants it.

J