Category Archives: Development

All things to do with coding

textarea highlight / select and scroll to text – cross browser – pure javascript

I wanted a cross browser solution to select and highlight text within a text area. Trawling the internet yielded some partial solutions.

But I could not find one that scrolled to the correct location without a hack or some jiggery pockery

So I took what others had done and made it better. This is a cross browser solution that works in IE, firefox and chrome

the code pure javascript


this is how to use it

how it works

Essentially, it uses the textareas full height (totalHeight), and the total number of new lines (totalLines). From this we can determine the line height

Now that we have the number of lines and the line height all we need now is to determine which line the selected text is on. To find this we take the total number of lines in the textare and deduct the number of new lines after our selected text

Finally to get the scroll to position we multiply the line number by the line position of the selected text

Windows.Forms Settings : Auto Save state (size and position) of all my Forms

We will cover three topics in one

  • Using a single settings variable to save ever forms window state
  • Base class inheritance in winforms
  • Data contracts and JSON

In a nutshell, we will serialise and deserialise into a strongly typed custom settings class to and from JSON to store out our windows forms window states, in a settings variable in the project, using a custom settings class that is present in a baseClass that every form within your project will inherit from

What are data contracts

A data contract is essentially a simple way of serialising a class into a string for storage and/or transport

In simple terms, when you mark a class as a data contract you are telling .NET that this class will have properties that can be stored as a string (in our case serialised to JSON).

this is how to mark a class as a data contract

And members that you would like to store in your JSON should be marked as data members like so

How do data contracts work with JSON?

A long time ago I wrote a generic serialiser/deserialiser to convert datacontract classes to and from JSON, this is the code

we are going to reference these function later in this article

How do we use inheritance in winforms

Windows forms classes that you are exposed to are essentially partial classes. If you have a project open that contains a Windows.Forms.Form, then unhide all documents and take a look at the difference between the code behind the form that you see and the designer generated code. The file names will have this structure

  • frmName.vb
  • frmName.designer.vb

Partial classes are a really nice way to extend the reach of a single class, but separate the code file

So, create a baseclass ready to be inherited by all of your windows forms

  • frmName.vb
  • frmName.designer.vb
  • BaseForm.vb

create the project settings property

next we create our custom project settings property “FormSizesAndLocations”


The custom settings class

we need our settings class to be able to do the following

  • read the settings from the config
  • save a forms window state to the config
  • name, width, height, x position, y position, maximised, minimised

here is our custom settings class for saving window state and reading window state, note the data contract attribute and the data member attributes to those properties we want to persist

The BasePage class that will do all the work

Now lets create a base page class, in this class we will put the logic to handle the position save and load of any form that then inherits this class

Rather than describe the code, you should really be able to understand it, so lets dive into the forms base class

And there you have it

EWS & .NET how to get started

Getting started with Exchange Web Service (EWS)

Firstly you might want to configure your security groups as per my article titled “Exchange Web Service (EWS) configuration” then return and continue.

EWS is a powerful way to access Microsoft Exchange over https. Doing this via .NET is a doddle.

I am going to assume you know how to add a web reference to your .net project.

your exchange server will be publishing EWS on the following URL


All you need to do is add a webreference to your .NET project by pointing to the above url. The important thing to remember is that you will actually be using a different URL when it comes to binding in code. The url shape will be like this


Once you have your web reference in place, and in this example we will be calling the reference EWS, the first thing you are going to need to do is declare a new instance like so

The GetNewEWSBinding() returns a binding. The binding is on one of the mailboxes within the saEWSImpersonatable security group mentioned in the article previously mentioned at the begining of this one.
The following version of the function has a default binding mailbox defined in a variable at the package level of the SSIS package this script task resides in; it also checks for an InTest switch to swap between two mailboxes when in test or production. Binding credentials can be configured manually for a specific user, this user must be a member of the security group sgEWSImpersonate as described in the article mentioned at the beginning of this one. Finally there is an override optional parameter to provide if you wish to specify a specific mailbox to bind to instead of the default.
You can amend this to your requirements

As soon as you have your binding you are ready to start working with the mailbox.

