Wednesday, January 20, 2010

Convert data table to data reader

Convert data table to data reader
In some situations you may need to convert your data table to data reader, suppose you have a Data table named dt and getDataFromDB() is a function that returns a data table, here is the steps to convert data table to data reader.

DataTable dt = new DataTable();
dt = getDataFromDB();
DataTableReader dtr;
dtr = dt.CreateDataReader();
while (dtr.Read())
{
   //Do your tasks
}

Posted via email from fenildesai's posterous

Tuesday, January 19, 2010

30 Common String Operations in C# and VB.NET

30 Common String Operations in C# and VB.NET


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;

VB.NET

    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());

    }

VB.NET

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);

    }

VB.NET

      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);

VB.NET

      ' 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" } };

 

VB.NET

     ' 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); 

VB.NET

    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");

    }

VB.NET

      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);

VB.NET

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);

VB.NET

      ' Assuming you have a Byte Array byte[] b

      strModified = Encoding.Unicode.GetString(b)

pppp

line

Posted via email from fenildesai's posterous

Use .NET Built-in Methods to Save Time and Headaches

Use .NET Built-in Methods to Save Time and Headaches

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.

Code Block #1 – Check string for nullity or emptiness

NOT Recommended

  1. str = "something"  
  2. if (str == null || str == String.Empty)  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Recommended

  1. str = "something"  
  2. if (String.IsNullOrEmpty(str))  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

  1. str = "something"  
  2. if (str == null || str.Trim() == String.Empty)  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Recommended (C# 4.0 Only)

  1. str = "something"  
  2. if (String.IsNullOrWhiteSpace(str))  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Code Block #3 – Copy an Array

NOT Recommended

  1. string[] source = new string[] { "a""b""c" };  
  2. string[] dest = new string[3];  
  3. for (int i=0; i < source.Length; i++)  
  4. {  
  5.     dest[i] = source[i];  
  6. }  

Recommended

  1. string[] source = new string[] { "a""b""c" };  
  2. string[] dest = new string[3];  
  3. Array.Copy(surce, dest, source.Length);  

Code Block #4 – Check if a char is a digit

NOT Recommended

  1. char c = '1';  
  2. if (c == '1' || c == '2' || c == '3' ||  
  3.     c == '4' || c == '5' || c == '6' ||  
  4.     c == '7' || c == '8' || c == '9' ||  
  5.     c == '0')  
  6. {  
  7.     // It's a digit!  
  8. }  

Recommended

  1. char c = '1';  
  2. if (Char.IsDigit(c))  
  3. {  
  4.     // It's a digit!  
  5. }  

Code Block #5 – Combine Paths

NOT Recommended

  1. string folder = @"C:\MyDir";  
  2. string file = "MyFile.docx";  
  3. // Combine to make a path  
  4. string path = folder + @"\" + file;  

Recommended

  1. string folder = @"C:\MyDir";  
  2. string file = "MyFile.docx";  
  3. // Combine  
  4. string path = System.IO.Path.Combine(folder, file);  

Code Block #6 – Get file extension out of a file path

NOT Recommended

  1. string path = @"C:\MyDir\MyFile.docx";  
  2. string extension = path.Substring(path.LastIndexOf("."));  

Recommended

  1. string path = @"C:\MyDir\MyFile.docx";  
  2. string extension = System.IO.Path.GetExtension(path);  

Code Block #7 – Get MyDocuments Path

NOT Recommended

  1. // Probably some nasty stuff here  

Recommended

  1. Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  

Code Block #8 – Check if object is of a specific type

NOT Recommended

  1. object obj = "str";  
  2. if (obj.GetType() == typeof(String))  
  3. {  
  4.     // It's a string!  
  5. }  

Recommended

  1. object obj = "str";  
  2. if (obj is String)  
  3. {  
  4.     // It's a string!  
  5. }  

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).

Code Block #9 – Set default enum value

NOT Recommended

  1. public class MyClass  
  2. {  
  3.     private enum Sample   
  4.     {  
  5.         A,  
  6.         B,  
  7.         C  
  8.     }  
  9.     static Sample s = Sample.B; // Set default value explicitly  
  10.     public static void Run()  
  11.     {     
  12.         Console.WriteLine(s); // Prints B  
  13.     }  
  14. }  

Recommended

  1. public class MyClass  
  2. {  
  3.     private enum Sample   
  4.     {  
  5.         A,  
  6.         B = 0, // Make B the default value  
  7.         C  
  8.     }  
  9.     static Sample s; // Default value will be used  
  10.     public static void Run()  
  11.     {     
  12.         Console.WriteLine(s); // Prints B  
  13.     }  
  14. }  

Code Block #10 – Check if a string starts with another string

NOT Recommended

  1. string str = "Hello World";  
  2. if (str.Substring(0, 5) == "Hello")  
  3. {  
  4.     // String starts with Hello!              
  5. }  

Recommended

  1. string str = "Hello World";  
  2. if (str.StartsWith("Hello"))  
  3. {  
  4.     // String starts with Hello!          
  5. }  

Code Block #11 – Convert list of items of one type to a list of items of a different type

NOT Recommended

  1. List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });  
  2. List<string> convertedList = new List<string>();  
  3. foreach (int item in list)  
  4. {  
  5.     convertedList.Add(item.ToString());  
  6. }  

Recommended

  1. List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });  
  2. List<string> convertedList = list.ConvertAll<string>(Convert.ToString);  

Code Block #12 – Check if a string contains a number and get the number

NOT Recommended

  1. string str = "4";  
  2.   
  3. int num = 0;  
  4. bool success = false;  
  5. try   
  6. {  
  7.     num = Convert.ToInt32(str);  
  8.     success = true;  
  9. }  
  10. catch  
  11. {  
  12.     success = false;  
  13. }  
  14.   
  15. if (success)  
  16. {  
  17.     // Do something with the number  
  18. }  

Recommended

  1. string str = "4";  
  2.   
  3. int num = 0;  
  4. if (Int32.TryParse(str, out num))  
  5. {  
  6.     // Do something with the number  
  7. }  

Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)

NOT Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.   
  4. var fs = new FileStream(file, FileMode.Create);            
  5. var sw = new StreamWriter(fs);  
  6. sw.Write(str);  
  7.   
  8. sw.Close();  
  9. fs.Close();  

Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.   
  4. File.WriteAllText(file, str);  

Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)

NOT Recommended

  1. string input = "sdfds";  
  2. string result = null;  
  3. if (input == null)  
  4. {  
  5.     result = "Input is null!";  
  6. }  
  7. else  
  8. {  
  9.     result = input;  
  10. }  

Recommended

  1. string input = "sdfds";  
  2. 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).

Posted via email from fenildesai's posterous

Laws of Computer Programming

Laws of Computer Programming
1.    Any given program, once deployed, is already obsolete.

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.

Posted via email from fenildesai's posterous

T-SQL: Recently Executed Query

T-SQL: Recently Executed Query

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

Posted via email from fenildesai's posterous

Monday, January 18, 2010

Limiting the length of a multiline textbox

Limiting the length of a multiline textbox

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

Posted via email from fenildesai's posterous

Setting the default Button for a TextBox in ASP.NET

Setting the default Button for a TextBox in ASP.NET

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 + "')");

The code behind generates the following code:

<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.

Posted via email from fenildesai's posterous

Had a Gr8 time @PUG Developer Summit - 16th Jan 2010

Had a Gr8 time @PUG Developer Summit - 16th Jan 2010
Hi,

Last Saturday, I attended my first PUG Developer Summit & it was really gr8 fun. Got to know a lot of new things.

The session started with Silverlight 4 which was given by Vikram Pendse - MVP . He showed some really cool demos, the one in which we can actually take photos or shoot videos from a Silverlight app was really amazing. All these is possible bcoz of the WebCam and Microphone integration inside Silverlight 4. U can have a look at the article which explains it in detail here.

Next session was on Visual Studio 2010 Enhancements, which was given by one of the SkillLabs trainer (forgot the name). He too showed very cool 2010 enhancements with demos. Specifically enhancements in ADO.NET 4.0 & ODataServices will be very useful from the developer's point of view.

Next was session on WCF 4.0 was was also given by one of the SkillLabs trainer - Mr. Farzan, very jolly person as he showed some of those skills with some cool marriage qoutes in between the session which actually served as examples for WCF enhancements. This session was also quite informative.Then had a nice lunch provided by PUG.

Next was a non-tecnical session on Concept Visualization taken by Sanjay Vyas - Founder of SkillLabs.in. By far this was the best session although non-technical but it taught of things tecnically. He showed that our brain works best with what is inherent to us. The more we see the more we understand. Our brain likes not only pictures, but likes to see moving picture with colours and sounds. and if these theory is applied to technical areas then would result in a greater yield. In a very non-technical way he made understood the concept of arrays & pointers and even the Windows architecture.This session was really very interesting. U can even visit his blog here. There's a nice article on Concept Visualization written by him.

