Click here to Skip to main content
15,896,527 members
Articles / Desktop Programming / XAML

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

Rate me:
Please Sign up or sign in to vote.
4.84/5 (108 votes)
7 Jul 2011CPOL9 min read 2.1M   30.9K   298  
Part 1 of a series describing the creation of a Silverlight business application using MEF, MVVM Light, and WCF RIA Services.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using IssueVision.Data.Web;
using IssueVision.Common;

namespace IssueVision.ViewModel
{
    [Export(ViewModelTypes.UserMaintenanceViewModel, typeof(ViewModelBase))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class UserMaintenanceViewModel : ViewModelBase
    {
        #region "Private Data Members"
        private enum UserMaintenanceOperation
        {
            Add,
            Delete,
            Update
        }
        private IIssueVisionModel _issueVisionModel;
        private UserMaintenanceOperation _operation;
        private string _userNameToDisplay;
        #endregion "Private Data Members"

        #region "Constructor"
        [ImportingConstructor]
        public UserMaintenanceViewModel(IIssueVisionModel issueVisionModel)
        {
            _issueVisionModel = issueVisionModel;

            // set up event handling
            _issueVisionModel.GetUsersComplete += new EventHandler<EntityResultsArgs<User>>(_issueVisionModel_GetUsersComplete);
            _issueVisionModel.SaveChangesComplete += new EventHandler<SubmitOperationEventArgs>(_issueVisionModel_SaveChangesComplete);
            _issueVisionModel.PropertyChanged += new PropertyChangedEventHandler(_issueVisionModel_PropertyChanged);

            // set initial user maintenance operation
            _userNameToDisplay = string.Empty;
            _operation = UserMaintenanceOperation.Update;
            IsUpdateUser = true;
            IsAddUser = false;

            // load all users
            _issueVisionModel.GetUsersAsync();
        }
        #endregion "Constructor"

        #region "ICleanup interface implementation"
        public override void Cleanup()
        {
            if (_issueVisionModel != null)
            {
                // unregister all events
                _issueVisionModel.GetUsersComplete -= new EventHandler<EntityResultsArgs<User>>(_issueVisionModel_GetUsersComplete);
                _issueVisionModel.SaveChangesComplete -= new EventHandler<SubmitOperationEventArgs>(_issueVisionModel_SaveChangesComplete);
                _issueVisionModel.PropertyChanged -= new PropertyChangedEventHandler(_issueVisionModel_PropertyChanged);
                _issueVisionModel = null;
            }
            // set properties back to null
            _allUsers = null;
            CurrentUser = null;
            // unregister any messages for this ViewModel
            base.Cleanup();
        }
        #endregion "ICleanup interface implementation"

        #region "Public Properties"

        private IEnumerable<User> _allUsers;

        public CollectionViewSource AllUsersSource { get; private set; }

        private IEnumerable<string> _userTypeEntries = null;

        public IEnumerable<string> UserTypeEntries
        {
            get
            {
                if (_userTypeEntries == null)
                {
                    _userTypeEntries = new string[]
                    {
                        IssueVisionServiceConstant.UserTypeUser,
                        IssueVisionServiceConstant.UserTypeAdmin
                    };
                }
                return _userTypeEntries;
            }
        }

        private User _currentUser;

        public User CurrentUser
        {
            get { return _currentUser; }
            private set
            {
                if (!ReferenceEquals(_currentUser, value))
                {
                    _currentUser = value;
                    this.RaisePropertyChanged("CurrentUser");
                }
            }
        }

        private bool _isAddUser;

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

        private bool _isUpdateUser;

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

        #endregion "Public Properties"

        #region "Public Commands"

        private RelayCommand _addUserCommand = null;

        public RelayCommand AddUserCommand
        {
            get
            {
                if (_addUserCommand == null)
                {
                    _addUserCommand = new RelayCommand(
                        () => this.OnAddUserCommand(),
                        () => (this._issueVisionModel != null) && !(this._issueVisionModel.HasChanges));
                }
                return _addUserCommand;
            }
        }

        private void OnAddUserCommand()
        {
            try
            {
                if (!_issueVisionModel.IsBusy)
                {
                    // cancel any changes before adding a new user
                    if (_issueVisionModel.HasChanges)
                    {
                        this._issueVisionModel.RejectChanges();
                    }

                    this.CurrentUser = _issueVisionModel.AddNewUser();

                    this._operation = UserMaintenanceOperation.Add;
                    IsUpdateUser = false;
                    IsAddUser = true;
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        private RelayCommand<IssueVision.Data.Web.User> _removeUserCommand = null;

        public RelayCommand<IssueVision.Data.Web.User> RemoveUserCommand
        {
            get
            {
                if (_removeUserCommand == null)
                {
                    _removeUserCommand = new RelayCommand<Data.Web.User>(
                        g => this.OnRemoveUserCommand(g),
                        g => (this._issueVisionModel != null) && !(this._issueVisionModel.HasChanges) && (g != null));
                }
                return _removeUserCommand;
            }
        }

        private void OnRemoveUserCommand(Data.Web.User g)
        {
            try
            {
                if (!_issueVisionModel.IsBusy)
                {
                    // cancel any changes before deleting a user
                    if (_issueVisionModel.HasChanges)
                    {
                        this._issueVisionModel.RejectChanges();
                    }

                    // ask to confirm deleting the current user
                    DialogMessage dialogMessage = new DialogMessage(
                        this,
                        CommonResources.DeleteCurrentUserMessageBoxText,
                        s =>
                        {
                            if (s == MessageBoxResult.OK)
                            {
                                // if confirmed, removing CurrentUser
                                this._issueVisionModel.RemoveUser(g);

                                // cache the current user name as empty string
                                _userNameToDisplay = string.Empty;

                                this._operation = UserMaintenanceOperation.Delete;
                                IsUpdateUser = true;
                                IsAddUser = false;

                                this._issueVisionModel.SaveChangesAsync();
                            }
                        })
                    {
                        Button = MessageBoxButton.OKCancel,
                        Caption = CommonResources.ConfirmMessageBoxCaption
                    };

                    AppMessages.PleaseConfirmMessage.Send(dialogMessage);
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        private RelayCommand _submitChangeCommand = null;

        public RelayCommand SubmitChangeCommand
        {
            get
            {
                if (_submitChangeCommand == null)
                {
                    _submitChangeCommand = new RelayCommand(
                        () => this.OnSubmitChangeCommand(),
                        () => (this._issueVisionModel != null) && (this._issueVisionModel.HasChanges));
                }
                return _submitChangeCommand;
            }
        }

        private void OnSubmitChangeCommand()
        {
            try
            {
                if (!_issueVisionModel.IsBusy)
                {
                    if (this.CurrentUser != null)
                    {
                        // this should trigger validation even if the following field is not changed and is null
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.Name))
                            this.CurrentUser.Name = string.Empty;
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.FirstName))
                            this.CurrentUser.FirstName = string.Empty;
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.LastName))
                            this.CurrentUser.LastName = string.Empty;
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.Email))
                            this.CurrentUser.Email = null;
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.NewPassword))
                            this.CurrentUser.NewPassword = string.Empty;
                        if (string.IsNullOrWhiteSpace(this.CurrentUser.NewPasswordConfirmation))
                            this.CurrentUser.NewPasswordConfirmation = string.Empty;

                        if (this.CurrentUser.TryValidateProperty("Name") && this.CurrentUser.TryValidateProperty("FirstName")
                            && this.CurrentUser.TryValidateProperty("LastName") && this.CurrentUser.TryValidateProperty("Email")
                            && this.CurrentUser.TryValidateProperty("NewPassword") && this.CurrentUser.TryValidateProperty("NewPasswordConfirmation")
                            && this.CurrentUser.TryValidateProperty("UserType"))
                        {
                            // following settings are there to prevent validation errors
                            this.CurrentUser.Password = this.CurrentUser.NewPassword;
                            this.CurrentUser.PasswordAnswer = "PasswordAnswer";
                            this.CurrentUser.PasswordAnswerConfirmation = "PasswordAnswer";

                            // cache the current user name
                            _userNameToDisplay = this.CurrentUser.Name;

                            // change is from User Maintenance screen
                            this.CurrentUser.IsUserMaintenance = true;

                            this._issueVisionModel.SaveChangesAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        private RelayCommand _cancelChangeCommand = null;

        public RelayCommand CancelChangeCommand
        {
            get
            {
                if (_cancelChangeCommand == null)
                {
                    _cancelChangeCommand = new RelayCommand(
                        () => this.OnCancelChangeCommand(),
                        () => (this._issueVisionModel != null) && (this._issueVisionModel.HasChanges));
                }
                return _cancelChangeCommand;
            }
        }

        private void OnCancelChangeCommand()
        {
            try
            {
                if (!_issueVisionModel.IsBusy)
                {
                    // ask to confirm canceling the current user in edit
                    DialogMessage dialogMessage = new DialogMessage(
                        this,
                        CommonResources.CancelCurrentUserMessageBoxText,
                        s =>
                        {
                            if (s == MessageBoxResult.OK)
                            {
                                // cache the current user name
                                _userNameToDisplay = this.CurrentUser.Name;

                                // if confirmed, cancel any change to CurrentUser
                                this._issueVisionModel.RejectChanges();

                                // reload the user list after cancel
                                _issueVisionModel.GetUsersAsync();
                            }
                        })
                    {
                        Button = MessageBoxButton.OKCancel,
                        Caption = CommonResources.ConfirmMessageBoxCaption
                    };

                    AppMessages.PleaseConfirmMessage.Send(dialogMessage);
                }
            }
            catch (Exception ex)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(ex);
            }
        }

        #endregion "Public Commands"

        #region "Private Methods"

        private void _issueVisionModel_GetUsersComplete(object sender, EntityResultsArgs<User> e)
        {
            if (!e.HasError)
            {
                // cancel any changes before setting AllUsersSource
                if (_issueVisionModel.HasChanges)
                {
                    this._issueVisionModel.RejectChanges();
                }

                // set AllUsersSource
                this._allUsers = e.Results.OrderBy(g => g.Name);

                AllUsersSource = new CollectionViewSource();
                AllUsersSource.Source = this._allUsers;
                AllUsersSource.View.CurrentChanging += new CurrentChangingEventHandler(View_CurrentChanging);
                AllUsersSource.View.CurrentChanged += new EventHandler(View_CurrentChanged);
                // notify that AllIssuesSource has changed
                this.RaisePropertyChanged("AllUsersSource");

                // set CurrentUser
                if (e.Results.Count() >= 1)
                {
                    if (e.Results.FirstOrDefault(n => n.Name == _userNameToDisplay) == null)
                    {
                        // set the first row as the current user
                        var enumerator = this._allUsers.GetEnumerator();
                        enumerator.MoveNext();
                        this.CurrentUser = enumerator.Current;
                    }
                    else
                    {
                        this.CurrentUser = e.Results.FirstOrDefault(n => n.Name == _userNameToDisplay);
                        AllUsersSource.View.MoveCurrentTo(this.CurrentUser);
                    }
                }

                // set operation back to update
                _operation = UserMaintenanceOperation.Update;
                IsUpdateUser = true;
                IsAddUser = false; 
            }
            else
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void View_CurrentChanging(object sender, CurrentChangingEventArgs e)
        {
            MessageBoxResult theResult = MessageBoxResult.OK;

            if (_issueVisionModel.HasChanges)
            {
                // ask to confirm canceling the current user in edit
                DialogMessage dialogMessage = new DialogMessage(
                    this,
                    CommonResources.CancelCurrentUserMessageBoxText,
                    s => theResult = s)
                {
                    Button = MessageBoxButton.OKCancel,
                    Caption = CommonResources.ConfirmMessageBoxCaption
                };

                AppMessages.PleaseConfirmMessage.Send(dialogMessage);

                if (theResult == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void View_CurrentChanged(object sender, EventArgs e)
        {
            // cancel any changes before editing another user
            if (_issueVisionModel.HasChanges)
            {
                this._issueVisionModel.RejectChanges();
            }
            // assign the new current item to CurrentUser
            this.CurrentUser = (User)AllUsersSource.View.CurrentItem;
        }

        private void _issueVisionModel_SaveChangesComplete(object sender, SubmitOperationEventArgs e)
        {
            if (!e.HasError)
            {
                if (_operation == UserMaintenanceOperation.Update)
                {
                    // user update successful
                    DialogMessage dialogMessage = new DialogMessage(
                                this,
                                CommonResources.UserMaintenanceUpdatedText,
                                null)
                    {
                        Button = MessageBoxButton.OK,
                        Caption = CommonResources.UserMaintenanceUpdatedCaption
                    };

                    AppMessages.StatusUpdateMessage.Send(dialogMessage);
                }

                // reload the user list after add/delete/update
                _issueVisionModel.GetUsersAsync();
            }
            else
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void _issueVisionModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("HasChanges"))
            {
                AddUserCommand.RaiseCanExecuteChanged();
                RemoveUserCommand.RaiseCanExecuteChanged();
                SubmitChangeCommand.RaiseCanExecuteChanged();
                CancelChangeCommand.RaiseCanExecuteChanged();
            }
        }

        #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)


Written By
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

Comments and Discussions