Tuesday, 20 December 2011

DropDownList has a SelectedValue which is invalid because it does not exist in the list of items

This issue is sometimes caused by changing the datasource of a drop down in the same page lifecycle.

This can be fixed by clearing the selection and selected item of the drop down list before rebinding to a new datasource.

eg:

Friday, 16 December 2011

How to load a drop down in a jqGRid with inline editing

Javascript:


aspx:

cs:

How to fire a non static code behind method from a javascript postback

I have found an interesting way of firing code behind methods from javascript functions without creating static web methods and ajax calls.

This in conjunction with an UpdatePanel produces a method that can be called from javascript that does not refresh the page.

If an update panel is used, then its a good idea to use the Id for a control inside the update panel so its marked for asyncrous postback, then differentiate between methods using the event argmument

to post back to the server using a javascript function the following code can be used:



We can then set the code behind to inspect the Request.Form collection for any postback information.

This can be very powerful as potentially any code behind method can be called!

Wednesday, 14 December 2011

How to Show a jQuery Dialog from Code behind

If you need to show a jQuery dialog from codebehind you can do so with the following code:

aspx:



js in aspx:

Note: dlg.parent().appendTo(jQuery('form:first')) is required so the dialog can be the same state after postback



code behind:

Basically we are adding a script to page load to create the dialog by calling our javascript method.

Thursday, 8 December 2011

Application pool crashes with The identity of application pool, 'your app pool' is invalid

I have had an issue with an application pool crashing with an error saying the identity of the application pool is invalid. After changing the username and password multiple times it became clear an incorrect password is not an issue.

The application pool was actually running as a local user on the web server. In order for a user account to be used in an application pool it needs to be added to a local security group (I have never done this before so its certainly not always the case).

To get it working be sure that the account is a member of the local security group "IIS_WPG", for membership in the IIS_WPG group is needed to run the w3wp.exe worker process.

Friday, 2 December 2011

Showing a modal dialog while page is updating

If you want to show a modal dialog while an update panel is updating it can be achieved with the following code:

Markup:


Javascript

Tuesday, 15 November 2011

Custom Resource File Considerations

1) Pages need a default resource file
2) Custom resource file is added after

Temporary asp.net files needs to be cleared

Monday, 7 November 2011

jQuery document.ready and update panels

If you want to use jQuery document.ready but have update panels on the page then the even is not fired on partial page refreshes.

In this case, another handler needs to be added so call the ready event at the end of every request.

The code below can be used to achieve this.

Thursday, 3 November 2011

Visual Studio Installer Project - Unable to build project output group 'Content Files from (Your website) (Active)'

Often when building MSI Windows Installers from ASP.NET Web Projects within Visual Studio.NET you'll get this error:

Unable to build project output group 'Content Files from SOMEWEB (Active)'

And you'll have no idea why this happened, no descriptive error message, nada.

Turns out that this is the MSI builder's way of telling you that it can't physically find a Content File that is referenced in the Project (CSPROJ, or VBPROJ).

The trick is turn on 'Show All Files' and open every folder until you find one with the Yellow Yield Icon. This subtle tip is telling you that this file doesn't exist on disk, but it does exist in the Project. Right-Click on it and Exclude From Project.

When the MSI Installer builder can't find a file marked as Content it fails

Friday, 14 October 2011

Referencing Control libraries in Web.Config - not each page

I have had an issue where there are different versions of assemblies loaded for the Microsoft report viewer. This was caused because the web config was referencing one version of the dll's and the pages were referencing another.

To fix this issue I removed all references to the report viewer assembly that were contained in aspx pages, and added an entry to the reportviewer dll to the web config so it can be accessed via the specified tag.

eg:

extracts from the web.config, here you can see the referenced ReportViewer assemblies, and where the controls are.



You can then use the report viewer controls in an asp page with the following:

Thursday, 8 September 2011

Using a Form tag or Panel to handle Submit on pressing Enter

If you need to submit a form when the enter key is pressed there are a couple of simple options.

There is a property on both the Form Tag, and an ASP Panel called 'DefaultButton' simply specifying the ID of the button in this property will fire the button click when the enter key is pressed whilst in that container.

Tuesday, 6 September 2011

Show label on ReportViewer report based on whether its the last page

If you need to show a field on a Reportviewer report based on whether its the last page of the report or no (eg Totals etc) then it can be achieved with the following code:

To Show on Last page should be:


To Show on All pages but the last should be:

Show Page X of Y in ReportViewer Footer

if you need to show the current page and total page count on a ReportViewer report it can be achieved with the following expression:

Thursday, 18 August 2011

How to compare dates from an Ajax Calendar Extender

Markup:



Javascript:

Dynamically create and show a jQuery UI dialog from Javascript

If you need to create a jQuery UI Dialog dynamically from javascript, heres how!

Tuesday, 16 August 2011

Awesome CSS3 buttons

Here's a link to an awesome CSS3 button

CSS 3 buttons

Monday, 15 August 2011

How to check whether a column exists in a particular database (SQL)

If you need to check for a particular column in SQL server but you don't know which table it is in then it can be found with the following query:

Monday, 8 August 2011

Add "Open with Notepad" to the Context Menu for All Files

Open regedit.exe through the start menu search or run box, and then browse down to the following key:



Right-click on “shell” and choose to create a new key, calling it “Open with Notepad”. Create a new key below that one called “command”. Double-click on the (Default) value in the right-hand pane and enter in the following:



The change should take effect immediately… just right-click on any file and you’ll see the next menu entry.

Monday, 1 August 2011

TargetInvocationException - Object Does Not Match Target Type

If you have a gridview in asp.net that is bound to a list of objects that are not all the same type (they are all derivatives of the same base class) you may get an error saying the Object does not match the target type.

This is because the gridview looks at the type of the first item in the grid and expects all other items to be the same type.

There is an easy work around for this which can be achieved by converting all of the columns to template fields so the properties are evaluated separately.

Tuesday, 26 July 2011

Web Application not loading debug symbol information

If a web application is not loading debug information check the build configuration settings. My project would not load symbols if compiled for x86. Renaming the bin directory and setting to compile for any CPU was a work around.

If anyone knows a solution to this to fix it properly please comment!

Friday, 22 July 2011

CSS3 Button generation

Here is a link to a good CSS 3 button generator:

http://css3buttongenerator.com/

Wednesday, 20 July 2011

Shrink DIV to content

To shrink a DIV to fit its contents use the following css

Tuesday, 19 July 2011

How to name the output filename of an msi installer project

Right click on the installer project and go to properties. There is an option on the properties page for "Output file name". You will need to change the file name for both debug, and release configurations.

Tuesday, 12 July 2011

GridView - Fire selected index changed on row click

If you want to be able to make the asp.net GridView fire the selected index changed event from any click in a row, then this can be achieved with the below code before the Page or Gridview is rendered.

Wednesday, 15 June 2011

Move window hidden from view.

Activate the window, Press Alt-Space to show context menu, then M for move, an arrow key, then use the mouse.

Friday, 3 June 2011

DATEPART considerations

Just a quick not on Using the DATEPART(WEEKDAY, value) function in SQL server.

My sql server is set up to use Sunday as the first day of the week which res returning the wrong day for my DATEPART queries.

To set the first day of the week to Monday you can use:


To set the first day of the week to Sunday you can use:


To check what DATEFIRST is currently set to you can use:

Thursday, 2 June 2011

Chuck Norris Programmer Jokes

1. When Chuck Norris throws exceptions, it’s across the room.
2. All arrays Chuck Norris declares are of infinite size, because Chuck Norris knows no bounds.
3. Chuck Norris doesn’t have disk latency because the hard drive knows to hurry the hell up.
4. Chuck Norris writes code that optimizes itself.
5. Chuck Norris can’t test for equality because he has no equal.
6. Chuck Norris doesn’t need garbage collection because he doesn’t call .Dispose(), he calls .DropKick().
7. Chuck Norris’s first program was kill -9.
8. Chuck Norris burst the dot com bubble.
9. All browsers support the hex definitions #chuck and #norris for the colors black and blue.
10. MySpace actually isn’t your space, it’s Chuck’s (he just lets you use it).
11. Chuck Norris can write infinite recursion functions…and have them return.
12. Chuck Norris can solve the Towers of Hanoi in one move.
13. The only pattern Chuck Norris knows is God Object.
14. Chuck Norris finished World of Warcraft.
15. Project managers never ask Chuck Norris for estimations…ever.
16. Chuck Norris doesn’t use web standards as the web will conform to him.
17. “It works on my machine” always holds true for Chuck Norris.
18. Whiteboards are white because Chuck Norris scared them that way.
19. Chuck Norris doesn’t do Burn Down charts, he does Smack Down charts.
20. Chuck Norris can delete the Recycling Bin.
21. Chuck Norris’s beard can type 140 wpm.
22. Chuck Norris can unit test entire applications with a single assert.
23. Chuck Norris doesn’t bug hunt as that signifies a probability of failure, he goes bug killing.
24. Chuck Norris’s keyboard doesn’t have a Ctrl key because nothing controls Chuck Norris.
25. When Chuck Norris is web surfing websites get the message “Warning: Internet Explorer has deemed this user to be malicious or dangerous. Proceed?”.
26. Chuck Norris CAN divide by 0.
27. Chuck Norris can overflow your stack just by looking at it.
28. Chuck Norris doesn’t need sudo, he just types “Chuck Norris” before his commands.
29. Chuck Norris can instantiate an abstract class.
30. The class object inherits from Chuck Norris
31. Chuck Norris can write multi-threaded applications with a single thread
32. There is no Esc key on Chuck Norris’ keyboard, because no one escapes Chuck Norris.
33. Visual SourceSafe actually works for Chuck Norris.

Thursday, 26 May 2011

Application Pool stops when started

If you are using a custom identity for and application pool and get either of the following errors:

A failure was encountered while launching the process serving application pool 'WAP'. The application pool has been disabled.


or

The identity of application pool 'WAP' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool. Therefore, the application pool has been disabled.


then you may need to grant some permissions to the account you are using.

Here is a list of things to try

  • Add user to IIS_WPG group
  • Add user to local admin group and adding the "Act as part of the os" right.
  • run aspnet_regiis -ga "domain\user" on the user account you are using
  • Check password
  • Grant the Log on as service role in local / group policy

Friday, 20 May 2011

Loading a Drop down List in Row Created

If you need to populate a drop down list in a Grid View row created event you may find that the items in the list are appearing twice.

I found this problem is caused if you call databind on the drop down list from within the Row Created event of the grid view. It looks as though the drop down list is automatically calling DataBind when the gridview calls the Row Databound event.

Removing the call to databind from the row created event fixed the issue.

eg:

Thursday, 19 May 2011

Style textboxes with css

I have recently had an issue with applying a css class to a text box as it was continually being ignored.

After about 2 hours of searching I found out it was being overridden because a skin file was changing the css class.

Long story short, If you want to apply custom classes to the same type of control, don't use a skin file. I removed the skin file, never to be used again, and replaced with the following css:

Monday, 9 May 2011

Ajax Controls Toolkit: ModalPopup extender with UpdatePanel

Scenario: show popup (preferably modal) with editable fields in a Master-Detail mode and provide ability to accept or reject update.

Straightforward combination of ModalPopup extender with UpdatedPanel, containing data-bound controls will work pretty much out of the box with few caveats to consider, mainly with OK/Cancel buttons:

1. Place both OK and Cancel buttons outside the Update panel, otherwise when leaving the page you may get a JScript error "Microsoft JScript runtime error: Sys.InvalidOperationException: Handler was not added through the Sys.UI.DomEvent.addHandler method.".
When client-side objects of the Update Panel are being disposed, the cleanup script tries to remove all registered handlers. If buttons are inside of the UpdatePanel, their handlers are still registered as for all child controls by default, but weren’t re-attached during the callback. Obviously, you can spend time and do it properly, but simply re-placing the buttons will do the job while keeping layout appearance unaltered.

2. Now our buttons are outside of the UpdatePanel and we need to make it aware of relevant Click events. So we will have to add trigger to serve the OK operation:


Same will do for a Cancel operation but it will work just fine (and with less code) by setting ModalPopup.CancelControlID property.

3. In the case of the Cancel button a ModalPopup “window” will be closed automatically but if you want it to be closed after the OK click, you should do it manually by calling the mpMyPopup.Hide() method.

4. If databound controls were changed on a callback then don't forget to call the UpdatePanel.Update() method to refresh the data.

5. Another important point to mention is that you have multiple popup control extenders on a page, including user controls that contain the extenders the Popup Control ID, and Cancel Control ID etc must be unique.

Most but not all information found at:
http://lazyloading.blogspot.com/2009/03/ajax-controls-toolkit-modalpopup.html

Friday, 6 May 2011

Use Fiddler with Blackberry simulator

In order to use Fiddler with Blackberry simulators the MDS simulator needs to be configured to use a proxy by amending the config file for the MDS simulator.

This is as simple as opening the config file at 'C:\Program Files (x86)\Research In Motion\BlackBerry Email and MDS Services Simulators 4.1.2\MDS\config\rimpublic.property' for a default installation.

Once the config file is open you need to look for the section titled [HTTP HANDLER] and add the following three lines



The proxy port in this example is 8888 which is the default port used by Fiddler.

The complete HTTP handler section should look similar to the following:

Blackberry Simulator - Insufficient Network Coverage


I have been doing a bit of mobile web development and had a problem when testing the site in a Blackberry simulator.

The message displayed on the black berry when doing a postback reads 'There is insufficient network coverage to process your request. Please try again later.'

The simulator has full signal and 3g etc is enabled. After doing a bit of research it appears the message is displayed becuase the page is trying to submit the form with a 'POST' action which causes this problem on both the Blackberry simulator and actual Blackberry devices. To get around this issue you can specify the form method to use 'GET' which resolves the problem.

eg:

Wednesday, 4 May 2011

jQuery Mobile Document Ready not firing

I have had a problem when using jQuery Mobile document ready on a mobile web application. When jQuery navigates to a new page, the only content that is rendered is contained in the div with data-role 'page'. My javascript was at the bottom of the page outside this div and not firing. I moved the javascript into the div with role 'page' and its now working.

Tuesday, 19 April 2011

Bring window to front with jQuery and Javascript

If you open a popup window via javascript it often appears behind the current page so the user may not notice it. A simple solution for this problem is to bring the window to the fron when it has finished loading. This can be achieved with a simple bit of jQuery and Javascript.

Wednesday, 13 April 2011

Javascript check for undefined or null object/variable

Tuesday, 12 April 2011

Disable a button with jQuery and still do postback

If you want to disable a button in a web application to stop it being clicked more than once when a long running process starts this is possible with jQuery.

The one pitfall that comes with disabling a submit button on the client side is that it will cancel the browser’s submit, and thus the postback. Setting the UseSubmitBehavior property to false tells .NET to inject the necessary client script to fire the postback anyway, instead of relying on the browser’s form submission behavior.

for example:
(aspx)


(javascript)

Saturday, 9 April 2011

How to install a patch from the command line

msiexec.exe /p YourPatchInstaller.msp

Thursday, 7 April 2011

ReportViewer - object datasource, nested objects return #Error

If you are using Visual studio 2010 and Report viewer you may have experienced the problem with using Nested Properties on the report with the fields returning #Error.

This has been fixed in Service Pack 1 for Visual studio 2010 although you must ensure all classes referenced in the report have the [Serializable] attribute for EVERY property that is a user type, they must also be a public class, and also a public constructor with no parameters. Without these you will still get the error. When a class is serialized it cannot be unserialized without the Default constructor as the class is instanitated with that constructor, then the properties set once the class is created. It also seems that if the entire class cannot be serialized the report will not show it.

To use a nested property on the report the following expression should be entered:

=Fields!Supplier.Value.SupplierLocation.Address1

This expression adds a field to the report that is three properties deep from the object the report is bound to.

The report datasource binds to an Order class, the order class contains a Supplier property, and the Supplier class contains a Supplier Location Property.

The Order, Supplier and Supplier Location class must use the [Serializable] attribute, and also any other property of any of the classes referenced. eg, Just make every class in your project Serializable and you should be good to go. ( technically you dont need every class but this was easier than checking every property of each nested object to make sure its serializable.

eg:


UPDATE: 16/06/2011

I tried to do another report with a different object and the #Error problem returned. However, After going though every single property that is a class in my datasource, and adding the serializable attribute to the report started working again. So, Every property of the object needs to be serializable, otherwise it seems the whole object cannot be serialized.

Checklist:
  • ALL classes are serializable (every user type in the class must be serializable, and any user type in a property of a usertype must be serialzable)
  • ALL classes have a public parameterless constructor
  • ALL classes used in the report must have the public modifier
  • If any property of the datasource, or any property of a property cannot be serialized then your will get the #Error. Just make sure everything is serializable
  • Make sure there will be no infinite recursion issues - eg, class A has a property of class B, and class B has a property of class A. Use XMLIgnore / ScriptIgnore attributes

UPDATE: 22/06/2011

Sample project can now be downloaded from

Sample Web Project

MIME Types

<>
Type/sub-typeExtension
application/envoyevy
application/fractalsfif
application/futuresplashspl
application/htahta
application/internet-property-streamacx
application/mac-binhex40hqx
application/msworddoc
application/msworddot
application/octet-stream*
application/octet-streambin
application/octet-streamclass
application/octet-streamdms
application/octet-streamexe
application/octet-streamlha
application/octet-streamlzh
application/odaoda
application/olescriptaxs
application/pdfpdf
application/pics-rulesprf
application/pkcs10p10
application/pkix-crlcrl
application/postscriptai
application/postscripteps
application/postscriptps
application/rtfrtf
application/set-payment-initiationsetpay
application/set-registration-initiationsetreg
application/vnd.ms-excelxla
application/vnd.ms-excelxlc
application/vnd.ms-excelxlm
application/vnd.ms-excelxls
application/vnd.ms-excelxlt
application/vnd.ms-excelxlw
application/vnd.ms-outlookmsg
application/vnd.ms-pkicertstoresst
application/vnd.ms-pkiseccatcat
application/vnd.ms-pkistlstl
application/vnd.ms-powerpointpot
application/vnd.ms-powerpointpps
application/vnd.ms-powerpointppt
application/vnd.ms-projectmpp
application/vnd.ms-workswcm
application/vnd.ms-workswdb
application/vnd.ms-workswks
application/vnd.ms-workswps
application/vnd.openxmlformats-officedocument.presentationml.presentationpptx
application/vnd.openxmlformats-officedocument.spreadsheetml.sheetxlsx
application/vnd.openxmlformats-officedocument.wordprocessingml.documentdocx
application/winhlphlp
application/x-bcpiobcpio
application/x-cdfcdf
application/x-compressz
application/x-compressedtgz
application/x-cpiocpio
application/x-cshcsh
application/x-directordcr
application/x-directordir
application/x-directordxr
application/x-dvidvi
application/x-gtargtar
application/x-gzipgz
application/x-hdfhdf
application/x-internet-signupins
application/x-internet-signupisp
application/x-iphoneiii
application/x-javascriptjs
application/x-latexlatex
application/x-msaccessmdb
application/x-mscardfilecrd
application/x-msclipclp
application/x-msdownloaddll
application/x-msmediaviewm13
application/x-msmediaviewm14
application/x-msmediaviewmvb
application/x-msmetafilewmf
application/x-msmoneymny
application/x-mspublisherpub
application/x-msschedulescd
application/x-msterminaltrm
application/x-mswritewri
application/x-netcdfcdf
application/x-netcdfnc
application/x-perfmonpma
application/x-perfmonpmc
application/x-perfmonpml
application/x-perfmonpmr
application/x-perfmonpmw
application/x-pkcs12p12
application/x-pkcs12pfx
application/x-pkcs7-certificatesp7b
application/x-pkcs7-certificatesspc
application/x-pkcs7-certreqrespp7r
application/x-pkcs7-mimep7c
application/x-pkcs7-mimep7m
application/x-pkcs7-signaturep7s
application/x-shsh
application/x-sharshar
application/x-shockwave-flashswf
application/x-stuffitsit
application/x-sv4cpiosv4cpio
application/x-sv4crcsv4crc
application/x-tartar
application/x-tcltcl
application/x-textex
application/x-texinfotexi
application/x-texinfotexinfo
application/x-troffroff
application/x-trofft
application/x-trofftr
application/x-troff-manman
application/x-troff-meme
application/x-troff-msms
application/x-ustarustar
application/x-wais-sourcesrc
application/x-x509-ca-certcer
application/x-x509-ca-certcrt
application/x-x509-ca-certder
application/ynd.ms-pkipkopko
application/zipzip
audio/basicau
audio/basicsnd
audio/midmid
audio/midrmi
audio/mpegmp3
audio/x-aiffaif
audio/x-aiffaifc
audio/x-aiffaiff
audio/x-mpegurlm3u
audio/x-pn-realaudiora
audio/x-pn-realaudioram
audio/x-wavwav
image/bmpbmp
image/cis-codcod
image/gifgif
image/iefief
image/jpegjpe
image/jpegjpeg
image/jpegjpg
image/pipegjfif
image/pngpng
image/svg+xmlsvg
image/tifftif
image/tifftiff
image/x-cmu-rasterras
image/x-cmxcmx
image/x-iconico
image/x-portable-anymappnm
image/x-portable-bitmappbm
image/x-portable-graymappgm
image/x-portable-pixmapppm
image/x-rgbrgb
image/x-xbitmapxbm
image/x-xpixmapxpm
image/x-xwindowdumpxwd
message/rfc822mht
message/rfc822mhtml
message/rfc822nws
text/csscss
text/h323323
text/htmlhtm
text/htmlhtml
text/htmlstm
text/iulsuls
text/plainbas
text/plainc
text/plainh
text/plaintxt
text/richtextrtx
text/scriptletsct
text/tab-separated-valuestsv
text/webviewhtmlhtt
text/x-componenthtc
text/x-setextetx
text/x-vcardvcf
video/mpegmp2
video/mpegmpa
video/mpegmpe
video/mpegmpeg
video/mpegmpg
video/mpegmpv2
video/quicktimemov
video/quicktimeqt
video/x-la-asflsf
video/x-la-asflsx
video/x-ms-asfasf
video/x-ms-asfasr
video/x-ms-asfasx
video/x-msvideoavi
video/x-sgi-moviemovie
x-world/x-vrmlflr
x-world/x-vrmlvrml
x-world/x-vrmlwrl
x-world/x-vrmlwrz
x-world/x-vrmlxaf
x-world/x-vrmlxof

ReportViewer - Prints Extra blank pages or splits accross multiple pages

If you are using report viewer and find that when you export to PDF or print the report blank pages are coming out, or some fields are on the page on there own. This is to do with page size and margins.

When you are editing the rdlc file in design mode, firstly click on an empty part of the BODY area of your design. Hit F4 to see the properties tab. Here, you will see a "Size" property. This can be expanded for the width and height. The width you see here represents the width that the body of your report requires as printable area. Even if you have white space all over, the page knows that it needs to keep it as a printable area. It reserves the space, in some sense. As for the height, the system generally knows that it can grow or shrink as necessary, unless you have specified otherwise within your controls therein. So the width is what will, usually, play the most important role.

Next, click on an empty area of the report (outside the header, body, and footer; basically the gray area around the design), then hit F4 to view the properties panel. Under the "Layout" category of the properties, you will see 3 different options: InteractiveSize, Margins, PageSize. Each of those Size attributes can be expanded to show the Width and Height. The Margins attribute can be expanded for the left/right/top/bottom.

Basically, the pdf export works out of the PageSize (though I generally try to keep Interactive and Page size equal). When the pdf file is rendered via the ReportViewer's built-in export function, the width and height of each "page" within the pdf will be determined by the width and height in the report's PageSize attribute (you could override this if you used your own custom code for the pdf rendering). As for the margins, they specify how much space MUST be left blank and unprintable between the printable area reserved for your report and the edge of the page.

In other words: Your report's Body's Width, Plus the Report's Left Margin, Plus the Report's Right Margin, MUST be smaller than or equal to the Report's PageSize's Width!

So...if your margins are too wide, or if your report's body is too wide, or if the PageSize's width is too narrow, the rendered result is forced to be broken down to multiple pages in order to fit!

For example: If my report's body has width 7.75", my Left margin is 0.5", my right margin is 0.5", and the width specified in the PageSize is 8.5", my report will always use 2 pages for each 1 page of data. The 7.75" width of the body, plus 0.5"+0.5" for the margins add up to 8.75", which is larger than the 8.5" available in my page. So the first 7.5" (or so) of each page of my report's body will be shown in the first page, and the rest will be split down to the next page. This will not be done inside the report viewer, as it allows for the report to grow beyond the page size by just adding a scrollbar, but it will be annoyingly noticeable in the pdf export. In order to make my example report fit in 1 page, I can either try and reduce the body of my report to 7.5" or less, or I can reduce the left and right margins by a total of 0.25" or more (for example, set them to 0.3" for a total reduction of 0.4"), or I can increase the PageSize to something larger than 8.75". Note: Acrobat Reader is pretty smart and knows about various paper sizes. Therefore, while arbitrary PageSizes will work, it is typically best to use real page sizes. As such, in my last example I would rather set the PageSize to have Width = 11" and Height = 8.5", which is a real letter-size in landscape! Adobe will typically understand this and print properly. Also Note: Some printers, especially older ones, have trouble printing with less than 0.3" margins. If you want to be nice to your users, you should best keep the margins large enough for those older printers ;)

