5,696,038 members and growing! (10,780 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

Anonymous Personalization Trick in Web Parts

By Daron Yndem

My favorite feature of ASP.NET 2.0 is Web Parts. But the anonymous users in ASP.NET cannot save personalization data and can't use Web Parts design options. This article describes how we can solve this problem in a tricky way.
XML, SQL, VBWindows, .NET, .NET 2.0, WinXP, ASP.NET, SQL 2005, IIS 6, VS.NET2002, VS2005, SQL Server, IIS, Visual Studio, DBA, Dev

Posted: 13 Nov 2005
Updated: 13 Nov 2005
Views: 41,193
Bookmarked: 35 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
15 votes for this Article.
Popularity: 4.06 Rating: 3.45 out of 5
2 votes, 13.3%
1
3 votes, 20.0%
2
0 votes, 0.0%
3
2 votes, 13.3%
4
8 votes, 53.3%
5

Introduction

ASP.NET 2.0 provides a Web Parts framework, allowing programmers to easily integrate drag ’n drop menus etc. in their web portals. This framework is easy to use and all client based design settings are stored by ASP.NET data providers in an easy way. The developer has nothing to do with the save or load process of Web Parts design based settings. This article will not cover how we can use Web Parts. It’s possible to find lots of articles around the web about Web Parts.

ASP.NET 2.0 Web Parts framework works with the Membership framework as well as the Forms or Windows authentication modes. The problem is that, if you don’t want to use any authentication mode, you can’t use Web Parts. The client user, who will able to change the web site's design with Web Parts, should be authenticated. If not authenticated, the ASP.NET Web Parts framework can’t save users' design settings with data providers and for that reason can’t allow even to switch design modes.

The Idea

If we just need that all users connecting to our web site be authenticated, we need to register all users to our web site's authentication system. We will use Forms Authentication and provide some tricky ways. Users will be registered with our site in a hidden way with some cookie. We will recognize our visitors with their cookie and authenticate them automatically to get Web Parts design options available for them.

Using Hidden Authentication

First, we will set up our web site for Forms Authentication. You just need to modify your Web.Config file as below:

        <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
        <authentication mode="Forms" />

We will provide for each visitor a cookie to recognize the user's identity to be able to show them their design settings. We need an identity name for each visitor. We will create a random guide number to use as identity.

Dim MyCookieName As String = "Reminder"
Dim MyCookie As System.Web.HttpCookie = Request.Cookies(MyCookieName)
Dim UserID As String
UserID = System.Guid.NewGuid.ToString.Replace("-", "")
MyCookie = New System.Web.HttpCookie(MyCookieName, UserID)
MyCookie.Expires = DateTime.Now.AddYears(10)
Response.Cookies.Add(MyCookie)

Our cookie name is “Reminder”. You can change the name for your projects. Our Cookie data is the random guide name “UserID” that we generated using .NET Framework's “System.Guid.NewGuid” class. Now we can programmatically recognize our visitors each time they visit our web portal.

We should now authenticate our user with his GUID name "UserID" to our Forms Authentication system. In a normal situation ASP.NET uses cookies to store Forms Authentication data. We will just simulate that process manually.

Dim authTicket As FormsAuthenticationTicket = _
    New FormsAuthenticationTicket(1, UserID, DateTime.Now, _
    DateTime.Now.AddSeconds(30), False, "roles")
Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket)
authCookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
Response.Cookies.Add(authCookie)

Now our user is authenticated to our web site with Forms Authentication and can access Web Parts design properties.

We will have lots of visitors designing our web site for themselves and then just never visit again our web site or just delete their cookie and loose their identity as well as their design settings. So why do we need to store all visitor design settings if they haven’t visited our web site since last year? With the code below we connect manually to the ASP.NET Membership data store and delete users settings and profile manually, checking the last activity date of the user.

Dim LastDate As Date = Date.Now.AddYears(-1)

Dim cnn As System.Data.SqlClient.SqlConnection = New _
  System.Data.SqlClient.SqlConnection(_
  ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)
Dim cmd As System.Data.SqlClient.SqlCommand

cmd = New System.Data.SqlClient.SqlCommand("DELETE FROM" & _ 
      " aspnet_PersonalizationPerUser where UserID IN " & _ 
      "(SELECT UserID from aspnet_Users where " & _ 
      "[LastActivityDate] < @Date)", cnn)
cmd.Parameters.Add("@Date", Data.SqlDbType.DateTime)
cmd.Parameters.Item("@Date").Value = LastDate
Try
    cnn.Open()
    cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
    cnn.Close()
End Try

cmd = New System.Data.SqlClient.SqlCommand("DELETE FROM" & _ 
      " aspnet_Users where [LastActivityDate] < @Date", cnn)
cmd.Parameters.Add("@Date", Data.SqlDbType.DateTime)
cmd.Parameters.Item("@Date").Value = LastDate
Try
    cnn.Open()
    cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
    cnn.Close()
    cmd.Dispose()
    cnn.Dispose()
End Try

The complete solution is as below:

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