In my next article on EWS, I will discuss how to declare your EWS binding objects using object initialisers, you will be able to declare and run requests against EWS using less code.
ie Dim x as object With {.parameter = value, .parameter = value}

ASP.NET Combine & Minify CSS & JSS on the fly (Also tested in Umbraco) in 5 easy steps

Automatically Combine, minify, compress and much more on the fly.
Here you will learn in 5 steps how to implement the combine and minify project originally from codeplex into any .net application. I’ve just tested this on an Umbraco installation and it works flawlessly, the project also makes use of 2 open source libraries.

The original project can be found I have converted this project from c# to vb and made some considerable further optimisations in the code around the caching mechanism.

The two other libraries included are:


Along with a lot of custom code to automatically provide a cached based minify & compress  for your css & jss files. But it doesn’t stop there you can also use this project to remove white space from the html rendering to the client (default operation), all comments and commented code in .js and .css file includes is striped , you can insert VersionId’s in font urls and images and even preload images.

Ok so lets break it down.

What does it do and how?

Taking the .js and .css includes in particular, during the request life-cycle of the .net engine combineAndMinify will scan the header of the page just prior to rendering to the client, it will collect up the .js and .css includes, minify, compress, remove comments and white spaces and place the new combined content into the cache. So that’s one cache record for the .js and one for the .css. It will then strip out all the include references from the page header and replace them with a unique include reference pointing to the cached version for the browser to process. in your webconfig you have told IIS that all requests to .js and .css files must be routed through the combineandminify class, so when the browser then requests the include eg 33212cce52b6065a.js, the combineAndMinify handler then pulls the content from the cache and sends it to the client.

This process optimises your site in two ways, it caches the includes, and provides the client with only one include per type to request from the server.

The unique names are calculated using logic on various aspects, for example if you wished that the caching occur per page or for the entire website at domain level.

Out of the box the combineAndMinify is intelligent enough not to touch any include that references a different domain, and is in fact very customisable in that respect.

Furthermore it also knows when any of the files that it has cached change and will automatically update the cached version on the active request the change has been detected on.

See the full spec on codeplex.

Configuration settings:

Config Attribute Default Value Possbile Values
removeWhitespace false true/false
insertVersionIdInFontUrls false true/false
insertVersionIdInImageUrls false true/false
makeImageUrlsLowercase false true/false
prioritizedImages true true/false
preloadAllImages false true/false
enableCookielessDomains Always Never
minifyJavaScript true true/false
minifyCSS true true/false
combineJavaScriptFiles PerGroup None/PerGroup/All
combineCSSFiles PerGroup None/PerGroup/All
headCaching None None/PerSite/PerFolder/PerPage/PerUrl
exceptionOnMissingFile Never Never/Always/ReleaseModeOnly/DebugModeOnly
active ReleaseModeOnly Never/Always/ReleaseModeOnly/DebugModeOnly

If your even half technical you can guess what half of these configuration settings do, if you need a further understanding on all the configuration settings please visit the codeplex project website because its beyond the scope of this how to.


  1. Copy the binaries to your bin folder and add references to them or include the project into your solution
  2. Copy and rename “HeadAdapter.browser.txt” to HeadAdapter.browser to your App_Browsers folder
  3. make the required changes to your web.config file
  4. change the combineAndMinify config attribute “active” from “Never” to “Always”
  5. test the solution in firefox, ie or chrome and verify the compression in firebug F12 Developer tools or FireBug Lite respectively.

The converted, enhanced version of the project compiled to binaries and other  files you will need:




If anyone has any problems at all, I will help where I can. If you want the version of this project then let me know and I’ll send it over.

How to make a copy of a NameValueCollection

This is a rare requirement but should you need to heres how

Where New_NVC is your new declared NameValueCollection and OLD_NVC is the NameValueCollection you wish to copy.

How to convert NameValueCollection to a QueryString and visa versa

I needed a full proof way to desipher a querystring that might potentially be slightly malformed
Similarly i also needed a way to build up a querystring, potentially replacing existing values while building the string

So a malformed querystring could be

I say malformed, this isn’t strictly malformed but if you tried to split this into an array of strings you might run into errors
So to pull this into a valid collection you do the following

Then to perform operations on the collection simply do the following

Here’s how to build a querystring, including easy ability to change existing values and turn it into a valid encoded querystring in one line

The output of FinishedEncodedQueryString is


Visual Studio VS 2010 not stopping at breakpoints

Ever wondered why suddenly you cannot debug because the compiler isnt breaking on your breakpoints.

There are several reasons for this.

make sure that.
1. Your project is compiling when you begin debugging (check this in build > configuration manager)
2. Ensure your projects are compiling in debug mode not release (check this in build >configuration manager)
3. In the Webconfig ensure you are in debug mode

4. The (project properties > startup options > debuggers has the ASP.NET checkbox checked)
5. Delete all pdb files in your bin folder
6. Ensure every project referenced is set to build under (build > configuration manager)
7. Do a full clean and rebuild. (build > clean solution) (build > rebuild solution)

Finally and this is the one that caught me out
8. Check you are not setting a cookie cache timeout of positive time, I was expiring my page after 1 day. The best way to check this is to load a page in debug, knowing your break point will not be stopped at. Once the page is fully loaded hit ctrl F5 to force full reload of the page. If your breakpoint is stopped at then you know its a cache problem.

jcarousel No width / height set for items

If you use jquery, then the chances are you are using the jcarousel library.

Well im new to jquery but have come along at an accelerated rate, perhaps because of my OO background.

Ok so you hit this page likely because you got this error

jCarousel: No width/height set for items. This will cause an infinite loop. Aborting…

When i tried to nail down what the cause was i stumbled across a post that told me to add css styles for width and height. This was all well and good until i wanted to apply styling to more than one carousel on the page. Anyway what took me a few hours to figure out I support open and collaborative minds by sharing it here.

The error occurs regardless of widthand height attribute of you jarousel item. You need to set the width and height of the first parent of the carousel. If you follow this design pattern below, you cant go wrong

Firstly im assuming you have already included a reference to your already downloaded jcarousel library. There is really only one of them so you cant go wrong in finding it. here

1. Markup for your page containing the jcarousel element (note wrapped in a containing div)

Your initialising jscript to bring your carousel to life (note applied to the ordered list)

Your CSS (note applied to the wrapping div)

The reason why we do this is because the jcarousel class ammends the html markup so that styles will no longer apply because the objects will no longer exist, or have the same name at the jcarousel object level.

Hope this helped those who were stuck as I was.

ASP.NET Master Page Nested inheritance

I seem to be asked this a lot so i thought i would mention this online so hopefully people will no longer ask me, they’ll find the answer when they ask google

You are trying to inherit from a masterpage and you recieve the following error

the page has one or more < asp:content> that do not correspond with < asp:ContentPlaceHolder> controls in masterpage

Script tags are the culprit around 80% of the time. For some reason the visual studio designer doesnt like not fully closing your script tags at design time.

Change all of you script tags from this

< script type="text/javascript" src="js/myjs.js" /> 

correcting it to this:

< script type="text/javascript" src="js/myjs.js" ><  /script>

Any you should be good to go.

Diagnostics.PerformanceCounter Input string was not in a correct format

when you try to get performance information you receive the following error at the initialiser

Dim Ram As New Diagnostics.PerformanceCounter(“Memory”, “Available MBytes”)

Input string was not in a correct format

Starting “perfmon” from your run box to open the performance monitor presents you with a message box

Performance Monitor Control
Unable to add these counters:

\Memory\Available MBytes
\Memory\% Committed Bytes In Use
\Memory\Cache Faults/sec
\Memory\Cache Faults/sec
\PhysicalDisk(*)\% Idle Time
\PhysicalDisk(*)\Avg. Disk Queue Length
\Network Interface(*)\Bytes Total/sec

Easy fix, you need to rebuild your performance counters. I copied c:\windows\system32\PerfStringBackup.ini from a machine whos counters were working, replaced the one on the broken machine. Open a command prompt, navigate to the same location and run the following

lodctr /R:PerfStringBackup.INI

This will reload your counters

If that fails try what microsoft suggest Here