Walkthrough: Using Authentication Service with Silverlight Navigation Application
[ This document was written for WCF Services Version 1 Service Pack 2 and might not be up to date Please see Release Notes or Changelog for a list of changes since WCF RIA Services ]
In this walkthrough, you learn how to set up your server and client projects in an Open Ria Services solution to work with an authentication service. When you create a solution with the Silverlight Navigation Application template and enable Open Ria Services, you can access the ASP.NET Membership framework by adding an authentication service. The authentication service exposes authentication, roles, and profiles from the server project to the client project. You use the authentication service to validate user credentials, restrict access to resources based on roles, and store profile properties.
Note: The Silverlight Business Application automatically implements the authentication service. For more information, see Walkthrough: Using Authentication Service with Silverlight Business Application.

Prerequisites

This and the other walkthroughs presented in the Open Ria Services documentation require several prerequisite programs, such as Visual Studio and the Silverlight Developer Runtime and SDK, be installed and configured properly, in addition to Open Ria Services and the Open Ria Services Toolkit. They also require installing and configuring SQL Server 2008 R2 Express with Advanced Services and installing the AdventureWorks OLTP and LT database.
Detailed instructions for the satisfaction of each of these prerequisites are provided by the topics within the Prerequisites for Open Ria Services node. Follow the instructions provided there before proceeding with this walkthrough to ensure that you encounter as few problems as possible when working through this Open Ria Services walkthroughs.

Configuring the Server Project for Authentication, Roles, and Profiles

To use the authentication service from a Silverlight application, you must configure the authentication on the server project. You configure authentication in the Web.config file. After configuring authentication, you can also configure roles and profiles on the server project, if you want to use those features from the Silverlight application. In this walkthrough, you will configure all three features. Finally, you add an authentication service which exposes the enabled features to the client.

To configure the server project

  1. 1.
    In Visual Studio, select File, New, and then Project.
    The New Project dialog box appears.
  2. 2.
    Select the Silverlight project type.
  3. 3.
    Select the Silverlight Navigation Application template and name the application ExampleNavigationApplication.
  4. 4.
    Click OK.
    The New Silverlight Application dialog box appears.
  5. 5.
    Make sure that the Host the Silverlight application in a new Web site check box is selected and that the New Web project type is set to ASP.NET Web Application Project.
  6. 6.
    Select the Enable Open Ria Services check box.
  7. 7.
    Click OK to create the solution.
  8. 8.
    In the server project (ExampleBusinessApplication.Web), open the Web.config file.
  9. 9.
    In the \ element, add an \ element and set the mode property to Forms.
    <authentication mode="Forms"></authentication>
  10. 10.
    In the \ element, add a \ element and set the enabled property to true.
    <roleManager enabled="true"></roleManager>
  11. 11.
    In the \ element, add a \ element, set the enabled property to true, and include a profile property named DefaultRows.
    <profile enabled="true">
    <properties>
    <add type="System.Int32" defaultValue="10" name="DefaultRows"/>
    </properties>
    </profile>
    The completed \ element should include the following elements.
    <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms"></authentication>
    <roleManager enabled="true"></roleManager>
    <profile enabled="true">
    <properties>
    <add type="System.Int32" defaultValue="10" name="DefaultRows"/>
    </properties>
    </profile>
    </system.web>
  12. 12.
    Save the Web.config file.
  13. 13.
    In the Solution Explorer, right-click the server project, select Add and then New Item.
    The Add New Item dialog box appears.
  14. 14.
    Select the Authentication Domain Service template and name it AuthenticationDomainService.
    ​
    ​
  15. 15.
    Click Add.
  16. 16.
    Open the authentication service code file (AuthenticationDomainService.cs or AuthenticationDomainService.vb) and add the DefaultRows property that you defined in the Web.config file to the User class.
    <EnableClientAccess()> _
    Public Class AuthenticationDomainService
    Inherits AuthenticationBase(Of User)
    ​
    End Class
    ​
    Public Class User
    Inherits UserBase
    ​
    Public Property DefaultRows As Integer
    ​
    End Class
    [EnableClientAccess]
    public class AuthenticationDomainService : AuthenticationBase<User>
    {
    }
    ​
    public class User : UserBase
    {
    public int DefaultRows { get; set; }
    }
  17. 17.
    Build the solution.
In this section, you will use the ASP.NET Web Site Administration Tool to create a user and role. You will login as this user in a later section.