Tuesday, 29 March 2011

Could not load file or assembly CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304

If you get the error Could not load file or assembly CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304 when an application is deployed on to a server this could be caused before the incorrect crystal runtime could be installed on the server.

To begin with I downloaded the latest crystal reports 2008 runtime and installed on the server. This seemed to install version 12.0 assemblies. After a bit of searching on the net it seems that the version number of the assemblies changed to 13.0 in the Crystal reports for Visual Studio 2010 version. This means there is a seperate runtime to install if this is what the reports were built against.

The correct runtime can be downloaded from here:

SAP VS.net runtime distributions

Failed to open the connection. Database Vendor code 4060

I recently had a problem deploying crystal reports to a server after an upgrade to crystal reports for visual studio 2010. When running the report from the web application I was getting the error 'Failed to open the connection. Database Vendor code 4060'

It dawned on me that is may be due to an issue similar to the 'double hop' problem where ReportViewer looses its impersonation context. This was easy to resolve by changing the application pool identity to a user that has access to the datasources and databases. Sure enough everything started to play nicely after the application pool was changed to match the user the web application was impersonating.

If you are interested in the ReportViewer double hop problem then here is the link:

Report Viewer Impersonation Context

Friday, 25 March 2011

BlackBerry MDS Simulator does not launch

Problem

The BlackBerry MDS Simulator appears to have started successfully; however, the command prompt window disappears after a few seconds.

Cause

