Wednesday, October 31, 2012

Get querystring parameter by Javascript

function queryString(ji) {
    hu =;
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];

Tuesday, October 23, 2012

Error: Object must implement IConvertible

When passing a Guid parameter to an SqlDatasource, you should not define the Type.


At first I tried using the type "String", but that caused the error

Object must implement IConvertible

Saturday, August 18, 2012

Setting Culture in ASP.NET

Difference between Culture and UICulture

Culture defines culture dependent objects like currency, date, currency and number formatting.  This can only defined using a specific culture (ex: en-GB not en)

UICulture defines which resources (local and global) will be loaded for this page.  Both neutral and specific cultures.

Setting Culture dynamically at runtime

Culture and UICulture need to be set in the InitializeCulture event

protected override void InitializeCulture()
if (Request.Form["DropDownList1"] != null)
//can be neutral i.e. en or en-GB
UICulture = Request.Form["DropDownList1"];
//requires a specific culture ex: de-DE
Culture = Request.Form["DropDownList1"];

Wednesday, August 1, 2012

Return nth index of a delimited string in TSQL

CREATE FUNCTION [dbo].[fn_SplitSelect] (@sep VARCHAR(32), @s VARCHAR(MAX), @index INT)

        DECLARE @xml XML
        SET @XML = N'' + REPLACE(@s, @sep, '') + ''

        SELECT @ret = Item
        FROM (
                    SELECT r.value('.','VARCHAR(5)') as Item, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS rownum
                    FROM @xml.nodes('//root/r') AS RECORDS(r)
                    ) t
             WHERE t.rownum = @index

        RETURN @ret

Friday, July 27, 2012

T-SQL: Script to enter list of colours

I couldn't find a list, so i created one from the list of colours used by HTML. Enjoy :) Does anybody know of a website where you can find these kind of scripts?
/****** Object:  Table [dbo].[Colours]    Script Date: 07/27/2012 10:07:49 ******/
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'AliceBlue ', N'#F0F8FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'AntiqueWhite ', N'#FAEBD7')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Aqua ', N'#00FFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Aquamarine ', N'#7FFFD4')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Azure ', N'#F0FFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Beige ', N'#F5F5DC')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Bisque ', N'#FFE4C4')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Black ', N'#000000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'BlanchedAlmond ', N'#FFEBCD')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Blue ', N'#0000FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'BlueViolet ', N'#8A2BE2')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Brown ', N'#A52A2A')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'BurlyWood ', N'#DEB887')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'CadetBlue ', N'#5F9EA0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Chartreuse ', N'#7FFF00')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Chocolate ', N'#D2691E')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Coral ', N'#FF7F50')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'CornflowerBlue ', N'#6495ED')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Cornsilk ', N'#FFF8DC')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Crimson ', N'#DC143C')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Cyan ', N'#00FFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkBlue ', N'#00008B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkCyan ', N'#008B8B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkGoldenRod ', N'#B8860B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkGray ', N'#A9A9A9')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkGrey ', N'#A9A9A9')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkGreen ', N'#006400')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkKhaki ', N'#BDB76B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkMagenta ', N'#8B008B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkOliveGreen ', N'#556B2F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Darkorange ', N'#FF8C00')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkOrchid ', N'#9932CC')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkRed ', N'#8B0000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkSalmon ', N'#E9967A')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkSeaGreen ', N'#8FBC8F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkSlateBlue ', N'#483D8B')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkSlateGray ', N'#2F4F4F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkSlateGrey ', N'#2F4F4F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkTurquoise ', N'#00CED1')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DarkViolet ', N'#9400D3')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DeepPink ', N'#FF1493')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DeepSkyBlue ', N'#00BFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DimGray ', N'#696969')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DimGrey ', N'#696969')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'DodgerBlue ', N'#1E90FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'FireBrick ', N'#B22222')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'FloralWhite ', N'#FFFAF0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'ForestGreen ', N'#228B22')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Fuchsia ', N'#FF00FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Gainsboro ', N'#DCDCDC')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'GhostWhite ', N'#F8F8FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Gold ', N'#FFD700')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'GoldenRod ', N'#DAA520')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Gray ', N'#808080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Grey ', N'#808080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Green ', N'#008000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'GreenYellow ', N'#ADFF2F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'HoneyDew ', N'#F0FFF0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'HotPink ', N'#FF69B4')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'IndianRed  ', N'#CD5C5C')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Indigo  ', N'#4B0082')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Ivory ', N'#FFFFF0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Khaki ', N'#F0E68C')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Lavender ', N'#E6E6FA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LavenderBlush ', N'#FFF0F5')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LawnGreen ', N'#7CFC00')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LemonChiffon ', N'#FFFACD')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightBlue ', N'#ADD8E6')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightCoral ', N'#F08080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightCyan ', N'#E0FFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightGoldenRodYellow ', N'#FAFAD2')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightGray ', N'#D3D3D3')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightGrey ', N'#D3D3D3')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightGreen ', N'#90EE90')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightPink ', N'#FFB6C1')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSalmon ', N'#FFA07A')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSeaGreen ', N'#20B2AA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSkyBlue ', N'#87CEFA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSlateGray ', N'#778899')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSlateGrey ', N'#778899')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightSteelBlue ', N'#B0C4DE')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LightYellow ', N'#FFFFE0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Lime ', N'#00FF00')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'LimeGreen ', N'#32CD32')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Linen ', N'#FAF0E6')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Magenta ', N'#FF00FF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Maroon ', N'#800000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumAquaMarine ', N'#66CDAA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumBlue ', N'#0000CD')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumOrchid ', N'#BA55D3')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumPurple ', N'#9370D8')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumSeaGreen ', N'#3CB371')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumSlateBlue ', N'#7B68EE')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumSpringGreen ', N'#00FA9A')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumTurquoise ', N'#48D1CC')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MediumVioletRed ', N'#C71585')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MidnightBlue ', N'#191970')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MintCream ', N'#F5FFFA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'MistyRose ', N'#FFE4E1')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Moccasin ', N'#FFE4B5')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'NavajoWhite ', N'#FFDEAD')
print 'Processed 100 total records'
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Navy ', N'#000080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'OldLace ', N'#FDF5E6')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Olive ', N'#808000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'OliveDrab ', N'#6B8E23')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Orange ', N'#FFA500')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'OrangeRed ', N'#FF4500')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Orchid ', N'#DA70D6')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PaleGoldenRod ', N'#EEE8AA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PaleGreen ', N'#98FB98')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PaleTurquoise ', N'#AFEEEE')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PaleVioletRed ', N'#D87093')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PapayaWhip ', N'#FFEFD5')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PeachPuff ', N'#FFDAB9')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Peru ', N'#CD853F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Pink ', N'#FFC0CB')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Plum ', N'#DDA0DD')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'PowderBlue ', N'#B0E0E6')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Purple ', N'#800080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Red ', N'#FF0000')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'RosyBrown ', N'#BC8F8F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'RoyalBlue ', N'#4169E1')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SaddleBrown ', N'#8B4513')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Salmon ', N'#FA8072')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SandyBrown ', N'#F4A460')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SeaGreen ', N'#2E8B57')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SeaShell ', N'#FFF5EE')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Sienna ', N'#A0522D')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Silver ', N'#C0C0C0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SkyBlue ', N'#87CEEB')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SlateBlue ', N'#6A5ACD')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SlateGray ', N'#708090')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SlateGrey ', N'#708090')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Snow ', N'#FFFAFA')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SpringGreen ', N'#00FF7F')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'SteelBlue ', N'#4682B4')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Tan ', N'#D2B48C')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Teal ', N'#008080')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Thistle ', N'#D8BFD8')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Tomato ', N'#FF6347')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Turquoise ', N'#40E0D0')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Violet ', N'#EE82EE')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Wheat ', N'#F5DEB3')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'White ', N'#FFFFFF')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'WhiteSmoke ', N'#F5F5F5')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'Yellow ', N'#FFFF00')
INSERT [dbo].[Colours] ([Colour], [Code]) VALUES (N'YellowGreen ', N'#9ACD32')

Wednesday, July 25, 2012

Using Resource Files in ASP.NET

There are 2 types of resource files, local and global resource files.  Local resource files are used for a specific page, while global resources can be used throughout a site.

Local Resource files

Local resource files must be stored in the ASP.NET folder App_LocalResources.  These files have the extension .resx and must be named like the page.  If the page is named About.aspx, then the resource page will be About.aspx.resx.  This will be the default resource file for the page.  In order to create a resource file for another language, you will need to create another file with the language 2 letter ISO code.  If you need resources for the German language for example, the file will need to be named  You can also use specific languages like About.aspx.en-GB.resx

Implicit Localization

To easiest way to create a resource file, is to use the tool provided in Visual Studio. From the Tools menu, select Generate Local Resource.  This will create a resource file for the form you are viewing.

The tool will generate resource keys for every string property for every control

Explicit Localization

In explicit localization, you can manually attach a resource to a control's property like so


Global Resource files

Global resource files are stored in the App_GlobalResources ASP.NET folder.  Use these resources for text which will be used more than once in your website.  I typically use it for common words such as 'Save', 'Edit', 'Delete', etc.. These files also have the .resx extension.  In order to use them from mark up, use the same syntax as the explicit localization mentioned above

Using and accessing resources programmatically

There are 2 ways to retrieve values at runtime.  If the global resources are available in your project you can use the following syntax which also provides intellisense
string myText = Resources.SharedLocalizedText.WelcomeText;
If the file is not available at design time, you can use the following method
string myText = Convert.ToString(GetGlobalResourceObject("MyGlobalResourceFile", "WelcomeText"));

The first parameter is the name of the global resource file (without the extension) and the second is the resource key which you want to retrieve from the file

Thursday, June 21, 2012

Using Cache in ASP.NET

if (Cache["Name"] != null)

Label1.Text = "Hello," + (string)Cache["Name"];


Label1.Text = "Hello, guest! ";

Setting Cache Expiry

Cache.Insert("Name", "Kevin", null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);

Thursday, June 14, 2012

How to: Add CSS file in ASP.NET at runtime

Adding CSS file in ASP.NET programatically

HtmlGenericControl si = new HtmlGenericControl();
si.TagName = "link";
si.Attributes.Add("type", "text/css");
si.Attributes.Add("href", "css/module.css");
si.Attributes.Add("rel", "stylesheet");

Tuesday, June 12, 2012


Creating a theme

Themes should be defined in the special App_Themes folder.

  1. Right-click your website in Solution Explorer, click Add ASP.NET Folder, and then click Theme.
  2. Within the App_Themes folder, you define an individual folder for each theme in your application. Example: Professional or Simple

You can then create skin files or style sheets in each of these theme folders.

Applying the theme

This can be done either on the page level by using the attributes Theme or StyleSheetTheme in the @Page directive.  The difference between Theme and StyleSheetTheme is that StyleSheetTheme sets properties before the page's controls properties are set, while Theme properties are set after the page sets the controls properties.

This means that if in the theme folder, we have set the label colour to Red and in the page we set the label colour to Green, the label will be red if using Theme but green if using StyleSheetTheme.

Or as commonly used, apply it to the whole website through the web.config in the system.web section

<pages Theme=”themeName”>


<pages StyleSheetTheme=”themeName”>

Changing theme at runtime programattically

In order to change the theme by code, use the PreInit event to change either the 'Theme' of the page.  If you want that the user changes the theme upon a button click or a change in dropdown, just store the value in  a session variable, and then set the session variable's value to the page.theme in the preinit event

protected void Page_PreInit(object sender, EventArgs e)
Page.Theme = "Simple";

To change StyleSheetTheme at runtime, you can't do the same as the above or you will get the error

The StyleSheetTheme property cannot be set, please override the property instead.

In order to apply the StyleSheetTheme at runtime, you must override the property like so:

public override String StyleSheetTheme
    get { return "Simple"; }
Ideally, use the above code in a base page which all your pages derive from.

Monday, June 11, 2012

Batch file to restart IIS service

Batch file to restart service

net stop "IIS Admin Service"
net start "IIS Admin Service"

You can change the name in the quotes to whatever other service.  If you run it manually, make sure to "Run it as administrator".  If you are using it in a scheduled task, you will need to give it the necessary permissions

If you get:
The following services are dependent on the IIS Admin Service service. Stopping the IIS Admin Service service will also stop these services.

World Wide Web Publishing Service

Do you want to continue this operation? (Y/N)

Then edit the batch file to include another parameter for this choice

net stop "IIS Admin Service" /yes
net start "IIS Admin Service"

[EDIT 2]
Apparently using the above will sometimes stop all websites

Wednesday, June 6, 2012

ASPxSpinEdit validation: number greater than 0

The only way I could find is to use the client-side validation event

or use regex if you find a good expression

Saturday, June 2, 2012

Using Master Pages in ASP.NET 4

Master Pages

Master pages contain a different page directive from normal pages.  Instead of @Page, masterpages have @Master.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %>

The Master page must have a contentplaceholder tag, where the pages deriving from this page will be inserted.

<asp:ContentPlaceHolder ID="MainContent" runat="server"/>

Content Pages

When creating a new page, you can derive from a selected Master Page by ticking 'Select master page'. After clicking 'Add', you will be prompted to select the masterpage from your website.

Adding a web page with master page
You can also do this by adding the following attribute in the @Page directive of the content page:

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" %>

This can also be done throughout the website by defining the masterpage in the pages element in the Web.config file. Any content pages that do not have the contentplaceholder will not apply the master page.

    <pages masterPageFile="~/Site.master" />

You can also change the page title from the content page by using the Title attribute in the Page directive.

The content page must contain a content control.  The markup written in this control will eventually be rendered in the contentplaceholder (with the same id) of the masterpage. You can have multiple content controls in a content page, as long as there are the same number of contentplaceholders in the masterpage

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        Put content here.

Note that the content place holder cannot be nested in other controls or tags or otherwise you will get the following error.  Same happens if there is no content placeholder in a content page.

Content controls have to be top-level controls in a content page or a nested master page that references a master page.

Note: Setting the EnableViewState property on the content page to true but setting the same property
to false in the master page, will result in having view state disabled because the setting on the
master page takes priority.

Getting controls from the Master Page

In order to get a control inside the master page from the content page you can use the FindControl method of the Master page property:

this.Master.FindControl("HeadLoginView") as LoginView;

Getting data from the Master Page

If you need a property from the master page, you will need to reference the master page in the content page by using the @MasterType directive

<%@ MasterType VirtualPath="~/Site.master" %>

Then from the content page, we can access the property that we need

lblUser.Text = this.Master.CurrentUser;

Changing Master Page dynamically

protected void Page_PreInit(object sender, EventArgs e)
this.MasterPageFile = String.Format("~/{0}.master", "Site2");

Wednesday, May 16, 2012

T-SQL: Select node value from xml column

SQL Code:

Column name is wau_xml

SELECT wau_xml.value('(/Document/VersionNo)[1]', 'int') FROM Table

XML in column:




Thursday, April 19, 2012

Error: A connection was successfully established with the server, but then an error occurred during the pre-login handshake

The local machine suddenly started giving me the error

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

In order to solve it, try the following

  1. Clean your Visual Studio solution
  2. Rebuild project
  3. Reset IIS
  4. Run the project again
This did the trick for me

Friday, April 13, 2012

AppendDataboundItems for ASPxCombobox

In order to mimic the 'AppendDataBound' feature found in normal ASP.NET comboboxes for devexpress and add items to a bound control, you need to use the databound event to insert the new values if you need a server side solution

