Category Archives: .NET

vb.net or asp.net or other .net related topic

HTML 5 ASP.NET Drag n Drop IE Chrome Firefox

drag and drop, cross browser support in asp.net

part of a project involved allowing a user to select from a list of 200+ items, and it needed to be easy. So, we decided to provide users with a drag and drop facility

Drag and drop has been around for quite some time, and its a little tricky to get it right. I’m going to show you the basics that i used to enable a drag and drop between lists

What are we after?

we want draggable lists that will do the following

  • Two lists
  • drag and drop
  • support multi select
  • support re order of list items

The end result

this is what the HTML will look like once the page has rendered, go ahead, give it a try. Try selecting multiple items then dragging them over

as you play around with the drag and drop, monitor your browser console to view the events that are firing

notice that when you change the selected fields the text area displays a comma separated list of selected items

Filter list
Choice fields

  • Name 1
  • Name 2
  • Name 3
  • Name 4
  • Name 5
  • Name 6
  • Name 7
  Selected fields

  • Name 8
  • Name 9
  • Name 10
  • Name 11
  • Name 12
  • Name 13
  • Name 14

 

This drag and drop is tied together with just 4 javascript functions, tied to the browser drag events

  • handleStartDrag()
  • handleDragEnter()
  • handleDragOver()
  • handleDropped()

there are ancillary functions that bind events and respond to the filter

  • fltrChanged()
  • UpdatehiddenFields()
  • bindUIactions()

How its done

In a nutshell

The rendered HTML

So whats going on ?

Well a few things are happening here, CSS is styling our stuff. ASP.NET is loading the repeater and generating our “li” elements for the un-ordered lists. And jQuery is doing the rest

the keys points to note here are:

  • the classes used {ctlDrop, ctlDrag} (for CSS and more importantly jQuery hooks)
  • the draggable attribute on the items tell the browser these are allowed to be dragged
  • the use if ID‘s and Data- attributes as hooks for our functionality

how it works

first up i will say you have to do a few inexplicable things to get drag and drop working, but its a given, just do it and don’t ask, or you’ll simply lose your mind like many other techies who ask the “why did they do that?” question. like me

1. enable jQuery to support passing a payload across drag n drop.
2. declare a variable in your class to hold the last entered item that the drag action has entered.

The singleton script layout looks like this

 

The Code

Loading the form

The code infront

jumping straight in, we need two lists, driven by some data source. Here is how we load the lists, using .net repeaters

Notice we have a hidden field in the right hand column, this will be used to stored the selected values, as the selection changes

Code Behind – the repeater code

On our data bind we add list items to the list, and some information to the each list item. Class, draggable, data-fieldName, data-ordinal.

jQuery – the ancillary functions

bindUIactions()

We will bind to the dragover and the drop event on the elements with class ctlDrop

We will bind to the dragstart, dragenter, drop and click events of the elements with class ctlDrag

Finally we will bind to the txtfltr element so we can filter our list

UpdateHiddenFields()

handling the collecting of the selected items into a comma separated list is relatively simple, and this function will be called from the end of the drop event

jQuery – The Drag and Drop routines

handleStartDrag()

The start drag routine, a must have to set the sllowed effect property, this is searchable on the drop if you need to.

handleDragOver()

The drag over routine, this is another must have, without this, obscurely no draggable item will drop. Don’t ask just do

handleDragEnter()

The drag enter routine, this is required because internet explorer doesn’t correctly record which element the drop occurs over, so here we record the last entered element before the drop. And thus we have cross browser compatibility

handleDropped()

The drop routine, this is where all of the hard work is done. If you are a public facing website you might want to add screening of the mime type that is dropped, just incase its not what you are expecting. I’m not doing that here, our project was internal

 

the javascript file is available for download here dragndrop

the CSS is available for download here dragndrop CSS

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”

projectsettings

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

asp.net ReportViewerControl The size of the request headers is too long

Bad Request – Request Too Long

HTTP Error 400. The size of the request headers is too long.

When you use the “Microsoft.ReportViewer.WebForms”control in asp.net

You’ve eaten too many cookies Reserved.ReportViewerWebControl.axd

If like me you use the report viewer control to display reports from SSRS to the world wide web you may have come across an ever increasing number of cookies from the control.
I don’t really have time to look into this in any detail as im working to a deadline at the moment and as such need to resolve this asap.
I think this is perhaps something to do with the fact I am using masterpages with iframes to both separate the CSS and pull out the parameters into an intermediate step.

Anyway my solution was to wipe the cookie from the request cookies collection so they dont get a chance to stack up.
Create class in you App_Code and past the following code into the file

you could adapt this to only delete if the number of cookies exceeded a certain level

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

https://<DomainName|IPAddress|Servaername>/EWS/Services.wsdl

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

https://<DomainaName|IPAddress|Servaername>/EWS/exchange.asmx

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}
Example

SQL 2008 SSRS Web Service access from .NET

When you try to access a report server web service to execute code you get an error similar to, where the scheme or header varies a tiny bit

The HTTP request is unauthorized with client authentication scheme ‘Basic’. The authentication header received from the server was ‘Negotiate,NTLM

Basically my situation is that we have a MS 2008 Server running SSRS outside of our domain in the DMZ. However we need to execute code on a domain machine that will connect and run over 100 reports on the SSRS Server, then dump them on a share in our domain in excel format.

To get around the negotiation problem you need to make sure the SSRS server is allowing connections configured using basic authentication

Find the file

rsreportserver.config

This is usually buried in the install folder

C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer

Then change the authentication to support your desired connection authentication type

More info at MSDN
Once you have done that you should be good to connect.
Here is some sample code to get you started with connecting to your web service and pulling back a list of items

.NET Entity Layer The member with identity ‘Result’ does not exist in the metadata collection

“The member with identity ‘Result’ does not exist in the metadata collection.
Parameter name: identity”

If you have stumbled across this error when trying to perform a transaction against your DB or any other action via your entity layer. If it is indeed a Microsoft SQL Database or any other database I would highly recommend you disable triggers on the affected tables and re run your test.

This error is the entity layer running home to its default error when either the error cannot be translated or the what ever is being returned from the transaction cannot be understood.

So if you stumble across this error, its because the entity layer is performing an operation that is causing a secondary separate operation which is where the underlying error is kicking back from, either because an error was raised or because the return is in an unexpected format.

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 http://combineandminify.codeplex.com/ 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:

EcmaScript.NET.modified.dll
Yahoo.Yui.Compressor.dll

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:

configuration>combineAndMinify
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
cookielessDomains
enableCookielessDomains Always Never
Always/ReleaseModeOnly/DebugModeOnly
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.

Implementation

  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 vb.net converted, enhanced version of the project compiled to binaries and other  files you will need:

CombineAndMinify_Dlls

HeadAdapter.browser.txt

web.config.txt

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

String.replace ignorecase

Replace a string but ignore the case, I keep forgetting about this little handy function

Heres an example of usage

How to pull together ASP.NET, jQuery, ashx, SQL

I want to cover something that is very detailed and not for the faint hearted.
You will need a moderate to advanced understanding of ASP.NET forms based web applications, javascript and the jQuery library, .NET handlers, transact and stored procedures in SQL Server.
If you stick around and read this article to the end, you will gain a solid grasp of:

1. Understand how to use the power of MS SQL Server full text searching, leveraged with jQuery via .NET
2. learn how to use the jQuery tmpl library to its full potential
3. learn how to use .NET handlers making use of datacontract and datamember applied to classes, serialising and deserialising to and from JSON.
4. Understand concepts employed when designing for high traffic scaleable web apps
5. pickup some nice tips, tricks, concepts and design methodologies that will stay with you and take you forward

Ok in a nutt shell i will be explaining how to build the search engine i have just single handedly built in 2 months, thanks to the power of .NET, jQuery and SQL server without which this would not have been possible.
You can see how it works by typing something in the search box here http://www.lowcarboneconomy.com
If you just had a look, im sure you’ll agree its pretty cool. If your an ultra geek and decided to snoop into the code, good luck its hugely compressed and minified, if you wanted help with anything, just ask me.

So lets begin.. oh wait, i dont have time to continue right now…. watch this space for updates

A google style FTS Full Text Search using MS Sql server 2008

People are used to searching the internet and thanks to google, yahoo and bing everyone can find what they want within a few keystrokes and mouse clicks.
This means that people have been self trained from countless hours spent searching the web using these search engines. We developers can make use of this by providing the same style search in our applications.
Enter the Ivory .Net Language Implementation Kit. What is Ivory ? well Ivory is a developer kit for implementing languages on a .NET platform. You can write your own grammar class to be loaded into the ivory dll in the form of EBNF.
The grammar class basically contains the logic behind how we will provide a Google style syntax for our search engine. Using either c# or vb.net writing in the Extended Backus Naur Form (EBNF). Now i don’t profess to be an expert in EBNF, far from it in fact. I simply want to use the already built class found in this kit “FullTextSearchQueryConverter” found in Irony.Samples.FullTextSearch called SearchGrammer and insert it in between my search form and the database call.

The first thing your going to need is the kit, you must download it from here Irony Kit Once you have downloaded it and had a little test of your own you are likely ready to implement it.

Before you continue its in your interest to already have a search facility built that uses the full text search engine in sql server

Let’s beginPersonally I code in vb so I converted the SearchGrammer Class SearchGrammer
Add the aforementioned class to your project.
To integrate this into our search tool you need to locate the area just prior to where you called your Full text Search crunch against the DB.
I integrated mine in the following way.

1. Instantiate our Irony dll and load the grammer class
2. Run the search text through the engine to generate the fts clause
3. Verify there we no errors
4. Pass FTS to db call

Personally I instantiate the Irony class and load the search grammer when my main search class is instantiated.

From a topographical perspective this is the code needed to execute this type of search from anywhere in my application

Where qry is the search object containing amongst other things the search text from the input, and oDS is the returned results from the query
Line 1 instantiates the FT search class, this instantiates the irony dll and loads the searchgrammer like so.

To use this to generate the full text search query I can now perform the following from any part of the class

Where FriendlySearchString is the input string from your user, and ftstring contains the TFS search query we can pass over to which ever means you are using to build the query.
The last thing you will need is the CheckParseErrors() method

I posted a discussion within the irony forum that says a similar thing to this post found here

I hope this helped those who needed a how to on implementing irony as your google style FTS generator in your .NET apps.