Allan S. Hansen

I experienced the following rather unhelpful exception at work today.
Padding is invalid and cannot be removed

With a stacktrace something along the following:

System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) +7596702
System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) +208
System.Security.Cryptography.CryptoStream.FlushFinalBlock() +33
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) +225
System.Web.Security.FormsAuthentication.Decrypt(String encryptedTicket) +246

After doing some searching and more or less complex debugging, and resetting the application pool and what not, I find the simple solution.

I had two projects running on my localhost which both used the default cookie name for forms authentication, which then apparently conflicted with each other. Do’h.
But well, problem solved.

Some days ago a YouTube video appeared of a Danish women looking for the father of her child – which she supposedly met some evening and didn’t remember the name or nationality of.
The video can be seen here: http://www.youtube.com/watch?v=F8Seo5j_mNU
Now, many people thought it was real and it sort of vent “viral” which can be seen in the comments.

It has now been revealed that the video is a fake (oh the horrors – welcome to the Internet)  and is an advertisement from a Danish ad agency to promote “Denmark”, called “VisitDenmark“.
Well – that’s that to begin with, and I didn’t really care …. until I saw a representative for the agency in the news on a Danish TV station talking about he trick, which prompted my reaction.

The representative, sad there and kept repeating a memorized mantra that it was to promote awareness of the place called Denmark (duh)  and when asked if they had thought of the consequences and image they’d project of the Danish women, she repeated another memorized line of keywords – that they believed it promoted an image of “independent” women, taking “choices” in a “society” which allows them to take their own choice…….and other such keywords.
If I were a specialist in body language however, I’d also say she was lying about that – as she spoke those memorized keywords with erratic movements of upper body and head, and the attempts at emphasizing the keywords compared to the rest of the words, but I’m not a specialist – so….. It just looked like it wasn’t a reaction they had anticipated and needed to come up with excuses fast.

Funny though – my, and many others, impression of the messaged conveyed, was instead that they promoted Danish women as easy, willing to sleep with random tourists without knowing their names or nationality.
Visit Demark and try our easy women…. That’s the message they convey in my opinion.
The general reaction so far from people and politicians alike are also that it is distasteful attempt of promoting Denmark, and many remarks on both YouTube and elsewhere are the same interpretation as mine.

I guess we’ll see if this plan creates publicity and works or not…. Because I’m not a subscriber of the “any publicity is good publicity” theory – many people deliberate avoid products when displayed in stupid adverts or when companies lies to the public. This is no difference whether it is milk bought in the supermarket or awareness of a nation.

I can’t wait to see the consequences for VisitDenmark – because I’m sure we’ll see some and this case isn’t over yet.

Edit: I’ve added a new link because it seems the original one was pulled. Long live the internet. :)

Some time ago Google announced more insight in how the nofollow
attribute worked, and since then I’ve received an explosion in comment
spam.

So now I’ve taken the liberty of enabling moderating of comments, to
stem up against this inrease in spams – too bad people have to ruin it
for others.

Funnily enough some of these spamming idiots have the gall to put
“nospam” in as e-mail address ….. so I guess spam is an issue for them
as well. 

With any luck, moderated comments will just be temporary, but
well – it never hurt anybody to wait a little while with putting a
comment on-line.

Today I was faced with a problem where the close method on a SQLDataReader took ages – well 10 seconds or so – to complete.

Then I read the following snippet from the documentation:
The Close method fills in the values for output parameters, return values and RecordsAffected, increasing the time that it takes to close a SqlDataReader that was used to process a large or complex query. When the return values and the number of records affected by a query are not significant, the time that it takes to close the SqlDataReader can be reduced by calling the Cancel method of the associated SqlCommand object before calling the Close method.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx

So I tried calling cancel on the command prior to closing the reader and presto – the SQLDataReader closed very fast.

Once again, reading the documentation solved my problem and from this day on, I'll try to cancel the command prior to every close, just to see if it saves some time :)

I mentioned in my last blog post that you can use scripts in XSLT, so I just wanted to show shortly how you can use scripts to show the power it can yield.
Firstly – add a namespace to your XSLT file:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:scripts="urn:scripts.this">

