George's Blog

Learning to Geek...

  Home  |   Contact  |   Syndication    |   Login
  6 Posts | 0 Stories | 3 Comments | 0 Trackbacks

News

Twitter












Archives

Other Blogs

Monday, May 19, 2008 #

My topic for the week is ViewState. What is ViewState. Here is a pretty good example I found online at ASP 101 by John Peterson

"It's probably easiest to explain with an example. Let's say you're about to buy something online. You've filled out your name, address, payment info, and given these people, whom you've never met, information you normally wouldn't share with your closest friends (but that's another rant altogether). You submit the form and the server comes back saying there's an error and you need to go back and add -'s to your phone number or some other petty little thing. You click the back button in your browser and you stare at the screen in dread as you realize all the entries you typed are now gone and you have to start all over! The site in question didn't maintain your viewstate. "

ViewState was introduced to help eliminate the difficulties of programming in a stateless environment, meaning that the state of controls is not saved between postbacks. It was added in ASP.NET as a convienent way to store the state of objects between these postbacks of a page. ViewState comes at a cost to use though...Performance. You can turn off viewstate by using the attribute EnableViewState="false". By using viewstate you are adding to the size of each page that is created. ViewState works by adding HiddenFields to the response(__ViewState), which helps maintain the sesson of the objects on a page. If you were to look at the source of your page you will see something like this.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwMjg4NjgzM2QYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFLmN0bDAwJE1haW4kY3RsMDgkY3RsMDIkY3RsMDIkY3RsMDIkY2hrUmVtZW1iZ/>

The information in the value is all the information for the page.


Friday, May 16, 2008 #

Authentication in the web.config. Authentication is the process that determines the identity of a user. When you log onto your machine at the start of the day and you are asked for your username and password you are authenticating yourself. Who are you? On the web, once you are authenticated you then have authorization. What are you as a user allowed to see on a particular site. You could log in and your role as a user could be Administrator. Having the role of admin allows you to see files, links, folder and pages that another user won’t be able to see.

In one of my previous post I quickly talked about Authentication and Authorization. Today as my last day of studying some details about the web.config, I am going to revisit these two web.config elements and expand my thoughts on them.

There are three modes options you can have in your web.config within the <authentication> element. Windows, Forms, Passport. To quickly cover these, Windows is more used for the intranet, Forms is more used for standard web pages and passport is Microsoft’s authenticating system. Forms is what we are going to cover today.

Set your web.config up to use forms. This turns on everything you need to start using the membership services.

<system.web>

<authentication mode=”Forms”>

</system.web>

 

When a user enters a site for the first time he is an anonymous user. Anonymous is the default authentication mode. You can configure your web.config file to redirect the anonymous user to a specific page within the site to become authenticated. After the users is redirected to this login page and once he passes the authentication process he will be issued a cookie.

 

<system.web>

<authentication mode=”Forms”>

                <forms name=”ASPXAUTH”

                                loginUrl=”login.aspx”

        timeout=”30” />

</system.web>

 

The code above we added a loginUrl attribute which will take all anonymous users to the login.aspx page. Once authenticated the user will be directed to the default.aspx page. The name attribute is the name used for the cookie sent to the end uers. The timeout attribute is the time until the cookie will expire. The time above is set to 30 minutes.  These are the basics for the authentication element.

 

Some other thoughts on the web.config file.

 

Where is the machine.config file located? Why would I need to know this?

You can find the machine config file C:\WINDOWS\Microsoft.NET\Framework\v2.0.xxxxx\CONFIG

It is important to know where this file is because it houses the default settings for all you applications, not just web applications. I wouldn’t change anything within this file unless you know what you are doing. If you take information from here and paste it within you web.config you will override the machine.config for that particular application. As an example. I don’t like having a password be a minimum of seven characters with at least one nonalphnumeric character included. I include the code below into my web.config file and now I have overridden what the machine.config has set up.

 

                                <membership>

                                                <providers>

<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>

                                                </providers>

                                </membership>


Thursday, May 15, 2008 #

My week long look into the web.config file is almost done. On top of all the other studying that I am doing in all things .NET I am focusing on one item per week and reading extra, coding extra and blogging about that particular item. So this week was configurations. I have read quite a bit on an elementary level and thought about some more complex issues. I am biased I guess but my brother's (Bill Evjen) chapter on configurations in his Professional ASP.NET 2.0 book covers quite a bit and is quite easy to follow. I am not sure what to investigate next week, so I am taking recommendations. Onward though with day 4 on configurations.

An important portion of your web.config file will consist of the Page Configuration. The page configuration is important  because it will enable you to control some of the default behaviors for each and every .aspx page that is part of your web application. Below is a sample page element.

<pages buffer="[True|False]"
   enableEventValidation="[True|False]"
   enableSessionState="[True|False|ReadOnly]"
   enableViewState="[True|False]"
   enableViewStateMac="[True|False]"
   smartNavigation="[True|False]"
   autoEventWireup="[True|False]"
   pageBaseType="typename, assembly"
   userControlBaseType="typename"
   validateRequest="[True|False]"
   masterPageFile="file path"
   theme="string"
   styleSheetTheme="string"
   maxPageStateFieldLength="number"
   compilationMode="[Always|Auto|Never]"
   pageParserFilterType="string"
   viewStateEncryptionMode="[Always|Auto|Never]"
   maintainScrollPositionOnPostBack="[True|False]"
   asyncTimeout="number"></pages>

By having the page element in your web.config file you are setting up you pages globally in one place instead of using the page directive on each page. You can set up each page in one place and make your changes globally. The attributes that you may find yourself using the most are in bold above.

enableSessionState - Specifics whether the session state for the page should be enabled. Your options are true, false, or ReadOnly.

enableViewState - Allows you to turn on/off your viewstate for all your controls on your aspx pages.

masterPageFile - Specifies which master page you are using for your pages. Be careful how you use this attribute if your application uses more than one masterpage. Some sites us multiple masterpages.

theme - Sets the theme for the pages and you are NOT allowed to overwrite the theme on the individual pages

styleSheetTheme - Sets the theme for the pages and it DOES allow you to overwrite the themes on the individual pages.


Wednesday, May 14, 2008 #

How to access the ASP.NET configuration settings.

If you had the following information in your web.config file. How would you access this information. The idea is to have this information in one place within your application and you can now spread this information to multiple areas on your application. If you then have to change the information you only have to change it in one place as opposed to changing it in multiple places.

  <appSettings>
      <add key="myConnectionString" value="theConnectionStringWouldGoHere" />
  </appSettings>

label1.Text = ConfigurationManager.AppSettings("myConnectionString");

If you ran this the label would have the value of the appSettings configuration. You can now use this feature in your code behind to bind to your connection string in your web.config file.

Another way to set the connection string.

  <connectionStrings>
      <add name="myConnectionString" connectionString="thisIsWhereTheConnectionStringGoes" />
  </connectionStrings>

To call this connection string from the code you use syntax that is similar to the appSettings syntax

label.Text = ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString;


Tuesday, May 13, 2008 #

Most used web.config settings

1. <authentication> -

<system.web>
    <authentication mode="Windows" />
</system.web>

<system.web>
    <authentication mode="Forms" />
</system.web>

<system.web>
    <authentication mode="Passport" />
</system.web>

The code above shows the type of authentication you are going to use for your site. Windows will be windows authentication, which is used normally within an intranet. Forms is used for setting up a traditional website and passport is set up by Microsoft

2. <authorization> - Authorization refers to the permissions granted to a user. The webconfig refers to them as roles. The web.config takes a number of deny and allow tags within the authorization. You could for instance have a role of admin. You could then have specific files only allowed for those that are in the admin role.

<!-- SET UP AUTHORIZATION USING LOCATION TAG -->
<location path="AdminSites">
   <system.web>
     <authorization>
       <allow roles="admin" />
       <deny users="*" />
     </authorization>
   </system.web>
</location>

The code above uses a location tag. The location tag will clearify the directory we are setting up. The directory "AdminSites" is only available to those that are in the admin role and denied to all other members. 

3. <customErrors>

<customErrors defaultRedirect="ErrorPage.aspx" mode="On">   
    <error statusCode="500" redirect="servererror.aspx" />
    <error statusCode="404" redirect="filenotfound.aspx" />
    <error statusCode="403" redirect="AccessDenied.aspx" /> 
</customErrors>

When you encounter and error on a page you typically will receive a page that lists the error and a trace of the methods that were run right up until the error. If you use the customError configuration you will be able to direct the client to a page that will give a better presentation other than an error screen. You use the defaultRedirect attribut to be the default error page. Within the customError element you can add other errror pages for specific errors the client may encounter.

4. <pages> - The page element list page specific properties. Using the pages element will eliminate the use of changing elements within the page directive of your application. Below is an extensive list of the attributes used within the page element

<pages    
   buffer="[True|False]"
   enableEventValidation="[True|False]"
   enableSessionState="[True|False|ReadOnly]"
   enableViewState="[True|False]"
   enableViewStateMac="[True|False]"
   smartNavigation="[True|False]"
   autoEventWireup="[True|False]"
   pageBaseType="typename, assembly"
   userControlBaseType="typename"
   validateRequest="[True|False]"
   masterPageFile="file path"
   theme="string"
   styleSheetTheme="string"
   maxPageStateFieldLength="number"
   compilationMode="[Always|Auto|Never]"
   pageParserFilterType="string"
   viewStateEncryptionMode="[Always|Auto|Never]"
   maintainScrollPositionOnPostBack="[True|False]"
   asyncTimeout="number"
>

5. <sessionState> - The attributes that are connected with the sessionState element are - mode, cookieless, timeout, stateConnectionString, sqlConnectionString and stateNetworkTimeout.

<configuration>
   <system.web>
      <sessionState mode="InProc"
                    cookieless="true"
                    timeout="20"/>
      </sessionState>
   </system.web>
</configuration>

6. <appSettings>

<configuration>
    <appSettings>
        <add key="Application Name" value="MyApplication" />
    </appSettings>
</configuration>

 The appSettings element allows you to put data into the web.config so you do not have to have the code in multiple places within the application. Your application will simply call the appSettings element and get the data that it needs. The appSettings element is a key/value pair, it supports a sub-element called add.


Monday, May 12, 2008 #

Web.Config Information

- Contains information that controls module loading, security configuration, session state configuration, application language and compilation settings.

- Also contains application specific items such as database connection strings.

- Must be placed in the root directory

- The Web config can be placed in sub-directories but those configurations will only be made available to the files within that sub-directory.

- Each web application in ASP.NET inherits thier base web.config from the machine.config

- The web.config can detect changes made, ASP.NET will restart the application when changes are made to the web.config file.

- The root element of the web.config file should always be <configuration>

-What typically goes in the <system.web> group

<authorization>, <authentication>, <compliation>, <customerErrors>, <SessionState>, <globalization>, <httpRuntime>, <trace>

- The web.config file is protected by IIS so clients cannot access or break into the file capturing important configuration information.

- Configurations made on the machine.config encompass all applcations whereas web.config files only affect that particular applcation.

- You can actually have an application without a web.config file - you would by default use the settings laid out by the machine.config. If you add a web.config file you can override the settings of the machine.config.