If Page.IsPostBack = False Then
    Dim authCookie As HttpCookie = _
        Request.Cookies(FormsAuthentication.FormsCookieName)
    If authCookie Is Nothing Then
        Dim MyCookieName As String = "Reminder"
        Dim MyCookie As System.Web.HttpCookie = _
                     Request.Cookies(MyCookieName)
        Dim UserID As String
        If MyCookie Is Nothing Then
            UserID = System.Guid.NewGuid.ToString.Replace("-", "")
            MyCookie = New System.Web.HttpCookie(MyCookieName, UserID)
            MyCookie.Expires = DateTime.Now.AddYears(10)
            Response.Cookies.Add(MyCookie)
        Else
            UserID = MyCookie.Value
        End If
        Dim authTicket As FormsAuthenticationTicket = New _
          FormsAuthenticationTicket(1, UserID, DateTime.Now, _
          DateTime.Now.AddSeconds(30), False, "roles")
        Dim encryptedTicket As String = _
            FormsAuthentication.Encrypt(authTicket)
        authCookie = New HttpCookie(FormsAuthentication.FormsCookieName, _
                                                        encryptedTicket)
        Response.Cookies.Add(authCookie)
        Response.Redirect(Request.Url.ToString)
    End If
    
    Dim LastDate As Date = Date.Now.AddYears(-1)
    
    Dim cnn As System.Data.SqlClient.SqlConnection = New _
      System.Data.SqlClient.SqlConnection(_
      ConfigurationManager.ConnectionStrings(_
      "LocalSqlServer").ConnectionString)
    Dim cmd As System.Data.SqlClient.SqlCommand
 
    cmd = New System.Data.SqlClient.SqlCommand("DELETE FROM" & _ 
          " aspnet_PersonalizationPerUser where UserID IN " & _ 
          "(SELECT UserID from aspnet_Users where " & _ 
          "[LastActivityDate] < @Date)", cnn)
    cmd.Parameters.Add("@Date", Data.SqlDbType.DateTime)
    cmd.Parameters.Item("@Date").Value = LastDate
    Try
        cnn.Open()
        cmd.ExecuteNonQuery()
    Catch ex As Exception
        Response.Write(ex.Message)
    Finally
        cnn.Close()
    End Try
    
    cmd = New System.Data.SqlClient.SqlCommand("DELETE FROM" & _ 
          " aspnet_Users where [LastActivityDate] < @Date", cnn)
    cmd.Parameters.Add("@Date", Data.SqlDbType.DateTime)
    cmd.Parameters.Item("@Date").Value = LastDate
    Try
        cnn.Open()
        cmd.ExecuteNonQuery()
    Catch ex As Exception
        Response.Write(ex.Message)
    Finally
        cnn.Close()
        cmd.Dispose()
        cnn.Dispose()
    End Try
End If

End Sub

The scenario starts with checking the Forms Authentication cookie. If we have already authenticated the user, we need not do anything. If there isn’t the Forms Authentication cookie, we check further if we have got our identity cookie. If there is an identity cookie “Reminder”, we can load the user's identity and authenticate it with Forms Authentication. This way, all users' old design settings comes automatically to our web portal. If the user doesn’t have our “Reminder” cookie, we create an identity and store it for that user and authenticate it with the new identity to the authentication system.

After having done all this process, we check for old users and delete the ones which don’t have at least one year activity on the web portal.

Conclusion

You just need to use this system on the "Page_Load" event of your web forms where you are using web parts design properties. Have fun using this tricky method on your future portal developments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Daron Yndem


Daron Yöndem is an ASP.NET MVP and INETA Turkey Lead. He is the founder of DEVELOAD Software & Design; a local ISV specialized on RIA development, Silverlight and WPF. Daron has two books about ASP.NET AJAX published in Turkish and is a chronic writer in Turkish press including IT Magazines. He is the software editor of PC Magazine Turkey, a monthly journal. Moreover Daron is a Silverlight editor at the official Microsoft Turkey Developer Community Web Site called yazgelistir.com and Silverlight/VB.NET Editor at nedirTV.com, an INETA UG. He is constantly hosting seminars, training sessions at various universities and private sector.

Blog:http://daron.yondem.com
Occupation: Web Developer
Location: Turkey Turkey

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 22 of 22 (Total in Forum: 22) (Refresh)FirstPrevNext
GeneralWhich catalog(database) is used in this article?memberPadmaDarji3:19 30 Sep '08  
GeneralNice Articlemembersundeep385:30 29 Aug '08  
GeneralThanks a lot!memberjeevansd23:59 10 Jun '08  
General"Personalization is not enabled and/or modifiable" error (I guess the Cookie is expired?) [modified]memberRaxxa_3:02 28 Apr '08  
GeneralThanksmembersemgoksu11:58 26 Apr '08  
GeneralEasier with Authentication Mode "Windows"?membersamtaz5:16 17 Aug '07  
GeneralI get error "User does not have permission to perform this action"memberGoran___1:01 25 May '07  
GeneralSql Command Suggestmembertychi1:59 2 Apr '07  
GeneralRe: Sql Command SuggestmemberDaron Yöndem4:39 25 Apr '07  
GeneralC# Codemembercavedog68:35 12 Dec '06  
GeneralRe: C# CodememberDaron Yöndem3:58 22 Dec '06  
NewsRe: C# Code completed [modified]membersamtaz0:57 17 Aug '07  
GeneralRe: C# CodememberMatt Langley8:53 16 May '08  
GeneralCouple of ?'smemberrobertfah9:21 7 Nov '06  
AnswerRe: Couple of ?'smemberDaron Yöndem0:14 10 Dec '06  
QuestionCan I apply this code [modified]memberJamil Akhtar6:43 9 Aug '06  
AnswerRe: Can I apply this codememberDaron Yöndem23:09 15 Oct '06  
Generaleveryone can modify web pagememberhuqiwei5:50 20 Jul '06  
AnswerRe: everyone can modify web pagememberDaron Yöndem23:07 15 Oct '06  
QuestionHow to use Web Parts with Forms Authentication?memberBret Williams13:02 14 Jul '06  
AnswerRe: How to use Web Parts with Forms Authentication?memberDaron Yöndem12:34 24 Sep '06  
GeneralRe: How to use Web Parts with Forms Authentication?membernareshpatel9:28 15 Oct '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Nov 2005
Editor: Smitha Vijayan
Copyright 2005 by Daron Yndem
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project