Articles written by Paul Hayman

Clean a string in C# using RegEx

Clean a string in C# using RegEx public static string CleanString(string input, string replaceWith) {     return System.Text.RegularExpressions.Regex.Replace(input, @"[^a-z^0-9^ ^-^_]", replaceWith, System.Text.Re

Paul Hayman - 3,859 views

Rendering a Twitter Tweet with Razor and C# MVC4

Rendering a Twitter Tweet with Razor and C# MVC4 Using Linq to Twitter I pulled a feed which I needed to render on a website. The body of the tweet was something like : RT @KristyT: The Floppy Disk means Save, and 14 other old p

Paul Hayman - 5,094 views

Get the progress of active SQL backups using TSQL

Get the progress of active SQL backups using TSQL The following script returns the status of any running backups on Microsoft SQL Server SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)     AS [Percent Complete

Paul Hayman - 3,616 views

List all Tables SQL Server

List all Tables SQL Server Here's a tiny bit of SQL for listing all the Tables in a database: SELECT      * FROM      sys.tables

Paul Hayman - 63,037 views

List all Stored Procedures SQL Server

List all Stored Procedures SQL Server Here's a tiny bit of SQL for listing all the Stored Procedures in a database: SELECT      * FROM      sys.procedures

Paul Hayman - 9,314 views

SQL Server Database, kill active processes and take it offline

SQL Server Database, kill active processes and take it offline Use the following TSQL to kill the active processes on a database and take it offline. DECLARE @DatabaseName nvarchar(50) SET @DatabaseName = N'databasename' DECL

Paul Hayman - 3,912 views

Select list of all tables in a MS SQL Server database including row count

Select list of all tables in a MS SQL Server database including row count The following script lists all tables in a database and their row count. SELECT      [TableName] = so.name,      [RowCount]&n

Paul Hayman - 3,014 views

Truncate all Logs on a SQL Server with TSQL

Truncate all Logs on a SQL Server with TSQL Hers's some T-SQL for truncating all logs on a Microsoft SQL Server: DECLARE @DBName varchar(255) DECLARE @LogName varchar(255) DECLARE @DATABASES_Fetch int DE

Paul Hayman - 8,373 views

Enable 'xp_cmdshell' in SQL server without Surface Area Configuration Tool

Enable 'xp_cmdshell' in SQL server without Surface Area Configuration Tool Here's the script needed for enabling 'xp_cmdshell' on a SQL Server. This allows you to run commands like MKDIR etc from TSQL. EXECUTE SP_CONFIGURE 'show advanced options', 

Paul Hayman - 2,583 views

Rendering a Gravatar image with Razor and C# MVC4

Rendering a Gravatar image with Razor and C# MVC4 I wanted to write a Helper Extension for Razor which rendered a Gravatar image .. see below: <div class="Author" style="position:relative;">     <div style="position:absolute; top:

Paul Hayman - 6,620 views

Output Exchange Message Tracking Log to CSV or Excel

Output Exchange Message Tracking Log to CSV or Excel I needed to output the Microsoft Exchange 2010 Message Tracking Log to CSV, here's the Exchange PowerShell command I used: get-messagetrackinglog -Start "07/09/2010 00:00:00" -End "07/09/2010 23:59:00"&

Paul Hayman - 14,535 views

Select a list of databases missing Primary keys

Select a list of databases missing Primary keys The following T-SQL returns a list of tables in a database which have no primary key set.  select * from sys.tables where object_id not in (      select o

Paul Hayman - 3,317 views

FTP series codes

FTP series codes Code Description 100 The requested action is being initiated, expect another reply before proceeding with a new command. 110 Restart marker reply. 120 Service ready in nnn minutes. 125 Data connection already open, transfer starting

Paul Hayman - 6,320 views

AS2 removeMovieClip not unloading my movie

AS2 removeMovieClip not unloading my movie I recently had a problem where removeMovieClip would remove everything I asked it to except for a couple of movies. Eventually, I tracked it down to a problem with the ID I had given the movie. It seems that movie ID's with full stops in cause

Paul Hayman - 2,161 views

Stopping Focus Highlight on a mx.controls.TextInput in ActionScript on TAB

Stopping Focus Highlight on a mx.controls.TextInput in Action Script on TAB I recently had a problem with a mx.controls.TextInput which rendered a highlignt area below the TextInput when I tabbed into the control. After much hunting around, I found the following Action Script solution:

Paul Hayman - 1,738 views

The easiest Hex string to/from byte array I've found

The easiest Hex string to/from byte array I've found When looking for a utility function to convert from a hex string to a byte array, I found this example .. works a treat! http://programmerramblings.blogspot.com/2008/03/convert-hex-string-to-byte-array-and.html Code

Paul Hayman - 19,945 views

Browser version detection in Javascript

Browser version detection in Javascript var ns4 = (navigator.appName.indexOf("Netscape")>=0 &&            parseFloat(navigator.appVersion) >= 4 &&   

Paul Hayman - 2,828 views

Geting the position of the mouse pointer (cursor) in JavaScript (Works in IE7)

Geting the position of the mouse pointer in JavaScript (Works in IE7) The following function will return the position of the mouse pointer based on the event. It actually works in IE7. function getPosition(e) {     e&nb

Paul Hayman - 17,798 views

Instanciating an object from it's type name

Instanciating an object from it's type name Instanciating a control from it's type name is easy.. string typeName = "YourNameSpace.YourObject"; Type assType = Type.GetType(typeName); object dynamicControl = Activator.CreateInstance

Paul Hayman - 1,899 views

Get the Top and Left location of an element with JavaScript

The following code will return the top and left position for an element. var ns4 = (navigator.appName.indexOf("Netscape")>=0            &&&nbs

Paul Hayman - 6,273 views

Returning the first few items from an Array list or IEnumerable collection

Returning the first few items from an Array list or IEnumerable collection, like T-Sql top() I needed to bind the first 5 items in a List<T> to a repeater. Having recently discovered the .Distinct() extension, I had a look through the other methods attached to my List<T> and foun

Paul Hayman - 3,206 views

Returning a Distinct list of values from an array or IEnumerable cllection

Returning a Distinct list of values from an array or IEnumerable collection I recently had a list of Guids in a string which was returned from a group of checkboxes with identical names. I wanted to itterate through Guids and process each one only once. Basicaly, ignoring duplicates. I

Paul Hayman - 4,671 views

Credit Card Number Ranges

Credit Card Number Ranges Here is the basic set of credit card number ranges: Issuer Identifier Card Number Length Diner's Club/Carte Blanche 300xxx-305xxx, 36xxxx, 38xxxx 14 American Express 34xxxx, 37xxxx 15 VISA 4xxxxx 13, 16 MasterCard

Paul Hayman - 6,290 views

Cleaning a string using a regular expression ready for placing in a URL

Cleaning a string using a regular expression ready for placing in a URL public static string CleanForUrl(string text) {     return Regex.Replace(text, @"[^a-z^A-Z^0-9^-]", "-"); }

Paul Hayman - 4,225 views

Displaying XML just like Internet Explorer

Displaying XML just like Internet Explorer This is everything you need to display XML in your webpage the same way IE displays it when you open an XML document in IE. Html Register the js and place a literal where you'd like the XML to appear. <script src="

Paul Hayman - 8,355 views

The best CSS rounded corners method

The best CSS rounded corners method I love this example : Even More CSS Roudned Corners 2 Project Home Basic Example The HTML is simple <div class="dialog"><div class="content"><div class="t"></div>   <!-- Your c

Paul Hayman - 5,314 views

Converting a String to a ByteArray in c#

Converting a String to a Byte Array in c# Very simple.. here's how to convert a String to a Byte Array in c# byte[] yourByteArray = Encoding.ASCII.GetBytes("your string");

Paul Hayman - 4,732 views

Reading a key from the registry in c#

Reading a key from the registry in c# The following c# code shows how to read a key value from the registry. Registry.LocalMachine.OpenSubKey("SOFTWARE", true); RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\yourapp\\yourkey")

Paul Hayman - 7,925 views

Specifying an originator IP Address on a WebService Request using ServicePoint and HttpWebRequest

Specifying an originator IP Address on a WebService Request using ServicePoint and HttpWebRequest If you're running multiple IP Addresses on the same NIC in Windows 2003 server and you need a webservice call to originate from a certain one, you'll probably have found the same thing I did. .n

Paul Hayman - 7,586 views

Regex for a HTML tag

Regex for a HTML tag <.[^>]*> This can proove invaluable when you're wanting to replace keywords in HTML without spoiling the tags themselves. Particularly useful in SEO.

Paul Hayman - 2,947 views

Regex match html content without screwing up the tags

Regex match html content without screwing up the tags When needing to highlight words in a string containing HTML we found we soon ran into problems when the word we were searching for appeared in the middle of a tag.. Imagine the example: <a href="geekzilla.aspx">you

Paul Hayman - 18,227 views

Backup ALL your SQL Server 2005 databases using ONE script

Backup ALL your SQL Server 2005 databases using ONE script I wanted to backup all my databases... I had loads, creating a step for each db was getting tedious, so I wrote this script. Enjoy DEC

Paul Hayman - 81,516 views

Dynamically adding a CSS link to the page in c#

Dynamically adding a CSS link to the page in c# The following code adds a CSS link to the header node of a Html page. // register css HtmlHead head = (HtmlHead)Page.Header; HtmlLink link = new HtmlLink(); link.Attributes.Add("href",

Paul Hayman - 45,035 views

Scrollbar CSS style generator

Scrollbar CSS style generator Excellent online tool for generating css for scrollbars http://iconico.com/CSSScrollbar/

Paul Hayman - 4,025 views

Excellent IIS Metabase Helper

Excellent IIS Metabase Helper Found this : http://agramont.net/blogs/provware/default.aspx http://agramont.net/blogs/provware/archive/2006/07/31/Provware_3A00_-Getting-Started-_2800_Build-001_2900_.aspx Has the potential to be an excellent Metabase wrapper.

Paul Hayman - 2,090 views

Preventing Caching of an ASP.net page in c#

Preventing Caching of an ASP.net page in c# The following code prevents a page being cached. public static void PreventCaching(HttpContext context) {     context.Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24,

Paul Hayman - 3,088 views

Getting the Virtual Path of a Request in c#

Getting the Virtual Path of a Request in c# This simple bit of code will get you the Virtual Path of your current request. public static string GetVirtualPath(string url) {     if (HttpContext.Current.Request.Application

Paul Hayman - 18,878 views

Fixing Form Action on UrlRewrite (UrlRewriter)

Fixing Form Action on UrlRewrite IF you're rewriting URL's, you've probably come across the same problem I had. When posting back on the page, the real URL is used.. this is a real pain if you're writing a page which uses the RawUrl to serve up relevant content. I had a good loo

Paul Hayman - 5,482 views

Awesome Sidebar Gadget

Awesome Sidebar Gadget This gadget is awesome (ESPECIALLY IN LARGE MODE): http://gallery.live.com/liveItemDetail.aspx?li=426dc418-12ce-481a-b886-89a66ca9127e System Control is much more than your average shutdown gadget. Aside from the normal Shutdown, Restart, Lock, and Sle

Paul Hayman - 5,831 views

Date Regular Expression (dd/MMM/yyyy)

Date Regular Expression (dd/MMM/yyyy) The following matches: 01/JAN/2007 22/Feb/2006 But doesn't match: 01/01/2007 22/02/2007 01 Jan 2007 ^(([0-9])|([0-2][0-9])|([3][0-1]))\/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\/\d{4

Paul Hayman - 30,953 views

Hex code Regular Expression (#F0F0F0)

Hex code Regular Expression (#F0F0F0) The following matches valid HTML hexadecimal color codes. The # symbol is optional. It will except either the 3 digit form for the 216 Web safe colors, or the full 6 digit form. ^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$

Paul Hayman - 16,748 views

Email Regex Pattern

Email Regex Pattern ^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$

Paul Hayman - 5,627 views

Time Regular Expression

Time Regular Expression ^([0-1][0-9]|[2][0-3]):([0-5][0-9])$ 

Paul Hayman - 5,020 views

How to get more than 3GB in Windows Vista 32-bit

How to get more than 3GB in Windows Vista 32-bit Out if the box, Vista (32-bit) only detects a maximum of 3GB of RAM. You're probably gutted if you just bought a 4GB PC. Vista 32-bit systems can actually detect 4GB RAM (and more!). Sometimes the O.S. does not see the 4th GB of RAM but

Paul Hayman - 7,049 views

GeekZilla Google Analytics Report August 07

GeekZilla Google Analytics Report August 07

Paul Hayman - 2,604 views

Adding a Strong Name to an existing DLL that you don't have the source to

Adding a Strong Name to an existing DLL that you don't have the source to There are times when you need a DLL to have a strong name; putting it in the GAC for example. With 3rd party DLL's this could be a pain. This is how you do it: From a VS.NET command prompt, enter the following:

Paul Hayman - 70,694 views

Fixing Actionscript XML newline problem

Fixing Actionscript XML newline problem I was having a nightmare with a newline \n coming through from an XML document literally as \n when I passed the text into a DynamicText object in ActionScript 2, Flash CS3. Mark Page found this solution: function fixXMLNewLin

Paul Hayman - 6,605 views

GeekZilla Google Analytics Report July 07

GeekZilla Google Analytics Report July 07

Paul Hayman - 2,447 views

Custom JavaScript attributes work differently in IE compared to Firefox

Custom JavaScript attributes work differently in IE compared to Firefox Adding custom attributes to HTML tags is a really valuable programming method. It's something I do quite often. Consider the following code: <script>     function 

Paul Hayman - 7,273 views

Firefox doesn't use parentElement, it uses parentNode

Firefox doesn't use parentElement, it uses parentNode JavaScript in FireFox doesn't support the function parentElement. You should use parentNode instead. Example: myElement.parentNode;

Paul Hayman - 9,433 views

Setting default collation on a column

Setting default collation on a column The following will set the collation on a column in a table back to Database Default without dropping and recreating the table (unlike Enterprise Manager) ALTER TABLE [MyTable] ALTER COLUMN [MyColumn]   

Paul Hayman - 9,247 views

Comments now use Wiki text

Comments now use Wiki text Comments added to articles now use wiki text.. this means you can paste code, include hyperlinks, use smileys. To paste code : add #c# infront of each line for C#, #h# for html, #v# for vb.net or #s# for T-SQL

Paul Hayman - 9,871 views

Returning a value from a PageMethod

Returning a value from a PageMethod using MS AJAX NOTE: This is designed for v1.0.61025.0 of AJAXExtensionsToolbox.dll If you've ever returned data from a web service using MS AJAX this technique will look familar. Call the method from javascript by append PageMethods. to the fro

Paul Hayman - 42,468 views

What screen size should we be building sites for?

What screen size should we be building sites for? With high resolution screens becoming increasingly cheaper to buy, what screen size should we really be building websites for? I took some stats from GeekZilla (in google analytics) and was pleased to find that the most popular was reas

Paul Hayman - 12,411 views

Getting the ProviderUserKey for the Current User

Getting the ProviderUserKey for the Current User The following gets the ProviderUserKey for the current user. (Guid)Membership.GetUser().ProviderUserKey

Paul Hayman - 3,736 views

Rendering a Control to a String

Rendering a Control to a String This is a really handy little function for rendering a control to a string. Really handy if you want to pass back rendered HTML from a StaticPageMethod or WebService. private static string GetRenderedControl(Control contr

Paul Hayman - 5,793 views

Programmatically registering a client script in the ScriptManager

Programmatically registering a client script in the ScriptManager Registering a client script in the ScriptManager is easy! ScriptManager.RegisterClientScriptInclude(Page, typeof(Page),          "MyScript",    &n

Paul Hayman - 7,730 views

Calling a static "page method" from Javascript using MS AJAX

Calling a static "page method" from Javascript using MS AJAX Atlas gave us the ability to easily call Web Services from JavaScript. MS AJAX has gone one step further! We can now call methods in the codebehine of the current page from Javascript. Here's how: This is designed for v1.0.61

Paul Hayman - 175,045 views

Launching an Ajax ModalPopupExtender from JavaScript

Launching an Ajax ModalPopupExtender from JavaScript This is an updated version of the earlier (and very popular) Atlas article It is by far the simplest way to launch an Ajax ModalPopupExtender from javascript. The groundworks Add a hidden link for ModalPopup Extender to attach

Paul Hayman - 88,093 views

Introducing Microsoft Silverlight

Introducing Microsoft Silverlight Ref : http://blogs.msdn.com/tims/archive/2007/04/15/introducing-microsoft-silverlight.aspx It is with tremendous pleasure that I can reveal Microsoft Silverlight: our next-generation, cross-platform, cross-browser web client runtime. Silverlight (prev

Paul Hayman - 1,941 views

ASP.NET Framework 1.1 Validation not working in IE7?

ASP.NET Framework 1.1 Validation not working in IE7? I recently had a problem with an old Framework 1.1 website where the form would not post back if the page contained validators (CustomValidators to be exact). It caused me to do a lot of googling and in the end some javascript debugging.

Paul Hayman - 6,607 views

geekzilla preparing for a facelift

geekzilla preparing for a facelift We're getting ready to facelift geekzilla using kwiboo's Wiki Content Management System as the foundation, making it more powerful, scalable, easier to use and more pleasing to the eye. If you have any suggestions please add a comment to this article.

Paul Hayman - 2,271 views

Great site for Vista WallPaper and more!

Great site for Vista WallPaper and More http://neosmart.net/gallery/v/wallpapers/Vista/official/

Paul Hayman - 2,491 views

Linking from one CSS StyleSheet to Another

Linking from one CSS StyleSheet to Another Simply add the following to the top of your CSS StyleSheet to link it to another: @import "MyOtherStylesheet.css"; NOTE: the path is relative to the current StyleSheet

Paul Hayman - 5,974 views

Centering a DIV using the negative margin method

Centering a DIV using the negative margin method The following CSS will center a DIV whih is 500px wide. This method is very clean and works in all browsers. div {      position: absolute;     left: 50%;  &nb

Paul Hayman - 16,849 views

Sorting an XML document in C# using XSL

Sorting an XML document in C# using XSL I needed to sort some XML in C# before itterating through the document. In the end I used the XslCompiledTransform to apply an XSL stylesheet to the XML document. Works very quickly. For reference, this is how I did it. The code The follo

Paul Hayman - 20,847 views

LoginStatus not logging users out?

LoginStatus not logging users out? Have you noticed your LoginStatus control doesn't log the user out when you click Logout? Well, to fix this all you need to do is add an id attribute. This works <asp:LoginStatus runat="server" id="loginstatus1" /> Thi

Paul Hayman - 6,927 views

No more cellspacing, roll on border-collapse!

No more cellspacing, roll on border-collapse! Confused as to why applying a css margin:0px and padding:0px doesn't remove the gaps between cells in tables? You need border-collapse. The cellpadding and cellspacing attributes are not deprecated in HTML 4 (and not even in XHTML 1.1), how

Paul Hayman - 2,832 views

Adding a transparent background to a Vista Gadget

Adding a transparent background to a Vista Gadget Adding a transparent background to a gadget is easy! Simply create a transparent .png file and reference it from your Gadget HTML. Here is an example file (also attached to this article as a download): Here is the HTML you

Paul Hayman - 24,451 views

A simple guide to creating your first Vista Gadget

A simple guide to creating your first Vista Gadget Gadgets are simply HTML and JavaScript. The SideBar exposes a bunch of API's which are accessible from JavaScript and extends the HTML schema. In this short guide we will greate a simple "Hello World" gadget. The four steps Cre

Paul Hayman - 34,125 views

By Invitation Only

By Invitation Only The GeekZilla community has been opened up by invitation only The team and their friends have all been issued 5 invitations each to send out to their buddies. The site is still in state of beta, it will be interesting to see how this wider group of developers a

Paul Hayman - 2,626 views

Using a .Net 2.0 anonymous delegate when generating a thumbnail

Using a .Net 2.0 anonymous delegate when generating a thumbnail Rather than using a mehod which does nothing except return false. Use a .Net 2.0 anonymous delegate for the GetThumbnailImageAbort parameter. delegate() { return false; } Example System

Paul Hayman - 3,156 views

Web 2 Ajax Style Animated Gif's

Web 2 Ajax Style Animated Gif's When searching high and low for a ajax style wait icon I came across the following sites. The first is a very good source of web 2 style animated gifs: http://www.sanbaldo.com/wordpress/1/ajax_gif/ - Example: I also found this GIF generator

Paul Hayman - 24,383 views

Visual Studio Orcas Beta 1 Available

Visual Studio Orcas Beta 1 Available You can now download Visual Studio Orcas Beta 1. Use one of the links found here: The Team Suite Edition on a Virtual PC Team Suite on a Virtual PC with Team Foundation Server Download the C# Express Edition

Paul Hayman - 1,852 views

Handy fake latin generator

Handy fake latin generator 4guysfromrolla have a handy "fake latin" generator. It allows you to specify the number of paragraphs to generate. Source available too, although old asp. http://www.4guysfromrolla.com/demos/latin.asp?paras=2

Paul Hayman - 5,089 views

How to turn on automatic logon in Windows XP

How to turn on automatic logon in Windows XP Original : http://support.microsoft.com/kb/315231 INTRODUCTION This article describes how to configure Microsoft Windows XP to automate the logon process by storing your password and other pertinent information in the registry database.

Paul Hayman - 20,482 views

Convert to and from Hex

Convert to and from Hex Convert from an int to Hex String result = String.Format("{0:x2}", 255) Convert from Hex to an int int result = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);

Paul Hayman - 3,142 views

Google Applicance - googleoff / googleon Tags

Google Applicance - googleoff / googleon Tags I came across these recently... thought I'd share The googleoff/googleon tags disable the indexing of a part of a web page. The result is that those pages do not appear in search results when users search for the tagged word or phrase. For

Paul Hayman - 53,079 views

Non Capturing Groups

Non Capturing Groups Expressions can contain a lot of groups which you weren't interested in matching on. It is possible to tell .net not to capture these by placing a ?: at the beginning of the group. Apparently limiting the number of capturing groups has a positive increase on performance.

Paul Hayman - 2,529 views

Using Regex Look Arounds

Using Regex Look Arounds .net supports four types of "Look Around". These can be used to make sure that patterns do or do not appear before or after whatever it is you're matching on. Consider the following text: "my car will be off the road for 2 days. it's reg num is ab123abc"

Paul Hayman - 13,878 views

Installing XNA Beta

Installing XNA Beta Ok, I thought I'd document the installation process and any pitfalls I encountered. I decided to install XNA on a VMWare machine, just to keep things clean, this didn't work as XNA couldn't detect an appropriate Direct3d compatible graphics card, so I installed it on the

Paul Hayman - 6,601 views

Microsoft XNA (Beta) Released

Microsoft XNA (Beta) Released Microsoft have released Microsoft XNA Game Studio Express (Beta). With all the hype surrounding this release we should be in for a real treat! Are Microsoft going to corner the market by releasing tools which enable developers to write their own games? Sho

Paul Hayman - 3,553 views

Creating a Tag Cloud in C#

Creating a Tag Cloud in C# I wanted to add a TagCloud to GeekZilla and another bespoke development project. The first thing I did was look around the web for some examples (or free components). To my supprise none jumped out at me. So, I decided to write my own. At first I found myself

Paul Hayman - 76,529 views

DateTime.ToString() Patterns

DateTime.ToString() Patterns All the patterns: 0 MM/dd/yyyy 08/22/2006 1 dddd, dd MMMM yyyy Tuesday, 22 August 2006 2 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30 3 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM 4 ddd

Paul Hayman - 1,327,407 views

Custom Templated SiteMap Navigator Control

Custom Templated SiteMap Navigator Control After discovering the power of the SiteMap, especially when linked to Authentication, it wasn't long before binding the TreeView to the map was not enough. I needed to have total control over what was displayed to the user for each item, so I

Paul Hayman - 6,272 views

The null coalescing operator: ??

The null coalescing operator: ?? This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows: string newValue = someVa

Paul Hayman - 4,525 views

Restricting the number of rows in a dataview when binding to a repeater

Restricting the number of rows in a dataview when binding to a repeater The problem I needed to restrict the number of items bound to an asp:repeater. Basically I never wanted more than 10 items to be displayed. Options The right thing to do would be to restrict the number of

Paul Hayman - 13,725 views

ISBN Number regular expression

ISBN Number regular expression string pattern = @"ISBN\x20(?=.{13}$)\d{1,5}([- ])\d{1,7}\1\d{1,6}\1(\d|X)$"; Examples // Valid Console.WriteLine(Regex.IsMatch(@"ISBN 0 93028 923 4", @"ISBN\x20(?=.{13}$)\d{1,5}([- ])\d{1,7}\1\d{1,6}\1(\d|X)$

Paul Hayman - 11,636 views

IP Address regular expression

IP Address regular expression string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"  

Paul Hayman - 83,549 views

Using named match groups in expressions

Using named match groups in expressions The following code will return the value user Console.WriteLine(Regex.Match(@"test\user", @".*\\(.*?)$").Groups[1]); Sometimes it makes life easier to refer to the group by name rather than its position (or GroupNum). To do this we ne

Paul Hayman - 4,314 views

Using Regex.Replace

Using Regex.Replace Say you want to get the username from a fully qualified username such as MyDomain\AUser Most developers would turn to SubString and LastIndexOf functions .. for example string userName = @"MyDomain\AUser"; string result = userNam

Paul Hayman - 11,859 views

Code snippet for 'protected void MethodName(object sender, EventArgs e)' method

Code snippet for 'protected void MethodName(object sender, EventArgs e)' method When adding a method to handle server events (such as OnClick) I often found myself copying the Page_Load method and changing the name. I looked for a snippet which would create this method for me but had no luck

Paul Hayman - 4,575 views

Programmatically adding LINKs to HTML HEADER in Code Behind

Programmatically adding LINKs to HTML HEADER in Code Behind In this example I am adding a link to the html header pointing to an rss feed. HtmlLink link = new HtmlLink(); link.Attributes.Add("type", "application/rss+xml"); link.Attributes.Add("rel",&

Paul Hayman - 13,330 views

Enabling Service Broker

Enabling Service Broker The following T-Sql enables or disabled service broker on SqlServer 2005. The Service Broker is required by .net for SqlCacheDependency support -- Enable Service Broker: ALTER DATABASE [Database Name] SET ENABLE_BROKER; -- Di

Paul Hayman - 65,058 views

Using Regular Expressions to validate a filename in a FileUpload control

Using Regular Expressions to validate a filename in a FileUpload control Here's a little code snippet I use to ensure that the file that has been uploaded is of type JPG, JPEG, PNG or GIF // check anything has been uploaded if (ThumbnailImageUpload.Poste

Paul Hayman - 71,033 views

Generating a resized image with maximum image quality

Generating a resized image with maximum image quality Here's some code I use for generating a resized image with no Jpeg compression. public MemoryStream GetResized(Bitmap originalImage, int width, int height) {

Paul Hayman - 3,198 views

Email Address Regular Expression

Email Address Regular Expression string pattern = @"([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)"  

Paul Hayman - 4,562 views

Mail and News Regular Expression

Mail and News Regular Expression string pattern = @"(?<ignore>(^|\s|\W)[\W*])?(?<uri>((mailto|news){1}:[^(//\s,)][\w\d:#@%/;$()~_?\+-=\\\.&]+))"  

Paul Hayman - 3,715 views

URL Regular Expression

URL Regular Expression string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)"  

Paul Hayman - 153,537 views

Highlighting keywords in text using Regex.Replace (Perfect for SEO)

Highlighting keywords in text using Regex.Replace (Perfect for SEO) Why I needed to take some text and bold certain keywords before returning the data to the web browser to enhance my Search Engine Optimization Example The following example shows how I achieved this althou

Paul Hayman - 27,688 views

What is a FavIcon

What is a FavIcon FavIcon (short for Favorites Icon) is a feature that makes it possible to associate a special logo or other small graphic with a web page. The favicon is usually displayed next to the web site address. Much like the way shortcut icons are used on the computer desktop

Paul Hayman - 2,890 views

Adding a Favicon to your site

Adding a FavIcon to your site Found a handy little site which allows you to upload a GIF or Jpeg and returns you a static and animated FavIcon with all the HTML you need to implement. http://www.chami.com/html-kit/services/favicon/

Paul Hayman - 2,955 views

Triple DES encryption wrapper

Triple DES encryption wrapper Here is a handy wrapper for Triple DES encryption:

Paul Hayman - 21,846 views

Launching an Atlas ModalPopupExtender from JavaScript

Launching an Atlas ModalPopupExtender from JavaScript Looking for an Ajax version of this article?? Looking round the web there are some crazy ways people are trying to launch the ModalPopupExtender from JavaScript, the most common way being setting a timeout which calls the Click meth

Paul Hayman - 54,475 views

Using a DataSet as a return type on an Atlas Javascript WebService call

Using a DataSet as a return type on an Atlas Javascript WebService call If the WebService you are calling returns a DataSet it may not be obvious how to get to the data in the returned object. Here is a little example which may help you on your way..

Paul Hayman - 8,136 views

Calling a WebService (from JavaScript) with Atlas

Calling a WebService (from JavaScript) with Atlas This is too easy and damn powerful! WebServices can be called from JavaScript directly once the service is registered in the Script Manager. Script Manager Add your service to the manager as seen below: <atlas:Script

Paul Hayman - 5,926 views

Could not write to output file ... The directory name is invalid

Could not write to output file ... The directory name is invalid Recently had a problem deploying an app to a fresh 2003 server. Basically, the application wouldn't start, instead we recieved an error stating that the compiler couldn't write to the "Temporary ASP.NET Files" folder because th

Paul Hayman - 17,055 views

Remembering position of DragOverlayExtender with Profile

Remembering position of DragOverlayExtender with Profile You can get Atlas to store the last known position of your floating panel in the profile. Three things you need to do to get this to work. ProfileScriptService In the page with the DragOverlayExtender you'll need to

Paul Hayman - 5,644 views

Intellisence not working in web.config?

Intellisence not working in web.config? Visual Studio 2005 has an interesting "feature" where Intellisence will not pop up when you're editing a web.config file. Annoying eh? Well, I found that removing the namespace from the configuration tag kicks it all back into life. Change the fo

Paul Hayman - 3,781 views

Changing the password rules for Forms Authentication

Changing the password rules for Forms Authentication An annoying feature of the forms authentication controls shipped with VS2005 is that it forces users to enter non-alphanumberic characters in their passwords by default.. e.g. password would have to be password! Fortunately, this opt

Paul Hayman - 4,715 views

Stopping simultaneous logins (Forms Authentication)

Stopping simultaneous logins (Forms Authentication) The following code (called from a page load) will bump off users who are logged in when someone else logs in with the same credentials. publi

Paul Hayman - 5,643 views

Reading a file which is locked by another process

Reading a file which is locked by another process The following code snippet shows how to read a file which is locked by another process.. FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read,&nb

Paul Hayman - 42,294 views

StringOrDBNull method

StringOrDBNull This method accepts a string and returns DBNull.Value if the string is null or empty. public static object StringOrDBNull(string value) {     try     {    &n

Paul Hayman - 2,397 views

CLR Stored Procedure for searching files

CLR Stored Procedure for searching files I was recently asked to write a CLR stored procedure which would process a text file and return a row for each line in the file that contained text matching our search criteria. I'd never written a CLR stored proc before so it was an interesting

Paul Hayman - 16,016 views

Enabling TRUSTWORTHY on a SQL 2005 Database

Enabling TRUSTWORTHY on a SQL 2005 Database If your .NET stored procedure wants to have external access, the targer database will have to have TRUSTWORTHY set on.. this is how you do it. ALTER DATABASE databasename SET TRUSTWORTHY ON; GO

Paul Hayman - 50,464 views

Enabling CLR execution in SQL Server

Enabling CLR execution in SQL Server If you plan to run stored procedures you have written in .NET you will probably need to enable CLR execution on your server. To do this you'll need to run the following T-SQL sp_configure 'clr enabled', 1 GO RECONFIGURE GO

Paul Hayman - 4,485 views

Writing CLR Stored Procedures in C#

Writing CLR Stored Procedures in C# As SQL Server 2005 rolls out DBA's are going to be forced to learn either C# or Visual Basic or both. Until now these were client side languages and not knowing them had little impact on your job. And if you write code in these languages your going to have

Paul Hayman - 16,010 views

IsGuid() (Regular Expression Guid Match)

IsGuid() (Regular Expression Guid Match) A regular expression for validating a string as being a Guid is.. @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" Example usage Below is a function I try to keep handy which t

Paul Hayman - 98,993 views

class.Serialize()

class.Serialize() Handly little function which I include in most classes. This function returns the object serialized as XML, perfect for logging etc. /// <summary> /// Serialize this object /// </summary> /// <returns>XmlDocumen

Paul Hayman - 7,469 views

DTS, Excel and mixed format columns

DTS, Excel and mixed format columns I recently had a problem DTS importing an Excel spreadsheet which contained columns with mixed text and data values. After a bit of hunting around, I found an extended property IMEX=1. The IMEX=1 property forces everything to text when reading from a sour

Paul Hayman - 8,923 views

Fixing broken users after Database Restore

Fixing broken users after Database Restore Ever restored a Database which was created on a different server then not been able to use the same logon you had previously set up? This command fixes the problem with the account. -- Replace username with the account to fix sp_change_

Paul Hayman - 8,247 views

Programmatically resolving ~ URL's to the Virtual Root using ResolveURL()

Programmatically resolving ~ URL's to the Virtual Root using ResolveURL() It's common knowledge that a control, when Runat="server" will resolve it's src or href attribute to a virtual root when the URL starts with ~/ For example: <a href="~/Customers/Profile.aspx" Runat=

Paul Hayman - 40,154 views

Assigning an array of strings to a variable

Assigning an array of strings to a variable Declaring a string array with hard coded data is easy. string[] newString = new string[] {"one", "two", "three"} Passing hard coded array into method Likewise, passing an array of hard coded data

Paul Hayman - 4,220 views

Handy Keyboard Shortcuts for c# 2005

Handy Keyboard Shortcuts for c# 2005 The following keyboard shortcuts I find invaluable. It's amazing how many people still use the mouse to do everything. Document navigation Ctrl+Tab Switch documents Ctrl+Shift+Tab Reverse switch documents Ctrl+kk Drop a bookm

Paul Hayman - 7,726 views

Why not on by defaut? Turn on auto HTML attribute quotes in 2005

Why not on by defaut? Turn on auto HTML attribute quotes in 2005 Holy cow! Why wasn't this on by default??? How annoying is it that when typing in the HTML Source editor window Visual Studio doesn't add the "" for you automatically?? If it's going to complain profusely about the missing quot

Paul Hayman - 5,297 views

Error in Line 3?

Error in line 3 Some websites report an error in line 3 when using the asp.net controls such as login. We recently tracked this error down on one of our sites to the use of custom HttpHandlers. All requests to anything other than *.aspx were routing through our own handler.. Addi

Paul Hayman - 3,756 views

Evaluating Expressions

Evaluating Expressions You can evaluate sums in the fly using .net DataTables. This is how you do it (C# 2005). string sum = "(1+2)/4"; System.Data.DataTable evaluator = new System.Data.DataTable("temp"); double result;   resu

Paul Hayman - 5,251 views