11/17/10

Change Silverlight Business Application template to handle login state events

If you have created  a Silverlight Application on Visual Studio 2010, you have probably used the Business Application template. The template already has implementation to wire the login and registration tasks for the application. The login state information however is encapsulated in the LoginStatus control, and the application does not have any wiring to handle those events.  The MainPage needs to handle those events to enable certain user interface elements that should only be available after the user has logged in successfully. The MainPage acts as the master page (ASP.net) for the application.
 To enable an application to received these events, we need to make the following changes:
Edit the LoginStatus.xaml.cs file and add the following code segment in the LoginStatus class:
public delegate void LoginHandler(object sender, AuthenticationEventArgs e);
public event LoginHandler LoginStateChange;          //event to send when status changes

Look for the authentication event handlers and add the LoginStateChange call. The code should look as follows:
private void Authentication_LoggedIn(object sender, AuthenticationEventArgs e)
{
      this.UpdateLoginState();
      LoginStateChange(this, e);  //send event
}

private void Authentication_LoggedOut(object sender, AuthenticationEventArgs e)
{
      this.UpdateLoginState();           
      LoginStateChange(this, e); //send event
}

Now edit the MainPage.xaml.cs file and in the constructor add the LoginStateChange handler. The code should look as follows:

public MainPage()
{
       InitializeComponent();
       LoginStatus ctrl = new LoginStatus();
       ctrl.LoginStateChange += new LoginStatus.LoginHandler(LoginStateChange);
       this.loginContainer.Child = ctrl;                        
}

Add the event handler and check for the user status to make an element visible. In this example, I am using a container named menu which I added to the MainPage.xaml file. Replace the container name with something you have previously defined in your file otherwise you will get a compilation error.

void LoginStateChange(object sender, AuthenticationEventArgs e)
{
     menu.Visibility = (e != null && e.User.Identity.IsAuthenticated) ?
                        System.Windows.Visibility.Visible :
                      System.Windows.Visibility.Collapsed;           
}

I hope it helps


og-bit.com