Then you can use the scripts in various situations.
For example, I had to parse some “Yes” and “No” into Boolean strings “true” and “false” (for business logic reasons) so I made a script for that in the bottom of my XSLT file (I made the scripts in C# syntax):

<msxsl:script language="C#" implements-prefix="scripts">
    <![CDATA[
        //return true or false as string instead of "yes" and "no"
    public string getBooleanString(string s0)
    {
      if ((String.Equals(s0, "yes", StringComparison.OrdinalIgnoreCase))
      { return "true"; }
      if (String.Equals(s0, "no", StringComparison.OrdinalIgnoreCase))
      { return "false"; }
      return s0;
    }
    ]]>
</msxsl:script>

Now, I could use this script in my XSLT matching like this:

<xsl:value-of select ="scripts:getBooleanString(./VALUE)"/>

This makes a call to the C# script “getBooleanString” with the value, the script will test it for “Yes” and “No” and return “true” or “false” respectively, or the string itself it it wasn’t one of the two.
Some of the other things I used this for was to compare strings case with case insensitive, and to hold temporary values to avoid having to run through my XSLT file multiple time in the transformation process.  I also had to convert some number formats to use period as decimal point instead (due to language specific settings), so I made a script which changes between period and comma.

It is a powerful tool to have in the XSLT toolbox.

Jun 012009

I have been working quite a bit with doing XSLT on some large XML files lately.
During this I worked with the XslCompiledTransform class in .NET, which make transformations really easy and it works very fast.

An advantage of this class is also that it enables you to utilize scripts within your XSLT file, which enables you to make for example C# functions, for various tasks. I’ll write more about that in a later blog entry to keep this one simple and to the point.

The syntax (in vb.net) for doing a transformation using XslCompiledTransform is as simple as the following:

 'Create settings which eanble scripting in the XSLT file
Dim xmlSettings As New XsltSettings
xmlSettings.EnableScript = True
'create a XML reader for the XLST file
Dim xsltFile As XmlReader = XmlReader.Create("XSLT FILE")
'create a Transform object
Dim xslTransform As New XslCompiledTransform
'Load XSLT file with Settings into transform object
xslTransform.Load(xsltFile, xmlSettings, Nothing)
'Do the transformation.
xslTransform.Transform("INPUT XML FILE", "OUTPUT XML FILE")

The main disadvantage I’ve found for using this transformation is the huge memory usage it uses.
In my own situation, the process used about 3.5 times as much memory as my source XML file, meaning that a source file about 450MB my .NET process was killed on a 32 bit computer with an out of memory exception.

The actual memory usage will of course vary depending on how complex your transformation is, so the 3.5 number is not meant to be nothing more than an indicator that it is memory intensive.
It is however very fast, and I managed to transform very large files in a manner of seconds, thus if you can live with the memory consumption it is quite effective.

Having to do some optimizing of processes over the last period of time, I decided to do some quick benchmark of the various string comparisons, to see how they performened against each other.

The ones I was interested in was the String.Equal and String.Compare, so I decided to make some quick testing.

I made a WinForm and used the following code to test with:

      For i As Integer = 0 To 100000

            If String.Equals("item", "ITEM", StringComparison.InvariantCultureIgnoreCase) Then

                Debug.WriteLine("yes")

            End If

        Next

        For i As Integer = 0 To 100000

            If String.Equals("item", "ITEM", StringComparison.CurrentCultureIgnoreCase) Then

                Debug.WriteLine("yes")

            End If

        Next

        For i As Integer = 0 To 100000

            If String.Equals("item", "ITEM", StringComparison.OrdinalIgnoreCase) Then

                Debug.WriteLine("yes")

            End If

        Next

        For i As Integer = 0 To 100000

            If String.Compare("item", "ITEM", True) = 0 Then

                Debug.WriteLine("yes")

            End If

        Next

        For i As Integer = 0 To 100000

            If String.CompareOrdinal("item", "item") = 0 Then

                Debug.WriteLine("yes")

            End If

        Next

        Dim regex As New System.Text.RegularExpressions.Regex("item", System.Text.RegularExpressions.RegexOptions.Compiled Or System.Text.RegularExpressions.RegexOptions.IgnoreCase)

        For i As Integer = 0 To 100000

            If regex.IsMatch("item") Then

                Debug.WriteLine("yes")

            End If

        Next

The specifics of the code aren’t that interesting, it was mostly to create some comparable numbers, so I use just one string “item” to compare to “ITEM” (except for CompareOrdinal, which is mostly there as a benchmark).

Anyways I was quite surprised at the numbers when I ran the code through RedGate’s ANTS performance profiler.

For the String.Equals with the various options, the following numbers were meassured:

StringComparison.InvariantCultureIgnoreCase gave 51.490ms (the actual number is irrelevant, it is the relative difference I’m interested in)

StringComparison.CurrentCultureIgnoreCase gave 65.747ms which is close enough to the above that I’ll say those two are quite similar.

StringComparison.OrdinalIgnoreCase however only took 12.378 for the same amount of iterations and true checks. This surprised me a bit.

String.Compare took 66.004ms, which is similar to the CurrentCultureIgnoreCase.

CompareOrdinal only took 8.056ms, but of course is case sensitive, so it doesn’t quite match up to this situation (unless you spend less time running a ToUpper on your compare clauses).

RegEx.IsMatch took a staggering 375.127ms with compiled and ignore clause, but then again – you shouldn’t use regular expression for something as trivial as this anyway. Regular expression is a very powerful tool in its own right, this was just to compare.

The big surprise is that there is such a big difference between using StringComparison.OrdinalIgnoreCase in your String.Equals compared to the other options. I’ll refer to the msdn documentation for the specifics of the different types (http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx) , but shallowly said – the Ordinal as the name says ignores culture specific matching.

So if that is acceptable in a given situation, using String.Equals with OrdinalIgnoreCase is by far the best option when comparing strings.

Again note the numbers aren’t numerically important, the relative difference existed as I ran the code several times, with OrdinalIgnoreCase winning out significantly each time.

In a production function I had made, I was able to shave several percent off my execution time, simply by switching from String.Compare to String.Equals with OrdinalIgnoreCase option used.

That was an easy way of gaining performance in my book.

I love using the WITH statement in VB.NET/ASP.NET because it eases up on the typing and helps “group together” functionality.
However, I found a fun little something when using the WITH statement, which I wanted to share.

It seems that you can assign a new object reference within a WITH statement to the specific object, however you can’t assign values to said new reference. Strange indeed, but I’m sure there’s some underlying reason.
Here some code to illustrate.

Suppose I have a class:

Private Class Test
        Private m_Text As String

        Public Property TextValue() As String
            Get
                Return m_Text
            End Get
            Set(ByVal value As String)
                m_Text = value
            End Set
        End Property
End Class

Then I have some code which uses this class in a WITH statement:

Dim obj As New Test()
obj.TextValue = "Test"
  For i As Integer = 0 To 10
   With obj
     If Not String.IsNullOrEmpty(.TextValue) Then
          System.Diagnostics.Debug.WriteLine("VALUE: " & .TextValue)
    Else
         System.Diagnostics.Debug.WriteLine("VALUE NOTHING")
    End If
    obj = New Test()
    .TextValue = "test" & i
   End With
Next

When run this provides the output:
VALUE: Test
VALUE NOTHING

And "nothing" for every subsequent run.
So it is possible to assign a new reference to the “obj” object reference, but the assignment of the new TextValue is ignored.

Not that usefull, but fun enough in my book :) (yes, I’m a geek

Recently I’ve grown increasingly tired of television and the fact that stupidity and mediocrity is celebrated to the degree it is. The most annoying thing is that we pay good money for the privilege to have half-assed game shows or reality programs with people whose only prerequisite is – well, what’s the opposite of talent and smarts.

Not a few days ago I was channel surfing and stumbled upon a game show where some random person had to tell answer truthfully to some (very) private questions, and they’d win money if the lie detector matched their answers. 

Of course these people are casted so the ones with most dirty laundry are accepted – nobody would reward me for sitting there revealing mundane secrets: “Are you afraid of spiders?”, “yes”, “congratulations you’ve won XXX money”.
Anyways – the questions I’ve been able to bring myself to watch before moving on in despair for the human race, was about how the person had been cheating on a significant other, or taken drugs, or stolen from friends, or been in jail for violence or…..
Okay, one thing is bringing yourself to tell these things on public television – but what struck me as most annoying, most insane, most absurd – was the audience reaction.
They applauded and cheered the person on when answering truthfully. “Have you stolen money from somebody who’ve helped you get out of drug problems?”, “Yes”, queue audience cheering and applauding.

One thing is these sad people get on TV, another is celebrating them. Who’s the culprit – the ones visiting the show, getting paid for being messed up;  Or the ones cheering them on?
As much as I dislike the stupidity of the people going on the shows – I dislike the audiences even more. The people watching and the people reading the tabloids for new exciting information about the breakfast of contestants, and what not.

Another show I saw recently was somebody who where in economical problems. Now granted that is serious problems – but the real kicker here is that they earned so much money to begin with. They were rather wealthy and still used a load more than they could afford.
What about instead of using resources on wealthy people, the networks take those money and spend on the real unfortunate ones. The ones without job, without income, actually living on the street. But I digress – that isn’t TV worthy and doesn’t pull in ratings – but somebody spending 10 grand more than the 50 they already earn each month is?
Seriously….what is up with this?

Well sure, some credit is due, some TV shows do celebrate talent and brains and what not, and reward those – however it does not seem to be what is focused on even in those instances most of the time anyway.

Take something like the “singing contests” shows which we see en mass now in all countries and in various forms. Who do people turn in to see? The people who’re awful at it, getting chewed out by the judges – how we celebrate their stupidity. Quiz shows, then we still root for them to fail, to make a fool of themselves.  Because then we’ll all feel much better about ourselves. Beauty contestants answering poorly regarding atlas and education is celebrated online.
Survival shows or Big Brother or lock somebody away in a luxury hotel where they’ll have to vote each other off – oh the human drama aspect, the conflicts which pop up – that draw people in.

Are our own lives getting to be so damn boring that we have to celebrate the stupidity for it to somehow make our own lives more bearable or is it some sort of vindictiveness. “They’re not better than me; see how awful/stupid/evil they act/are”.

And strangely enough – I just saw the movie "Live!" ….. What a view into the future of television, and when thinking about it, the movie suddenly doesn’t seem that farfetched. Is it just a picture of things to come? Most likely.

So, finally got my VGA to DVI adapter only to find out that my monitor already supported VGA connection (d’oh), and then I got my old computer booted up.
Seems it contained a 700 MHz CPU and 256 RAM with a couple of gigs of hard drive. Plenty of power for my needs – perhaps a little too much for some of my old games, but we’ll see.

However it was extremely unstable, chrasing and locking up left and right and booting up very slowly – time to dig out a Win98 disc and reformat I think. Phew – can’t remember last time I reformatted a computer instead of just buying a new harddrive :D

Some other problems I noticed right off the bat was that even though there is a soundcard installed, it didn’t seem to produce any sound. So I will have to check whether it is installed properly, and if it even works.
The CPU fan made quite a lot of noise (dust problem I hope), so will have to look at that as well.
I’ll need to identify the graphics card, so I can install a proper version of direct X (5 or 6 most likely) which I’ll have to pull from an old disc, as I do not intend the computer to connect to the internet.
The running of a CD yielded a BSOD, which I hope will be fixed with a reformat – otherwise I might have to look into a new CD drive (properly around 4-16x speed) or burn my original CDs to new discs so I can test if it is scratches which cause the problem. Some of these CDs are old – back to mid 90s.
I’ll need to find drivers online for various things and get them burned down and installed. For example – drivers for my old Joystick (which is a Wingman Interceptor – best joystick ever), the soundcard (if it works), the graphic card and what else I find.

So there are still plenty of things to do to get it working properly – but with a bit of luck – I have the entire machine already build and only software problems remain and I don’t have to worry about hardware.

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera