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
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.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.MyIssuesViewModel, typeof(ViewModelBase))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MyIssuesViewModel : ViewModelBase
    {
        #region "Private Data Members"
        private IIssueVisionModel _issueVisionModel;
        #endregion "Private Data Members"

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

            // set up event handling
            _issueVisionModel.SaveChangesComplete += new EventHandler<SubmitOperationEventArgs>(_issueVisionModel_SaveChangesComplete);
            _issueVisionModel.GetMyIssuesComplete += new EventHandler<EntityResultsArgs<Issue>>(_issueVisionModel_GetMyIssuesComplete);
            _issueVisionModel.PropertyChanged += new PropertyChangedEventHandler(_issueVisionModel_PropertyChanged);

            // load my issues
            _issueVisionModel.GetMyIssuesAsync();
        }
        #endregion "Constructor"

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

        #region "Public Properties"

        private IEnumerable<Issue> _myIssues;

        public CollectionViewSource MyIssuesSource { get; private set; }

        private Issue _currentIssue;

        public Issue CurrentIssue
        {
            get { return _currentIssue; }
            private set
            {
                if (!ReferenceEquals(_currentIssue, value))
                {
                    _currentIssue = value;
                    this.RaisePropertyChanged("CurrentIssue");
                }
            }
        }

        #endregion "Public Properties"

        #region "Public Commands"

        private RelayCommand<SelectionChangedEventArgs> _selectionChangedCommand = null;

        public RelayCommand<SelectionChangedEventArgs> SelectionChangedCommand
        {
            get
            {
                if (_selectionChangedCommand == null)
                {
                    _selectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(
                        e => this.OnSelectionChangedCommand(e));
                }
                return _selectionChangedCommand;
            }
        }

        private void OnSelectionChangedCommand(SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                // cancel any changes before editing another issue
                if (_issueVisionModel.HasChanges)
                {
                    AppMessages.CancelChangesMessage.Send();
                }
                var enumerator = e.AddedItems.GetEnumerator();
                enumerator.MoveNext();
                // edit the new selected issue
                AppMessages.EditIssueMessage.Send((Issue)enumerator.Current);
            }
        }

        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)
                {
                    AppMessages.SubmitChangesMessage.Send();
                }
            }
            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 issue in edit
                    DialogMessage dialogMessage = new DialogMessage(
                        this,
                        CommonResources.CancelCurrentIssueMessageBoxText,
                        s =>
                        {
                            if (s == MessageBoxResult.OK)
                            {
                                // if confirmed, cancel this issue
                                AppMessages.CancelChangesMessage.Send();
                            }
                        })
                    {
                        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_SaveChangesComplete(object sender, SubmitOperationEventArgs e)
        {
            if (e.HasError)
            {
                // notify user if there is any error
                AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void _issueVisionModel_GetMyIssuesComplete(object sender, EntityResultsArgs<Issue> e)
        {
            if (!e.HasError)
            {
                // cancel any changes before setting MyIssuesSource
                if (_issueVisionModel.HasChanges)
                {
                    AppMessages.CancelChangesMessage.Send();
                }

                this._myIssues = e.Results.OrderBy(g => g.StatusID).ThenBy(g => g.Priority);

                MyIssuesSource = new CollectionViewSource();
                MyIssuesSource.Source = this._myIssues;
                MyIssuesSource.View.CurrentChanging += new CurrentChangingEventHandler(View_CurrentChanging);
                // notify that MyIssuesSource has changed
                this.RaisePropertyChanged("MyIssuesSource");

                // set the first row as the current issue
                if (e.Results.Count() >= 1)
                {
                    var enumerator = this._myIssues.GetEnumerator();
                    enumerator.MoveNext();
                    this.CurrentIssue = enumerator.Current;

                    AppMessages.EditIssueMessage.Send(this.CurrentIssue);
                }
            }
            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 issue in edit
                DialogMessage dialogMessage = new DialogMessage(
                    this,
                    CommonResources.CancelCurrentIssueMessageBoxText,
                    s => theResult = s)
                {
                    Button = MessageBoxButton.OKCancel,
                    Caption = CommonResources.ConfirmMessageBoxCaption
                };

                AppMessages.PleaseConfirmMessage.Send(dialogMessage);

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

        private void _issueVisionModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("HasChanges"))
            {
                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)

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 | Mobile
Web04 | 2.8.140827.1 | Last Updated 7 Jul 2011
Article Copyright 2010 by Weidong Shen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid