Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

A Sample Silverlight 4 Application Using MEF, MVVM, and WCF RIA Services - Part 1

, 7 Jul 2011 CPOL
Part 1 of a series describing the creation of a Silverlight business application using MEF, MVVM Light, and WCF RIA Services.
IssueVisionforSilverlightSetup20110630.zip
IssueVision for Silverlight Setup
IssueVisionSetup.msi
setup.exe
IssueVision_for_Silverlight_setup.zip
IssueVisionSetup.msi
setup.exe
IssueVision_Silverlight20110630.zip
IssueVision.Silverlight
Assemblies
GalaSoft.MvvmLight.Extras.SL4.dll
GalaSoft.MvvmLight.SL4.dll
MenuControls.dll
System.Windows.Controls.DataVisualization.Toolkit.dll
System.Windows.Controls.Toolkit.dll
System.Windows.Controls.Toolkit.Internals.dll
System.Windows.Interactivity.dll
Database
IssueVision.Client
IssueVision.Client.csproj.user
Assets
Signin.png
Controls
Properties
Views
IssueVision.Common
IssueVision.Common.csproj.user
Controls
Helpers
Models
Properties
Resources
Themes
IssueVision.Data
IssueVision.Data.csproj.user
Properties
Web
Resources
IssueVision.Data.Web
IssueVision.edmx
Helpers
MetadataClasses
Properties
Resources
Services
IssueVision.Model
IssueVision.Model.csproj.user
Properties
IssueVision.Setup
IssueVisionSetup.vdproj
IssueVision.ViewModel
IssueVision.ViewModel.csproj.user
Properties
IssueVision.Web
IssueVision.Web.csproj.user
Properties
IssueVision_Silverlight_20110316.zip
GalaSoft.MvvmLight.Extras.SL4.dll
GalaSoft.MvvmLight.SL4.dll
MenuControls.dll
System.Windows.Controls.DataVisualization.Toolkit.dll
System.Windows.Controls.Toolkit.dll
System.Windows.Controls.Toolkit.Internals.dll
System.Windows.Interactivity.dll
IssueVision.Client.csproj.user
Signin.png
DataSources
IssueVision.Data.Web.IssueVisionContext.datasource
IssueVision.Data.Web.PasswordResetContext.datasource
IssueVision.Common.csproj.user
IssueVision.Data.csproj.user
IssueVision.edmx
DataTypes
IssueVision.Model.csproj.user
IssueVisionSetup.vdproj
IssueVision.ViewModel.csproj.user
IssueVision.Web.csproj.user
IssueVision_Silverlight_20110606.zip
GalaSoft.MvvmLight.Extras.SL4.dll
GalaSoft.MvvmLight.SL4.dll
MenuControls.dll
System.Windows.Controls.DataVisualization.Toolkit.dll
System.Windows.Controls.Toolkit.dll
System.Windows.Controls.Toolkit.Internals.dll
System.Windows.Interactivity.dll
IssueVision.Client.csproj.user
Signin.png
IssueVision.Common.csproj.user
IssueVision.Data.csproj.user
IssueVision.edmx
IssueVision.Model.csproj.user
IssueVisionSetup.vdproj
IssueVision.ViewModel.csproj.user
IssueVision.Web.csproj.user
IssueVision_Silverlight_Setup.zip
IssueVisionSetup.msi
setup.exe
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Windows.Markup;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using IssueVision.Common;
using IssueVision.Data.Web;

namespace IssueVision.ViewModel
{
    [Export(ViewModelTypes.MainPageViewModel, typeof(ViewModelBase))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MainPageViewModel : ViewModelBase
    {
        #region "Private Data Members"
        private IAuthenticationModel _authenticationModel;
        private IPasswordResetModel _passwordResetModel;
        private IIssueVisionModel _issueVisionModel;
        #endregion "Private Data Members"

        #region "Constructor"
        [ImportingConstructor]
        public MainPageViewModel(IAuthenticationModel authModel, IPasswordResetModel passModel, IIssueVisionModel issueVisionModel)
        {
            _authenticationModel = authModel;
            _passwordResetModel = passModel;
            _issueVisionModel = issueVisionModel;

            // set up event handling
            _authenticationModel.AuthenticationChanged += new EventHandler<AuthenticationEventArgs>(_authenticationModel_AuthenticationChanged);
            _authenticationModel.LogoutComplete += new EventHandler<LogoutOperationEventArgs>(_authenticationModel_LogoutComplete);
            _authenticationModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_authenticationModel_PropertyChanged);
            _passwordResetModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_passwordResetModel_PropertyChanged);
            _issueVisionModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_issueVisionModel_PropertyChanged);

            // call LoadUserAsync() to check whether authenticated or not
            _authenticationModel.LoadUserAsync();

            // set the initial values
            this.IsBusy = _authenticationModel.IsBusy || _passwordResetModel.IsBusy || _issueVisionModel.IsBusy;
            this.IsLoggedIn = _authenticationModel.User.Identity.IsAuthenticated;
            this.IsLoggedOut = !(_authenticationModel.User.Identity.IsAuthenticated);
            this.IsAdmin = _authenticationModel.User.IsInRole(IssueVisionServiceConstant.UserTypeAdmin);
            if (_authenticationModel.User.Identity.IsAuthenticated)
                this.WelcomeText = "Welcome " + _authenticationModel.User.Identity.Name;
            else
                this.WelcomeText = string.Empty;
            // set the initial theme selection
            this.IsBureauBlueTheme = true;
            this.IsExpressionLightTheme = false;
            this.IsShinyBlueTheme = false;
            this.IsTwilightBlueTheme = false;
            // set the current active screen
            this.CurrentScreenText = ViewTypes.HomeView;
        }
        #endregion "Constructor"

        #region "Public Properties"

        private bool _isBusy;

        public bool IsBusy
        {
            get { return _isBusy; }
            private set
            {
                if (value != _isBusy)
                {
                    _isBusy = value;
                    this.RaisePropertyChanged("IsBusy");
                }
            }
        }

        private bool _isLoggedOut;

        public bool IsLoggedOut
        {
            get { return _isLoggedOut; }
            private set
            {
                if (value != _isLoggedOut)
                {
                    _isLoggedOut = value;
                    this.RaisePropertyChanged("IsLoggedOut");
                }
            }
        }

        private bool _isLoggedIn;

        public bool IsLoggedIn
        {
            get { return _isLoggedIn; }
            private set
            {
                if (value != _isLoggedIn)
                {
                    _isLoggedIn = value;
                    this.RaisePropertyChanged("IsLoggedIn");
                }
            }
        }

        private bool _isAdmin;

        public bool IsAdmin
        {
            get { return _isAdmin; }
            private set
            {
                if (value != _isAdmin)
                {
                    _isAdmin = value;
                    this.RaisePropertyChanged("IsAdmin");
                }
            }
        }

        private string _welcomeText;

        public string WelcomeText
        {
            get { return _welcomeText; }
            private set
            {
                if (value != _welcomeText)
                {
                    _welcomeText = value;
                    this.RaisePropertyChanged("WelcomeText");
                }
            }
        }

        private string _currentScreenText;

        public string CurrentScreenText
        {
            get { return _currentScreenText; }
            private set
            {
                if (value != _currentScreenText)
                {
                    _currentScreenText = value;
                    this.RaisePropertyChanged("CurrentScreenText");
                }
            }
        }


        private bool _isBureauBlueTheme;

        public bool IsBureauBlueTheme
        {
            get { return _isBureauBlueTheme; }
            private set
            {
                if (value != _isBureauBlueTheme)
                {
                    _isBureauBlueTheme = value;
                    this.RaisePropertyChanged("IsBureauBlueTheme");
                }
            }
        }

        private bool _isExpressionLightTheme;

        public bool IsExpressionLightTheme
        {
            get { return _isExpressionLightTheme; }
            private set
            {
                if (value != _isExpressionLightTheme)
                {
                    _isExpressionLightTheme = value;
                    this.RaisePropertyChanged("IsExpressionLightTheme");
                }
            }
        }

        private bool _isShinyBlueTheme;

        public bool IsShinyBlueTheme
        {
            get { return _isShinyBlueTheme; }
            private set
            {
                if (value != _isShinyBlueTheme)
                {
                    _isShinyBlueTheme = value;
                    this.RaisePropertyChanged("IsShinyBlueTheme");
                }
            }
        }

        private bool _isTwilightBlueTheme;

        public bool IsTwilightBlueTheme
        {
            get { return _isTwilightBlueTheme; }
            private set
            {
                if (value != _isTwilightBlueTheme)
                {
                    _isTwilightBlueTheme = value;
                    this.RaisePropertyChanged("IsTwilightBlueTheme");
                }
            }
        }

        #endregion "Public Properties"

        #region "Public Commands"

        private RelayCommand<Boolean> _logoutCommand = null;

        public RelayCommand<Boolean> LogoutCommand
        {
            get
            {
                if (_logoutCommand == null)
                {
                    _logoutCommand = new RelayCommand<Boolean>(
                        g => this.OnLogoutCommand(g));
                }
                return _logoutCommand;
            }
        }

        private void OnLogoutCommand(Boolean forceLogout)
        {
            try
            {
                if (!this._authenticationModel.IsLoggingOut)
                {
                    if (!this._issueVisionModel.HasChanges)
                    {
                        // return back to the Home screen
                        AppMessages.ChangeScreenMessage.Send(ViewTypes.HomeView);
                        this.CurrentScreenText = ViewTypes.HomeView;
                        // then logout
                        this._authenticationModel.LogoutAsync();
                    }
                    else
                    {
                        // there are pending changes
                        MessageBoxResult theResult = MessageBoxResult.Cancel;

                        if (forceLogout)
                        {
                            // if forceLogout is true, no need to ask for confirmation
                            theResult = MessageBoxResult.OK;
                        }
                        else
                        {
                            // ask to confirm canceling any pending changes
                            DialogMessage dialogMessage = new DialogMessage(
                                this,
                                CommonResources.CancelAnyChangesMessageBoxText,
                                s => theResult = s)
                            {
                                Button = MessageBoxButton.OKCancel,
                                Caption = CommonResources.ConfirmMessageBoxCaption
                            };

                            AppMessages.PleaseConfirmMessage.Send(dialogMessage);
                        }

                        if (theResult == MessageBoxResult.OK)
                        {
                            // if confirmed, cancel any pending changes
                            this._issueVisionModel.RejectChanges();
                            // return back to the Home screen
                            AppMessages.ChangeScreenMessage.Send(ViewTypes.HomeView);
                            this.CurrentScreenText = ViewTypes.HomeView;
                            // then logout
                            this._authenticationModel.LogoutAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        private RelayCommand<string> _changeThemeCommand = null;

        public RelayCommand<string> ChangeThemeCommand
        {
            get
            {
                if (_changeThemeCommand == null)
                {
                    _changeThemeCommand = new RelayCommand<string>(
                        g => this.OnChangeThemeCommand(g),
                        g =>
                            {
                                var themeResource = Application.GetResourceStream(
                                    new Uri("/IssueVision.Client;component/Assets/" + g, UriKind.Relative));
                                return themeResource != null;
                            });
                }
                return _changeThemeCommand;
            }
        }

        private void OnChangeThemeCommand(String g)
        {
            try
            {
                if (g == "BureauBlue.xaml" || g == "ExpressionLight.xaml" ||
                    g == "ShinyBlue.xaml" || g == "TwilightBlue.xaml")
                {
                    // remove the old one
                    Application.Current.Resources.MergedDictionaries.RemoveAt(Application.Current.Resources.MergedDictionaries.Count - 1);
                    // find and add the new one
                    var themeResource = Application.GetResourceStream(new Uri("/IssueVision.Client;component/Assets/" + g, UriKind.Relative));
                    ResourceDictionary rd = (ResourceDictionary)(XamlReader.Load(new StreamReader(themeResource.Stream).ReadToEnd()));
                    Application.Current.Resources.MergedDictionaries.Add(rd);

                    // notify the change
                    if (g == "BureauBlue.xaml")
                    {
                        IsBureauBlueTheme = true;
                        IsExpressionLightTheme = false;
                        IsShinyBlueTheme = false;
                        IsTwilightBlueTheme = false;
                    }
                    else if (g == "ExpressionLight.xaml")
                    {
                        IsBureauBlueTheme = false;
                        IsExpressionLightTheme = true;
                        IsShinyBlueTheme = false;
                        IsTwilightBlueTheme = false;
                    }
                    else if (g == "ShinyBlue.xaml")
                    {
                        IsBureauBlueTheme = false;
                        IsExpressionLightTheme = false;
                        IsShinyBlueTheme = true;
                        IsTwilightBlueTheme = false;
                    }
                    else if (g == "TwilightBlue.xaml")
                    {
                        IsBureauBlueTheme = false;
                        IsExpressionLightTheme = false;
                        IsShinyBlueTheme = false;
                        IsTwilightBlueTheme = true;
                    }
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        private RelayCommand<string> _changeScreenCommand = null;

        public RelayCommand<string> ChangeScreenCommand
        {
            get
            {
                if (_changeScreenCommand == null)
                {
                    _changeScreenCommand = new RelayCommand<string>(
                        g => this.OnChangeScreenCommand(g),
                        g => g != null);
                };
                return _changeScreenCommand;
            }
        }

        private void OnChangeScreenCommand(String g)
        {
            try
            {
                if (this.CurrentScreenText != g)
                {
                    if (!this._issueVisionModel.HasChanges)
                    {
                        // if no pending changes, switch to the new screen
                        switch (g)
                        {
                            case ViewTypes.HomeView:
                                // return back to the Home screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.HomeView);
                                this.CurrentScreenText = ViewTypes.HomeView;
                                break;
                            case ViewTypes.NewIssueView:
                                // open the NewIssue screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.NewIssueView);
                                this.CurrentScreenText = ViewTypes.NewIssueView;
                                break;
                            case ViewTypes.AllIssuesView:
                                // open the AllIssues screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.AllIssuesView);
                                this.CurrentScreenText = ViewTypes.AllIssuesView;
                                break;
                            case ViewTypes.MyIssuesView:
                                // open the MyIssues screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.MyIssuesView);
                                this.CurrentScreenText = ViewTypes.MyIssuesView;
                                break;
                            case ViewTypes.BugReportView:
                                // open the BugReport screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.BugReportView);
                                this.CurrentScreenText = ViewTypes.BugReportView;
                                break;
                            case ViewTypes.MyProfileView:
                                // open the MyProfile screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.MyProfileView);
                                this.CurrentScreenText = ViewTypes.MyProfileView;
                                break;
                            case ViewTypes.UserMaintenanceView:
                                // open the UserMaintenance screen
                                AppMessages.ChangeScreenMessage.Send(ViewTypes.UserMaintenanceView);
                                this.CurrentScreenText = ViewTypes.UserMaintenanceView;
                                break;
                            default:
                                throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        // there are pending changes
                        MessageBoxResult theResult = MessageBoxResult.Cancel;

                        // ask to confirm canceling any pending changes
                        DialogMessage dialogMessage = new DialogMessage(
                            this,
                            CommonResources.CancelAnyChangesMessageBoxText,
                            s => theResult = s)
                        {
                            Button = MessageBoxButton.OKCancel,
                            Caption = CommonResources.ConfirmMessageBoxCaption
                        };

                        AppMessages.PleaseConfirmMessage.Send(dialogMessage);

                        if (theResult == MessageBoxResult.OK)
                        {
                            // if confirmed, cancel any pending changes
                            this._issueVisionModel.RejectChanges();
                            // and switch to the new screen
                            switch (g)
                            {
                                case ViewTypes.HomeView:
                                    // return back to the Home screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.HomeView);
                                    this.CurrentScreenText = ViewTypes.HomeView;
                                    break;
                                case ViewTypes.NewIssueView:
                                    // open the NewIssue screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.NewIssueView);
                                    this.CurrentScreenText = ViewTypes.NewIssueView;
                                    break;
                                case ViewTypes.AllIssuesView:
                                    // open the AllIssues screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.AllIssuesView);
                                    this.CurrentScreenText = ViewTypes.AllIssuesView;
                                    break;
                                case ViewTypes.MyIssuesView:
                                    // open the MyIssues screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.MyIssuesView);
                                    this.CurrentScreenText = ViewTypes.MyIssuesView;
                                    break;
                                case ViewTypes.BugReportView:
                                    // open the BugReport screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.BugReportView);
                                    this.CurrentScreenText = ViewTypes.BugReportView;
                                    break;
                                case ViewTypes.MyProfileView:
                                    // open the MyProfile screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.MyProfileView);
                                    this.CurrentScreenText = ViewTypes.MyProfileView;
                                    break;
                                case ViewTypes.UserMaintenanceView:
                                    // open the UserMaintenance screen
                                    AppMessages.ChangeScreenMessage.Send(ViewTypes.UserMaintenanceView);
                                    this.CurrentScreenText = ViewTypes.UserMaintenanceView;
                                    break;
                                default:
                                    throw new NotImplementedException();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        #endregion "Public Commands"

        #region "Private Methods"

        private void _authenticationModel_AuthenticationChanged(object sender, AuthenticationEventArgs e)
        {
            this.IsLoggedIn = e.User.Identity.IsAuthenticated;
            this.IsLoggedOut = !(e.User.Identity.IsAuthenticated);
            this.IsAdmin = e.User.IsInRole(IssueVisionServiceConstant.UserTypeAdmin);

            if (e.User.Identity.IsAuthenticated)
            {
                this.WelcomeText = "Welcome " + e.User.Identity.Name;
                // if ProfileResetFlag is set
                // ask the user to reset profile first
                if (e.User is LoginUser)
                {
                    if (((LoginUser)e.User).ProfileResetFlag)
                    {
                        // open the MyProfile screen
                        AppMessages.ChangeScreenMessage.Send(ViewTypes.MyProfileView);
                        this.CurrentScreenText = ViewTypes.MyProfileView;
                    }
                    else
                    {
                        // otherwise, open the home screen
                        AppMessages.ChangeScreenMessage.Send(ViewTypes.HomeView);
                        this.CurrentScreenText = ViewTypes.HomeView;
                    }
                }
            }
            else
                this.WelcomeText = string.Empty;
        }

        private void _authenticationModel_LogoutComplete(object sender, LogoutOperationEventArgs e)
        {
            // even if e.HasError is True, we still set logout done.
            this.IsLoggedIn = false;
            this.IsLoggedOut = true;
            this.IsAdmin = false;
            _authenticationModel.LoadUserAsync();
        }

        private void _authenticationModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "IsBusy":
                    this.IsBusy = _authenticationModel.IsBusy || _passwordResetModel.IsBusy || _issueVisionModel.IsBusy;
                    break;
            }
        }

        private void _passwordResetModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "IsBusy":
                    this.IsBusy = _authenticationModel.IsBusy || _passwordResetModel.IsBusy || _issueVisionModel.IsBusy;
                    break;
            }
        }

        private void _issueVisionModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "IsBusy":
                    this.IsBusy = _authenticationModel.IsBusy || _passwordResetModel.IsBusy || _issueVisionModel.IsBusy;
                    break;
            }
        }

        #endregion "Private Methods"
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Weidong Shen
Software Developer (Senior)
United States United States
Weidong has been an information system professional since 1990. He has a Master's degree in Computer Science, and is currently a MCSD .NET

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 7 Jul 2011
Article Copyright 2010 by Weidong Shen
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid