Archive for the 'Languages' Category

Showing Query String parameters in a page in SharePoint

I came across an interesting little problem with putting query string parameters for an HTTP request into a SharePoint page.

I was using a Dataview web part, which accepts query string parameters into the filter that it runs over the data that it’s going to display. That’s pretty cool – I had a list of items with a status column, and I wanted to be able to filter the items based on that status, and that the status would come from the query string. However, on the page, I also wanted to show a title with what was being filtered by in it. So, for example, my url might read:

http://server/site/page.aspx?status=Ready

And I wanted the title in the page to read “Filtering by ‘Ready‘”.

What I didn’t appear to be able to do was to just use the request object . Something like

<%= Request.QueryString.ToString() %>

won’t work as code blocks aren’t, apparently, allowed in the file – the error message is “code blocks are not allowed in this file”. Okay, given that SharePoint designer is supposed to open these pages up to ‘Power Users’ I do get why code blocks aren’t allowed. But I really wanted to write code, and there had to be a way to do that. Well, Kirk Allen Evans has figured out how – you have to enable them in the PageParserPaths section of the web.config file. (It’s strange how easy it is to forget the web.config file that controls SharePoint sometimes). Just to repeat his example (in case blue and red on black is difficult to read):

<PageParserPaths>
<PageParserPath VirtualPath="/pages/*" CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>

This example allows code blocks for all files under the /pages directory of my web application – it’s worth noting that this is for the web application in IIS, not a SharePoint site collection or the like.

Okay, so that works – great. However, there are security implications, and this is probably best only used for development environments. I’ve written a bit about under what conditions our inline code will run.

In our instance our customer is kind of reluctant to make changes on their server. Changing the web.config file would be a bit of a big deal. (As a side note, this is a bit restrictive – I think a blog posting on that is due sometime). So what could we do without a server footprint?

Well, without code in the page, we would need a web control to call in that page – that would work also. It’d be trivial to write one. However, that requires deployment, marking as safe in the web.config file, etc., so really that just pushes the problem into another file.

Thus, I ended up getting a bit ‘old skool’ – JavaScript in the page to write the value from the query string on the client. I came up with:

<script type="text/javascript">
var query = window.location;
var regex = /letter=([^&=]+)/i;
var match = regex.exec( query );
if( match != null ) {
document.write( "Filtering by '" + match[1] + "'" );
}
</script>

Made a function, this became:

function getQueryParam(key) {
var regex = new RegExp(key+"=([^&=]+)","i");
var match = regex.exec(
window.location );
if( match != null ) {
return match[1];
} else {
return null;
}
}

What this code does is it gets the page’s url (window.location), runs a regular expression looking for the ‘letter’ parameter, and if it find one, it outputs some text to the document. A bit noddy, but simple and it works – with no server footprint. Of course, you do need JavaScript enabled…

Visual Studio Installer Projects and SVN

Installer projects in Visual Studio are for creating the Setup.exe and the MSI for installing the other projects in a solution. However, I discovered an oddity that caused havoc with our source control system. Read more »

Handling Errors when doing file IO

I came across a pattern in .NET that I’d not thought of before. The scenario is, I’m reading from a file and deserializing it’s contents (a List of ‘Foo’ objects). Exceptions can be thrown at two points:

  • When I’m reading the file
  • When I’m deserialising the xml

Obviously, I want to make sure that the file handle is released if the deserialisation fails. However, I can’t deal with that in a single try block, as if the exception is in the file IO, then the file handle won’t exist to close in a finally block! Read more »

.NET Framework versions, language versions, and CLR versions – all a bit fraught…

The .NET framework is a bit confusing until you get your head round the components of it, and the way that Microsoft name things.

.NET has a thing called the common language runtime (CLR). (This is the .NET equivalent of the Java Runtime). Different versions are essentially different VMs, and can coexist. The CLR runs code that is an Intermediate Language (IL) (aka the Common Intermediate Language (CIL)). Whatever code you write in C# or VB.NET actually only gets partially compiled into IL code. It’s a lot like Java Bytecode.

The Base Classes are the library of DLLs for the framework (and are sometimes incorrectly referred to as the framework). Think of it as Win32 for .NET. These constitute the .NET API – and have different versions too. A different version of the base classes, though, does not mean a different CLR – for example, frameworks version 2, 3 and 3.5 all use the same CLR, but present a different external API and have different language features. Indeed, the base classes of framework version 3.5 are a superset of version 3, which are a superset of 2. This means framework 2 code will run on machines with the 3.5 installed.

The languages have different versions too, and this is where things start to get confusing. The different language versions have different compilers, which emit backward compatible IL. This is to be expected since there is no new version of the CLR. In plain terms this means that all the new language features can be used with older projects. E.g. C# 3.0 code can run on the .NET 2 Framework, provided you haven’t used any of the libraries that are part of a later framework. The C# 3.0 code will be partially compiled into the same version of IL code as your C# 2.0 code, so the only problems come if you are using libraries that aren’t part of that .NET Framework.

 (Note to self – must remember – C# version is independent of  Framework version)

So why would you want to use C# 3.0 over C# 2.0? Well, the language adds a number of new features too – such as automatic properties, relaxed delegates, object initialisers, type inference, anonymous types, extension methods, lambdas and partial methods.

Hopefully this chart might explain things a bit. I’m pretty sure it’s right, although I’m recreating it from memory and can’t entirely remember…


Framework Version 1.1

Framework Version 2.0

Framework Version 3

Framework Version 3.5

CLR

1.1

2.0

2.0

2.0

Library versions

1.1

2.0

3.0 (including 2.0 sp1)

3.5 (including 2.0 sp1 & 3.0 sp1)

Similar chart here:

http://www.leonmeijer.nl/archive/2007/06/11/50.aspx

…though the Microsoft guy who presented to me didn’t say anything about a CLR 3.0. I suppose there may be one which is backwardly compatibile?

DateTimePicker – no BackColor property, not nullable

More Windows forms stuff. I don’t like really complex Web forms controls ‘cos sometimes they seem a bit flakey – but I’m beginning to wonder if Windows Forms stuff is any better.

Two problems with the DateTimePicker. First, it can’t have a null value. What? You might not want to have a value in it? That’s craaazzzy! Inconceivable! What do you mean that your database tables allow null values in a DateTime column?

All you can do is set ShowCheckbox to ‘true’. This will give you a little checkbox, to turn on or off the editing of the value. You could then wrap the DateTimePicker, and return yourself null if the ‘Checked’ value is false.

Secondly, it has no BackColor property, so I couldn’t colour it pink when the field was invalid, meaning it had to have a value – therefore, the checkbox mentioned above has to be ‘Checked’. I managed to get around this by subclassing the DateTimePicker – but had some problems when you then focussed on it to try to edit it. My solution (below) was to turn off any background colour during editing…

Read more »

TableLayoutPanel – doesn’t autosize or autoscroll correctly

I’ve been doing some Windows forms programming lately – not really my thing, but needs must. I’ve got an application which needs to dynamically create a form at run time, and so I’m using a System.Windows.Forms.TableLayoutPanel.

All the controls contained by the TableLayoutPanel resize automatically, and the TableLayoutPanel automatically provides scrollbars. “Great!”, I thought, “This will deal with large forms nicely.” Wrong!

The problem is when form has too many fields – it becomes deeper than the display area of the TableLayoutPanel. This is fine – the TableLayoutPanel should automatically add a vertical scrollbar, and adjust the size of the controls it contains to fit in the smaller area. Except it doesn’t. What I actually get is this:

Problems with TableLayoutPanel

Notice that I’ve got a vertical scrollbar, but it hasn’t resized the child components. This, they overlap some of the fields – and I now have a nice horizontal scrollbar. Arse.

I eventually found that others had had this problem and told Microsoft about it. However, they’ve decided not to fix it. Thanks Microsoft, that cost me an hour and half – it’d be wise to fix it. I found the answer from the same link – add a vertical scrollbar’s width as padding on the right of the TableLayoutPanel.

Add an event handler

I keep using this snippet of code:

if( window.addEventListener ) {
window.addEventListener("load", fn, false );
} else if( window.attachEvent ) {
window.attachEvent("onload", fn );
}

It’s just a tidier way of attaching a function ‘fn’ to an event. It also allows multiple handlers per event. There could be another ‘else’ where we just assign the function to an event (e.g. window.onload = fn ) but that would only support one handler per event.

Adding Snippets in Visual Studio

I keep forgetting how to do this, and have to do so every time I want to create a new SharePoint workflow.

  1. Open Visual Studio.
  2. Right click on toolbars and ‘Customize’
  3. Click ‘Commands’ Tab.
  4. Click on the ‘Tools’ category.
  5. Add the ‘Code Snippets Manager’.
  6. Add ‘C:\Program Files\Microsoft Visual Studio 8\Xml\1033\Snippets\SharePoint Server Workflow’ to your snippets
  7. It should be straight forward from there…

Comments from my old blog:

Are you using your own project templates? I’m curious because using the MOSS Workflow Project templates (both state machine and sequential)–the templates that come with the MOSS SDK–and I have the snippets already available to me.

Anyway, just throwing that out there.

By Peter {faa780ce-0f0a-4c28-81d2-3 at 17:30:01 Monday 10th September 2007

Nope, these are the ones out of the SDK. I’m not clear why, but in some VMs that I use the snippets aren’t immediately available after I install it. And normally the ‘Code Snippets Manager’ is already available too – but not always. I haven’t figured out what factor causes these things to occur :/

But yes Peter, you’re right – normally they should be available.

By Andy B at 11:16:21 Tuesday 11th September 2007

The Pain of VB6

So, I’ve been forced to spend a couple of weeks modifying some code I wrote a couple of years back, in VB6. One word – crap. That’s the word for both the language, and my code.

Visual Basic 6 is just painful to code with. ‘Dim’? I’d say. The inability to return arrays from a function keeps catching me out. And I detest the way that no matter what I do, I can’t stop Visual Studio beeping errors at me and show message boxes when I try to leave an incomplete line so that I can copy and paste a variable name.

The worst part is, though, that it doesn’t really promote good program structure – well, not to me anyway. I’m often not entirely convinced that Object Oriented Programming actually reuses much code – but it does force it to be structured and organised. My code in this project, well, it isn’t. It’s suffered that sort of ‘evolutionary’ growth rather than proper, designed expansion. And some of it has to excapsulate an API that is archaic, irritating, and dangerous. (I’ve been debugging for memory leaks, dammit. Yes, this API forces me to allocate/deallocate memory).

What a sucky language. It really makes you appreciate Java/C#.

Benchmark: Speed of Encryption and Decryption using .NET Framework classes

I was reading about security stuff in the .NET framework, and dealing with cryptographic classes in it, and it sort of set me wondering. Here are all these different encryption classes, with different block and keys sizes, cipher modes, all that jazz – but what are their performances like? Specifically, I’d read something saying how some ‘weaker’ encryption algorithms are better (in some speed-critical applications) ‘cos they’re faster. I wondered how much?

Thus, I decided to benchmark the Symmetric alogrithms in the .NET Framework – DES, Triple DES, RC2 and Rijndael. To make life interesting, I thought I’d try them with differenct key sizes and block sizes, and cipher modes.

So, I’ve linked to definitions of these factors, but for those who don’t want to read vast chunks of Wikipedia, here are my (simplified) definitions. For anyone really interested in learning how to program with encryption properly (and in learning why their 128 bit key probably isn’t 128 bits strong) I can strongly recommend the book ‘Practical Cryptography’ by Bruce Schneier and Niels Ferguson.

Symmetric ciphers are ones like you used when you were a kid. You have some operation that turns a message into garbage, and then the reverse of that operation turns that garbage into a message. Some algorithms don’t have a reverse – they are asymmetric ciphers, and are a whole different kettle of fish.

Keys are the password you use with your cipher. For example, if you’re cipher as a kid was to shift all letters in the alphabet, then the key might be the numbers of characters shifted. Big keys are harder to break. Think of it as being just like a password or PIN number. If I tell you that my PIN is 4 digits, you might be tempted to guess all 10,000 possibilities, and on average you’d figure my PIN out after 5000 tries. If my PIN was 8 digits, then there is 100,000,000 options – and you’re less likely to try all the possibilities, eh?

Block sizes. Well, okay, some ciphers work on blocks of data, rather than each byte (or each ‘letter’). These are block ciphers. There are also stream ciphers, where each byte is encrypted one by one. Anyway, in block ciphers there is a limit to how much data can be encrypted without ‘leaking’ information. Larger block sizes can encrypt more data without that leakage. (That’s not to say that the block has been decrypted, but an attacker could start to learn things about the contents of that block.)

Cipher modes don’t really have a parallel with how you did codes as a kid. I guess I would describe it that if the cipher is about how you make an apparently random set of bits, then the cipher mode is about how you then use them. There are lots of different modes, but the .NET framework classes only seem to support 3 – ECB (Electronic Cookbook), CBC (Cipher block chaining) and CFB (Cipher Feedback).

So, what are the algorithms:

  • DES – An old encryption standard, now regarded as offering poor security, but so widely used that it is still in operation as a legacy system.
  • Triple DES – An improved version of DES, made by essentially applying the DES 3 times.
  • RC2 – A moderately old encryption algorithm. Flexible key lengths, but short block size.
  • Rijndael (aka AES) – The latest encryption standard. The Rijndael algorithm was selected from several as part of a competition. It wasn’t regarded as the most secure, but it was quite quick. The Advanced Encryption Standard (AES) is actually a subset of Rijndael.

The Test

I found a nice text file – “The complete works of Shakespeare” – as my test data.

For each algorithm, for each mode, key and block size, the test program encrypted and decrypted the data twenty times, and reported the average ‘time’ for each operation. I was using the Win32 QueryPerformanceCounter function, which doesn’t really return a time so much as cycles. However, all the tests were done on the same machine, so they’ll do just fine for comparison purposes.

Results

With the several factors tested, there are many ways of slicing the data. It’s worth noting that these results are pretty rough, as the times taken also include file IO operations, and with any modern PC there’s also something else happening at any single time. Also, the times are the total time taken to encrypt and decrypt, which might not be the same for each operation. Treat the results as a loose guide.

First let’s look at the raw results. You can get the results here (Excel file).

Unsurprisingly, DES is fastest – given it’s age, and the low level of security it offers now. Triple DES with the longest key it supports was generally slowest. RC2 covered the full range of results, which is also unsurprising, given it’s flexibility, and Rijndael sort of falls in the middle.

The first thing I noticed was how few tests there were using DES or Triple DES. RC2 and Rijndael are much more flexible in their use.

Next, it’s interesting to note that RC2, DES and Triple DES using Cipher Feedback Mode (CFB) were all very, very slow. They all seem to suffer very badly using CFB.

So, excluding the CFB results then (as they are so exceptionally slow), what do the other results show? Well, Rijndael does not suffer so badly in CFB, although CFB is slower.

ECB appears slightly slightly faster in the table, though examining the CBC Mode Graph shows little difference.

To compare the modes, I looked at just the operations done with the Rijndael cipher.

Again, we see little difference between ECB and CBC, so I guess there’s no reason not to use the more secure CBC mode over ECB (for an example of it’s weakness see here). Also, for 128 bit blocks (as required by the AES standard), CFB is as quick as ECB.

Rijndael is not great in CFB mode with blocks of longer than 128 bits.

Okay, so let’s focus on just one mode (CBC) and look at the results shown in the CBC Mode Graph. Well, it’s interesting to note that RC2 with a 112 bit key was quite quick – faster than with some shorter keys. However, it’s only about 6.5% longer to use 128 bit Rijndael – which is a key that is 14% longer. Doubling the key with Rijndael to 256 was only 10% longer than 128.

Longer blocks take longer to encrypt and decrypt. 64 bit blocks seems a little short these days, only being safe for up to a couple of hundred megabytes. 128 bits seems more reasonable. 256 bits seems excessive. Rijndael seems to have little penalty for using 256 bits over 128, though if you do, you’re not using an AES standard encryption.

Conclusion

DES and Triple DES are old. DES isn’t secure, and Triple DES doesn’t seem to offer much given Rijndael and RC2 being much faster than it.

In terms of cipher modes, these classes only seem to support ECB, CFB anc CBC. ECB is generally regarded as being a poor mode – it’s not very secure. CFB was typically slower than CBC, and as Microsoft have already implemented the classes, some of the advantages CFB (i.e. encryption and decryption being identical operations) have been lost.

So, then examining Rijndael in CBC mode, well, there is little penalty for using 256 bit keys or 256 bit blocks. However, it’s probably worth sticking to 128 bit blocks as 1) it is plenty, and 2) it is AES compatible.

All in all, I was surprised by how similar a lot of the results were for different algorithms, and I was surprised by how slow some of the CFB mode operations were.

To be honest, I can’t really think of a reason not to use Rijndael with 128 bit blocks, in CBC mode. Unless time is a really critical factor, 256 bit keys are stronger. Finally, the RijndaelManaged class in the framework is a managed class, rather than a wrapper for a COM object.

So, the winner is Rijndael!

Comments from my old blog:

 

This is a very informative article. I have just started looking into encryption, and I have come across nothing on the internet that is as concise as your article.
Will you be doing something similar with asymmetric encryption as well?

By Firoz at 06:22:04 Friday 9th February 2007

 

Yup, well, at some point. The truth is, in the .NET 2.0 framework, there isn’t a lot of other asymmetric algorithms. RSA is about it. I think in the .NET 3.0 framework there is elliptical curve, and that would be interesting…

So, yes, when I get around to it.

By Andy B at 10:09:43 Friday 13th April 2007

« Previous PageNext Page »

 Subscribe in a reader