To add users with the ASP.NET Web Site Administration Tool

  1. 1.
    To open the ASP.NET Web Site Administration Tool, first select the server project in the Solution Explorer.
  2. 2.
    On the Project menu, select ASP.NET Configuration.
    If you do not see the ASP.NET Configuration option in the Project menu, it may be because you have selected the client project.
    ​
    ​
  3. 3.
    Select the Security tab in ASP.NET Web Site Administration Tool.
    ​
    ​
  4. 4.
    In the Roles section, click the Create or Mange roles link.
  5. 5.
    Add a new role named Managers and click the Add Role button.
    ​
    ​
  6. 6.
    In the lower-right corner, click the Back button.
  7. 7.
    In the Users section, click the Create user link.
  8. 8.
    Create a new user with the following values and select the Managers role check box.
    User Name: CustomerManager
    Security Question: Favorite color?
    Security Answer: Blue
    Managers role: selected
    ​
    ​
  9. 9.
    Click the Create User button.
  10. 10.
    Close the ASP.NET Web Site Administration Tool.

Configuring the Client for Authentication

You must configure the client project to use the authentication mode that matches the authentication mode you configured in the server project.

To configure the client project

  1. 1.
    In the client project, open the code-behind file for the App.xaml file (App.xaml.cs or App.xaml.vb).
  2. 2.
    In the constructor, create a new instance of the WebContext class.
  3. 3.
    Set the Authentication property to a new instance of the FormsAuthentication class, and add the WebContext instance to the ApplicationLifetimeObjects.
    Public Sub New()
    InitializeComponent()
    ​
    Dim webcontext As New WebContext
    webcontext.Authentication = New OpenRiaServices.Client.Authentication.FormsAuthentication
    Me.ApplicationLifetimeObjects.Add(webcontext)
    End Sub
    public App()
    {
    this.Startup += this.Application_Startup;
    this.UnhandledException += this.Application_UnhandledException;
    ​
    InitializeComponent();
    ​
    WebContext webcontext = new WebContext();
    webcontext.Authentication = new OpenRiaServices.Client.Authentication.FormsAuthentication();
    this.ApplicationLifetimeObjects.Add(webcontext);
    }

Adding Login Functionality to the Client

In this section, you will add Silverlight controls that enable the user to provide user name and password for logging in. You will add code that calls the Login method with the user's credentials. You will also set which controls are visible based on whether the user is logged in.
For simplicity, the login user interface is added to the Home page in this walkthrough. In your application, you may want to create a separate login page.

To login and logout a user

  1. 1.
    In Solution Explorer, expand the Views folder in the client project.
  2. 2.
    Open the Home.xaml file.
  3. 3.
    After the TextBlock named ContentText, add the following XAML.
    The XAML includes a TextBox for providing a user name, a PasswordBox for providing a password, a Button for submitting the login request, and a TextBlock and HyperlinkButton for logging out which are only displayed after the user has logged in.
    <TextBlock x:Name="WelcomeText" Style="{StaticResource ContentTextStyle}" Visibility="Collapsed"></TextBlock>
    <HyperlinkButton x:Name="LogoutButton"
    Content="Logout"
    Click="LogoutButton_Click"
    Visibility="Collapsed">
    </HyperlinkButton>
    <Border x:Name="LoginBorder"
    Margin="10,10,0,0"
    BorderThickness="2"
    BorderBrush="Black"
    HorizontalAlignment="Left"
    CornerRadius="15"
    Padding="10"
    Background="BlanchedAlmond"
    Width="300">
    <Grid HorizontalAlignment="Left">
    <Grid.RowDefinitions>
    <RowDefinition></RowDefinition>
    <RowDefinition Height="30" ></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition></RowDefinition>
    <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="0"
    Grid.ColumnSpan="2"
    Grid.Column="0"
    FontWeight="Bold"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="Log In Existing User">
    </TextBlock>
    <TextBlock Grid.Row="1"
    Grid.Column="0"
    HorizontalAlignment="Right"
    VerticalAlignment="Center"
    Text="User Name: ">
    </TextBlock>
    <TextBox x:Name="UserName"
    VerticalAlignment="Center"
    Grid.Row="1"
    Grid.Column="1"
    Width="100">
    </TextBox>
    <TextBlock Grid.Row="2"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Password: ">
    </TextBlock>
    <PasswordBox x:Name="Password"
    VerticalAlignment="Center"
    Grid.Row="2"
    Grid.Column="1"
    Width="100">
    </PasswordBox>
    <TextBlock x:Name="LoginResult"
    TextWrapping="Wrap"
    Visibility="Collapsed"
    Grid.Row="3"
    Grid.ColumnSpan="2"
    Foreground="Red">
    </TextBlock>
    <Button x:Name="LoginButton"
    Margin="0,5,0,0"
    Grid.Row="4"
    Grid.Column="1"
    Content="Log In"
    Click="LoginButton_Click">
    </Button>
    </Grid>
    </Border>
  4. 4.
    Open the code-behind file for the home page (Home.xaml.cs or Home.xaml.vb).
  5. 5.
    Add a using or an Imports statement for the OpenRiaServices.Client.Authentication namespace.
  6. 6.
    Add the following code to the Home class.
    The code includes event handlers for logging in and logging out, callback methods for completed login and logout operations, and a method that set the visibility of controls based on whether the user is authenticated.
    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
    SetControlVisibility(WebContext.Current.User.IsAuthenticated)
    End Sub
    ​
    Private Sub LoginButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim lp As LoginParameters = New LoginParameters(UserName.Text, Password.Password)
    WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
    LoginButton.IsEnabled = False
    LoginResult.Text = ""
    End Sub
    ​
    Private Sub LoginOperation_Completed(ByVal lo As LoginOperation)
    If (lo.HasError) Then
    LoginResult.Text = lo.Error.Message
    LoginResult.Visibility = System.Windows.Visibility.Visible
    lo.MarkErrorAsHandled()
    ElseIf (lo.LoginSuccess = False) Then
    LoginResult.Text = "Login failed. Please check user name and password."
    LoginResult.Visibility = System.Windows.Visibility.Visible
    ElseIf (lo.LoginSuccess = True) Then
    SetControlVisibility(True)
    End If
    LoginButton.IsEnabled = True
    End Sub
    ​
    Private Sub SetControlVisibility(ByVal isAuthenticated As Boolean)
    If (isAuthenticated) Then
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name
    WelcomeText.Visibility = System.Windows.Visibility.Visible
    LogoutButton.Visibility = System.Windows.Visibility.Visible
    Else
    LoginBorder.Visibility = System.Windows.Visibility.Visible
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed
    End If
    End Sub
    ​
    Private Sub LogoutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    WebContext.Current.Authentication.Logout(AddressOf Me.LogoutOperation_Completed, Nothing)
    End Sub
    ​
    Private Sub LogoutOperation_Completed(ByVal lo As LogoutOperation)
    If (Not (lo.HasError)) Then
    SetControlVisibility(False)
    Else
    Dim ew As ErrorWindow = New ErrorWindow("Logout failed.", "Please try logging out again.")
    ew.Show()
    lo.MarkErrorAsHandled()
    End If
    End Sub
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    SetControlVisibility(WebContext.Current.User.IsAuthenticated);
    }
    ​
    private void LoginButton_Click(object sender, RoutedEventArgs e)
    {
    LoginParameters lp = new LoginParameters(UserName.Text, Password.Password);
    WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
    LoginButton.IsEnabled = false;
    LoginResult.Text = "";
    }
    ​
    private void LoginOperation_Completed(LoginOperation lo)
    {
    if (lo.HasError)
    {
    LoginResult.Text = lo.Error.Message;
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    lo.MarkErrorAsHandled();
    }
    else if (lo.LoginSuccess == false)
    {
    LoginResult.Text = "Login failed. Please check user name and password.";
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    }
    else if (lo.LoginSuccess == true)
    {
    SetControlVisibility(true);
    }
    LoginButton.IsEnabled = true;
    }
    ​
    private void SetControlVisibility(bool isAuthenticated)
    {
    if (isAuthenticated)
    {
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed;
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name;
    WelcomeText.Visibility = System.Windows.Visibility.Visible;
    LogoutButton.Visibility = System.Windows.Visibility.Visible;
    }
    else
    {
    LoginBorder.Visibility = System.Windows.Visibility.Visible;
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed;
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed;
    }
    }
    ​
    private void LogoutButton_Click(object sender, RoutedEventArgs e)
    {
    WebContext.Current.Authentication.Logout(this.LogoutOperation_Completed, null);
    }
    ​
    private void LogoutOperation_Completed(LogoutOperation lo)
    {
    ​
    if (!lo.HasError)
    {
    SetControlVisibility(false);
    }
    else
    {
    ErrorWindow ew = new ErrorWindow("Logout failed.", "Please try logging out again.");
    ew.Show();
    lo.MarkErrorAsHandled();
    }
    }
  7. 7.
    Run the solution.
    ​
    ​
  8. 8.
    Log in as CustomerManager with [email protected] for the password.
    Notice that the Login area is no longer displayed, but the welcome text and logout link are now displayed.
    ​
    ​
  9. 9.
    Click Logout link and close Web browser.

Adding New Users from the Client

The authentication service does not contain an operation to create new users. To register a new user, you create an empty domain service and add an operation for adding a user to the ASP.NET Membership framework.

