Monday, March 30, 2009

C# - ADO.NET - How to Copy DataRow(s) of one DataTable to another?

Clearly simple codes just to remembering them for later!


DataTable trgtDtaTbl = new DataTable();
trgtDtaTbl = srcDtaTbl.Clone();
foreach (DataRow srcDR in srcDtaTbl.Rows)
{
// "if (srcDR is not qualified) continue;"
DataRow tmpDR = trgtDtaTbl.NewRow();
tmpDR.ItemArray = srcDR.ItemArray;
trgtDtaTbl.Rows.Add(tmpDR);
}



DataTable destDtaTbl = new DataTable();
string tmpFltr = srcDtaTbl.DefaultView.RowFilter;
srcDtaTbl.DefaultView.RowFilter = String.Empty;

destDtaTbl = srcDtaTbl.DefaultView.ToTable().Copy();

srcDtaTbl.DefaultView.RowFilter = tmpFltr;

Share/Bookmark

Sunday, March 29, 2009

Regular Experessions - Part 2 - WildCards

To match repeated characters there are symbols for regular expression that makes the job possible.

Metacharacter Description Equivalent
------------- ----------- ----------
* Matches the preceding character or {0,}
subexpression zero or more times.

+ Matches the preceding character or {1,}
subexpression one or more times.

? Matches the preceding character or {0,1}
subexpression zero or one time.

{n} Matches the preceding character or
subexpression exactly n times. n>0

{n,m} Matches the preceding character or
subexpression at least n and at most
m times. (n > 0), (m > 0), (n <= m)

? (nongreedy) - A nongreedy pattern matches as
little of the searched string as
possible.
- A greedy pattern (default) matches
as much of the searched string as
possible.
? follows any other quantifiers [*,
+, ?, {n}, {n,m}], makes a nongreedy
pattern. Example: in string "aaaaa",
a+? matches a single 'a', but a+
matches all a's.

a|b Matches either a or b. a|book matches
a or book and (a|b)ook matches aook
or book.

[abcd] A character set, matches any one of
the enclosed characters. Example: [ab]
matches 'a' in "Plane".

[a-z] A range of characters. Example: to match
all alphanumeric characters [a-zA-Z0-9].

Share/Bookmark

Friday, March 27, 2009

Regular Experessions - Part 1 - Regex (System.Text.RegularExpressions)

A regular expression is a set of characters that can be compared to a string to determine whether it meets specified format requirements. For validation purposes and to check user inputs, regular expressions are an extremely efficient way.

To use regular expression class and related methods, you need to add its namespace:

using System.Text.RegularExpressions;
...
if (txtRegExp.Text == String.Empty) return;
if (Regex.IsMatch(txtRegExp.Text, @"^\d{3}$"))
MessageBox.Show(String.Format("This strings '{0}' contains 3 digits.",
txtRegExp.Text));
...

In above example regular expression string is "^\d{3}$",
- Leading Caret (^) represent the start of string.
- $ sign represents the end of the string.
- \d means numeric digits.
- {3} indicates three sequential numeric digits.

If you omit leading caret ^ the regular expression would be "\d{3}$" and the expression still matching any string which ending with three digit numbers.
Share/Bookmark

Thursday, March 26, 2009

Compressed Streams - GZipStream

GZipStream class allow you to write compressed streams which can consume less storage space. Using GZipStream, you can read and write only individual byte and byte arrays and if your data type is other than bytes, you should use StreamWriter and StreamReader to save strings in a compressed stream.



FileStream fs =
new FileStream(@"C:\fb\tst.txt",
FileMode.Create,
FileAccess.ReadWrite);
FileStream fsCmprs =
new FileStream(@"C:\fb\txtCmprs.txt",
FileMode.Create,
FileAccess.ReadWrite);
GZipStream gzCmprs =
new GZipStream(fsCmprs,
CompressionMode.Compress);

StreamWriter sw = new StreamWriter(fs);
StreamWriter swCmprs = new StreamWriter(gzCmprs);

for (int i = 0; i < 10000; i++)
{
sw.WriteLine(String.Format("{0}_ this is a test.", i));
swCmprs.WriteLine(String.Format("{0}_ this is a test.", i));
}

sw.Flush();
sw.Close();

swCmprs.Flush();
swCmprs.Close();

gzCmprs.Close();
fsCmprs.Close();
fs.Close();


Share/Bookmark

Thursday, March 5, 2009

T-SQL - OPENROWSET( BULK ...


OPENROWSET
( BULK 'data_file' ,
{ FORMATFILE = 'format_file_path' [ ]
| SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }
} )

::=
[ , CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' } ]
[ , ERRORFILE = 'file_name' ]
[ , FIRSTROW = first_row ]
[ , LASTROW = last_row ]
[ , MAXERRORS = maximum_errors ]
[ , ROWS_PER_BATCH = rows_per_batch ]


OPENROWSET supports bulk operations too through a built-in BULK provider
that enables data from a file to be read and returned as a rowset.

BULK
Uses the BULK rowset provider for OPENROWSET to read data from a file.
In SQL Server, OPENROWSET can read from a data file directly which it
lets you use OPENROWSET with a simple SELECT statement.

With bulk options and arguments you can control the start position and
end of reading data, how to deal with errors, and how data is interpreted.

'data_file'
Full path of the data file whose data is to be copied into the target table.

FORMATFILE = 'format_file_path'
Full path of a format file, for more info look at the following URL:
http://msdn.microsoft.com/en-us/library/ms178129.aspx

SINGLE_BLOB
Returns the contents of data_file as a single-row, single-column rowset
of type varbinary(max).

Note: It's recommended only use this option to import XML dat because
only SINGLE_BLOB supports all Windows encoding conversions.

SINGLE_CLOB
It returns the contents as a single-row, single-column rowset of type
varchar(max) using the collation of the current database when you read
an ASCII data file.

SINGLE_NCLOB
It returns the contents as a single-row, single-column rowset of type
nvarchar(max) using the collation of the current database when you read
an UNICODE data file.

Some notes about using OPENROWSET with the BULK Option
OPENROWSET(BULK...) function:

* A FROM clause that is used with SELECT can call OPENROWSET(BULK...)
instead of a table name, with full SELECT functionality.
OPENROWSET with the BULK option requires an alias in the FROM clause.
Column aliases can be specified. If a column alias list is not specified,
the format file must have column names. Specifying column aliases overrides
the column names in the format file, such as:
FROM OPENROWSET(BULK...) AS table_alias
FROM OPENROWSET(BULK...) AS table_alias(column_alias,...n)
* A SELECT...FROM OPENROWSET(BULK...) statement queries the data in a file
directly, without importing the data into a table.
* Using OPENROWSET(BULK...) as a source table in an INSERT or MERGE statement
bulk imports data from a data file into a SQL Server table.
* When the OPENROWSET BULK option is used with an INSERT statement, the BULK
clause supports table hints.

To bulk import data, call OPENROWSET(BULK ..) from a SELECT ... FROM clause within
an INSERT statement. The basic syntax for bulk importing data is:

INSERT ... SELECT * FROM OPENROWSET(BULK...)

Simple examples:

USE test
INSERT INTO myTable (dataFileClmn)
SELECT * FROM OPENROWSET(BULK 'C:\DataFile.txt', SINGLE_NCLOB) as A

USE test
INSERT INTO myXmlFilesTable (xmlFileClmn)
SELECT * FROM OPENROWSET(BULK 'C:\TestXml.xml', SINGLE_BLOB) AS A

Share/Bookmark

Monday, March 2, 2009

C# - DataGridView - delete a row by context menu strip

"How to remove a data row from a DataGridView control using a context menu strip"

The following codes just show one of possible methods to do the job.

To keep the DataGridView row index which is selected by right click, we need a private variable in our form class, let's call it iDGVrow2Del. You need to drag and drop a context menu strip control to your form that we call it mnuStrp4DgvMyData too for our example. Then you should show the menu when user right click on a row in your DataGridView which we call it dgvMyData here. To find when the user does right click, you can write your code in CellMouseUp method of DataGridView and if you found a right click, just you need to keep the row index and then Show the context menu. The menu can keep just an item with "Delete Row" as its text. At last code for Click event of that menu strip object to check if the row is not an empty new row in your DataGridView then remove it using its index in iDGVrow2Del variable from your Row collection of the DataGridView. Here you go ... The simple sample code is as following:


private int iDGVrow2Del = 0;

private void dgvMyData_CellMouseUp(object sender,
DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.dgvMyData.Rows[e.RowIndex].Selected = true;
this.iDGVrow2Del = e.RowIndex;

this.dgvMyData.CurrentCell =
this.dgvMyData.Rows[e.RowIndex].Cells[1];

this.mnuStrp4DgvMyData.Show(this.dgvMyData, e.Location);
}
}

private void mnuStrp4DgvMyData_Click(object sender, EventArgs e)
{
if (!this.dgvMyData.Rows[this.iDGVrow2Del].IsNewRow)
this.dgvBcktSrch.Rows.RemoveAt(this.iDGVrow2Del);
}

Share/Bookmark