Specifying/changing the database when using Web Parts in an ASP.NET application

When using Web Parts in an ASP.NET application, if personalization is enabled (which is the best reason for using Web Parts), the personalization is stored in a SQL database.

This article details the steps to set this up or to change the default location. The default is the sql express instance on a development machine – my preference is for the SQL 2008 database on my network, but you will also need to specify the database to use when deploying your application.

The database used by the WebPart, or more precisely the WebPartManager, is the same one used by the membership and role providers. To create the database on either SQL2005 or SQL2008, run aspnet_regsql from the C:WindowsMicrosoft.NETFrameworkv2.0.50727 folder. This will run a wizard allowing you to specify where you would like the database created – you will need an instance of SQL Server 2005 or 2008 installed before doing this.

Once this is completed, you need to tell your ASP.NET application to use this database. This is configured in the web.config file by copying the following into the <system.web> tags:

     <webParts>
      <personalization defaultProvider="SqlPersonalizationProvider">
        <providers>
          <add name="SqlPersonalizationProvider"
            type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"
            connectionStringName="AspNetDbConnectionString"
            applicationName="/" />
        </providers>
        <authorization>
          <deny users="*" verbs="enterSharedScope" />
          <allow users="*" verbs="modifyState" />
        </authorization>
      </personalization>
    </webParts>

All that’s left then is to create the database connection specified in the connectStringName specified above:

  <connectionStrings>
    <add name="AspNetDbConnectionString"
        connectionString="Data Source=MSSQLSERVER2008;Initial Catalog=aspnetdb;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

You may need to adjust the security settings to allow access to anonymous users, but that is beyond the scope of this article.

Since the WebPartManager uses the provider pattern, with a bit more work, you could also create a custom provider and use any other database store.

Enjoy!

Posted in Development | Tagged , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre user="" computer="" escaped="">