Monday, April 20, 2009

C# - DataGridViewColumn.SortMode

.SortMode Property is related to the sort mode for the column in DataGridView control.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.sortmode.aspx

....
Share/Bookmark

Sunday, April 19, 2009

Regex - Free sources about regular expressions


A very valuable source for regular expressions:
http://www.regexlib.com/

Regular expression cheat sheets:
http://regexlib.com/CheatSheet.aspx
OR
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
OR
http://opencompany.org/download/regex-cheatsheet.pdf
...
Share/Bookmark

Regex - Reformat a string by regular expressions

Sometimes we have strings with different formats but same meaning, then may be it's better to keep them all with an standard format in our report to keep consistency and make it easier for users.

One example is format of a phone number, the standard format can be considered as "(###) ###-####" and here we have a solution by regular expression even though that many different regular expressions would work.

Match m = Regex.Match(str,
@"^\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$" );
string newStr = String.Format("({0}) {1}-{2}",
m.Groups[1], m.Groups[2], m.Groups[3] );


In above regular expression pattern, each \d{n} part is surrounded by parenthesis which makes that part as a separate group (then each of items exists in Match.Groups array) that can be easily used using String.Format, another reformatting method is Regex.Replace, it's a static method and in the following example it replace dates in mm/dd/yy format to dd-mm-yy format:

string newStr = Regex.Replace(str,
@"\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b",
"${day}-${month}-${year}" );

In above pattern, ${day} inserts the substring captured by the group (?\d{1,2}) and so on.

Note: \b in above pattern specifies that the match must occur on a boundry between \w (alphanumeric) and \W (nonalphanumeric) characters. It means a word boundary, which are the first and last characters in words separated by any nonalphanumeric characters.
Share/Bookmark

Regex - String input validation by regular expressions

Using regular expression is one of the most efficient ways to bring security to validate user input. As an example, the following regular expression works to match valid names:

[a-zA-Z'-‘Ãâå\s]{1,40}
...
using System.Text.RegularExpressions;
...
Regex.IsMatch(s, @"^[a-zA-Z'-‘Ãâå\s]{1,40}$" )
...

Generally most input validation should be pessimistic and allow only input that consists entirely of approved characters. In this way, may user encounter with some restrictions but it helps to protect against malicious input such as SQL injection attacks.
Share/Bookmark

C# - How to bind a TextBox to a DataGridView column

The goal is "bind a TextBox to a column in a DataGridView control" to be able to edit the cell in that columns for each rows and also show the value of the cell in that column when user move through the grid rows.

In the following code, imagine that we have a DataGridView called dgvTst and a TextBox control that called txtTst. To bind, CellClick event of DataGridView is coded as following:

private void dgvTst_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (txtTst.DataBindings.Count > 0)
txtTst.DataBindings.RemoveAt(0);

// The code binds column index 2 to the TextBox control
txtTst.DataBindings.Add(
new Binding("Text", dgvTst[2, e.RowIndex], "Value", false) );
}


Share/Bookmark

Wednesday, April 15, 2009

Visual Studio - Is it possible to install both VS 2005 and VS 2008 on same machine?

Yes, it's possible to have both on same machine.

If you have multiple version of Visual Studio on your system, to open a solution, right click the file and select "Open With" from the context menu, then you see "Microsoft Visual Studio Version Selector", if you use it, the solution automatically opens with the correct version (2005 or 2008) and it's depend on the VS version which you created your solution.
Share/Bookmark

Monday, April 13, 2009

C# - A common question - Value-type vs Reference-type - Struct vs Class

Value types:
Simplest types in the .NET, they contain their data directly instead of containing a reference to the memory that stored the data. Instances of value types are stored in an area of memory called the "stack", it brings performance and minimal overhead to create, change, read, or remove them.

Three general value types:
- Built in types
(sbyte, byte, short, int, uint, long, float, double, decimal)
(char, bool, date)
- User-defined types
(structures - by "struct")
- Enumerations
(enum - symbols that have fixed values)

Structures:
You can define them by "struct" and simply they are stored on the stack and they contain their data directly. Structures are composite of other types. Structure can store multiple values and it can have methods, those methods usually works on values which are stored in the structure.

You should define a structure rather than a class, if the user defined type will perform better as a value type than a reference type. Generally structures meet all the following criteria:

* Represents a single value logically
* Has an instance size that is less than 16 bytes. (Interesting)
* Is not frequently changed after creation.
* Is not cast (Converting between types) to a reference type.

If you assign an structure to another one, it will copy data and changing value in each one, doesn't affect the values in another one cuz data of structures are stored in different places in "stack".

Question:
You pass a value type variable into a method as an arguments, the method changes the variable, when the method returns, the variable has not changed, why?
A: Passing a value type into a method, creates a copy of the data.

----------------------------------
Reference types:
Most types in .NET are reference types (a few thousand!). Reference types store the address of their data (like pointers). The actual data that the address refers is stored in an area of memory called the "heap". Garbage collection manages the memory used by the heap by disposing of items that are no longer referenced. Assigning a reference type to another doesn't copy the data because a reference type just directly store the address of data.

Class is a reference type.
C# struct/class Differences
Share/Bookmark

Saturday, April 11, 2009

C# - Control.Tag property


Share/Bookmark

Tuesday, April 7, 2009

C# - List.FindIndex Method

Searches for an element that matches the conditions
defined by the specified predicate, and returns the
zero-based index of the first occurrence within the
entire List<(Of <(T>)>).


List<T>.FindIndex Method (Predicate<T>)

Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)

public int FindIndex(
Predicate<T> match
)



List<string> myLst = new List<string>();
...
// fill the list
...
int iIndx = 0;
if ( (iIndx = myLst.FindIndex(iIndx, StartWithEqualSign)) != -1 )
{
// Code for the row in the list which you found
}


// Search predicate returns true if a string starts with "=".
private static bool StartWithEqualSign(String s)
{
bool retVal = false;
if ( (s.Length > 0) && (s.Substring(0, 1) == "=") )
retVal = true;
return retVal;
}

Share/Bookmark

Monday, April 6, 2009

C# - ADO.NET - How to generate a DataTable based on table schema

In refer to another blog entry with title of
"Read table schema by SqlDataReader" in this weblog,
http://iborn2code.blogspot.com/2009/04/c-adonet-how-to-get-table-schema.html
now the following code shows how to use the
table schema to generate a DataTable based on
the schema:


DataTable retDtaTbl = new DataTable();

if (tblSchema.Rows.Count == 0)
return retDtaTbl;

tblSchema.DefaultView.Sort = "ColumnOrdinal";
foreach (DataRow rowSchema in tblSchema.Rows)
retDtaTbl.Columns.Add(
rowSchema["ColumnName"].ToString(),
System.Type.GetType( rowSchema["DataType"].ToString() ) );

Share/Bookmark