The following are possible causes:

An incorrect version of the Java® software development kit (SDK) or Java Development Kit (JDK) is installed on the computer, or the SDK or JDK is missing.
The path environment variable is not set correctly.
The Java_Home environment variable is pointing to the incorrect Java version.
There is interference with existing environment variables.
Resolution

Complete the following:

Verify that a supported version of the SDK or JDK is installed as follows:
Review the Add/Remove Programs to determine the current version installed.
Search Windows® Explorer for the Java installation directory (e.g., C:\Program Files\Java\jdk1.5.0_21).
If there is no Java SDK or JDK installed, install one.

If an incorrect version of Java SDK or JDK is installed, remove it and install the version that is supported by BlackBerry JDE. See here for a list of supported versions of Java for the the BlackBerry JDE.When the installation is complete, make sure that the Java directory is created and that the environment variable has been set correctly.

When the installation is complete, make sure that the Java directory is created and that the environment variable has been set correctly.


Check the path environment variable:
Right-click My Computer and then select Properties. On the Advanced tab, click Environment Variables.
Verify that the C:\Program Files\Java\jdk1.5.0_21 directory appears first in the path environment variable, as in the following example:
C:\Program Files\Java\jdk1.5.0_21;C:\Perl\bin\;C:\Oracle\Ora81\bin;C:\Program Files\Oracle\jre\1.1.7\bin;%SystemRoot%\system32;%SystemRoot%


Note: If there are multiple versions of Java installed by other applications, move the Java SDK path to the beginning of the list.



Check the “JAVA_HOME” environment variable.
Right-click My Computer and select Properties. On the Advanced tab, click Environment Variables.
Verify that the Java_Home variable is pointing to the correct version of Java. The BlackBerry JDE software does not require the Java_Home variable to be set. It can be removed as long as there are no conflicts with other applications running on your local computer.
Edit the \INSTALL_DIRECTORY\MDS\setBMDSEnv.bat file and remove the reference to %cd%\ from the following line:

@set BMDS_CLASSPATH=%BMDS_CLASSPATH%;"%cd%\%1"


The line should now read as follows:


@set BMDS_CLASSPATH=%BMDS_CLASSPATH%;"%1"


Save this change and restart the BlackBerry MDS Simulator.

Monday, 21 March 2011

How to open a window from a button in an update panel

If you have a control in an update panel and you dont want to add the whole control as a postback trigger ( if you are using a gridview and want one partiular row command to open a window for example ) then you can achieve this with the following code.

How to create a Unique index based on two columns

I had a requirement to have a constraint on a database table to not allow duplicate document no's in the table. This was complicated by the fact you could have the same document no in two different records in the table if the databaseID of the record was different. The constraint should also only be in place if there is a Value in the document No column.

Here is the SQL Query to add the constraint in SQL 2008.



If you are using SQL 2005 then you can achieve this by creating a view and adding a constraint to the view.

Friday, 18 March 2011

How to Add Virtual PC hard disk to Virtual Box

If you want to get a VPC image mounted into Virtual Box without it blue screening on startup.

Here is how:
  1. Create a new Virtual Machine
  2. Set the details for the VM
  3. Set memory as normal
  4. Untick the Boot Hard disk Option
  5. Finish creating the machine
  6. Go into the Storage settings for the machine. Under the IDE Controller section click the add new Hard Disk Button
  7. Click choose existing disk
  8. Browse to the existing file
  9. You should now be good to Go. The reason it wont boot if you don’t add the disk as an IDE controller is because by default the disk is added as SATA and the virtual pc disks were not set up as SATA. If you selected the disk during the initial wizard then you will need to remove it from the SATA controller in the Storage settings and add it to the IDE controller

Thursday, 17 March 2011

Error Reading File: Source Safe and Virtual PC

If you are using Source Safe in a virtual PC and it is behaving slowly and producing Error Reading from File messages then its likely you may have a duplicate MAC address if the virtual PC has been copied.

To resolve this make sure the virtual PC is closed and not in a saved state.

Edit the .vmc file to remove the MAC address. Find the following line:



Remove the number so the line appears as follows:


After you remove the number, Virtual PC will create a new MAC address the next time you start the virtual machine.

Thursday, 10 March 2011

IIS Service Unavailable after setting 32bit (IIS 6.0)

I was having the "Service Unavailable" issue after I changed IIS to 32 bit mode. I found a solution that worked for me:

Our problem was that ASP.net was trying to run a 64 bit DLL, which failed after we reset IIS to 32 bit mode. All we needed to do was change the bitness of the ASP.net DLL to 32 bit mode. To do that, first turn on the server service. Once that service is running, run the following:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i -enable

This will reinstall ASP.NET with the appropriate bitness.

Configuring IIS to Run 32-bit Applications on 64-bit Windows (IIS 6.0)

To enable IIS 6.0 to run 32-bit applications on 64-bit Windows
  1. Open a command prompt and navigate to the %systemdrive%\Inetpub\AdminScripts directory.
  2. Type the following command:
    cscript.exe adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 “true”
  3. Press ENTER.

Monday, 7 March 2011

JQuery Mobile: Switching Pages: new page does not get style

When clicking on any relatively linked page the new page is loaded and displayed but it does not contain any of the formatting love jquery mobile normally applies. When visiting any of these pages by themselves they all render properly but the same issue exists where you cant navigate between them.

The problem: In jQuery Mobile Alpha 2.0 all pages in the same root will not receive the proper style when linking to each other.

