31 March 2010

How To: Use Regular Expressions to Constrain Input in ASP.NET

patterns & practices Developer Center
J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley
Microsoft Corporation
May 2005

Applies To

  • ASP.NET version 1.0
  • ASP.NET version 1.1
  • ASP.NET version 2.0

Summary

This How To shows how you can use regular expressions within ASP.NET applications to constrain untrusted input. Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. You can use them to constrain input, apply formatting rules, and check lengths. To validate input captured with server controls, you can use the RegularExpressionValidator control. To validate other forms of input, such as query strings, cookies, and HTML control input, you can use the System.Text.RegularExpressions.Regex class.
This How To shows how you can use regular expressions within ASP.NET applications to constrain untrusted input.

Contents

Objectives
Overview
Using a RegularExpressionValidator Control
Using the Regex Class
Common Regular Expressions
Additional Resources

Objectives

  • Use regular expressions to constrain input, apply format rules, and check lengths.
  • Use the ASP.NET RegularExpressionValidator control to constrain and validate input.
  • Use the Regex class to constrain and validate input.
  • Learn common regular expressions that can be used to constrain input.

Overview

If you make unfounded assumptions about the type, length, format, or range of input, your application is unlikely to be robust. Input validation can become a security issue if an attacker discovers that you have made unfounded assumptions. The attacker can then supply carefully crafted input that compromises your application by attempting SQL injection, cross-site scripting, and other injection attacks. To avoid such vulnerability, you should validate text fields (such as names, addresses, tax identification numbers, and so on) and use regular expressions to do the following:
  • Constrain the acceptable range of input characters.
  • Apply formatting rules. For example, pattern-based fields, such as tax identification numbers, ZIP Codes, or postal codes, require specific patterns of input characters.
  • Check lengths.
Regular expression support is available to ASP.NET applications through the RegularExpressionValidator control and the Regex class in theSystem.Text.RegularExpressions namespace.

Using a RegularExpressionValidator Control

If you capture input by using server controls, you can use the RegularExpressionValidator control to validate that input. You can use regular expressions to restrict the range of valid characters, to strip unwanted characters, and to perform length and format checks. You can constrain the input format by defining patterns that the input must match.
To validate a server control's input using a RegularExpressionValidator
  1. Add a RegularExpressionValidator control to your page.
  2. Set the ControlToValidate property to indicate which control to validate.
  3. Set the ValidationExpression property to an appropriate regular expression.
  4. Set the ErrorMessage property to define the message to display if the validation fails.
The following example shows a RegularExpressionValidator control used to validate a name field.

<%@ language="C#" %>
<form id="form1" runat="server">
    <asp:TextBox ID="txtName" runat="server"/>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    <asp:RegularExpressionValidator ID="regexpName" runat="server"     
                                    ErrorMessage="This expression does not validate." 
                                    ControlToValidate="txtName"     
                                    ValidationExpression="^[a-zA-Z'.\s]{1,40}$" />
</form>
The regular expression used in the preceding code example constrains an input name field to alphabetic characters (lowercase and uppercase), space characters, the single quotation mark (or apostrophe) for names such as O'Dell, and the period or dot character. In addition, the field length is constrained to 40 characters.
Using ^ and $
Enclosing the expression in the caret (^) and dollar sign ($)markers ensures that the expression consists of the desired content and nothing else. A ^matches the position at the beginning of the input string and a $ matches the position at the end of the input string. If you omit these markers, an attacker could affix malicious input to the beginning or end of valid content and bypass your filter.

Using the Regex Class

If you are not using server controls (which means you cannot use the validation controls) or if you need to validate input from sources other than form fields, such as query string parameters or cookies, you can use the Regex class within the System.Text.RegularExpressions namespace.
To use the Regex class
  1. Add a using statement to reference the System.Text.RegularExpressions namespace.
  2. Call the IsMatch method of the Regex class, as shown in the following example.
    // Instance method:
    Regex reg = new Regex(@"^[a-zA-Z'.]{1,40}$");
    Response.Write(reg.IsMatch(txtName.Text));
    
    // Static method:
    if (!Regex.IsMatch(txtName.Text, 
                       @"^[a-zA-Z'.]{1,40}$"))
    {
      // Name does not match schema
    }
For performance reasons, you should use the static IsMatch method where possible to avoid unnecessary object creation.
The following example shows how to use a regular expression to validate a name input through a regular client-side HTML control.

<%@ Page Language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <body>
    <form id="form1" method="post" action="HtmlControls.aspx">
        Name:
        <input name="txtName" type="text" />
        <input name="submitBtn" type="Submit" value="Submit"/>
    </form>
  </body>
</html>

<script runat="server">

  void Page_Load(object sender, EventArgs e)
  {
    if (Request.RequestType == "POST")
    {
      string name = Request.Form["txtName"];
      if (name.Length > 0)
      {
        if (System.Text.RegularExpressions.Regex.IsMatch(name, 
                                           "^[a-zA-Z'.]{1,40}$"))
          Response.Write("Valid name");
        else
          Response.Write("Invalid name");
      }
    }
  }

</script>
Use Regular Expression Comments
Regular expressions are much easier to understand if you use the following syntax and comment each component of the expression by using a number sign (#). To enable comments, you must also specify RegexOptions.IgnorePatternWhitespace, which means that non-escaped white space is ignored.

Regex regex = new Regex(@"
                        ^           # anchor at the start
                       (?=.*\d)     # must contain at least one numeric character
                       (?=.*[a-z])  # must contain one lowercase character
                       (?=.*[A-Z])  # must contain one uppercase character
                       .{8,10}      # From 8 to 10 characters in length
                       \s           # allows a space 
                       $            # anchor at the end", 
                       RegexOptions.IgnorePatternWhitespace);

Common Regular Expressions

Some common regular expressions are shown in Table 1.
Table 1. Common Regular Expressions
Field Expression Format Samples Description
Name ^[a-zA-Z''-'\s]{1,40}$ John Doe
O'Dell
Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. You can modify this list.
Social Security Number ^\d{3}-\d{2}-\d{4}$ 111-11-1111 Validates the format, type, and length of the supplied input field. The input must consist of 3 numeric characters followed by a dash, then 2 numeric characters followed by a dash, and then 4 numeric characters.
Phone Number ^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$ (425) 555-0123
425-555-0123
425 555 0123
1-425-555-0123
Validates a U.S. phone number. It must consist of 3 numeric characters, optionally enclosed in parentheses, followed by a set of 3 numeric characters and then a set of 4 numeric characters.
E-mail ^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$ someone@example.com Validates an e-mail address.
URL ^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$ http://www.microsoft.com Validates a URL
ZIP Code ^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$ 12345 Validates a U.S. ZIP Code. The code must consist of 5 or 9 numeric characters.
Password (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$ Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
Non- negative integer ^\d+$ 0
986
Validates that the field contains an integer greater than zero.
Currency (non- negative) ^\d+(\.\d\d)?$ 1.00 Validates a positive currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point. For example, 3.00 is valid but 3.1 is not.
Currency (positive or negative) ^(-)?\d+(\.\d\d)?$ 1.20 Validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point.

Additional Resources
For more information, see the regular expression tutorial at http://www.regular-expressions.info/tutorial.html.

 
Trovato qui.

25 March 2010

Tronca i log e compatta tutti i database (Sql2005)

Versione sia per Sql2000 che per Sql2005:
-- TRONCA I LOG E COMPATTA TUTTI I DATABASE
set nocount on


USE master
GO

EXEC sp_msForEachDB '
BACKUP LOG [?] WITH TRUNCATE_ONLY
DBCC SHRINKDATABASE (''?'', TRUNCATEONLY) WITH NO_INFOMSGS
'

Versione con cursore per Sql2005:
-- TRONCA I LOG E COMPATTA TUTTI I DATABASE ONLINE
-- VERSIONE PER SQL 2005
USE master
GO

set nocount on

declare	cur cursor for
select	name
from	sys.databases
where	database_id > 4 and
		state_desc = 'ONLINE'
order by 
		name

open cur

declare @nomeDB as nvarchar(255)

fetch next from cur into @nomedb

while @@fetch_status = 0 
begin
	print 'Processing ' + @nomeDB + '...'
	
	BACKUP LOG @nomeDB WITH TRUNCATE_ONLY
	DBCC SHRINKDATABASE (@nomeDB, TRUNCATEONLY) WITH NO_INFOMSGS

	fetch next from cur into @nomedb
end


close cur
deallocate cur

print ''
print 'Done.'

23 March 2010

Realizzare un AdRotator lato client con ASP.NET e jQuery

Il controllo AdRotator risulta utile tutte le volte in cui vogliamo visualizzare una serie banner pubblicitari in pagina, ma ha il problema di aggiornare il proprio contenuto solo in risposta ad un postback; ciò lo rende di fatto poco utilizzabile in scenari basati su AJAX o su applicazioni Silverlight, dato che in questi casi il numero di banner visualizzati diminuirebbe drasticamente a causa dei pochi refresh di pagina.
In contesti simili è possibile implementare una logica analoga sfruttando jQuery per invocare un servizio remoto e aggiornare l'interfaccia della pagina. Supponiamo allora di aver implementato, lato server, un metodo in grado di recuperare il prossimo banner da visualizzare:
[WebMethod]
public static string GetNextAdvertisement() 
{ 
    var rnd = new Random(DateTime.Now.Millisecond); 
    int index = rnd.Next(1, 5); 

    var serializer = new JavaScriptSerializer(); 
    return serializer.Serialize(new 
    { 
        ImageUrl = string.Format("images/Banner{0}.png", index), 
        Url = string.Format("advertisement.ashx?idx={0}", index) 
    }); 
}


Nel nostro esempio, la logica utilizzata per determinare il risultato è basata su numeri casuali, ma in uno scenario reale è possibile ovviamente implementare funzionalità più complesse, che accedano ad un database per recuperare un elenco di inserzionisti e memorizzino il numero di visualizzazioni di ogni banner. Il risultato è comunque un oggetto che contiene due proprietà ImageUrl e Url, serializzato in formato JSON utilizzando ilJavaScriptSerializer.
Grazie all'attributo WebMethod, questo metodo viene esposto da ASP.NET come un servizio ed è invocabile lato client tramite una chiamata AJAX simile alla seguente:


function askForNewBanner() { 
$.ajax({
url: "default.aspx/GetNextAdvertisement",
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { updateBanner(data.d); }
});
}


La funzione askForNewBanner utilizza il metodo jQuery.ajax per effettuare la chiamata remota al servizio. Esso consente di specificare un gran numero di parametri secondo cui deve avvenire la comunicazione; senza entrare troppo nei dettagli, nel nostro esempio l'URL è dato dall'indirizzo della pagina seguito dal nome del metodo. Quando l'invocazione si conclude con successo, il risultato ottenuto viene passato alla funzioneupdateBanner che deve effettivamente occuparsi di modificare il markup HTML.
In pagina il banner è realizzato con un div che contiene un link e un'immagine:


<div id="adv" style="visibility:hidden"> 
<a href="#">
<img src="" alt="adv" />
</a>
</div>


La funzione updateBanner è in grado di modificarne il contenuto a partire dalla stringa JSON fornita in input:


function updateBanner(data) { 
var obj = $.parseJSON(data);
$('#adv a').attr("href", obj.Url);
$('#adv a img').attr("src", obj.ImageUrl);
$('#adv').css("visibility", "visible");
}


Tramite il metodo jQuery.parseJSON, infatti, è possibile convertire una stringa JSON valida in un vero e proprio oggetto Javascript, che possiamo poi utilizzare per modificare il contenuto dell'immagine e impostare il relativo link.
Fino ad ora, insomma, siamo riusciti a realizzare un'infrastruttura client che interroga un servizio remoto e visualizza un banner pubblicitario in pagina in base alla risposta ottenuta. A questo punto non resta che temporizzarne l'esecuzione, in modo che gli inserzionisti possano essere effettivamente ruotati anche senza che avvengano refresh di pagina, ad esempio utilizzando il plugin jQuery Timers per mostrarne uno diverso ogni 30 secondi:


$(function() { 
askForNewBanner();
$(document).everyTime("30s", function() {
askForNewBanner();
});
});



Trovato qui

22 March 2010

Speed Up Windows 7 Taskbar Navigation with a Registry Hack

The fundamental problem was that you needed two clicks to navigate to your document if you have two instances of a program running. Or you're stuck with hovering for what feels like an eternity.

At Windows 7 Forums I finally found a nice step in the right direction. Full post is here, but summarized below. In short, this hack causes an applications last active window to activate when you click the taskbar icon, and the next window in the second click, etc. The hover preview still works if you hover to begin with, but if you want the preview after you've click on an app's icon in the taskbar, you can Ctrl+Click to bring it back. The current default settings are the exact opposite (that is, Ctrl+Click cycles through the last active windows of an application).

  • Launch regedit.exe
  • Navigate in the left tree control to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
  • Go to Edit->New->DWORD (32-bit) Value
  • Name the value LastActiveClick
  • Hit enter to assign the value and change it to 1
  • Restart Explorer and you're good to go.

To restart Explorer without rebooting, open the Task Manager (Ctrl+Shift+Esc) and end the Explorer.exe process. Then create a new task (under "File") and paste "explorer.exe".

19 March 2010

How To Replace Notepad in Windows 7

It used to be that Notepad was a necessary evil because it started up quickly and let us catch a quick glimpse of plain text files. Now, there are a bevy of capable Notepad replacements that are just as fast, but also have great feature sets.
Before following the rest of this how-to, ensure that you’re logged into an account with Administrator access.
Note: The following instructions involve modifying some Windows system folders. Don’t mess anything up while you’re in there! If you follow our instructions closely, you’ll be fine.
Choose your replacement
There are a ton of great Notepad replacements, including Notepad2, Metapad, and Notepad++. The best one for you will depend on what types of text files you open and what you do with them. We’re going to use Notepad++ in this how-to.
The first step is to find the executable file that you’ll replace Notepad with. Usually this will be the only file with the .exe file extension in the folder where you installed your text editor. Copy the executable file to your desktop and try to open it, to make sure that it works when opened from a different folder.
In the Notepad++ case, a special little .exe file is available for the explicit purpose of replacing Notepad.If we run it from the desktop, it opens up Notepad++ in all its glory.
sshot-1
Back up Notepad
You will probably never go back once you switch, but you never know. You can backup Notepad to a special location if you’d like, but we find it’s easiest to just keep a backed up copy of Notepad in the folders it was originally located.
In Windows 7, Notepad resides in:
  • C:\Windows
  • C:\Windows\System32
  • C:\Windows\SysWOW64 in 64-bit versions only
Navigate to each of those directories and copy Notepad.
sshot-2
Paste it into the same folder.
sshot-3
If prompted, choose to Copy, but keep both files.
sshot-4
You can keep your backup as “notepad (2).exe”, but we prefer to rename it to “notepad.exe.bak”.
sshot-6
Do this for all of the folders that have Notepad (2 total for 32-bit Windows 7, 3 total for 64-bit).
Take control of Notepad and delete it
Even if you’re on an administrator account, you can’t just delete Notepad – Microsoft has made some security gains in this respect. Fortunately for us, it’s still possible to take control of a file and delete it without resorting to nasty hacks like disabling UAC.
Navigate to one of the directories that contain Notepad. Right-click on it and select Properties.
sshot-7
Switch to the Security tab, then click on the Advanced button.
sshot-8
Note that the owner of the file is a user called “TrustedInstaller”.
sshot-9
You can’t do much with files owned by TrustedInstaller, so let’s take control of it. Click the Edit… button. Select the desired owner (you could choose your own account, but we’re going to give any Administrator control) and click OK.
sshot-10
You’ll get a message that you need to close and reopen the Properties windows to edit permissions. Before doing that, confirm that the owner has changed to what you selected.
sshot-11
Click OK, then OK again to close the Properties window. Right-click on Notepad and click on Properties again.
Switch to the Security tab. Click on Edit….
sshot-12
Select the appropriate group or user name in the list at the top, then add a checkmark in the checkbox beside Full control in the Allow column.
sshot-14
Click OK, then Yes to the dialog box that pops up.
sshot-15
Click OK again to close the Properties window.
Now you can delete Notepad, by either selecting it and pressing Delete on the keyboard, or right-click on it and click Delete.
sshot-16
You’re now free from Notepad’s foul clutches!
sshot-17
Repeat this procedure for the remaining folders (or folder, on 32-bit Windows 7).
Drop in your replacement
Copy your Notepad replacement’s executable, which should still be on your desktop.
sshot-18
Browse to the two or three folders listed above and copy your .exe to those locations. If prompted for Administrator permission, click Continue.
sshot-19
If your executable file was named something other than “notepad.exe”, rename it to “notepad.exe”. Don’t be alarmed if the thumbnail still shows the old Notepad icon.
sshot-20
Double click on Notepad and your replacement should open.
sshot-21
To make doubly sure that it works, press Win+R to bring up the Run dialog box and enter “notepad” into the text field. Press enter or click OK.
sshot-22
sshot-23
Now you can allow Windows to open files with Notepad by default with little to no shame! All without restarting or having to disable UAC!

18 March 2010

Downlad a web page – Scaricare una pagina web – Iron AdBlock.ini update

option explicit

' -----------------------------------------------------------------------------
' PARAMETERS
' -----------------------------------------------------------------------------
const source = "http://fanboy.co.nz/adblock/iron/adblock.ini"
const destination = "C:\Program Files (x86)\SRWare Iron\adblock.ini"
' -----------------------------------------------------------------------------


UpdateAdBlock source, destination


sub UpdateAdBlock(source, destination)
	
	' download adblock.ini
	GetHtmlPage source, destination
	
	' show message
	dim s : s = ReadFirstLines(destination, 3)
	MsgBox s, vbInformation, "Adblock updated"

end sub


sub GetHtmlPage (up_http, down_http)

	dim xmlhttp : set xmlhttp = createobject("msxml2.xmlhttp.3.0")
	xmlhttp.open "get", up_http, false
	xmlhttp.send

	dim fso : set fso = createobject ("scripting.filesystemobject")

	dim newfile : set newfile = fso.createtextfile(down_http, true)
	
	'and the text from the XMLHTTP response can then be written to the file:
	newfile.write (xmlhttp.responseText)

	'the file must then be closed:
	newfile.close

	set newfile = nothing
	set xmlhttp = nothing
	set fso = nothing

end sub


function ReadFirstLines(fileName, numberOfLines)
	
	const wChar = "§"
	dim res
	
	' open text file
	dim fso : set fso = createobject ("scripting.filesystemobject")
	dim ts : set ts = fso.OpenTextFile(fileName)
	
	' read the first x lines
	dim x
	for x = 1 to numberOfLines
		res = res & ts.ReadLine & wChar
	next
	
	ts.close
	set ts = Nothing
	set fso = Nothing
	
	' format output string
	if len(res) > 1 then
		res = left(res, len(res) - 1)
		res = replace(res, wChar, vbCrlf)
	end if
	
	ReadFirstLines = res
	
end function
Trovato qui.

01 March 2010

Console Screen Buffer

If you plan on making any console based games with the screen refreshing constantly you will find it flickers a lot unless you use what is known as a buffer. Here I show you a class that has a couple of functions to draw to, and then output the "image" to the console.

public class ScreenBuffer
{					
    //initiate important variables
    public static char[,] screenBufferArray = new char[roomWidth,roomHeight]; //main buffer array
    public static string screenBuffer; //buffer as string (used when drawing)
    public static Char[] arr; //temporary array for drawing string
    public static int i = 0; //keeps track of the place in the array to draw to
 
    //this method takes a string, and a pair of coordinates and writes it to the buffer
    public static void Draw(string text, int x, int y)
    {
        //split text into array
        arr = text.ToCharArray(0,text.Length);
        //iterate through the array, adding values to buffer 
        i = 0;
        foreach (char c in arr)
        {
            screenBufferArray[x + i,y] = c;
            i++;
        }   
    }
 
    public static void DrawScreen()
    {
        screenBuffer = "";
        //iterate through buffer, adding each value to screenBuffer
        for (int iy = 0; iy < roomHeight-1; iy++)
        {
            for (int ix = 0; ix < roomWidth; ix++)
            {
                screenBuffer += screenBufferArray[ix, iy];
            }
        }
    //set cursor position to top left and draw the string
        Console.SetCursorPosition(0, 0);
        Console.Write(screenBuffer);
        screenBufferArray = new char[Game.roomWidth, Game.roomHeight];
    //note that the screen is NOT cleared at any point as this will simply overwrite the existing values on screen. Clearing will cause flickering again.
    }
 
}

roomWidth and roomHeight are the width and height of your console screen respectively. This can easily be set using

Console.SetWindowSize(roomWidth,roomHeight);

Usage

Usage is very simple with this class. First of all you'll need to create the class by using

ScreenBuffer sb = new ScreenBuffer();

This simply create an instance of the ScreenBuffer class with the reference "sb" (you can change this to whatever you want). To draw to it all you need to do is use the method Draw.

ScreenBuffer.Draw("text here",x,y);

Beware that this method will not handle new lines correctly. This could be easily added by using a check within the draw function, and if it detects \n simply jump the the next line in the array. Now all you need to do is call the DrawScreen method at the end of the frame you are displaying and the array will be flushed onto the console screen, giving you a flicker free game!

~ knighty (Graeme Pollard - )

Trovato qui.