### Query documentation via HTTP GET Source: https://openriaservices.gitbook.io/openriaservices/llms.txt Perform a GET request to the documentation index with 'ask' and 'goal' parameters to receive a tailored answer. ```http GET https://openriaservices.gitbook.io/openriaservices/readme.md?ask=&goal= ``` -------------------------------- ### Get Products Method with Ordering Source: https://openriaservices.gitbook.io/openriaservices/gg602749/ee807305.md Configures the query to return products ordered by ProductID for Entity Framework compatibility. ```csharp public IQueryable GetProducts() { return this.ObjectContext.Products.OrderBy(p => p.ProductID); } ``` ```vb Public Function GetProducts() As IQueryable(Of Product) Return Me.ObjectContext.Products.OrderBy(Function(p) p.ProductID) End Function ``` -------------------------------- ### Implement Custom Authorization Attribute Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee707357.md Examples of creating custom authorization attributes by overriding the Authorize or IsAuthorized methods. ```vb Public Class CheckAttendeeNameAttribute Inherits System.Web.DomainServices.AuthorizationAttribute Public Overrides Function Authorize(ByVal principal As System.Security.Principal.IPrincipal) As Boolean If (principal.IsInRole("Attendee") And principal.Identity.Name.StartsWith("A")) Then Return True Else Return False End If End Function End Class ``` ```vb Public Class RestrictAccessToAssignedManagers Inherits AuthorizationAttribute Protected Overrides Function IsAuthorized(ByVal principal As System.Security.Principal.IPrincipal, ByVal authorizationContext As System.ComponentModel.DataAnnotations.AuthorizationContext) As System.ComponentModel.DataAnnotations.AuthorizationResult Dim eph As EmployeePayHistory Dim selectedEmployee As Employee Dim authenticatedUser As Employee eph = CType(authorizationContext.Instance, EmployeePayHistory) Using context As New AdventureWorksEntities() selectedEmployee = context.Employees.SingleOrDefault(Function(e) e.EmployeeID = eph.EmployeeID) authenticatedUser = context.Employees.SingleOrDefault(Function(e) e.LoginID = principal.Identity.Name) End Using If (selectedEmployee.ManagerID = authenticatedUser.EmployeeID) Then Return AuthorizationResult.Allowed Else Return New AuthorizationResult("Only the authenticated manager for the employee can add a new record.") End If End Function End Class ``` ```csharp public class CheckAttendeeNameAttribute : System.Web.DomainServices.AuthorizationAttribute { public override bool Authorize(System.Security.Principal.IPrincipal principal) { if (principal.IsInRole("Attendee") && principal.Identity.Name.StartsWith("A")) { return true; } else { return false; } } } ``` ```csharp public class RestrictAccessToAssignedManagers : AuthorizationAttribute { protected override AuthorizationResult IsAuthorized(System.Security.Principal.IPrincipal principal, AuthorizationContext authorizationContext) { EmployeePayHistory eph = (EmployeePayHistory)authorizationContext.Instance; Employee selectedEmployee; Employee authenticatedUser; using (AdventureWorksEntities context = new AdventureWorksEntities()) { selectedEmployee = context.Employees.SingleOrDefault(e => e.EmployeeID == eph.EmployeeID); authenticatedUser = context.Employees.SingleOrDefault(e => e.LoginID == principal.Identity.Name); } if (selectedEmployee.ManagerID == authenticatedUser.EmployeeID) { return AuthorizationResult.Allowed; } else { return new AuthorizationResult("Only the authenticated manager for the employee can add a new record."); } } } ``` -------------------------------- ### Configure Authentication Service on Startup Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee707353.md Load the user state during application startup to initialize the authentication context. ```vbnet Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup WebContext.Current.Authentication.LoadUser(AddressOf OnLoadUser_Completed, Nothing) Me.RootVisual = New MainPage() End Sub Private Sub OnLoadUser_Completed(ByVal operation As LoadUserOperation) ' Update UI, if necessary End Sub ``` ```csharp private void Application_Startup(object sender, StartupEventArgs e) { WebContext.Current.Authentication.LoadUser(OnLoadUser_Completed, null); this.RootVisual = new MainPage(); } private void OnLoadUser_Completed(LoadUserOperation operation) { // update UI, if necessary } ``` -------------------------------- ### Data Bind to Computed Property Source: https://openriaservices.gitbook.io/openriaservices/ee707349/ee707345/ee707331.md Example of binding a UI element to the newly created computed property. ```xml ``` -------------------------------- ### Initialize Page Constructor Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Load reports and configure UI visibility for authenticated users upon page initialization. ```vbnet Public Sub New() InitializeComponent() LoadReports() If (WebContext.Current.User.IsAuthenticated) Then SettingsButton.Visibility = System.Windows.Visibility.Visible End If End Sub ``` -------------------------------- ### Implement Database Initializer Source: https://openriaservices.gitbook.io/openriaservices/ee707336/hh556025.md Implements a custom initializer that seeds the database with initial Product and Category data. ```csharp public class ProductDbContextInitializer : DropCreateDatabaseAlways { protected override void Seed(ProductDbContext context) { Category[] categories = new Category[] { new Category { CategoryID = 1, CategoryName = "Food", Description = "Edible stuff", Products = new Product[] { new Product { ProductID = 1, ProductName = "Candy", UnitPrice = 10}, new Product { ProductID = 2, ProductName = "Fruits", UnitPrice = 20, Discontinued = true }, new Product { ProductID = 5, ProductName = "Cereal", UnitPrice = 10}, }.ToList()}, new Category { CategoryID = 2, CategoryName = "Clothes", Description = "Personal stuff", Products = new Product[] { new Product { ProductID = 3, ProductName = "Shirt", UnitPrice = 50}, new Product { ProductID = 4, ProductName = "Cap", UnitPrice = 15}, }.ToList()}, new Category { CategoryID = 3, CategoryName = "Furniture", Description = "Household stuff", Products = new Product[] { new Product { ProductID = 6, ProductName = "Table", UnitPrice = 100}, new Product { ProductID = 7, ProductName = "Chair", UnitPrice = 60}, new Product { ProductID = 8, ProductName = "Lamp", UnitPrice = 20, Discontinued = true }, }.ToList()}, }; foreach (var category in categories) { context.Categories.Add(category); } } ``` -------------------------------- ### Initialize Page Constructor Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942449.md Sets up event handlers and initial data loading within the page constructor. ```vbnet Public Sub New() InitializeComponent() Me.Title = ApplicationStrings.ReportsPageTitle AddHandler WebContext.Current.Authentication.LoggedIn, AddressOf Authentication_LoggedIn AddHandler WebContext.Current.Authentication.LoggedOut, AddressOf Authentication_LoggedOut LoadReports() End Sub ``` ```csharp public Reports() { InitializeComponent(); this.Title = ApplicationStrings.ReportsPageTitle; WebContext.Current.Authentication.LoggedIn += new System.EventHandler(Authentication_LoggedIn); WebContext.Current.Authentication.LoggedOut += new System.EventHandler(Authentication_LoggedOut); LoadReports(); } ``` -------------------------------- ### Initialize WebContext in Client Application Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee707353.md Configure the WebContext with an authentication provider and add it to the application lifetime objects during startup. ```vbnet Public Sub New() InitializeComponent() Dim webcontext As New WebContext webcontext.Authentication = New OpenRiaServices.Client.Authentication.FormsAuthentication Me.ApplicationLifetimeObjects.Add(webcontext) End Sub ``` ```csharp 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); } ``` -------------------------------- ### Configure Windows Authentication in App Startup Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ee707360.md Update the application constructor to use WindowsAuthentication instead of FormsAuthentication. ```vb Public Sub New() InitializeComponent() Dim webContext As New WebContext() 'webContext.Authentication = New FormsAuthentication() webContext.Authentication = New WindowsAuthentication() Me.ApplicationLifetimeObjects.Add(webContext) End Sub ``` ```csharp public App() { InitializeComponent(); WebContext webContext = new WebContext(); //webContext.Authentication = new FormsAuthentication(); webContext.Authentication = new WindowsAuthentication(); this.ApplicationLifetimeObjects.Add(webContext); } ``` -------------------------------- ### Implement Child Window Logic Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ff713719.md Code-behind to initialize the new entity and handle commit or cancel actions. ```vbnet Partial Public Class EmployeeRegistrationWindow Inherits ChildWindow Public Sub New() InitializeComponent() NewEmployee = New Employee addEmployeeDataForm.CurrentItem = NewEmployee addEmployeeDataForm.BeginEdit() End Sub Public Property NewEmployee As Employee Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles OKButton.Click Me.addEmployeeDataForm.CommitEdit() Me.DialogResult = True End Sub Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles CancelButton.Click NewEmployee = Nothing addEmployeeDataForm.CancelEdit() Me.DialogResult = False End Sub End Class ``` ```csharp public partial class EmployeeRegistrationWindow : ChildWindow { public EmployeeRegistrationWindow() { InitializeComponent(); NewEmployee = new Employee(); addEmployeeDataForm.CurrentItem = NewEmployee; addEmployeeDataForm.BeginEdit(); } public Employee NewEmployee { get; set; } private void OKButton_Click(object sender, RoutedEventArgs e) { addEmployeeDataForm.CommitEdit(); this.DialogResult = true; } private void CancelButton_Click(object sender, RoutedEventArgs e) { NewEmployee = null; addEmployeeDataForm.CancelEdit(); this.DialogResult = false; } } ``` -------------------------------- ### Implement Login Operation Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee707353.md Handle user login by passing credentials to the authentication service and processing the operation result. ```vbnet 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 ``` ```csharp 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; } ``` -------------------------------- ### Implement User Authentication and Registration in C# Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Handles login, logout, and registration logic within a Silverlight or WPF Page. Requires OpenRiaServices.Client.Authentication and a generated DomainContext. ```csharp 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; } } ``` -------------------------------- ### Handle Settings Button Click Event Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Opens the ProfileWindow when the settings button is clicked. ```vbnet Private Sub SettingsButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim settingsWindow = New ProfileWindow() settingsWindow.Show() End Sub ``` ```csharp private void SettingsButton_Click(object sender, RoutedEventArgs e) { Views.ProfileWindow settingsWindow = new Views.ProfileWindow(); settingsWindow.Show(); } ``` -------------------------------- ### Configure Profile in Web.config Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee707350.md Enable the profile system and define properties within the system.web section of the server project's configuration file. ```xml ``` -------------------------------- ### Implement SettingsButton click handler Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942449.md Event handler logic to instantiate and display the ProfileWindow when the settings link is clicked. ```vb Private Sub SettingsButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim settingsWindow As New ProfileWindow settingsWindow.Show() End Sub ``` ```csharp private void SettingsButton_Click(object sender, RoutedEventArgs e) { ExampleBusinessApplication.Views.ProfileWindow settingsWindow = new ExampleBusinessApplication.Views.ProfileWindow(); settingsWindow.Show(); } ``` -------------------------------- ### Define a CustomerPresentationModel class Source: https://openriaservices.gitbook.io/openriaservices/ee707348/ee707356/ee707347.md Create a class in the server project with properties representing the desired fields from multiple entities. Ensure the class includes a property marked with the [Key] attribute. ```vbnet Public Class CustomerPresentationModel _ Public Property CustomerID As Integer Public Property FirstName As String Public Property LastName As String Public Property EmailAddress As String Public Property Phone As String Public Property AddressType As String Public Property AddressLine1 As String Public Property AddressLine2 As String Public Property City As String Public Property StateProvince As String Public Property PostalCode As String Public Property AddressID As Integer Public Property AddressModifiedDate As DateTime Public Property CustomerModifiedDate As DateTime End Class ``` ```csharp public class CustomerPresentationModel { [Key] public int CustomerID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string Phone { get; set; } public string AddressType { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string StateProvince { get; set; } public string PostalCode { get; set; } public int AddressID { get; set; } public DateTime AddressModifiedDate { get; set; } public DateTime CustomerModifiedDate { get; set; } } ``` -------------------------------- ### Declare Domain Context Namespace Source: https://openriaservices.gitbook.io/openriaservices/ee707349/ee707363.md Namespace declaration for the server project containing the domain context, replacing ExampleApplication.Web with your specific project name. ```xml xmlns:domain="clr-namespace:ExampleApplication.Web" ``` -------------------------------- ### Implement the FetchSovereigns method Source: https://openriaservices.gitbook.io/openriaservices/ee707336/gg602754.md Provides a method that returns a list of Sovereign entity instances. ```csharp public List FetchSovereigns() { List sovereignList = new List { new Sovereign() {UniqueId = 1, Name = "John", House = "Plantagenet", Dominion = "Angevin Empire", ReignStart = 1167, ReignEnd = 1216, Sobriquet = "Lackland" }, new Sovereign() {UniqueId = 2, Name = "Charles", House = "Stuart", Dominion = "England, Scotland, & Ireland", ReignStart = 1625, ReignEnd = 1649, Sobriquet = "The Martyr" }, new Sovereign() {UniqueId = 3, Name = "William", House = "Dunkeld", Dominion = "Scotland", ReignStart = 1165, ReignEnd = 1249, Sobriquet = "The Lion" }, new Sovereign() {UniqueId = 4, Name = "Elizabeth", House = "Tudor", Dominion = "England", ReignStart = 1555, ReignEnd = 1609, Sobriquet = "The Virgin Queen" }, new Sovereign() {UniqueId = 5, Name = "Ivan", House = "Vasilyevich", Dominion = "Russia", ReignStart = 1533, ReignEnd = 1584, Sobriquet = "The Terrible" }, new Sovereign() {UniqueId = 6, Name = "Charles", House = "Valois", Dominion = "France", ReignStart = 1380, ReignEnd = 1422, Sobriquet = "The Mad" } }; return sovereignList; } ``` -------------------------------- ### Implement ProfileWindow for user settings Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md A ChildWindow implementation that initializes a ComboBox with user preferences and saves updates to the WebContext. ```vbnet Partial Public Class ProfileWindow Inherits ChildWindow Public Sub New() InitializeComponent() Dim userDefaultRows = WebContext.Current.User.DefaultRows.ToString() For Each cbi As ComboBoxItem In defaultRows.Items If (cbi.Content.ToString() = userDefaultRows) Then defaultRows.SelectedItem = cbi Exit For End If Next End Sub Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles OKButton.Click Dim newSelection = Integer.Parse(defaultRows.SelectionBoxItem.ToString()) If (newSelection <> WebContext.Current.User.DefaultRows) Then WebContext.Current.User.DefaultRows = newSelection WebContext.Current.Authentication.SaveUser(True) End If Me.DialogResult = True End Sub Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles CancelButton.Click Me.DialogResult = False End Sub End Class ``` ```csharp public partial class ProfileWindow : ChildWindow { public ProfileWindow() { InitializeComponent(); string userDefaultRows = WebContext.Current.User.DefaultRows.ToString(); foreach (ComboBoxItem cbi in defaultRows.Items) { if (cbi.Content.ToString() == userDefaultRows) { defaultRows.SelectedItem = cbi; break; } } } private void OKButton_Click(object sender, RoutedEventArgs e) { int newSelection = int.Parse(defaultRows.SelectionBoxItem.ToString()); if (newSelection != WebContext.Current.User.DefaultRows) { WebContext.Current.User.DefaultRows = newSelection; WebContext.Current.Authentication.SaveUser(true); } this.DialogResult = true; } private void CancelButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = false; } } ``` -------------------------------- ### Initialize DomainContext and Load Data Source: https://openriaservices.gitbook.io/openriaservices/ee707336/hh556025.md Logic to initialize the DomainContext and load data into the DataGrid, placed within the MainPage constructor. ```csharp ctx = new NWDomainContext(); ctx.Load(ctx.GetProductsQuery()); ctx.Load(ctx.GetCategoriesQuery()); this.dataGrid1.ItemsSource = ctx.Products; ``` -------------------------------- ### Initialize Reports Page Constructor Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Initializes the page components and sets the visibility of the settings button based on the user's authentication status. ```csharp public Reports() { InitializeComponent(); LoadReports(); if (WebContext.Current.User.IsAuthenticated) { SettingsButton.Visibility = System.Windows.Visibility.Visible; } } ``` -------------------------------- ### Instantiate Context and Load Data Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ff713719.md Initializes the OrganizationContext and loads employee data into the DataGrid. ```vbnet Partial Public Class EmployeeList Inherits Page Dim _OrganizationContext As New OrganizationContext Public Sub New() InitializeComponent() Me.dataGrid1.ItemsSource = _OrganizationContext.Employees _OrganizationContext.Load(_OrganizationContext.GetEmployeesQuery()) End Sub 'Executes when the user navigates to this page. Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs) End Sub End Class ``` ```csharp public partial class EmployeeList : Page { OrganizationContext _OrganizationContext = new OrganizationContext(); public EmployeeList() { InitializeComponent(); this.dataGrid1.ItemsSource = _OrganizationContext.Employees; _OrganizationContext.Load(_OrganizationContext.GetEmployeesQuery()); } // Executes when the user navigates to this page. protected override void OnNavigatedTo(NavigationEventArgs e) { } } ``` -------------------------------- ### MainPage Implementation Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ee707376.md Complete implementation of the MainPage class for loading and binding data. ```csharp namespace RIAServicesExample { public partial class MainPage : UserControl { private CustomerDomainContext _customerContext = new CustomerDomainContext(); public MainPage() { InitializeComponent(); LoadOperation loadOp = this._customerContext.Load(this._customerContext.GetCustomersQuery()); CustomerGrid.ItemsSource = loadOp.Entities; } } } ``` -------------------------------- ### Implement User Authentication and Registration in VB.NET Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Handles login, logout, and user registration operations using OpenRiaServices.Client.Authentication and RegistrationDomainContext. Requires appropriate UI controls to be defined in the corresponding XAML file. ```vbnet 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 ``` -------------------------------- ### Load Data in Silverlight with VB.NET Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942449.md Handles data loading and UI visibility based on user authentication status and roles. ```vbnet Private Sub LoadReports() If (WebContext.Current.User.IsAuthenticated) Then numberOfRows = WebContext.Current.User.DefaultRows AddHandler WebContext.Current.User.PropertyChanged, AddressOf User_PropertyChanged LoadRestrictedReports() Else CustomersGrid.Visibility = System.Windows.Visibility.Collapsed SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed End If Dim loadProducts = context.Load(context.GetProductsQuery().Take(numberOfRows)) ProductsGrid.ItemsSource = loadProducts.Entities End Sub Private Sub LoadRestrictedReports() Dim loadSales = context.Load(context.GetSalesOrderHeadersQuery().Take(numberOfRows)) SalesOrdersGrid.ItemsSource = loadSales.Entities SalesOrdersGrid.Visibility = System.Windows.Visibility.Visible If (WebContext.Current.User.IsInRole("Managers")) Then Dim loadCustomers = context.Load(context.GetCustomersQuery().Take(numberOfRows)) CustomersGrid.ItemsSource = loadCustomers.Entities CustomersGrid.Visibility = System.Windows.Visibility.Visible Else CustomersGrid.Visibility = System.Windows.Visibility.Collapsed End If End Sub Private Sub User_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) If (e.PropertyName = "DefaultRows") Then LoadReports() End If End Sub Private Sub Authentication_LoggedIn(ByVal sender As Object, ByVal e As Authentication.AuthenticationEventArgs) LoadReports() End Sub Private Sub Authentication_LoggedOut(ByVal sender As Object, ByVal e As Authentication.AuthenticationEventArgs) CustomersGrid.Visibility = System.Windows.Visibility.Collapsed SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed End Sub End Class ``` -------------------------------- ### Implement User Registration Logic Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Handles the registration button click event to submit new user data and processes the completion of the registration operation. ```csharp 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; } ``` -------------------------------- ### Implement OnCreated for DomainContext Source: https://openriaservices.gitbook.io/openriaservices/ee707349/ee707345.md Customizes the domain context initialization to automatically load data upon creation. ```vbnet Imports OpenRiaServices.Client Namespace Web Partial Public Class EmployeeDomainContext Inherits DomainContext Private Sub OnCreated() Me.Load(Me.GetEmployeesQuery()) End Sub End Class End Namespace ``` ```csharp using OpenRiaServices.Client; namespace RIAServiceExample.Web { public partial class EmployeeDomainContext : DomainContext { partial void OnCreated() { this.Load(this.GetEmployeesQuery()); } } } ``` -------------------------------- ### Complete system.web Configuration Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md The combined configuration for authentication, roles, and profiles within the system.web element. ```xml ``` -------------------------------- ### Implement Profile Window Logic Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942449.md Code-behind for a Silverlight ChildWindow to initialize the ComboBox with current user settings and save changes to the data source. ```vb Imports System.Windows.Controls Imports System.Windows Partial Public Class ProfileWindow Inherits ChildWindow Public Sub New() InitializeComponent() Dim userDefaultRows = WebContext.Current.User.DefaultRows.ToString() For Each cbi As ComboBoxItem In defaultRows.Items If (cbi.Content.ToString() = userDefaultRows) Then defaultRows.SelectedItem = cbi Exit For End If Next End Sub Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles OKButton.Click Dim newSelection = Integer.Parse(defaultRows.SelectionBoxItem.ToString()) If (newSelection <> WebContext.Current.User.DefaultRows) Then WebContext.Current.User.DefaultRows = newSelection WebContext.Current.Authentication.SaveUser(True) End If Me.DialogResult = True End Sub Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles CancelButton.Click Me.DialogResult = False End Sub End Class ``` -------------------------------- ### Define NewUser class properties Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Defines the data structure and validation rules for user registration. ```vbnet Imports System.ComponentModel.DataAnnotations Public Class NewUser _ _ _ Public Property UserName As String _ _ _ Public Property Email As String _ _ _ Public Property Password As String _ _ Public Property ConfirmPassword As String _ Public Property RecordsToShow As Integer _ Public Property SecurityQuestion As String _ Public Property SecurityAnswer As String End Class ``` ```csharp using System; using System.ComponentModel.DataAnnotations; namespace ExampleNavigationApplication.Web { public class NewUser { [Key] [Required()] [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage="Invalid user name. It must contain only alphanumeric characters")] public string UserName { get; set; } [Key] [Required()] [RegularExpression(@"^([\w-\.]+)@(([\d{1,3}\.\d{1,3}\.\d{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[\d{1,3}])(\]?)$", ErrorMessage="Invalid email. An email must use the format username@mycompany.com")] public string Email { get; set; } [Required()] [RegularExpression("^.*[^a-zA-Z0-9].*$", 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; } } } ``` -------------------------------- ### Retrieve and Filter Customers via DomainContext Source: https://openriaservices.gitbook.io/openriaservices/ee707349/ee707370.md Demonstrates filtering and sorting data using LINQ queries on a domain context, then loading the results into a DataGrid. ```vbnet Partial Public Class MainPage Inherits UserControl Private _customerContext As New CustomerDomainContext Public Sub New() InitializeComponent() Dim query As EntityQuery(Of Customer) query = _ From c In Me._customerContext.GetCustomersQuery() _ Where c.Phone.StartsWith("583") _ Order By c.LastName Dim loadOp = Me._customerContext.Load(query) CustomerGrid.ItemsSource = loadOp.Entities End Sub End Class ``` ```csharp public partial class MainPage : UserControl { private CustomerDomainContext _customerContext = new CustomerDomainContext(); public MainPage() { InitializeComponent(); EntityQuery query = from c in _customerContext.GetCustomersQuery() where c.Phone.StartsWith("583") orderby c.LastName select c; LoadOperation loadOp = this._customerContext.Load(query); CustomerGrid.ItemsSource = loadOp.Entities; } } ``` -------------------------------- ### Configure Web.config Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ee707351.md Update the Web.config file with connection strings and service model settings required for the domain service. ```xml ``` -------------------------------- ### Implement Domain Service with Compositional Hierarchy Source: https://openriaservices.gitbook.io/openriaservices/ee707348/ee707356/ee707346.md A Domain Service implementation using LinqToEntitiesDomainService to manage SalesOrderHeader entities and their associated SalesOrderDetail entities. ```vbnet _ Public Class OrderDomainService Inherits LinqToEntitiesDomainService(Of AdventureWorksLT_DataEntities) Public Function GetSalesOrders() As IQueryable(Of SalesOrderHeader) Return Me.ObjectContext.SalesOrderHeaders.Include("SalesOrderDetails") End Function Public Sub UpdateSalesOrder(ByVal currentSalesOrderHeader As SalesOrderHeader) Dim originalOrder As SalesOrderHeader = Me.ChangeSet.GetOriginal(currentSalesOrderHeader) If (currentSalesOrderHeader.EntityState = EntityState.Detached) Then If (IsNothing(originalOrder)) Then Me.ObjectContext.Attach(currentSalesOrderHeader) Else Me.ObjectContext.AttachAsModified(currentSalesOrderHeader, Me.ChangeSet.GetOriginal(currentSalesOrderHeader)) End If End If For Each detail As SalesOrderDetail In Me.ChangeSet.GetAssociatedChanges(currentSalesOrderHeader, Function(o) o.SalesOrderDetails) Dim op As ChangeOperation = Me.ChangeSet.GetChangeOperation(detail) Select Case op Case ChangeOperation.Insert If ((detail.EntityState = EntityState.Added) _ = False) Then If ((detail.EntityState = EntityState.Detached) _ = False) Then Me.ObjectContext.ObjectStateManager.ChangeObjectState(detail, EntityState.Added) Else Me.ObjectContext.AddToSalesOrderDetails(detail) End If End If Case ChangeOperation.Update Me.ObjectContext.AttachAsModified(detail, Me.ChangeSet.GetOriginal(detail)) Case ChangeOperation.Delete If (detail.EntityState = EntityState.Detached) Then Me.ObjectContext.Attach(detail) End If Me.ObjectContext.DeleteObject(detail) End Select Next End Sub Public Sub DeleteSalesOrder(ByVal salesOrderHeader As SalesOrderHeader) If (salesOrderHeader.EntityState = EntityState.Detached) Then Me.ObjectContext.Attach(salesOrderHeader) End If Select Case salesOrderHeader.Status Case 1 ' in process Me.ObjectContext.DeleteObject(salesOrderHeader) Case 2, 3, 4 ' approved, backordered, rejected salesOrderHeader.Status = 6 Case 5 ' shipped Throw New ValidationException("The order has been shipped and cannot be deleted.") End Select End Sub End Class ``` -------------------------------- ### Invoke Operation Execution and Completion Handling Source: https://openriaservices.gitbook.io/openriaservices/ee707349/ee707370.md Demonstrates calling an invoke operation and processing the result or errors within a completion callback. ```vbnet Dim invokeOp As InvokeOperation(Of Integer) invokeOp = customerContext.GetLocalTemperature(selectedPostalCode, AddressOf OnInvokeCompleted, Nothing) Private Sub OnInvokeCompleted(ByVal invOp As InvokeOperation(Of Integer)) If (invOp.HasError) Then MessageBox.Show(String.Format("Method Failed: {0}", invOp.Error.Message)) invOp.MarkErrorAsHandled() Else result = invOp.Value End If End Sub ``` ```csharp InvokeOperation invokeOp = customerContext.GetLocalTemperature(selectedPostalCode, OnInvokeCompleted, null); private void OnInvokeCompleted(InvokeOperation invOp) { if (invOp.HasError) { MessageBox.Show(string.Format("Method Failed: {0}", invOp.Error.Message)); invOp.MarkErrorAsHandled(); } else { result = invOp.Value; } } ``` -------------------------------- ### Define a basic query method in DomainService Source: https://openriaservices.gitbook.io/openriaservices/ee707336/gg602754.md Implement a method returning an IEnumerable collection to expose data to the client. ```csharp public IEnumerable GetSovereigns() { Sovereign sovereign = new Sovereign(); return sovereign.FetchSovereigns(); } ``` -------------------------------- ### Implement AuthenticationDomainService and Custom User Class Source: https://openriaservices.gitbook.io/openriaservices/ee707361/ee942451.md Define the AuthenticationDomainService and extend the User class to include custom profile properties. ```vb _ Public Class AuthenticationDomainService Inherits AuthenticationBase(Of User) End Class Public Class User Inherits UserBase Public Property DefaultRows As Integer End Class ``` ```csharp [EnableClientAccess] public class AuthenticationDomainService : AuthenticationBase { } public class User : UserBase { public int DefaultRows { get; set; } } ``` -------------------------------- ### Initialize Domain Context Variables Source: https://openriaservices.gitbook.io/openriaservices/ee707348/ee707356/ff422034.md Declare instances of the required domain contexts for data operations. ```vb Private salesContext As New SalesDomainContext() Private customerContext As New CustomerDomainContext() ``` ```csharp private SalesDomainContext salesContext = new SalesDomainContext(); private CustomerDomainContext customerContext = new CustomerDomainContext(); ``` -------------------------------- ### Accessing and Saving User Profile Properties Source: https://openriaservices.gitbook.io/openriaservices/ee707361.md Demonstrates updating a user property and persisting the change using the authentication service. ```vbnet Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles OKButton.Click Dim newSelection = Integer.Parse(defaultRows.SelectionBoxItem.ToString()) If (newSelection <> WebContext.Current.User.DefaultRows) Then WebContext.Current.User.DefaultRows = newSelection WebContext.Current.Authentication.SaveUser(True) End If Me.DialogResult = True End Sub ``` ```csharp private void OKButton_Click(object sender, RoutedEventArgs e) { int newSelection = int.Parse(defaultRows.SelectionBoxItem.ToString()); if (newSelection != WebContext.Current.User.DefaultRows) { WebContext.Current.User.DefaultRows = newSelection; WebContext.Current.Authentication.SaveUser(true); } this.DialogResult = true; } ``` -------------------------------- ### Load Data in Code-Behind Source: https://openriaservices.gitbook.io/openriaservices/ee707336/ee707376.md Instantiates the DomainContext and loads data into the DataGrid using Visual Basic or C#. ```vbnet Imports System.Windows.Ria Imports RIAServicesExample.Web Partial Public Class MainPage Inherits UserControl Private _customerContext As New CustomerDomainContext Public Sub New() InitializeComponent() Dim loadOp = Me._customerContext.Load(Me._customerContext.GetCustomersQuery()) CustomerGrid.ItemsSource = loadOp.Entities End Sub End Class ``` ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using RIAServicesExample.Web; using System.Windows.Ria; namespace RIAServicesExample { public partial class MainPage : UserControl { private CustomerDomainContext _customerContext = new CustomerDomainContext(); public MainPage() { InitializeComponent(); LoadOperation loadOp = this._customerContext.Load(this._customerContext.GetCustomersQuery()); CustomerGrid.ItemsSource = loadOp.Entities; } } } ```