Thursday, 15 November 2007

Disabling the Window Close Button and System Close menu in a Windows Form

A useful snippet for disabling the X button on a window form in c#:

1. Use an api call to user32.api

Basically, this call uses GetSystemMenu() to get a handle to the menu with the close, maximize and minimize buttons. Then, the EnableMenuItem() call comes along and sets it so that the close button is greyed out (i.e. disabled).

NB. The code needs to go in the Paint handler because otherwise the changes to the close button will not be retained when the form is repainted (e.g. when you minimise and then restore).

C# Source:


Use these constants

///
/// Windows constant that represents the X button on a window
///
private const int SC_CLOSE = 0xF060;

///
/// Menu API Constant: Enables the menu item so that it can be selected and restores it from its grayed state.
///
private const int MF_ENABLED = 0;

///
/// Menu API Constant: Disables the menu item and grays it so it cannot be selected.
///
private const int MF_GREYED = 0x1;

///
/// Menu API Constant: Identifies menu item position by command.
///
private const int MF_BYCOMMAND = 0;

Then add references to the api windows methods:

///
/// Windows api call to get the system menu
///
/// hWnd Handle of window

/// revert Specifies the action to be taken. If this parameter is FALSE, GetSystemMenu returns a handle to the copy of the window menu currently in use. The copy is initially identical to the window menu, but it can be modified. If this parameter is TRUE, GetSystemMenu resets the window menu back to the default state. The previous window menu, if any, is destroyed.
/// returns variable: if the bRevert parameter is FALSE, the return value is a handle to a copy of the window menu. If the bRevert parameter is TRUE, the return value is NULL.
[DllImport("user32")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, int revert);

///
/// Windows api call to enabling a menu item
///
/// hWndMenu handle to the window menu
/// itemID item to enable
/// enable enable/disable/greyed
/// returns variable: The return value specifies the previous state of the menu item (it is either MF_DISABLED, MF_ENABLED, or MF_GRAYED). If the menu item does not exist, the return value is -1.
[DllImport("user32")]
private static extern int EnableMenuItem(IntPtr hWndMenu, int itemID, int enable);

This private field to represent if the close x is enabled/disabled

///
/// Flag to represent if a form window close x is enabled/disabled
///
private bool closeEnabled = false;

and finally a public property - so we can access this outside the form if required.

///
/// Property manages the visibility of the X close button on this form window
///
public bool CloseEnabled
{
get { return closeEnabled; }
set
{
//Decide on the state to pass based on the value being set
int setting = (value) ? MF_BYCOMMAND | MF_ENABLED : MF_BYCOMMAND | MF_GREYED;

try
{
EnableMenuItem(GetSystemMenu(this.Handle, 0), SC_CLOSE, setting);
}
catch { }
closeEnabled = value;
}
}


2) Set the 'ControlBox' property on the form to false

this.ControlBox = false;

However this disables the entire system menu strip - i.e. icon drop down etc. so may not be of use.

Also by holding down ALT-F4 - this often closes an application window and therefore you would need to capture this in the form_closing event - and set event args e to cancel.

i.e. e.cancel = false;

Thursday, 27 September 2007

Regular Expressions a bind - not anymore :) - Expresso

This great little tool found a while back saves a lot of hassle :)

Expresso by Ultrapico

Thursday, 13 September 2007

Long Text Fields in NHibernate

Beware if you do not include type="StringClob" on a large text field in the nhibernate mapping it will automatically chop to around 2000 characters - this is because it defaults the size when creating the parameter. You can avoid this by using the above :)

Tuesday, 4 September 2007

Useful system views on sql server - there are loads but here are the useful ones

all abbreviated sys.*

sys.sql_logins Lists all users who can access the database.
sys.columns Lists all columns on database
sys.tables Lists all tables on database
sys.assemblies Lists all assemblies on database
sys.foreign_keys Lists all foreign keys on database
sys.triggers Lists all triggers on database
sys.procedures Lists all procedures on database

Friday, 10 August 2007

Regular Expression for National Insurance Number

Here is a regular expression for the UK National Insurance Number accepting values such as AB123456C etc

^[A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}\s?[0-9]{2}\s?[0-9]{2}\s?[0-9]{2}\s?[A-DFM]{0,1}$

Monday, 23 July 2007

How do i find the xpath of an XmlNode in c#?

I came across this problem today where I was trying to find the xpath of the current node, so i could access the parent and remove that node from the collection. I knocked together some useful code to remove this. It basically works out the position of that node in the document and then which child it is on the child node.


/// <summary>
/// Gets an xpath to a node
/// </summary>
/// <param name="node">Node to get xpath for</param>
/// <returns>Xpath for node</returns>
private static string GetXPathToNode(XmlNode node)
{
if (node.NodeType == XmlNodeType.Attribute)
{
// attributes have an OwnerElement, not a ParentNode; also they have
// to be matched by name, not found by position
return String.Format(
"{0}/@{1}",
GetXPathToNode(((XmlAttribute)node).OwnerElement),
node.Name
);
}
if (node.ParentNode == null)
{
//Have root node - so return empty path
return "";
}

// the path to a node is the path to its parent, plus "/node()[n]", where
// n is its position among its siblings.
return String.Format(
"{0}/node()[{1}]",
GetXPathToNode(node.ParentNode),
GetNodePosition(node)
);
}

/// <summary>
/// Gets node position in relation to the child
/// </summary>
/// <param name="child">Child</param>
/// <returns>Position on parent</returns>
private static int GetNodePosition(XmlNode childNode)
{
for (int position = 0; position < childNode.ParentNode.ChildNodes.Count; position++)
{
if (childNode.ParentNode.ChildNodes[position] == childNode)
{
// need to add one as xpath index starts not at zero
return position + 1;
}
}
throw new InvalidOperationException("Missing Child Node");
}

Thursday, 12 July 2007

JavaScript popup window features

Here are the window.open options for the JavaScript window.open method, just set =1 if you want them included or =0 if you want them hidden.

status
Determines if you want the status bar at the bottom of the window to be shown

toolbar
This shows/hides the standard browser bar i.e. the back and forward buttons amongst others.

location
The location bar where you enter url’s.

menubar
This shows or hides the menu bar for the browser.

directories
This shows or hides the directories toolbar – i.e. whats new etc.

resizable
Enables/disables the user to resize the browser window.

scrollbars
Enable the scrollbars if the document takes up more area than the window

height
The height of the window in pixels. (i.e.: height='550')

width
The width of the window in pixels.

Tuesday, 19 June 2007

Granting permission to a user to create stored procedures on SQL Server 2005

To enable a user to create stored procedures on a SQL Server 2005 use

GRANT ALTER ON SCHEMA::dbo TO

GRANT CREATE PROCEDURE TO

Friday, 15 June 2007

How to remove all empty nodes from an XmlDocument in c#

I've used xsl before for stripping out unwanted empty nodes from passed xml - but now needed it for some c# code. So I created the following chunk of code and it works a treat.

This is the xslt which does all the hard work...


<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="no"/>
<xsl:strip-space elements="*" />
<xsl:template match="*[not(node()) and not(./@*)]"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


And some code...

//Xsl to strip stylesheet
string strippingStylesheet = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output omit-xml-declaration=\"no\" indent=\"no\"/><xsl:strip-space elements=\"*\" /><xsl:template match=\"*[not(node()) and not(./@*)]\"/><xsl:template match=\"@* | node()\"><xsl:copy><xsl:apply-templates select=\"@* | node()\"/></xsl:copy></xsl:template></xsl:stylesheet>";

//Set up empty node stripper
XmlDocument stripper = new XmlDocument();
stripper.LoadXml(strippingStylesheet);

//Compile here
StringWriter output = new StringWriter();
XslCompiledTransform emptyNodeRemover = new XslCompiledTransform();
emptyNodeRemover.Load(stripper);

//Port output to string
StringWriter output = new StringWriter();
emptyNodeRemover.Transform(new XmlNodeReader(source), null, output);
output.Flush();

//Reload source with emptied nodes
source.LoadXml(output.ToString());
output.Close();
output.Dispose();

Friday, 18 May 2007

Adding columns dynamically to a data grid control

Ok just a quick note here for the future. To add columns (i.e. bound or template etc) columns to a datagrid use the following:-

make sure the autogenerate on the data grid is switched off.

dataGrid1.AutoGenerateColumns=false;

then loop over the columns in the data source table.

foreach (DataColumn dc in dataTable.Columns)
{
BoundColumn newColumn = new BoundColumn();
newColumn.DataField = dc.ColumnName;
newColumn.HeaderText = ;

dataGrid1.Columns.Add(newColumn);
}

etc.

If you autogenerate the columns then the columns collection on the data grid will have no items.