Click here to Skip to main content
15,891,184 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.ServiceModel.DomainServices.Client;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using IssueVision.Data.Web;
using IssueVision.Common;


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

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

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

            // initiate a new issue
            Issue newIssue = this._issueVisionModel.AddNewIssue();
            AppMessages.EditIssueMessage.Send(newIssue);
        }
        #endregion "Constructor"

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

        #region "Public Commands"

        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
            {
                MessageBoxResult theResult = MessageBoxResult.Cancel;

                if (!_issueVisionModel.IsBusy)
                {
                    // ask to confirm canceling this new issue first
                    DialogMessage dialogMessage = new DialogMessage(
                        this,
                        CommonResources.CancelCurrentIssueMessageBoxText,
                        s => theResult = s)
                    {
                        Button = MessageBoxButton.OKCancel,
                        Caption = CommonResources.ConfirmMessageBoxCaption
                    };

                    AppMessages.PleaseConfirmMessage.Send(dialogMessage);

                    if (theResult == MessageBoxResult.OK)
                    {
                        // if confirmed, cancel this issue
                        AppMessages.CancelChangesMessage.Send();
                        // initiate a new issue again
                        Issue newIssue = this._issueVisionModel.AddNewIssue();
                        AppMessages.EditIssueMessage.Send(newIssue);
                    }
                }
            }
            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 of the new issue ID
                foreach (Entity entity in e.SubmitOp.ChangeSet.AddedEntities)
                {
                    Issue addedIssue = entity as Issue;
                    if (addedIssue != null)
                    {
                        // notify user of the new issue ID
                        DialogMessage dialogMessage = new DialogMessage(
                                    this,
                                    CommonResources.NewIssueCreatedText + addedIssue.IssueID,
                                    null)
                        {
                            Button = MessageBoxButton.OK,
                            Caption = CommonResources.NewIssueCreatedCaption
                        };

                        AppMessages.StatusUpdateMessage.Send(dialogMessage);
                    }
                }
                // save is successful, start another new issue
                Issue newIssue = this._issueVisionModel.AddNewIssue();
                AppMessages.EditIssueMessage.Send(newIssue);
            }
            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"))
            {
                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