To configure the server project for adding a new user

  1. 1.
    In the server project, add a new class file named NewUser.
  2. 2.
    Define the properties for registering a new user by adding the following code to the NewUser class.
    Imports System.ComponentModel.DataAnnotations
    ​
    Public Class NewUser
    ​
    <Key()> _
    <Required()> _
    <RegularExpression("^[a-zA-Z0-9_]*quot;, ErrorMessage:="Invalid user name. It must contain only alphanumeric characters")> _
    Public Property UserName As String
    ​
    <Key()> _
    <Required()> _
    <RegularExpression("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)quot;, ErrorMessage:="Invalid email. An email must use the format [email protected]")> _
    Public Property Email As String
    ​
    <Required()> _
    <RegularExpression("^.*[^a-zA-Z0-9].*quot;, ErrorMessage:="A password needs to contain at least one special character e.g. @ or #")> _
    <StringLength(50, MinimumLength:=7, ErrorMessage:="Invalid password. It must be contain at least 7 characters and no more than 50 characters.")> _
    Public Property Password As String
    ​
    <Required()> _
    <CustomValidation(GetType(RegistrationValidator), "IsPasswordConfirmed")> _
    Public Property ConfirmPassword As String
    ​
    <Range(1, 20)> _
    Public Property RecordsToShow As Integer
    ​
    <Required()> _
    Public Property SecurityQuestion As String
    ​
    <Required()> _
    Public Property SecurityAnswer As String
    End Class
    using System;
    using System.ComponentModel.DataAnnotations;
    ​
    namespace ExampleNavigationApplication.Web
    {
    public class NewUser
    {
    [Key]
    [Required()]
    [RegularExpression("^[a-zA-Z0-9_]*quot;, ErrorMessage="Invalid user name. It must contain only alphanumeric characters")]
    public string UserName { get; set; }
    ​
    [Key]
    [Required()]
    [RegularExpression(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)quot;, ErrorMessage="Invalid email. An email must use the format [email protected]")]
    public string Email { get; set; }
    ​
    [Required()]
    [RegularExpression("^.*[^a-zA-Z0-9].*quot;, ErrorMessage="A password needs to contain at least one special character e.g. @ or #")]
    [StringLength(50, MinimumLength = 7, ErrorMessage="Invalid password. It must be contain at least 7 characters and no more than 50 characters.")]
    public string Password { get; set; }
    ​
    [Required()]
    [CustomValidation(typeof(RegistrationValidator), "IsPasswordConfirmed")]
    public string ConfirmPassword { get; set; }
    ​
    [Range(1, 20)]
    public int RecordsToShow { get; set; }
    ​
    [Required()]
    public string SecurityQuestion { get; set; }
    ​
    [Required()]
    public string SecurityAnswer { get; set; }
    }
    }
    The ConfirmPassword property in the previous step is defined with a CustomValidationAttribute attribute. In the attribute, it specifies a RegistrationValidator class and a method named IsPasswordConfirmed. You must now define this custom validation class.
  3. 3.
    Add a new class named RegistrationValidator.shared.cs or RegistrationValidator.shared.vb.
  4. 4.
    Add the following code to the RegistrationValidator.shared file.
    Imports System.ComponentModel.DataAnnotations
    ​
    Public Class RegistrationValidator
    Public Shared Function IsPasswordConfirmed(ByVal confirmPassword As String, ByVal context As ValidationContext) As ValidationResult
    Dim data As Web.NewUser = CType(context.ObjectInstance, Web.NewUser)
    If (data.Password = confirmPassword) Then
    Return ValidationResult.Success
    Else
    Return New ValidationResult("Please confirm your password by providing it again.")
    End If
    End Function
    End Class
    using System.ComponentModel.DataAnnotations;
    ​
    namespace ExampleNavigationApplication.Web
    {
    public class RegistrationValidator
    {
    public static ValidationResult IsPasswordConfirmed(string confirmPassword, ValidationContext context)
    {
    NewUser data = (NewUser)context.ObjectInstance;
    if (data.Password == confirmPassword)
    {
    return ValidationResult.Success;
    }
    else
    {
    return new ValidationResult("Please confirm your password by providing it again.");
    }
    }
    }
    }
  5. 5.
    Add a new item to the server project and select the Domain Service Class template.
  6. 6.
    Name the file RegistrationDomainService.cs or RegistrationDomainService.vb and then click the Add button.
  7. 7.
    In the Add New Domain Service Class dialog box, select \ from the Available DataContexts/ObjectContexts list.
  8. 8.
    Click OK.
  9. 9.
    To create a domain operation that adds a new user through the Membership framework and saves a profile property, add the following code to the RegistrationDomainService class.
    The GetUsers method must be included to ensure that the NewUser entity class is generated for the client project. Only classes that are exposed through a public query operation are generated in the client project.
    After creating the user, the profile property named DefaultRows is set. In this case, the profile property is set as part of the domain operation for creating a user. In a later section, you will add code to set the profile property from the client project.
    Option Compare Binary
    Option Infer On
    Option Strict On
    Option Explicit On
    ​
    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.ComponentModel.DataAnnotations
    Imports System.Linq
    Imports OpenRiaServices.Hosting
    Imports OpenRiaServices.Server
    Imports System.Web.Profile
    ​
    <EnableClientAccess()> _
    Public Class RegistrationDomainService
    Inherits DomainService
    ​
    Public Sub AddUser(ByVal user As NewUser)
    Dim createStatus As MembershipCreateStatus
    Membership.CreateUser(user.UserName, user.Password, user.Email, user.SecurityQuestion, user.SecurityAnswer, True, Nothing, createStatus)
    ​
    If (createStatus <> MembershipCreateStatus.Success) Then
    Throw New DomainException(createStatus.ToString())
    End If
    ​
    Dim profile = ProfileBase.Create(user.UserName, True)
    profile.SetPropertyValue("DefaultRows", user.RecordsToShow)
    profile.Save()
    End Sub
    ​
    Public Function GetUsers() As IEnumerable(Of NewUser)
    Throw New NotSupportedException()
    End Function
    End Class
    ``` csharp namespace ExampleNavigationApplication.Web { using System; using System.Collections.Generic; using OpenRiaServices.Hosting; using OpenRiaServices.Server; using System.Web.Security; using System.Web.Profile;
[EnableClientAccess()]
public class RegistrationDomainService : DomainService
{
public void AddUser(NewUser user)
{
MembershipCreateStatus createStatus;
Membership.CreateUser(user.UserName, user.Password, user.Email, user.SecurityQuestion, user.SecurityAnswer, true, null, out createStatus);
​
if (createStatus != MembershipCreateStatus.Success)
{
throw new DomainException(createStatus.ToString());
}
​
ProfileBase profile = ProfileBase.Create(user.UserName, true);
profile.SetPropertyValue("DefaultRows", user.RecordsToShow);
profile.Save();
}
​
public IEnumerable<NewUser> GetUsers()
{
throw new NotSupportedException();
}
}
}
```

To configure the client project for adding new users

  1. 1.
    Open the Home.xaml file.
  2. 2.
    After the end tag for the LoginBorderBorder control, add the following XAML to create a second Border control with input controls to collect information for creating new users.
    The controls accept values for user name, password, password confirmation, e-mail address, security question, security answer, and the number of records to show on reports. The number of records to display will be saved as a profile property. All of the other values are used to create the user through ASP.NET Membership framework.
    <Border x:Name="RegisterBorder"
    Margin="10,10,0,0"
    BorderThickness="2"
    BorderBrush="Black"
    HorizontalAlignment="Left"
    CornerRadius="15"
    Padding="10"
    Background="BurlyWood"
    Width="400">
    <Grid HorizontalAlignment="Left">
    <Grid.RowDefinitions>
    <RowDefinition></RowDefinition>
    <RowDefinition Height="30" ></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition Height="30"></RowDefinition>
    <RowDefinition></RowDefinition>
    <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    ​
    <TextBlock Grid.Row="0"
    Grid.ColumnSpan="2"
    Grid.Column="0"
    FontWeight="Bold"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="Register New User">
    </TextBlock>
    <TextBlock Grid.Row="1"
    Grid.Column="0"
    HorizontalAlignment="Right"
    VerticalAlignment="Center"
    Text="User Name: ">
    </TextBlock>
    <TextBox x:Name="NewUsername"
    VerticalAlignment="Center"
    HorizontalAlignment="Left"
    Grid.Row="1"
    Grid.Column="1"
    Width="100">
    </TextBox>
    <TextBlock Grid.Row="2"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Password: ">
    </TextBlock>
    <PasswordBox x:Name="NewPassword"
    VerticalAlignment="Center"
    HorizontalAlignment="Left"
    Grid.Row="2"
    Grid.Column="1"
    Width="100">
    </PasswordBox>
    <TextBlock Grid.Row="3"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Confirm Password: ">
    </TextBlock>
    <PasswordBox x:Name="NewConfirmPassword"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Grid.Row="3"
    Grid.Column="1"
    Width="100">
    </PasswordBox>
    <TextBlock Grid.Row="4"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Email: ">
    </TextBlock>
    <TextBox x:Name="NewEmail"
    VerticalAlignment="Center"
    Grid.Row="4"
    Grid.Column="1"
    Width="200">
    </TextBox>
    <TextBlock Grid.Row="5"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Records to show: ">
    </TextBlock>
    <ComboBox Grid.Row="5"
    Grid.Column="1"
    x:Name="DefaultRows"
    HorizontalAlignment="Left"
    Width="50"
    Height="20"
    VerticalAlignment="Center">
    <ComboBoxItem Content="1"></ComboBoxItem>
    <ComboBoxItem Content="3"></ComboBoxItem>
    <ComboBoxItem Content="5"></ComboBoxItem>
    <ComboBoxItem Content="10" IsSelected="True"></ComboBoxItem>
    <ComboBoxItem Content="15"></ComboBoxItem>
    <ComboBoxItem Content="20"></ComboBoxItem>
    </ComboBox>
    <TextBlock Grid.Row="6"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Security Question: ">
    </TextBlock>
    <TextBox x:Name="SecurityQuestion"
    VerticalAlignment="Center"
    Grid.Row="6"
    Grid.Column="1"
    Width="200">
    </TextBox>
    <TextBlock Grid.Row="7"
    HorizontalAlignment="Right"
    Grid.Column="0"
    VerticalAlignment="Center"
    Text="Security Answer: ">
    </TextBlock>
    <TextBox x:Name="SecurityAnswer"
    VerticalAlignment="Center"
    Grid.Row="7"
    Grid.Column="1"
    Width="200">
    </TextBox>
    <TextBlock x:Name="registerResult"
    TextWrapping="Wrap"
    Visibility="Collapsed"
    Grid.Row="8"
    Grid.ColumnSpan="2"
    Foreground="Red">
    </TextBlock>
    <Button x:Name="RegisterButton"
    Click="RegisterButton_Click"
    Margin="0,5,0,0"
    Grid.Row="9"
    Grid.Column="1"
    Content="Register" >
    </Button>
    </Grid>
    </Border>
  3. 3.
    Open the Home.xaml.cs (or Home.xaml.vb) code-behind file.
  4. 4.
    Add a using or an Imports statement for the OpenRiaServices.Client, System.ComponentModel.DataAnnotations, and ExampleNavigationApplication.Web namespaces.
  5. 5.
    Add an event handler for the register button click event and add a callback method for domain operation. The callback method includes code to login the user after successfully creating the user account.
    Private Sub RegisterButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    RegisterButton.IsEnabled = False
    Dim context = New RegistrationDomainContext()
    Dim nu = New NewUser()
    Try
    nu.UserName = NewUsername.Text
    nu.Password = NewPassword.Password
    nu.Email = NewEmail.Text
    nu.ConfirmPassword = NewConfirmPassword.Password
    nu.RecordsToShow = Integer.Parse(DefaultRows.SelectionBoxItem.ToString())
    nu.SecurityQuestion = SecurityQuestion.Text
    nu.SecurityAnswer = SecurityAnswer.Text
    context.NewUsers.Add(nu)
    ​
    context.SubmitChanges(AddressOf RegisterUser_Completed, Nothing)
    Catch ve As ValidationException
    registerResult.Visibility = System.Windows.Visibility.Visible
    registerResult.Text = ve.Message
    RegisterButton.IsEnabled = True
    End Try
    End Sub
    ​
    Private Sub RegisterUser_Completed(ByVal so As SubmitOperation)
    If (so.HasError) Then
    Dim ew = New ErrorWindow("Registration failed.", "Please try registering again.")
    ew.Show()
    so.MarkErrorAsHandled()
    Else
    Dim lp = New LoginParameters(NewUsername.Text, NewPassword.Password)
    WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
    NewUsername.Text = ""
    NewPassword.Password = ""
    NewConfirmPassword.Password = ""
    NewEmail.Text = ""
    DefaultRows.SelectedIndex = 0
    SecurityQuestion.Text = ""
    SecurityAnswer.Text = ""
    End If
    RegisterButton.IsEnabled = True
    End Sub
    private void RegisterButton_Click(object sender, RoutedEventArgs e)
    {
    RegisterButton.IsEnabled = false;
    RegistrationDomainContext context = new RegistrationDomainContext();
    NewUser nu = new NewUser();
    try
    {
    nu.UserName = NewUsername.Text;
    nu.Password = NewPassword.Password;
    nu.Email = NewEmail.Text;
    nu.ConfirmPassword = NewConfirmPassword.Password;
    nu.RecordsToShow = int.Parse(DefaultRows.SelectionBoxItem.ToString());
    nu.SecurityQuestion = SecurityQuestion.Text;
    nu.SecurityAnswer = SecurityAnswer.Text;
    context.NewUsers.Add(nu);
    ​
    context.SubmitChanges(RegisterUser_Completed, null);
    }
    catch (ValidationException ve)
    {
    registerResult.Visibility = System.Windows.Visibility.Visible;
    registerResult.Text = ve.Message;
    RegisterButton.IsEnabled = true;
    }
    }
    ​
    private void RegisterUser_Completed(SubmitOperation so)
    {
    if (so.HasError)
    {
    ErrorWindow ew = new ErrorWindow("Registration failed.", "Please try registering again.");
    ew.Show();
    so.MarkErrorAsHandled();
    }
    else
    {
    LoginParameters lp = new LoginParameters(NewUsername.Text, NewPassword.Password);
    WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
    NewUsername.Text = "";
    NewPassword.Password = "";
    NewConfirmPassword.Password = "";
    NewEmail.Text = "";
    DefaultRows.SelectedIndex = 0;
    SecurityQuestion.Text = "";
    SecurityAnswer.Text = "";
    }
    RegisterButton.IsEnabled = true;
    }
  6. 6.
    Modify the SetControlVisibility method to set the visibility of RegisterBorder, as shown in the following code.
    Private Sub SetControlVisibility(ByVal isAuthenticated As Boolean)
    If (isAuthenticated) Then
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed
    RegisterBorder.Visibility = Windows.Visibility.Collapsed
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name
    WelcomeText.Visibility = System.Windows.Visibility.Visible
    LogoutButton.Visibility = System.Windows.Visibility.Visible
    Else
    LoginBorder.Visibility = System.Windows.Visibility.Visible
    RegisterBorder.Visibility = Windows.Visibility.Visible
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed
    End If
    End Sub
    private void SetControlVisibility(bool isAuthenticated)
    {
    if (isAuthenticated)
    {
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed;
    RegisterBorder.Visibility = System.Windows.Visibility.Collapsed;
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name;
    WelcomeText.Visibility = System.Windows.Visibility.Visible;
    LogoutButton.Visibility = System.Windows.Visibility.Visible;
    }
    else
    {
    LoginBorder.Visibility = System.Windows.Visibility.Visible;
    RegisterBorder.Visibility = System.Windows.Visibility.Visible;
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed;
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed;
    }
    }
    The following shows the complete code-behind file.
    Imports OpenRiaServices.Client.Authentication
    Imports OpenRiaServices.Client
    Imports System.ComponentModel.DataAnnotations
    ​
    Partial Public Class Home
    Inherits Page
    ​
    Public Sub New()
    InitializeComponent()
    End Sub
    ​
    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
    SetControlVisibility(WebContext.Current.User.IsAuthenticated)
    End Sub
    ​
    Private Sub LoginButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim lp As LoginParameters = New LoginParameters(UserName.Text, Password.Password)
    WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
    LoginButton.IsEnabled = False
    LoginResult.Text = ""
    End Sub
    ​
    Private Sub LoginOperation_Completed(ByVal lo As LoginOperation)
    If (lo.HasError) Then
    LoginResult.Text = lo.Error.Message
    LoginResult.Visibility = System.Windows.Visibility.Visible
    lo.MarkErrorAsHandled()
    ElseIf (lo.LoginSuccess = False) Then
    LoginResult.Text = "Login failed. Please check user name and password."
    LoginResult.Visibility = System.Windows.Visibility.Visible
    ElseIf (lo.LoginSuccess = True) Then
    SetControlVisibility(True)
    End If
    LoginButton.IsEnabled = True
    End Sub
    ​
    Private Sub SetControlVisibility(ByVal isAuthenticated As Boolean)
    If (isAuthenticated) Then
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed
    RegisterBorder.Visibility = Windows.Visibility.Collapsed
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name
    WelcomeText.Visibility = System.Windows.Visibility.Visible
    LogoutButton.Visibility = System.Windows.Visibility.Visible
    Else
    LoginBorder.Visibility = System.Windows.Visibility.Visible
    RegisterBorder.Visibility = Windows.Visibility.Visible
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed
    End If
    End Sub
    ​
    Private Sub LogoutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    WebContext.Current.Authentication.Logout(AddressOf Me.LogoutOperation_Completed, Nothing)
    End Sub
    ​
    Private Sub LogoutOperation_Completed(ByVal lo As LogoutOperation)
    If (Not (lo.HasError)) Then
    SetControlVisibility(False)
    Else
    Dim ew As ErrorWindow = New ErrorWindow("Logout failed.", "Please try logging out again.")
    ew.Show()
    lo.MarkErrorAsHandled()
    End If
    End Sub
    ​
    Private Sub RegisterButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    RegisterButton.IsEnabled = False
    Dim context = New RegistrationDomainContext()
    Dim nu = New NewUser()
    Try
    nu.UserName = NewUsername.Text
    nu.Password = NewPassword.Password
    nu.Email = NewEmail.Text
    nu.ConfirmPassword = NewConfirmPassword.Password
    nu.RecordsToShow = Integer.Parse(DefaultRows.SelectionBoxItem.ToString())
    nu.SecurityQuestion = SecurityQuestion.Text
    nu.SecurityAnswer = SecurityAnswer.Text
    context.NewUsers.Add(nu)
    ​
    context.SubmitChanges(AddressOf RegisterUser_Completed, Nothing)
    Catch ve As ValidationException
    registerResult.Visibility = System.Windows.Visibility.Visible
    registerResult.Text = ve.Message
    RegisterButton.IsEnabled = True
    End Try
    End Sub
    ​
    Private Sub RegisterUser_Completed(ByVal so As SubmitOperation)
    If (so.HasError) Then
    Dim ew = New ErrorWindow("Registration failed.", "Please try registering again.")
    ew.Show()
    so.MarkErrorAsHandled()
    Else
    Dim lp = New LoginParameters(NewUsername.Text, NewPassword.Password)
    WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
    NewUsername.Text = ""
    NewPassword.Password = ""
    NewConfirmPassword.Password = ""
    NewEmail.Text = ""
    DefaultRows.SelectedIndex = 0
    SecurityQuestion.Text = ""
    SecurityAnswer.Text = ""
    End If
    RegisterButton.IsEnabled = True
    End Sub
    End Class
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using OpenRiaServices.Client.Authentication;
    using OpenRiaServices.Client;
    using System.ComponentModel.DataAnnotations;
    using ExampleNavigationApplication.Web;
    ​
    namespace ExampleNavigationApplication
    {
    public partial class Home : Page
    {
    public Home()
    {
    InitializeComponent();
    ​
    }
    ​
    // Executes when the user navigates to this page.
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    SetControlVisibility(WebContext.Current.User.IsAuthenticated);
    }
    ​
    private void LoginButton_Click(object sender, RoutedEventArgs e)
    {
    LoginParameters lp = new LoginParameters(UserName.Text, Password.Password);
    WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
    LoginButton.IsEnabled = false;
    LoginResult.Text = "";
    }
    ​
    private void LoginOperation_Completed(LoginOperation lo)
    {
    if (lo.HasError)
    {
    LoginResult.Text = lo.Error.Message;
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    lo.MarkErrorAsHandled();
    }
    else if (lo.LoginSuccess == false)
    {
    LoginResult.Text = "Login failed. Please check user name and password.";
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    }
    else if (lo.LoginSuccess == true)
    {
    SetControlVisibility(true);
    }
    LoginButton.IsEnabled = true;
    }
    ​
    private void SetControlVisibility(bool isAuthenticated)
    {
    if (isAuthenticated)
    {
    LoginBorder.Visibility = System.Windows.Visibility.Collapsed;
    RegisterBorder.Visibility = System.Windows.Visibility.Collapsed;
    WelcomeText.Text = "Welcome " + WebContext.Current.User.Name;
    WelcomeText.Visibility = System.Windows.Visibility.Visible;
    LogoutButton.Visibility = System.Windows.Visibility.Visible;
    }
    else
    {
    LoginBorder.Visibility = System.Windows.Visibility.Visible;
    RegisterBorder.Visibility = System.Windows.Visibility.Visible;
    WelcomeText.Visibility = System.Windows.Visibility.Collapsed;
    LogoutButton.Visibility = System.Windows.Visibility.Collapsed;
    }
    }
    ​
    private void LogoutButton_Click(object sender, RoutedEventArgs e)
    {
    WebContext.Current.Authentication.Logout(this.LogoutOperation_Completed, null);
    }
    ​
    private void LogoutOperation_Completed(LogoutOperation lo)
    {
    ​
    if (!lo.HasError)
    {
    SetControlVisibility(false);
    }
    else
    {
    ErrorWindow ew = new ErrorWindow("Logout failed.", "Please try logging out again.");
    ew.Show();
    lo.MarkErrorAsHandled();
    }
    }
    ​
    private void RegisterButton_Click(object sender, RoutedEventArgs e)
    {
    RegisterButton.IsEnabled = false;
    RegistrationDomainContext context = new RegistrationDomainContext();
    NewUser nu = new NewUser();
    try
    {
    nu.UserName = NewUsername.Text;
    nu.Password = NewPassword.Password;
    nu.Email = NewEmail.Text;
    nu.ConfirmPassword = NewConfirmPassword.Password;
    nu.RecordsToShow = int.Parse(DefaultRows.SelectionBoxItem.ToString());
    nu.SecurityQuestion = SecurityQuestion.Text;
    nu.SecurityAnswer = SecurityAnswer.Text;
    context.NewUsers.Add(nu);
    ​
    context.SubmitChanges(RegisterUser_Completed, null);
    }
    catch (ValidationException ve)
    {
    registerResult.Visibility = System.Windows.Visibility.Visible;
    registerResult.Text = ve.Message;
    RegisterButton.IsEnabled = true;
    }
    }
    ​
    private void RegisterUser_Completed(SubmitOperation so)
    {
    if (so.HasError)
    {
    ErrorWindow ew = new ErrorWindow("Registration failed.", "Please try registering again.");
    ew.Show();
    so.MarkErrorAsHandled();
    }
    else
    {
    LoginParameters lp = new LoginParameters(NewUsername.Text, NewPassword.Password);
    WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
    NewUsername.Text = "";
    NewPassword.Password = "";
    NewConfirmPassword.Password = "";
    NewEmail.Text = "";
    DefaultRows.SelectedIndex = 0;
    SecurityQuestion.Text = "";
    SecurityAnswer.Text = "";
    }
    RegisterButton.IsEnabled = true;
    }
    }
    }
  7. 7.
    Run the solution.
    ​
    ​
  8. 8.
    Provide values to register a new user.
  9. 9.
    Close the Web browser.

Restricting Access to Domain Operations

You restrict access to a domain operation by applying either the RequiresAuthenticationAttribute attribute or the RequiresRoleAttribute attribute to the domain operation. Domain operations without an attribute are available to all users. Applying an attribute to domain operation does not prevent the user from calling the domain operation; however, users without the required credentials will receive an exception.

To restrict displayed data by roles

  1. 1.
    In Solution Explorer, select the server project and click the Show All Files button.
  2. 2.
    Right-click the App_Data folder and select Include in Project.