Example:
site/mobile/index.html <- contains a link to news.
site/mobile/news.html <- news will not receive style because index and news are in the same directory.

There are three solutions to fix this(for the time being before they release the next alpha).

Solution 1:
Use jquery 1.4.3 instead of 1.4.4. you lose icon in your headers but it's not a complete loss if you dont need them.

Solution 2:
place all your sub pages from your index in sub folders or in a sub folder. You cant use a flat site system but all the pages will style properly.
Example:
site/mobile/news/index.html

Solution 3:
add a "?" at the end of the hyperlink. This tells the jquery mobile that it needs to render a new page but it could be the same page so have it style properly. (if your hyperlinks already have GET variables in your URLs then you are all set.)
Example:
site/mobile/news.html?

Friday, 4 March 2011

Command Prompt from here context menu item


Navigate in your Registry to
HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell
and create a key called "Command Prompt" without the quotes.

Set the default string to whatever text you want to appear in the right-click menu.
Create a new key within your newly created command prompt named "command," and set the default string to
cmd.exe /k pushd %1
You may need to add %SystemRoot%\system32\ before the cmd.exe if the executable can't be found.
The changes should take place immediately. Right click a folder and your new menu item should appear.

Thursday, 3 March 2011

Fixing “ResGen.exe exited with code–1073741701” in Visual Studio 2010

Set the 32-bit flag on resgen.exe

Option 1:
  1. Open a Visual Studio command-prompt as an administrator
  2. Navigate to the Microsoft SDKs\Windows\v7.0A\bin directory.
  3. ***SAVE A COPY*** of your original resgen.exe file. This is very important if you want to be able to replace our tweak with the original file without having to repair your installation.
    copy resgen.exe regen.exe.old
  4. Set the 32-bit flag to true using corflags.exe
    corflags.exe resgen.exe /32BIT+ /Force
  5. Note the warning about strong name issues. On my machine the build now succeeds, without needing to do any additional work due to strong name issues. IF you have problems after trying this method, you can try the following to skip string name verification for that assembly-
  6. Register resgen.exe for strong name verification skipping using sn.exe
    sn.exe –Vr resgen.exe
    WARNING! This is a security risk. You are bypassing strongname verification for this assembly, making it possible for malicious code posing as resgen.exe to execute. To turn verification back on, use sn.exe –Vu resgen.exe

Option 2:
Add the following line to your csproj file ...













Option 3:
Try using the 64-bit version of tracker.exe, even for 32-bit builds, when targeting .NET 3.5 and lower. Indicate you want to run ResGen as a tool, and that it is ManagedIL (Managed32Bit doesn't work because of this flagging issue):

a. Add this to your MSBUILD command-line:


b. Or add this to your project:

System.InvalidOperationException: Request format is unrecognized

If you try browsing to a web service asmx file and get the error message

System.InvalidOperationException: Request format is unrecognized

This may be becuase the required protocol is disabled in the web config file.

Here is a list of the possible protocols that could be missing from the web or machine.config.

Tuesday, 1 March 2011

Could not load file or assembly 'your assembly name' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I just had a problem with the error message in IIS that reads:

Could not load file or assembly 'yourassemblyname' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'Sicon.API' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Now this message is not particularly helpful but after a while searching the problem was caused becuase the web application was installed on a 64bit server, in a 64bit application pool when the web application is compiled specifically for 32bit.

This is easy enough to fix by changing the application pool to allow 32bit applications from the advanced settings screen.

Wednesday, 23 February 2011

How to Compact your Virtual PC Hardisk Files (VHD)

  1. Download and install Virtual PC Service Pack 1.
  2. Defragment your guest operating system.
  3. Install Guest Additions if its not already
  4. From the CD menu, select Capture ISO Image and browse to the Virtual PC additions directory, which is %ProgramFiles%\Microsoft Virtual PC\Virtual Machine Additions by default.
  5. Mount Virtual Disk Precompactor.iso. By default with auto-run enabled, the precompactor will start automatically.
  6. When it has finished, unmount the ISO from the CD menu.
  7. Run the Virtual Disk Wizard from the File menu and follow the instructions to compact your VHD file.

Saturday, 19 February 2011

ReportViewer - Sub Report with integrated security problem

I have recently had a problem with using Sub Reports in Report Viewer when the SQL server is a seperate box from the web server. The initial data is loaded correctly but when the subreport processing event is fired the second SQL command comes back with a failed login error as it was trying to connect with the local system account of the web server. The connection strings to the database are all using Integrated Security so the impersonation context needs to be there to access the database as the correct user.

After much investigation is looks as though this is caused by a phenomenon called a 'double hop'. The request is sent from the web server, to the SQL server and identity information is passed across to the SQL server. When the sub report is processing the request is again made to the SQL server but at this point the indentity information is lost as it only lasts 2 'hops' This is aparently by design for NTLM authentiation. I have read this can be fixed by using Kerberos authentication but I know nothing about this.

Two solutions that I have come up with seem to work.

1) Change all connection strings to the database to explicity specify the UserID and Password for the SQL connection. This seems to work ok but unless you want to mess about encrypting web configs and connect strings then this isnt really an option.

2) Change the user account the web applications app pool is running under. I changed this account to use the same domain user account that the web application was impersonating. It seems the sub report request is using the identity of the application pool to connect. Changing this then uses the correct user account for the integrated security in the connection string. One thing to note with this method is that I had to change the Anonymous access user in IIS to also use this domain account as a login box was being presented when browsing to the site.

Here is the code for the aspx page that is loading the report. The problem manifests itself in the LocalReport_SubreportProcessing event.

Friday, 18 February 2011

How to open SQL server ports on the firewall

Start Notepad.
Copy and paste the following code into Notepad:


@echo ========= SQL Server Ports ===================
@echo Enabling SQLServer default instance port 1433
netsh firewall set portopening TCP 1433 "SQLServer"
@echo Enabling Dedicated Admin Connection port 1434
netsh firewall set portopening TCP 1434 "SQL Admin Connection"
@echo Enabling conventional SQL Server Service Broker port 4022
netsh firewall set portopening TCP 4022 "SQL Service Broker"
@echo Enabling Transact-SQL Debugger/RPC port 135
netsh firewall set portopening TCP 135 "SQL Debugger/RPC"
@echo ========= Analysis Services Ports ==============
@echo Enabling SSAS Default Instance port 2383
netsh firewall set portopening TCP 2383 "Analysis Services"
@echo Enabling SQL Server Browser Service port 2382
netsh firewall set portopening TCP 2382 "SQL Browser"
@echo ========= Misc Applications ==============
@echo Enabling HTTP port 80
netsh firewall set portopening TCP 80 "HTTP"
@echo Enabling SSL port 443
netsh firewall set portopening TCP 443 "SSL"
@echo Enabling port for SQL Server Browser Service's 'Browse' Button
netsh firewall set portopening UDP 1434 "SQL Browser"
@echo Allowing multicast broadcast response on UDP (Browser Service Enumerations OK)
netsh firewall set multicastbroadcastresponse ENABLE

Save the file as a .txt file by using the following name: OpenSqlServerPort.txt
Rename the OpenSqlServerPort.txt file to the following: OpenSqlServerPort.bat

run the batch file on the server you would like to open the ports and you should be good to go

Wednesday, 16 February 2011

Visual Studio 2010 Report Viewer - Object Datasource

I have had no end of issues trying to get the ReportViewer control in Visual Studio to work with business objects in a Web Application (not website)

When I tried to create a new report the datasources window would never pick up my business objects. Here is a solution that I finally got working.

Create a new class library project to host reports. This library can contain the object datasources added by using the Data menu, then Add New Datasource. The reason I could not do this in the Web Application is because this menu item is missing for Web Applications!

Anyway, once you have added the datasources, add a new report to the reporting class library, here it will have access to all of the datasources (my data sources are actually business objects in another class library) This report needs to be set as an embedded resource.

Once you have the report and datasources ready its time to add the ReportViewer to an aspx page. I ran into a problem here when setting the ReportViewer.LocalReport.ReportEmbeddedResource. It looks like the report viewer looks for the resource in the current assembly. Luckily this can be resolved by adding a helper class to the reporting library to set the embedded resource from within the library.

Here is the code for the helper function in the reporting library


and here is how you would use it in the aspx page
Update for .net 4.0 I had an issue where the report would not load after being compiled in .net 4.0. The message read: 'The report definition for report 'xxx.rdlc' has not been specified' even though it was clearly in the assembly. Changing the way the Embeded resource was loaded seemed to fix the problem with the following simple change to the SetReportEmbeddedResource method in the reporting assembly.

Friday, 11 February 2011

How to resize and Existing Virtual Box Image (.vdi)

Start off by creating a fresh new drive of the size you’re after using the VirtualBox user interface. Then, locate both the your old, smaller HD and the new, larger one and run the following command in the command prompt.


After some progress indicators have come and gone your hard disk should have been cloned to the larger one. You now need to use some software to expand your drive partition into the new space. Vista and W7 have this feature built in to Disk Management so you can just opt to extend the partition to fill the remaining space.

How to remove and EFI System Partition from a Hard Disk

If you have an external hard disk that has an EFI system partition (usually about 200MB) and want to remove it then this can be achieved by using DISKPART from the command prompt.

1. On the command prompt type diskpart
2. On the new diskpart prompt, type list disk. Note the Disk ### column.
3. Type, select disk ### (with ### being the partition you wish to delete. Usually partition 0 and with those 200 MB of size)
4. Finish by typing, clean.

Friday, 4 February 2011

SQL Server - Shrink Transaction Log with DBCC

If you need to shrink an SQL Server database transaction log the following command can be used.

Tuesday, 25 January 2011

Star wars episode IV A new hope in ASCII

If you want to see Star Wars created completely from text try the following. You will need internet access!










  • Click on start
  • Click "Run"
  • Type "CMD"
  • In the command prompt window type "telnet" and press enter
  • then type "o" and press enter
  • Now type "towel.blinkenlights.nl" And press enter
  • Now wait a few seconds and it will start Star wars episode IV A new hope

Wednesday, 12 January 2011

How to Copy and Object with Reflection

If you need to copy an object then one way of doing it is with reflection. This is useful if a new property is added to a class and you dont want to remember to update the copy function with the new field.

Calling private Methods and Properties

If you are using a 3rd party API and need to call a private method, or change the value of a private member variable then this is possible using Reflection in the System.Reflection Namespace.

Example Below

Friday, 7 January 2011

Getting performance data from SQL server

If you need to tweak a query to run a bit faster you can tell SQL server to also show performance data with the following command:

SET STATISTICS PROFILE ON

This will show each part of the query and how long it has taken etc.

To turn this off again use:

SET STATISTICS PROFILE OFF

Thursday, 6 January 2011

Implementing ICustomTypeDescriptor for dynamic properties

I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.

This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.

By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.

Take a look at the implementation of the data 'row' class below:


Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt

You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:



The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.