Wednesday, July 29, 2009

ASP.NET 3.5 WebConfigurationManager

ASP.NET 3.5 Web Project Connection Strings
This is just a quick sample of how to get a connection string in an ASP.NET 3.5 Web Project.
Assuming you've set up a Project Application Setting of Type (Connection String) you would have the following settings throughout.
References include
System.Configuration (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Configuration.dll)
Web.Config includes
<configuration>
<!-- ... More Stuff ... -->
<connectionstrings>
<add name="DatabaseConnection" connectionstring="Data Source=SQLServerName;Initial Catalog=DatabaseName;Uid=SQLLogin;Pwd=pa$$w0rd;">
</connectionstrings>
<!-- ... More Stuff ... -->
</configuration>
Code Behind Includes
private sub RunStoredProcedureSample()
    Using SqlClientConnection As New SqlConnection(WebConfigurationManager.ConnectionStrings("DatabaseConnection").ConnectionString())
        If Not SqlClientConnection.State = ConnectionState.Open Then
            SqlClientConnection.Open()
        End If
        Using SqlClientSqlCommand As New SqlCommand("spDoSomthing", SqlClientConnection)
            With SqlClientSqlCommand
                .CommandType = CommandType.StoredProcedure
                With .Parameters
                    .Clear
                    .AddWithValue("@Param1", Convert.ToString(Session("Something")))
                    .AddWithValue("@Param2", Something2)
                    .AddWithValue("@Param3", Convert.ToString(Session("ESomething3")))
                    .AddWithValue("@Param4", Something4)
                End With
                .ExecuteNonQuery()
            End With
        End Using
    End Using
End Sub
This has been the recommended way to deal with getting settings since .Net 2.0 but as most developers, I kept writing .NET 1.0 and/or .NET 1.1 based code even in .Net 2.0.
I know of entire .NET 2.0 certification programs instructed by individuals who have no working or academic experience actually using the .NET 2.0 framework specifications. Microsoft apparently is not concerned enough about the integrity of their certified training partners to enforce and/or police such things. Of course, if you have had the great misfortune of attempting to attend any of Microsoft’s “advanced” partner application and/or development webinars in the 2008/2009 sessions, you would have little doubt as to the lapse of quality control.
Anyway, since I cannot correct the system, maybe I can be of some assistance to others who are endeavoring to improve their own professional integrity through some small but often unaddressed basics that seem to always get lost in the discussions.
Now against the .NET 3.5 framework many of the deprecations have actually taken effect.

No comments: