Click here to Skip to main content
15,898,035 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 108.2K   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.Windows.Forms;
    using VAL.Model;
    using VAL.Model.Entities;
    using VAL.Controls;
    using VAL.Contracts;
    using VAL.Core.Properties;

    /// <summary>
    /// A screen to allow the system administrator to maintain a list of defined
    /// files
    /// </summary>
    public partial class FileMaintenance : PersistedForm
    {
        private File file;
        private ListViewItem selectedItem;

        /// <summary>
        /// The maximum size of icons in VAL shouldn't be larger than 100KB!
        /// </summary>
        private const int MaxIconSize = 102400;

        #region Construct and Load

        /// <summary>
        /// Ctor
        /// </summary>
        public FileMaintenance(IAdministratorService service)
        {
            InitializeComponent();
            this.Service = service;
            
            LoadLookups();
            LoadFiles();
        }

        private void FileMaintenance_Load(object sender, EventArgs e)
        {
            SetFormEditMode(false);
        }

        private IAdministratorService Service { get; set; }

        #endregion

        /// <summary>
        /// Loads up all the files that are defined in the database
        /// </summary>
        private void LoadFiles()
        {
            int iconIndex = 1;
            var files = Service.GetAllFiles();
            var fileItems = new ListViewItem[files.Length];

            this.applicationsList.BeginUpdate();

            for (int i = 0; i < files.Length; ++i)
            {
                var file = files[i];
                var lvi = new ListViewItem
                {
                    Text = file.Description,
                    Tag = file
                };

                try
                {
                    Image image = IconConverter.ImageFromByteArray(file.Icon);
                    this.fileImages.Images.Add(image);
                    lvi.ImageIndex = iconIndex;
                    ++iconIndex;
                }
                catch (Exception ex)
                {
                    log.Error("Couldn't create Icon Image", ex);
                    lvi.ImageIndex = 0;
                }

                fileItems[i] = lvi;                             
            }

            this.applicationsList.Items.AddRange(fileItems);
            this.applicationsList.EndUpdate();
        }

        private void LoadLookups()
        {
            var fileTypes = Service.GetFileTypes(); 
            BindingHelper.SetLookupBinding(this.fileType, fileTypes, "Description", "Id");
        }

        private void fileSearchButton_Click(object sender, EventArgs e)
        {
            fileDialog.Filter = Session.Configuration.AllowedFileTypeFilter;
            if (fileDialog.ShowDialog(this) == DialogResult.OK)
            {
                this.file.Name = System.IO.Path.GetFileName(fileDialog.FileName);
                this.file.Path = GetValidFilePath(fileDialog.FileName);

                GetFileIcon(fileDialog.FileName);

                BindObjectFields();
            }
        }

        private string GetValidFilePath(string fileName)
        {
            string path = System.IO.Path.GetDirectoryName(fileDialog.FileName);

            if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                path += System.IO.Path.DirectorySeparatorChar;

            return path;                    
        }

        private void GetFileIcon(string fileName)
        {
            try
            {
                var knownFile = KnownExplorerFile.GetInstance(fileName);
                this.file.Icon = IconConverter.ByteArrayFromImage(knownFile.Icon);
            }
            catch { } // Not interested in errors

        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (!this.applicationsList.Enabled)
            {
                SetFormEditMode(false);
            }
            else
            {
                this.Close();
            }
        }

        private void SetFormEditMode(bool editing)
        {
            applicationsList.Enabled = (!editing);
            this.detailsTabs.Enabled = editing;
            this.applyButton.Enabled = editing;

            if (!editing)
            {
                this.file = null;
                detailsTabs.SelectedTab = detailsTabs.TabPages[0];
                ClearEditFields(this);
            }
        }

        private void BindObjectFields()
        {
            BindingHelper.BindField(this.fileName, BindingProperties.Text, file, "Name");
            BindingHelper.BindField(this.filePath, BindingProperties.Text, file, "Path");
            BindingHelper.BindField(this.description, BindingProperties.Text, file, "Description");
            BindingHelper.BindField(this.notes, BindingProperties.Text, file, "Notes");
            BindingHelper.BindField(this.workGroup, BindingProperties.Text, file, "Workgroup");
            BindingHelper.BindField(this.command, BindingProperties.Text, file, "Command");
            BindingHelper.BindField(this.distributeTo, BindingProperties.Text, file, "DistributeTo");
            BindingHelper.BindField(this.fileType, BindingProperties.SelectedValue, file, "FileTypeId");
            BindingHelper.BindField(this.isActive, BindingProperties.Checked, file, "IsActive");
            BindingHelper.BindField(this.distributeToUserProfileCheck, BindingProperties.Checked, file, "DistributeToUserProfile");
           
            this.iconPreview.Image = IconConverter.ImageFromByteArray(file.Icon);
        }

        private void extendedTab_Click(object sender, EventArgs e)
        {

        }

        private void searchIconButton_Click(object sender, EventArgs e)
        {
            fileDialog.Filter = "Icon files|*.ico|Gif Files|*.gif|Executable files|*.exe|Portable Network Graphics|*.png";

            // Only continue if user didn't cancel
            if (fileDialog.ShowDialog(this) == DialogResult.OK)
            {
                if (fileDialog.FileName.EndsWith("exe"))
                {
                    // Attempt to extract an icon from the file
                    GetFileIcon(fileDialog.FileName);                   
                }
                else
                {
                    System.IO.FileInfo info = new System.IO.FileInfo(fileDialog.FileName);
                    if (info.Length > MaxIconSize)
                    {
                        Messaging.ShowError(Resources.MaximumIconSizeExceeded);
                        return;
                    }
                    KnownExplorerFile file = KnownExplorerFile.GetInstance(fileDialog.FileName);
                    this.file.Icon = IconConverter.ByteArrayFromImage(file.Icon);
                }

                BindObjectFields();
            }
        }

        private void applicationsList_DoubleClick(object sender, EventArgs e)
        {
            EditFile();
        }

        private void EditFile()
        {
            if (!TryGetListViewItem(applicationsList, out selectedItem))
                return;

            this.file = (File)selectedItem.Tag;

            // Binds the user GUI fields to those of our object
            BindObjectFields();
            SetFormEditMode(true);
        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetFormEditMode(true);

            this.file = new File();
            this.file.IsActive = true;

            BindObjectFields();
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditFile();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!TryGetListViewItem(applicationsList, out selectedItem))
                return;

            File file = (File)selectedItem.Tag;

            if (Messaging.AskQuestion(
                string.Format(Resources.FileDeletionPrompt, file.Description)) == DialogResult.Yes)
            {
                Service.DeleteFile(file.Id);
                this.applicationsList.Items.Remove(selectedItem);      
            }      
        }

        private void applyButton_Click(object sender, EventArgs e)
        {
            file.Icon = IconConverter.ByteArrayFromImage(this.iconPreview.Image);
            if (!file.IsValid)
            {
                Messaging.ShowError(file.ErrorMessage);
                return;
            }

            bool isNew = (file.Id == 0);

            #region New File - Some Sanity Checking
            if (isNew)
            {
                string fullPath = String.Concat(file.Path, file.Name);
                if (!System.IO.File.Exists(fullPath))
                {
                    if (Messaging.AskQuestion(string.Format(Resources.CannotFindFile, fullPath)) == DialogResult.No)
                        return;
                }
                if (!string.IsNullOrEmpty(file.DistributeTo))
                {
                    if (!System.IO.Directory.Exists(file.DistributeTo))
                    {
                        if (Messaging.AskQuestion(string.Format(Resources.CannotFindDirectory, file.DistributeTo)) == DialogResult.No)
                            return;
                    }
                }
            }
            #endregion

            file = Service.SaveFile(file);

            ListViewItem lvi;
            if (isNew)
                lvi = new ListViewItem();
            else
                lvi = selectedItem;

            lvi.Text = file.Description;
            lvi.Tag = file;

            // Only need to update the listimages or ListViewItems if this is a newly created item
            if (isNew)
            {
                fileImages.Images.Add(IconConverter.ImageFromByteArray(file.Icon));
                lvi.ImageIndex = this.fileImages.Images.Count - 1;

                this.applicationsList.Items.Add(lvi);
            }

            SetFormEditMode(false);
        }

        private void findWorkgroupButton_Click(object sender, EventArgs e)
        {
            this.fileDialog.Filter = "Workgroup Files|*.mdw";
            if (fileDialog.ShowDialog(this) == DialogResult.OK)
            {
                this.workGroup.Text = fileDialog.FileName;
            }
        }

        private void selectDistrubuteFolder_Click(object sender, EventArgs e)
        {
            folderBrowser.ShowNewFolderButton = true;
            if (this.distributeTo.Text.Length > 0)
                folderBrowser.SelectedPath = this.distributeTo.Text;
            
            if (folderBrowser.ShowDialog(this) == DialogResult.OK)
            {
                this.distributeTo.Text = folderBrowser.SelectedPath;
            }
        }

        private void fileType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Only enable the distribution options if this is an Access database
            if (fileType.SelectedValue != null)
            {
                bool isAccess = (Convert.ToInt32(fileType.SelectedValue)) == 2;

                if (!isAccess)
                    distributeTo.Text = string.Empty;

                this.distributeTo.Enabled = isAccess;
                this.selectDistrubuteFolder.Enabled = isAccess;
                this.workGroup.Enabled = isAccess;
                this.findWorkgroupButton.Enabled = isAccess;
            }
        }

        private void distributeToUserProfileCheck_CheckedChanged(object sender, EventArgs e)
        {
            bool distToUser = distributeToUserProfileCheck.Checked;

            this.distributeToLabel.Enabled = !distToUser;
            this.distributeTo.Enabled = !distToUser;
            this.selectDistrubuteFolder.Enabled = !distToUser;

            if (!distToUser)
            {
                this.distributeTo.Text = string.Empty;
            }
        }

    }
}

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