protected void myComboBox_DataBound(object sender, EventArgs e)
            myComboBox.Items.Add("All", "0").Index = 0;
            myComboBox.SelectedIndex = 0;

You can also do it at client side by using the following code

comboBox.ClientSideEvents.Init = "function(s, e) {s.InsertItem(0, '(ALL)', '');}";

LINQ SubmitChanges() not working

Just a small note:

The problem was because the table did not have a primary key set.  The DataContext class requires a primary key to update

ASP.NET: Get/Set value from/to cookies

string cookieName;
private int CookieValue
            int _intValue =0;
            if(Request.Cookies[cookieName] != null)
                int.TryParse(Request.Cookies[cookieName].Value, out _intValue);

            return _intValue;
            if(Request.Cookies[cookieName] != null)
                Response.Cookies.Add(new HttpCookie(cookieName, Convert.ToString(value)));
                Response.Cookies["cookieName"].Value = Convert.ToString(value);

Storing multiple values in cookies

Response.Cookies[cookieName]["age"] = 16;
Response.Cookies[cookieName]["Name"] = "John";
Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(1);

Thursday, April 12, 2012

Batch file to launch applications with delay

Here is the code.  10 is the delay in seconds

ping –n 10>nul
start "" "C:\Program Files\Mozilla Firefox\firefox.exe"
start "" "C:\Program Files\Internet Explorer\iexplore.exe"

Short and simple :)

Tuesday, March 20, 2012

Operation is not valid due to the current state of the object

I was getting the above error because of this attribute in web.config
<pages maxPageStateFieldLength="20"

Which converts viewstate from this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQ2NDc1NTU1Mw8WAh4HX2xpbmVQSwIMFgICAw9kFgYCBw8UKwAFDxYEHg9EYXR .. . . . “ />

To this

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0NzQ5NTI4" />
<input type="hidden" name="__VIEWSTATE1" id="__VIEWSTATE1" value="ODcPFgIeB19saW5lUEsC" />
<input type="hidden" name="__VIEWSTATE2" id="__VIEWSTATE2" value="DBYCAgMPZBYIAgMPPCsA" />
<input type="hidden" name="__VIEWSTATE3" id="__VIEWSTATE3" value="BAEADxYCHgVWYWx1ZQUM" />
<input type="hidden" name="__VIEWSTATE4" id="__VIEWSTATE4" value="VTFBID4gTGluZSAyZGQC" />
<input type="hidden" name="__VIEWSTATE5" id="__VIEWSTATE5" value="Bw8UKwAFDxYEHg9EYXRh" />
<input type="hidden" name="__VIEWSTATE6" id="__VIEWSTATE6" value="U291cmNlQm91bmRnHwEF" />
<input type="hidden" name="__VIEWSTATE7" id="__VIEWSTATE7" value="BjIxNDM5OGRkZDwrAAkB" />
<input type="hidden" name="__VIEWSTATE8" id="__VIEWSTATE8" value="CBQrAAQWBB4SRW5hYmxl" />
<input type="hidden" name="__VIEWSTATE9" id="__VIEWSTATE9" value="Q2FsbGJhY2tNb2RlZx4n" />
<input type="hidden" name="__VIEWSTATE10" id="__VIEWSTATE10" value="RW5hYmxlU3luY2hyb25p" />
<input type="hidden" name="__VIEWSTATE11" id="__VIEWSTATE11" value="emF0aW9uT25QZXJmb3Jt" />
<input type="hidden" name="__VIEWSTATE12" id="__VIEWSTATE12" value="Q2FsbGJhY2sgaGQPFgIe" />

And in .NET4, there’s a maximum amount of input fields which can be present in a form (default = 1000).  If exceeded, the error in the subject occurs :’(

Tuesday, March 13, 2012

LINQ - Specified cast is not valid using SingleOrDefault

Was getting the below error when using SingleOrDefault

System.InvalidCastException: Specified cast is not valid

The problem was that I had changed the database schema but forgot to refresh the LinqToSql (DataContext) file

Thursday, February 9, 2012

T-SQL: Disable/Enable trigger script

Disable trigger script

USE AdventureWorks
--Make sure we are in the correct DB

ALTER TABLE HumanResources.Employee DISABLE TRIGGER HumanResources.dEmployee
--disabletrigger from a specific table

Enable trigger script

USE AdventureWorks
--Make sure we are in the correct DB

ALTER TABLE HumanResources.Employee ENABLE TRIGGER HumanResources.dEmployee
--enable trigger from a specific table

Erros encountered

When using the following script

ENABLE TRIGGER HumanResources.dEmployee ON HumanResources.Employee

I was getting the error

Error Message : Incorrect syntax near 'ENABLE'.

Using the version indicated above using the ALTER TABLE syntax, solved this issue

Monday, February 6, 2012

TetraChalk: Tetris Clone in XNA

This is a game which everyone in game development must one time or another create. Here is my version of it and I am pleased to say that I managed to polish it a bit unlike most of the games that I start.

I will try to write a tutorial on how I created the game

XNA Falling Blocks game: Tetrachalk

For now, you can download the game here.  Please feel free to comment on the game in the comments section below.

Tuesday, January 31, 2012

T-SQL: Number of working days between 2 dates

Number of working days between 2 dates in SQL

Both days are inclusive
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'

   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)

Friday, January 27, 2012

AJAX Control toolkit: Get/Set ActiveTabIndex in client side

Set ActiveTabIndex in Javascript

Code behind:
btnMyButton.OnClientClick = "$find('" + tcDocumentLines.ClientID + "').set_activeTabIndex(0);"

OnClientClick="$find('<%=tcDocumentLines.ClientID %>').set_activeTabIndex(0);"

Get ActiveTabIndex in Javascript

You will first need to register to the OnClientActiveTabChanged event by using the code below. tcTabChanged is the client-side function which will be run when the tab is changed by the user

Then create a function which will be called and do your custom logic in it. The sender object will reference the tabContainer and therefore we can call the get_activeTabIndex() method by using sender.get_activeTabIndex()
 function tcTabChanged(sender, args) {
        tabIndex = sender.get_activeTabIndex();
        switch (tabIndex) {
            case 1: { alert(tabIndex); } break; }

Tuesday, January 17, 2012

Check if control exists by ClientInstanceName

In order to check whether a specific Devexpress control exists using javascript, you can use the ASPxClientUtils.IsExists method. If the control exists, the method words as expected. The problem rises when the control you are looking for doesn't exist as this will cause the error 'ReferenceError: myControl is not defined' in javascript. In order to solve this, first use the eval function to check whether the object exists and put it inside a try catch.
var obj = null;
try { obj = eval('myClientASPxGridview'); } catch (e) { }
if (ASPxClientUtils.IsExists(obj))
Link to ASPxClientUtils.IsExists documentation

Tuesday, January 3, 2012

ASPxGridview Error: LinqDataSource '' does not support the Update operation unless EnableUpdate is true

When using ASPxGridview binded to a LinqServerModeDataSource, make sure that EnableUpdate is set to false when you are handling the update in the rowupdating event. I was getting the error

LinqDataSource '' does not support the Update operation unless EnableUpdate is true

because I forgot to add the following lines in the rowupdating event, which tells the grid that the event has been handled. Omitting these 2 lines causes the code to think that the update needs to be handled by the linqdatasource, which results in the above error

void MyGrid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
   //Code to update, example:
   //int pb_pk; int.TryParse(Convert.ToString(e.Keys[0]), out pb_pk);
   //int pb_w3_Budget_fk; int.TryParse(Convert.ToString(e.NewValues["pb_w3_Budget_fk"]), out pb_w3_Budget_fk);
   //SqlDataProvider.PurchasingBudgets_Update(pb_pk, pb_w3_Budget_fk);
   e.Cancel = true;
   (sender as ASPxGridView).CancelEdit();