|
|
Use ViewState Properties Instead of Referencing ViewState DirectlyViewState Properties Prevent Misspelling Variable Names with Intellisense | | Have you ever misspelled a ViewState Variable Name? If you have, you probably found out only after trying to debug to find why your Web App was not running. Using ViewState properties gives Intellisense and removes the chance of misspelling the name of the ViewState variable name.
The code below shows a bad way to access a value from ViewState, yet if you are just starting ASP.NET development, it might seem the natural thing to do.
int page = ViewState["Step"];
|
There are at least a couple of things wrong with this approach. First, I would always be wondering how I saved the variable name in ViewState. In this example I used two different varaibles on purpose. Let's say that this code behind is for a wizard of sorts. I could have used a Wizard control, but it was not really applicable here. The page has a three step process, but it has numerous Panel controls that are being turned on and off as I move from one step to the next step. The pseudo wizard is simply displaying less panels on the second step than it did on the first step, etc. Since the original classic ASP application that I have converted did this with three separate pages, converting to one page, suggests moving from a "page" to a "Step", thus the two variable names. I maintain where I am and what to display with the ViewState variable. Using the line of code shown above, I may have to search for the name that I used in ViewState. Secondly, although it would be hard to misspell "Step", if I did, it would be found only at run time, not at compile time.
The code shown below uses a ViewState property to solve the problems mentioned previously. I have adopted a convention of starting every ViewState property with the letters VS. This will cause me to easily get to all ViewState properties in Intellisense easily. First, I will show a ViewState property followed by a use of it.
private int VSStep
{
get
{
if (ViewState["VSStep"] == null)
{
ViewState["VSStep"] = 0;
}
return int.Parse(ViewState["VSStep"].ToString());
}
set
{
ViewState["VSStep"] = value;
}
}
private string VSPin
{
get
{
if (ViewState["VSPin"] == null)
{
ViewState["VSPin"] = string.Empty;
}
return ViewState["VSPin"].ToString();
}
set
{
ViewState["VSPin"] = value;
}
}
|
The two properties just above illustrate that the ViewState properties can be of any type. Notice that the property get returns the proper type so that the program using the property does not normally have to worry about casting to the proper type in settng a local variable. Usage of the respective variables would be as follows;
int page = VSStep;
string pin = VSPin;
|
So much for the properties; the advantages are obvious. In coding the two lines shown immediately above, the instant I type "v", Intellisense is already moving to my ViewState property names, even if I have other variables beginning with a "v" or "V". Obviously, when I type "vs" my ViewState properties are clearly in view in Intellisense and I have only to make a quick choice as to which one to use. Regardless, of how many times I reference the same ViewState variable, I am always assured of having no spelling problems.
Well, the one remaining problem is the coding of the 16 lines of code, including curly braces and any whitespace. That seems like a chore that I want to automate so that, again, I do not leave the coding of the properties open to the possibility of a mistake in spelling, etc. If you have read many of my articles, you know that I always resort to an add-in or at least a macro to avoid repetitive coding where possible. Like General George Patton, "I don't like having to take the same ground twice." The following macro will work for C# developers and could easily be modified to generate VB.NET code. Obviously, I could use the CodeDom to generate the code, but it was faster to code the macro to hard code the code generation.
Public Sub CreateViewStateProperty()
Dim name As String =
InputBox("Enter name for ViewState Property, Type",
"ViewState Property Creation", "")
If name.Trim() = String.Empty Then Exit Sub
Dim nameType As String() = name.Split(",")
If nameType.Length < 2 Then Exit Sub
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
Dim sb As StringBuilder = New StringBuilder(1000)
Dim vsName As String = String.Format("ViewState[""{0}""]", nameType(0))
Dim type As String = nameType(1)
sb.Append(String.Format("private {0} {1}", nameType(1), nameType(0)) & vbCrLf)
sb.Append("{" & vbCrLf)
sb.Append(" get" & vbCrLf)
sb.Append(" {" & vbCrLf)
sb.Append(" if (" & vsName & " == null)" & vbCrLf)
sb.Append(" {" & vbCrLf)
If type = "string" Then
sb.Append(" " & vsName & " = string.Empty;" & vbCrLf)
ElseIf type = "int" OrElse type = "decimal" Then
sb.Append(" " & vsName & " = 0;" & vbCrLf)
ElseIf type = "DateTime" Then
sb.Append(" " & vsName & " = DateTime.Now;" & vbCrLf)
Else
sb.Append(" " & vsName & " = null;" & vbCrLf)
End If
sb.Append(" }" & vbCrLf)
sb.Append(vbCrLf)
If type = "string" Then
sb.Append(" return " & vsName & ".ToString();" & vbCrLf)
ElseIf type = "int" Then
sb.Append(" return int.Parse(" & vsName & ".ToString());" & vbCrLf)
ElseIf type = "DateTime" Then
sb.Append(" return Convert.ToDateTime(" & vsName & ");" & vbCrLf)
Else
sb.Append(" return " & vsName & ";" & vbCrLf)
End If
sb.Append(" }" & vbCrLf)
sb.Append(" set" & vbCrLf)
sb.Append(" {" & vbCrLf)
sb.Append(" " & vsName & " = value;" & vbCrLf)
sb.Append(" }" & vbCrLf)
sb.Append("}" & vbCrLf)
ts.Insert(sb.ToString())
End Sub
|
To use this macro, simply copy it to a module in the macro Editor. I usually have a module called MyMacros. Once saved there it is always visible in the Macro Explorer. To create a ViewState property, place your cursor where you want the property created in your class and then double-click the macro name in the Macro Explorer. An Input Box will display asking you to type the name of the ViewState property followed by a comma and the name of the type of the property (such as string, int, or DateTime). As shown those three types are the only ones supported by the macro. You can modify it for other often used types that you may need.
Once you enter the name,type; the property is generated in the window where you placed the cursor. From that time on you will never have to worry about how a value was stored in ViewState.
I hope this will help you to see the use of conventions, shortcuts, as well as the use of code generation wherever possible.
Need to automatically organize your code windows? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.
Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily. Try CSharpCompleter for 30 DAYS FREE.
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. |  |
You can also email me directly at les@KnowDotNet.com.
|
|