Last but not the least what I was actually waiting for was these session - Sharepoint 2010, as I was very eager to know about it. But bad luck the trainer had his laptop crash & the demos & ppt he had made for the session were all gone. But still he took help of some local guy & had the very nice ppt & a few demos about the new features of Sharepoint 2010. But still it was quite a bit boring at the end as it was already 5 pm.

That's it..EOD & all left..but I must tell that it was quite a informative session & being my first was really very excited & happy, more so that I was able to attend it as for quite a long time I wanted to attend it but work didn't allowed me 2..but then a Comp Off came to my rescue...Thanks...

Posted via email from fenildesai's posterous

SQL Server performance with NOCount On

SQL Server performance with NOCount On

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.

Posted via email from fenildesai's posterous

Design pattern – What can they mean?

Design pattern – What can they mean?

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

Posted via email from fenildesai's posterous

Programmatically set the Page Description and Keywords in Asp.Net 4.0

Programmatically set the Page Description and Keywords in Asp.Net 4.0

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";
this.Page.MetaKeywords = "ASP.NET, SQL, Sharepoint, dotnet";
this.Page.MetaDescription = "Some description of My blog";

If we already have some static tag value in the page markup then that will be replaced with the new content provided.

Posted via email from fenildesai's posterous

Asp.net 4.0 FormView Control Enhancement

Asp.net 4.0 FormView Control Enhancement

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.

Posted via email from fenildesai's posterous

Wednesday, January 13, 2010

Important SQL Server and Windows “End of Support” Dates you should know about….

Important SQL Server and Windows “End of Support” Dates you should know
about….

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:

http://blogs.msdn.com/sqlreleaseservices/archive/2009/10/08/end-of-service-pack-support-for-sql-server-2005-sp2-and-sql-server-2008-rtm.aspx

What does this “end of support” mean to you?

  • You cannot call or open a case with CSS for technical support if you are running these versions after the respective dates above. There are only 2 exceptions to this:
    • You are contacting CSS to get help with an upgrade to a supported version
    • You have a Premier Support Agreement and have purchased something called a Custom Support Agreement (CSA) (contact your Technical Account Manager if you want to consider this option)
  • Microsoft won’t produce any hotfixes or security updates for these specific versions (Custom Support Agreement customers are the exception)

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 can still contact CSS for support questions and issues
  • We will still provide security fixes for all
  • But for non-security hotfixes, you must purchase an Extended Hotfix Support Agreement which like the CSA is available to Premier customers through your Technical Account Manager

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:

  • CSS Platforms Support (which supports Windows) will not take a support case for Windows Server 2000 SP4 after July 13, 2010 unless you are trying to upgrade to a supported Windows OS (or have a CSA)
  • But let’s say you are running SQL Server 2000 SP4 which is still supported and have a SQL Server issue. CSS SQL Support would still take your case for an issue directly related to SQL Server. However, if when working the case, CSS determines the problem is specific to Windows Server 2000 SP4 and not a SQL Server issue (for example some type of disk I/O issue), then the support of the issue would stop as there is no support for that version of Windows after July 13, 2010.

Summary

Here is a summary of actions you should consider:

  • If you are running SQL Server 2005 SP2, you should upgrade immediately to SQL Server 2005 SP3 or SQL Server 2008 SP1 (Next week January 12, 2010 is the cutoff).
  • If you are running SQL Server 2008 RTM, you should upgrade to SQL Server 2008 SP1 very soon (before April 2010)
  • If you are running Windows Server 2000 SP4, you should make plans now to upgrade to Windows Server 2003, Windows Server 2008, or Windows Server 2008 R2 (July 13, 2010 is the cutoff). Your Windows upgrade choice may also require the need to upgrade SQL Server.

Posted via email from fenildesai's posterous

Monday, January 11, 2010

Access Viewstate across pages in ASP.NET

Access Viewstate across pages in ASP.NET
Introduction

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

01protected void Page_Load(object sender, EventArgs e)
02{
03    ViewState["Page1"] = "Page1 ViewState";
04    Server.Transfer("two.aspx");
05}
06 
07public 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

01private 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 
17protected 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

Posted via email from fenildesai's posterous