DataTable.Load(IDataReader);
Convert Data Reader to Data Table
DataTable.Load(IDataReader);
A cricketer by heart & a developer by mistake
In this article, I have compiled some common String operations that we encounter while working with the String class. All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.
C#
for (int i = 0; i < strOriginal.Length; i++)
{
MessageBox.Show(strOriginal[i].ToString());
}
or
foreach (char c in strOriginal)
{
MessageBox.Show(c.ToString());
}
For i As Integer = 0 To strOriginal.Length - 1
MessageBox.Show(strOriginal(i).ToString())
Next i
Or
For Each c As Char In strOriginal
MessageBox.Show(c.ToString())
Next c
2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.
C#
char[] delim = {' '};
string[] strArr = strOriginal.Split(delim);
foreach (string s in strArr)
{
MessageBox.Show(s);
}
Dim delim As Char() = {" "c}
Dim strArr As String() = strOriginal.Split(delim)
For Each s As String In strArr
MessageBox.Show(s)
Next s
3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.
C#
// only starting position specified
strModified = strOriginal.Substring(25);
MessageBox.Show(strModified);
// starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3);
MessageBox.Show(strModified);
' only starting position specified
strModified = strOriginal.Substring(25)
MessageBox.Show(strModified)
' starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3)
MessageBox.Show(strModified)
4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:
C#
// Single Dimensional String Array
string[] strArr = new string[3] { "string 1", "string 2", "string 3"};
// Omit Size of Array
string[] strArr1 = new string[] { "string 1", "string 2", "string 3" };
// Omit new keyword
string[] strArr2 = {"string 1", "string 2", "string 3"};
// Multi Dimensional String Array
string[,] strArr3 = new string[2, 2] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit Size of Array
string[,] strArr4 = new string[,] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit new keyword
string[,] strArr5 = { { "string 1", "string 2" }, { "string 3", "string 4" } };
' Single Dimensional String Array
Dim strArr As String() = New String(2) { "string 1", "string 2", "string 3"}
' Omit Size of Array
Dim strArr1 As String() = New String() { "string 1", "string 2", "string 3" }
' Omit new keyword
Dim strArr2 As String() = {"string 1", "string 2", "string 3"}
' Multi Dimensional String Array
Dim strArr3 As String(,) = New String(1, 1) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit Size of Array
Dim strArr4 As String(,) = New String(, ) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit new keyword
Dim strArr5 As String(,) = { { "string 1", "string 2" }, { "string 3", "string 4" } }
5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function. To use it in C#, you need to add a reference to the Microsoft.VisualBasic dll.
C#
string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
MessageBox.Show(strModified);
Dim strModified As String = StrReverse(strOriginal)
MsgBox(strModified)
6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).
C#
if ((string.Compare(strOriginal, strModified, false)) < 0)
{
MessageBox.Show("strOriginal is less than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) > 0)
{
MessageBox.Show("strOriginal is more than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) == 0)
{
MessageBox.Show("Both strings are equal");
}
If (String.Compare(strOriginal, strModified, False)) < 0 Then
MessageBox.Show("strOriginal is less than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then
MessageBox.Show("strOriginal is more than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then
MessageBox.Show("Both strings are equal")
End If
7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).
C#
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)
Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
C#
// Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b);
' Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b)
ppppline
During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.
In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.
Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.
NOT Recommended
str = "something" if (str == null || str == String.Empty) { // Oh no! the string isn't valid! }
Recommended
str = "something" if (String.IsNullOrEmpty(str)) { // Oh no! the string isn't valid! }
NOT Recommended
str = "something" if (str == null || str.Trim() == String.Empty) { // Oh no! the string isn't valid! }
Recommended (C# 4.0 Only)
str = "something" if (String.IsNullOrWhiteSpace(str)) { // Oh no! the string isn't valid! }
NOT Recommended
string[] source = new string[] { "a", "b", "c" }; string[] dest = new string[3]; for (int i=0; i < source.Length; i++) { dest[i] = source[i]; }
Recommended
string[] source = new string[] { "a", "b", "c" }; string[] dest = new string[3]; Array.Copy(surce, dest, source.Length);
NOT Recommended
char c = '1'; if (c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '0') { // It's a digit! }
Recommended
char c = '1'; if (Char.IsDigit(c)) { // It's a digit! }
NOT Recommended
string folder = @"C:\MyDir"; string file = "MyFile.docx"; // Combine to make a path string path = folder + @"\" + file;
Recommended
string folder = @"C:\MyDir"; string file = "MyFile.docx"; // Combine string path = System.IO.Path.Combine(folder, file);
NOT Recommended
string path = @"C:\MyDir\MyFile.docx"; string extension = path.Substring(path.LastIndexOf("."));
Recommended
string path = @"C:\MyDir\MyFile.docx"; string extension = System.IO.Path.GetExtension(path);
NOT Recommended
// Probably some nasty stuff here
Recommended
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
NOT Recommended
object obj = "str"; if (obj.GetType() == typeof(String)) { // It's a string! }
Recommended
object obj = "str"; if (obj is String) { // It's a string! }
As Adrian Aisemberg has pointed out, these samples are not entirely the same. The is keyword will return true also if obj is of a derivative type of String (in this sample).
NOT Recommended
public class MyClass { private enum Sample { A, B, C } static Sample s = Sample.B; // Set default value explicitly public static void Run() { Console.WriteLine(s); // Prints B } }
Recommended
public class MyClass { private enum Sample { A, B = 0, // Make B the default value C } static Sample s; // Default value will be used public static void Run() { Console.WriteLine(s); // Prints B } }
NOT Recommended
string str = "Hello World"; if (str.Substring(0, 5) == "Hello") { // String starts with Hello! }
Recommended
string str = "Hello World"; if (str.StartsWith("Hello")) { // String starts with Hello! }
NOT Recommended
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 }); List<string> convertedList = new List<string>(); foreach (int item in list) { convertedList.Add(item.ToString()); }
Recommended
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 }); List<string> convertedList = list.ConvertAll<string>(Convert.ToString);
NOT Recommended
string str = "4"; int num = 0; bool success = false; try { num = Convert.ToInt32(str); success = true; } catch { success = false; } if (success) { // Do something with the number }
Recommended
string str = "4"; int num = 0; if (Int32.TryParse(str, out num)) { // Do something with the number }
NOT Recommended
const string str = "put me in a file"; const string file = @"c:\logs\file.txt"; var fs = new FileStream(file, FileMode.Create); var sw = new StreamWriter(fs); sw.Write(str); sw.Close(); fs.Close();
Recommended
const string str = "put me in a file"; const string file = @"c:\logs\file.txt"; File.WriteAllText(file, str);
NOT Recommended
string input = "sdfds"; string result = null; if (input == null) { result = "Input is null!"; } else { result = input; }
Recommended
string input = "sdfds"; string result = input ?? "Input is null!";
This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).
2. It is easier to change the specification to fit the program than vice versa.
3. If a program is useful, it will have to be changed.
4. If a program is useless, it will have to be documented.
5. Only ten percent of the code in any given program will ever execute.
6. Software expands to consume all available resources.
7. Any non-trivial program contains at least one error.
8. The probability of a flawless demo is inversely proportional to the number of people watching, raised to the power of the amount of money involved.
9. Not until a program has been in production for at least six months will its most harmful error be discovered.
10. Undetectable errors are infinite in variety, in contrast to detectable errors, which by definition are limited.
11. The effort required to correct an error increases exponentially with time.
12. Program complexity grows until it exceeds the capabilities of the programmer who must maintain it.
13. Any code of your own that you haven’t looked at in months might as well have been written by someone else.
14. Inside every small program is a large program struggling to get out.
15. The sooner you start coding a program, the longer it will take.
16. A carelessly planned project takes three times longer to complete than expected; a carefully planned project takes only twice as long.
17. Adding programmers to a late project makes it later.
18. A program is never less than 90% complete, and never more than 95% complete.
19. If you automate a mess, you get an automated mess.
20. Build a program that even a fool can use, and only a fool will want to use it.
21. Users truly don’t know what they want in a program until they use it.
I am a regular reader of Pinal Dave's blog SqlAuthority. I always found something new in his blog to work with SQL Server. Here is something I would like to share: Get the recent executed SQL Queries from SQL Server.
1.
SELECT
deqs.last_execution_time
AS
[
Time
], dest.TEXT
AS
[Query]
FROM
sys.dm_exec_query_stats
AS
deqs
CROSS
APPLY sys.dm_exec_sql_text(deqs.sql_handle)
AS
dest ORDER
BY
deqs.last_execution_time
DESC
Limiting the length of an ASP.net mulitline textbox control is easy. Add a RegularExpressionValidator, set the ControlToValidateProperty to the ID of the TextBox you wish to validate and set the ValidationExpression property to :
^[\s\S]{0,300}$This tells the regex validator to limit the number of characters in the Textbox to 300.
Metacharacters
^ Start of Line
[] Character class (list the characters you want to match)
\s White space characters including new line
\S Non-white space characters
{intMin,intMax} Intervals; The minimium number of matches you want to require and the max number of matches you want to allow
Hitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being “clicked“. The method described below allows you to specify a default Button to submit when the user hits the enter key in a TextBox.
When you press a key on your keyboard, the js OnKeyPress event is fired. This calls a function to which we pass the id of the button associated with the TextBox. The function gets a reference to the button and simuilates a mouse-click on the Button. We perform a browser detection because IE and Netscape have different event models. The function finally returns false so that the keypress event is cancelled (otherwise a second form submit will be raised). This works with newer versions of IE/Netscape.function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
//code behind
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
This causes web control Button1 to be clicked when the enter key is hit inside TextBox1.Hi
When working with Database, the most difficult and important thing is to ensure that the database is as fast as possible. After a few year when the number of users in a database grow and the data also start to increase, the performance starts to slide down. At this point it is very difficult to optimize the database for better performance.This is reason enough that we should keep the performance in our mind from the very early stages of database life cycle. This is not very easy to do because of many factors like changing nature of business, unthought changes in database etc. But there are a few generic tips that can be followed for better performance of the database.
One of the simple tips to be followed is to set the nocount on. This should be a part of all the stored procedure. This one line of code should be there at the top of all the stored procedure. This turns off the messages that SQL Server sends back to the client after each T-SQL statement is executed. This is performed for all the following statements SELECT, INSERT, UPDATE, and DELETE.
This information is only handy when we use these statements in a query window like query analyzer. But there is no need of this information to be sent back to the client when we are using the stored procedures from the application. The @@rowcount variable would still work so there we can still pass the data on the number of rows to the client through and output parameter.
Hi
How and why did the design pattern started. So I started hunting in the google for my curiosity and found some interesting stuff. So I thought I would share them with you.
A repeatable solution for commonly occurring problem in the software programming is called design pattern. Design patterns are not finished designs for the problems, but are template and description on how the solve the problem, which might occur in different situations. Design patterns commonly show relations and interaction of different class or objects or types. They do not specify the final class or types that will be used, but give an abstract view of the solution.
As design patterns provide tested and proven development paradigms, they can speed up the process of development. For a design pattern to be effective, it must also consider issues that are not visible until the real implementation. Use of design patterns can prevent issues that cause major problems for coders and architects familiar with the pattern
Hi,
One of the small but new features in Asp.Net 4.0 is the addition of the Title, Metakeyword and Metadescription property in the page class itself. Now we can easily set the Title, Metakeyword and Metadescription (very important for sites looking for SEO.) from the page itself.
This makes adding these values based on some condition or from database very easy. To Add these value to the page now (Asp.Net 4.0) we can write following code.this.Page.Title = "Fenil Desai Blog";Hi,
another of the new features of Asp.net 4.0 is the enhancement(in terms of rendering) made in the Formview control. By default the Formview control would render table, tr and td tags for display of content. This can be of much trouble to many of the designer because they have little control over the rendered HTML.With Asp.net 4.0 you can disable the rendering of these HTML elements. (Mind you in Asp.Net 4.0 by default these HTML content are rendered.) To do this all you need to do is set the RenderTable property to False.<asp:FormView ID="FormView1" runat="server" RenderTable="false">This enhancement can make it easier to style the content of the control with CSS, because no unexpected tags are rendered by the control.
There are some important dates about the end of support for specific products and releases involving SQL Server and Windows that I want you to be aware of:
Important Upcoming SQL Server Support Dates
1) SQL Server 2005 Service Pack 2 support ends next week January 12, 2010. You should upgrade to SQL 2005 SP3 or SQL 2008 SP1 immediately.
2) SQL Server 2008 RTM support ends on April 13, 2010. You should make plans to upgrade to SQL Server 2008 SP1 soon.
A complete list of our support policy dates can be found on the following web site:
http://support.microsoft.com/lifecycle/
A very good discussion about these upcoming dates was published by our release services team for SQL Server back in October of last year. This includes what choices you have for support and what actions you should consider to stay supported:
What does this “end of support” mean to you?
I encourage you to do a few things to stay “ahead of the game” for the end of support dates for SQL and other Microsoft products in the future:
Important Upcoming Windows Support Dates
While not a SQL Server Support policy, end of support for Windows 2000 Server SP4 on July 13, 2010 could affect many SQL Server customers. Furthermore, Windows Server 2003 and 2003 R2 transition into “Extended Support”. The following article has a nice summary of these Windows Support dates:
http://support.microsoft.com/gp/lifean36
What is the difference between the “end of support” for Windows Server 2000 and “Extended Support” for Windows Server 2003?
The end of support for Windows Server 2000 is like our end of support above for SQL Server 2005 SP2 and SQL Server 2008 RTM. You can no longer contact CSS for support and no security updates or fixes will be available. The only exception is if you purchase a Custom Support Agreement through your Technical Account Manager.
The Windows 2000 End-of-Support Solution Center is a good resource to read about information on the end of support for Windows Server 2000.
Extended Support for Windows Server 2003 means that:
You may wonder how the end of support for Windows Server 2000 may affect you as SQL Server user? The biggest thing to consider is in order to be supported you need to upgrade to a new version of Windows. You could move to Windows Server 2003 but as stated that version is moving into Extended Support, so that may not be a good choice. If you still want standard hotfix support your choices are Windows Server 2008 or Windows Server 2008 R2.
The possible problem here you may encounter is if you are running SQL Server 2000 SP4 (the only official supported version of SQL Server 2000 which itself is in Extended Support). SQL Server 2000 SP4 is not supported on Windows Server 2008 or Windows Server 2008 R2. Therefore, if you make this jump to the new OS, you must also upgrade SQL Server to either SQL Server 2005 SP3 or SQL Server 2008 SP1.
One last question you may have. What happens if I stay on Windows Server 2000 SP4 after July 13, 2010 and I try to call in a case to CSS?. The answer depends on what type of problem you have:
Summary
Here is a summary of actions you should consider:
In this article I will explain how to change visual studio's default browser.
There was one question during my recent work in one of my ASP.NET Project.
“Is it possible to access the ViewState variable of one page on another page?”
My answer was “No” . Because i have read in books that Viewstate is page specific, it is available only on the same page on which it was created.Once you redirect to another page, the previous page’s viewstate is no longer accessible.
But that is not true. Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.
Let us create one sample application to understand this.
Step 1 : Create two page one.aspx & two.aspx
Step 2 : Code for one.aspx.cs
01 | protected void Page_Load( object sender, EventArgs e) |
02 | { |
03 | ViewState[ "Page1" ] = "Page1 ViewState" ; |
04 | Server.Transfer( "two.aspx" ); |
05 | } |
06 |
07 | public StateBag ReturnViewState() |
08 | { |
09 | return ViewState; |
10 | } |
As you can see, I have set a ViewState variable in Page Load and transfer the user to two.aspx page using the Server.transfer() method. This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. The return type of the method is StateBag class.
StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page’s or control’s viewstate.
Step 3 : Code for two.aspx.cs
01 | private StateBag PreviousPageViewState |
02 | { |
03 | get |
04 | { |
05 | StateBag returnValue = null ; |
06 | if (PreviousPage != null ) |
07 | { |
08 | Object objPreviousPage = (Object)PreviousPage; |
09 | MethodInfo objMethod = objPreviousPage.GetType().GetMethod |
10 | ( "ReturnViewState" ); |
11 | return (StateBag)objMethod.Invoke(objPreviousPage, null ); |
12 | } |
13 | return returnValue; |
14 | } |
15 | } |
16 |
17 | protected void Page_Load( object sender, EventArgs e) |
18 | { |
19 | if (PreviousPage != null ) |
20 | { |
21 | if (PreviousPageViewState != null ) |
22 | { |
23 | Label1.Text = PreviousPageViewState[ "Page1" ].ToString(); |
24 | } |
25 | } |
26 | } |
Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage property. Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.
Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page’s ViewState. It first checks whether PreviousPage is null or not, if it’s not null, then it creates an object of the previous page.
Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.
In Page_Load event, I am able to access the ViewState variable of ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.
Step 4: Run the application & see the effect
Hope this will helps