Click here to Skip to main content
15,892,746 members
Articles / Desktop Programming / Windows Forms

Visual Application Launcher

Rate me:
Please Sign up or sign in to vote.
4.91/5 (37 votes)
23 Jan 2012CPOL23 min read 107.7K   3.7K   116  
A WinForms UI using WCF services, Entity Framework, repository data access, repository caching, Unit of Work, Dependency Injection, and every other buzz work you can think of!
namespace VAL
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using VAL.Controls;
    using VAL.Core;
    using VAL.Model;
    using VAL.Model.Entities;

    /// <summary>
    /// The main application window
    /// </summary>
    public partial class MainWindow : PersistedForm
    {
        private ListViewItem[] applicationIcons;
        private bool layoutApplied;

        /// <summary>
        /// Default ctor
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            InitialiseHelp();

            // Enable \ Disable administator rights
            SetPermissions();

            // Load up any user defined window styles
            SplashScreen.SetStatus("Loading window settings");
            ApplyWindowStyles();
            Thread.Sleep(100);

            // Load up the files the user has permission to 
            SplashScreen.SetStatus("Loading file permissions");
            Thread.Sleep(100);

            LoadFiles();
        }

        private void SetPermissions()
        {
            this.launchAdminWindowToolStripMenuItem.Visible = 
                Thread.CurrentPrincipal.IsInRole(Session.Configuration.AdministratorDomainGroup);
        }

        private void InitialiseHelp()
        {
            string directory = Session.Configuration.HelpDirectory;
            if (!string.IsNullOrEmpty(directory))
            {
                if (!directory.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                    directory += System.IO.Path.DirectorySeparatorChar;

                this.helpProvider.HelpNamespace = directory + "VAL.chm";
            }            
        }

        private void ResetAll()
        {
            // Clear out the listview items
            applicationList.Items.Clear();

            // Reset the image lists
            smallImageList.Images.Clear();
            largeImageList.Images.Clear();
            smallImageList.ImageSize = new Size(16, 16);
            largeImageList.ImageSize = new Size(32, 32);

            applicationList.SmallImageList = smallImageList;
            applicationList.LargeImageList = largeImageList;
        }

        private void ChangeListViewMode(View newMode)
        {
            this.applicationList.View = newMode;
        }

        #region File Loading Background Worker Events
        
        private void LoadFiles()
        {
            applicationList.BeginUpdate();
            ResetAll();

            this.fileLoadWorker.RunWorkerAsync(Session.CurrentUser.Id);
        }

        private void fileLoadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            File[] files = null;
            using (var service = new VAL.ClientServices.UserServiceClient())
            {
                files = service.GetUserFiles(Convert.ToInt32(e.Argument));   
            }
            FileLoadProgressState state = new FileLoadProgressState(files.Length);
            fileLoadWorker.ReportProgress(0, state);

            for (int i = 0; i < files.Length; ++i)
            {
                var file = files[i];

                Image fileImage = IconConverter.ImageFromByteArray(file.Icon);

                state = new FileLoadProgressState(file, fileImage);
                fileLoadWorker.ReportProgress(i, state);
            }
        }

        private void fileLoadWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            FileLoadProgressState state = (FileLoadProgressState)e.UserState;
            if (state.Initialising)
            {
                this.toolStripProgressBar.Maximum = state.FileCount;
                this.applicationIcons = new ListViewItem[state.FileCount];
            }
            else
            {
                this.toolStripProgressBar.Value = e.ProgressPercentage;
                var file = state.File;

                this.smallImageList.Images.Add(state.Icon);
                this.largeImageList.Images.Add(state.Icon);

                var lvi = new ListViewItem();
                lvi.Text = file.Description;
                lvi.SubItems.Add(file.Notes);
                lvi.ImageIndex = e.ProgressPercentage;
                lvi.Tag = file;

                applicationIcons[e.ProgressPercentage] = lvi;
            }

        }

        private void fileLoadWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                #region Handle exception when no user permissions assigned
                if (e.Error != null)
                {
                    notifyIcon.ShowBalloonTip(10000, "Error during data load", e.Error.Message, ToolTipIcon.Error);
                    return;
                }

                #endregion

                this.toolStripProgressBar.Value = 0;                
                this.applicationList.Items.AddRange(this.applicationIcons);
            }
            finally
            {
                this.applicationList.EndUpdate();
            }            
        }

        #endregion

        #region Overrides

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool handled = false;
            if (keyData == Keys.F5)
            {
                LoadFiles();
                handled = true;
            }
            return handled || base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        private void smallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeListViewMode(View.SmallIcon);
        }

        private void iconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeListViewMode(View.LargeIcon);
        }

        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeListViewMode(View.List);
        }

        private void detailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeListViewMode(View.Details);
        }

        private void userSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var settings = new UserSettings())
            {
                if (settings.ShowDialog(this) == DialogResult.OK)
                    ApplyWindowStyles();
            }
        }

        private void ApplyWindowStyles()
        {
            var options = UserOptions.Current;

            try
            {
                applicationList.BackColor = Color.FromName(options.BackColor);
                applicationList.ForeColor = Color.FromName(options.ForeColor);
                applicationList.Font = new Font(options.FontName, options.FontSize);

                this.applicationList.Columns[0].Width = UserOptions.Current.Column1Size;
                this.applicationList.Columns[1].Width = UserOptions.Current.Column2Size;
            }
            catch
            {
                applicationList.Font = SystemFonts.MessageBoxFont;
                System.IO.File.Delete(UserOptions.OptionsPath);
            }

        }

        private void applicationList_DoubleClick(object sender, EventArgs e)
        {
            if (applicationList.SelectedItems.Count == 0)
                return;

            var selectedItem = applicationList.SelectedItems[0];
            File file = (File)selectedItem.Tag;

            LaunchFile(file);
        }

        private void LaunchFile(File file)
        {
            using (var wait = new WaitModal())
            {
                var context = TaskScheduler.FromCurrentSynchronizationContext();
                var task = Task.Factory.StartNew(() =>
                {
                    Launcher.LaunchFile(file);
                });
                task.ContinueWith(launch =>
                {
                    wait.Close();
                    Exception error = launch.Exception;
                    StringBuilder errorBuilder = new StringBuilder();
                    while (error != null)
                    {
                        errorBuilder.Append(error.Message + Environment.NewLine);
                        error = error.InnerException;
                    }

                    log.Error(errorBuilder.ToString(), launch.Exception);
                    Messaging.ShowError(errorBuilder.ToString());
                },
                System.Threading.CancellationToken.None,
                TaskContinuationOptions.OnlyOnFaulted, context);

                task.ContinueWith(launch =>
                {
                    wait.Close();
                },
                System.Threading.CancellationToken.None,
                TaskContinuationOptions.OnlyOnRanToCompletion, context);

                wait.ShowDialog(this);
            }
        }

        private void MainWindow_Layout(object sender, LayoutEventArgs e)
        {
            if (!layoutApplied)
            {
                layoutApplied = true;
                this.Activate();
                if (SplashScreen.SplashForm != null)
                    SplashScreen.CloseForm();
            }
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserOptions.Current.ListViewMode = this.applicationList.View;

            if (UserOptions.Current.ListViewMode == View.Details)
            {
                UserOptions.Current.Column1Size = this.applicationList.Columns[0].Width;
                UserOptions.Current.Column2Size = this.applicationList.Columns[1].Width;
            }

            UserOptions.Current.Save();
        }

        private void showFileInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (applicationList.SelectedItems.Count > 0)
            {
                ListViewItem lvi = applicationList.SelectedItems[0];
                File file = (File)lvi.Tag;

                var context = TaskScheduler.FromCurrentSynchronizationContext();
                var task = Task.Factory.StartNew(() =>
                {
                    return new FileInformation(file);
                })
                .ContinueWith(t => ShowTheForm(t.Result), context);
            }
        }

        private void ShowTheForm(FileInformation form)
        {
            using (form)
            {
                form.ShowDialog(this);
            }
        }

        private void launchAdminWindowToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType() == typeof(AdminWindow))
                {
                    if (form.WindowState == FormWindowState.Minimized)
                        form.WindowState = FormWindowState.Maximized;

                    form.Focus();
                    return;          
                }                        
            }

            var admin = new AdminWindow();
            admin.Show();
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadFiles();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.helpProvider.HelpNamespace))
            {
                Help.ShowHelp(this, helpProvider.HelpNamespace, HelpNavigator.TableOfContents);
            }
            else
            {
                Messaging.ShowInfo("The help file has not been configured for the application, help is unavailable");
            }
        }
    }
}

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
Technical Lead
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions