Click here to Skip to main content
15,886,755 members
Articles / Programming Languages / C#

Gmail for Windows 7

Rate me:
Please Sign up or sign in to vote.
4.94/5 (42 votes)
24 Jan 2010CPOL15 min read 150.4K   8.5K   111  
A little application to notify you of new Gmail using new Windows 7 features
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 System.Configuration;
using System.Reflection;
using System.IO;

namespace GmailForWin7
{
    /// <summary>
    /// Displays program settings and allows the user to change them.
    /// </summary>
    public partial class SettingsDlg : Form
    {
        private GmailMain _mainWin;

        public SettingsDlg(GmailMain mainWin)
        {
            _mainWin = mainWin;

            InitializeComponent();
            FillSettingsControls();
        }

        #region Properties

        /// <summary>
        /// Tells if the accounts were modified.
        /// </summary>
        public bool ChangedAccounts { get; protected set; }

        #endregion Properties

        #region Event Handlers

        private void _okButton_Click(object sender, EventArgs e)
        {
            if (SaveSettings())
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void _useSpecifiedBrowserRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            _browserExeTextBox.Enabled = true;
            _browserBtn.Enabled = true;
        }

        private void _defaultBrowserRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            _browserExeTextBox.Enabled = false;
            _browserBtn.Enabled = false;
        }

        private void _browserBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.CheckFileExists = true;
            dlg.Filter = "Executables (*.exe)|*.exe";
            dlg.Title = "Select Web Browser to use for links";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _browserExeTextBox.Text = dlg.FileName;
            }
        }

        private void _accountListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnableOrDisableAccountButtons();
        }

        private void _deleteAccountButton_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(this, "Delete this account?", "Delete Account", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                AccountInfo account = _accountListBox.SelectedItem as AccountInfo;
                if (null != account)
                {
                    _cancelButton.Text = "Close";
                    _mainWin.Accounts.Remove(account);
                    _accountListBox.Items.Remove(account);
                    ChangedAccounts = true;
                    SaveAccounts(null);
                    EnableOrDisableAccountButtons();
                }
            }
        }

        private void _editAccountButton_Click(object sender, EventArgs e)
        {
            AccountInfo account = _accountListBox.SelectedItem as AccountInfo;
            if (null != account)
            {
                AccountDlg dlg = new AccountDlg(_mainWin, account);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    _cancelButton.Text = "Close";
                    ChangedAccounts = true;
                    SaveAccounts(account);
                    
                }
            }
        }

        private void _addAccountButton_Click(object sender, EventArgs e)
        {
            AddNewAccount();
        }

        private void _browseForSoundButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.CheckFileExists = true;
            dlg.Filter = "Wav Files (*.wav)|*.wav";
            dlg.Title = "Select Web Browser to use for links";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _soundFileTextBox.Text = dlg.FileName;
            }   
        }

        private void soundRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            enableOrDisableSoundControls();
        }

        private void _playButton_Click(object sender, EventArgs e)
        {
            string soundFile = _soundFileTextBox.Text;
            if (!File.Exists(soundFile))
            {
                MessageBox.Show(this, "Could not open the file: " + soundFile, "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    using (System.Media.SoundPlayer player = new System.Media.SoundPlayer())
                    {
                        player.SoundLocation = soundFile;
                        player.PlaySync();
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("Could not play the file: {0} ({1})", soundFile, ex.Message);
                    MessageBox.Show(this, msg, "Error Playing Sound", MessageBoxButtons.OK, MessageBoxIcon.Error);   
                }
            }
        }

        private void SettingsDlg_Shown(object sender, EventArgs e)
        {
            BringToFront();
            Focus();
            // If this is being displayed for the initial run of the application (or for a new user)
            // then display add account dialog and then exit.
            // This is done in the Shown event to allow the caller's call to ShowDialog to not throw an ObjectDisposed exception.
            if (0 == _accountListBox.Items.Count)
            {
                AddNewAccount();
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        #endregion Event Handlers

        #region Helpers

        private void AddNewAccount()
        {
            AccountInfo newAccount = new AccountInfo();
            AccountDlg dlg = new AccountDlg(_mainWin, newAccount);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _cancelButton.Text = "Close";
                ChangedAccounts = true;
                _mainWin.Accounts.Add(newAccount);
                SaveAccounts(newAccount);
                EnableOrDisableAccountButtons();
            }
        }

        private void EnableOrDisableAccountButtons()
        {
            AccountInfo selected = _accountListBox.SelectedItem as AccountInfo;
            _addAccountButton.Enabled = (_accountListBox.Items.Count < GmailMain.MaxAccounts);
            _editAccountButton.Enabled = (null != selected);
            _deleteAccountButton.Enabled = (null != selected);
        }

        private void enableOrDisableSoundControls()
        {
            _soundFileTextBox.Enabled = _playSoundRadioButton.Checked;
            _browseForSoundButton.Enabled = _playSoundRadioButton.Checked;
            _playButton.Enabled = _playSoundRadioButton.Checked;
        }

        private void FillSettingsControls()
        {
            _intervalTextBox.Text = _mainWin.MailCheckIntervalInMinutes.ToString();

            // see if using specified browser
            bool usingSpecifiedBrowser = !string.IsNullOrEmpty(_mainWin.Browser);
            if (usingSpecifiedBrowser)
            {
                _browserExeTextBox.Text = _mainWin.Browser;
            }
            _useSpecifiedBrowserRadioButton.Checked = usingSpecifiedBrowser;
            _browserExeTextBox.Enabled = usingSpecifiedBrowser;
            _browserBtn.Enabled = usingSpecifiedBrowser;

            switch (_mainWin.NewMailSoundMode)
            {
                case SoundMode.None:
                    _noSoundRadioButton.Checked = true;
                    break;
                case SoundMode.Default:
                    _defaultSoundRadioButton.Checked = true;
                    break;
                case SoundMode.Specified:
                    _playSoundRadioButton.Checked = true;
                    break;
            }
            switch (_mainWin.MessageNotificationMode)
            {
                case NotificationMode.None:
                    _noNotificationRadioButton.Checked = true;
                    break;
                case NotificationMode.MessagesFoundSinceLastCheck:
                    _newMessagesNotificationRadioButton.Checked = true;
                    break;
                case NotificationMode.AllMessagesInInbox:
                    _allMessagesNotificationRadioButton.Checked = true;
                    break;
            }

            _soundFileTextBox.Text = _mainWin.NewMailSoundFile;

            FillAccountsListBox(null);
        }

        private void FillAccountsListBox(AccountInfo accountToSelect)
        {
            _accountListBox.Items.Clear();
            _accountListBox.Items.AddRange(_mainWin.Accounts.ToArray());
            if (null != accountToSelect) _accountListBox.SelectedItem = accountToSelect;
        }

        /// <summary>
        /// Save all account information to user config file.
        /// </summary>
        /// <param name="accountToSelect"></param>
        private void SaveAccounts(AccountInfo accountToSelect)
        {
            int index = 1;
            Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

            // First remove all old entries
            for (int removeIdx = 1; removeIdx <= 10; ++removeIdx)
            {
                string removeKey = string.Format("Account{0}", removeIdx.ToString());
                config.AppSettings.Settings.Remove(removeKey);
            }
            foreach (AccountInfo account in _mainWin.Accounts)
            {
                string key = string.Format("Account{0}", index.ToString());
                string value = account.ConfigString();
                config.AppSettings.Settings.Add(key, value);
                ++index;
            }

            // Update the config file
            config.Save();
            FillAccountsListBox(accountToSelect);
        }

        /// <summary>
        /// Save settings to user config file.
        /// </summary>
        /// <returns></returns>
        private bool SaveSettings()
        {
            bool hadError = false;

            string browserString = string.Empty;
            if (_useSpecifiedBrowserRadioButton.Checked)
            {
                browserString = _browserExeTextBox.Text;
                if (!System.IO.File.Exists(browserString))
                {
                    hadError = true;
                    _errorProvider.SetError(_useSpecifiedBrowserRadioButton, "Browser specified does not exist.");
                }
            }
            int intervalInt;
            string value = _intervalTextBox.Text;
            if (!int.TryParse(value, out intervalInt))
            {
                hadError = true;
                _errorProvider.SetError(_intervalTextBox, "Invalid number for interval.");
            }
            else if (0 > intervalInt)
            {
                hadError = true;
                _errorProvider.SetError(_intervalTextBox, "Interval must be greater than or equal to 0.");
            }

            if (!hadError)
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                config.AppSettings.Settings[GmailMain.SettingBrowser].Value = browserString;
                _mainWin.Browser = browserString;

                config.AppSettings.Settings[GmailMain.SettingInterval].Value = intervalInt.ToString();
                _mainWin.MailCheckIntervalInMinutes = intervalInt;

                NotificationMode notificationMode = NotificationMode.None;
                if (_newMessagesNotificationRadioButton.Checked) notificationMode = NotificationMode.MessagesFoundSinceLastCheck;
                else if (_allMessagesNotificationRadioButton.Checked) notificationMode = NotificationMode.AllMessagesInInbox;
                config.AppSettings.Settings[GmailMain.SettingNotificationMode].Value = notificationMode.ToString();
                _mainWin.MessageNotificationMode = notificationMode;

                SoundMode soundMode = SoundMode.None;
                if (_defaultSoundRadioButton.Checked) soundMode = SoundMode.Default;
                else if (_playSoundRadioButton.Checked) soundMode = SoundMode.Specified;
                config.AppSettings.Settings[GmailMain.SettingSoundMode].Value = soundMode.ToString();
                _mainWin.NewMailSoundMode = soundMode;

                config.AppSettings.Settings[GmailMain.SettingSoundFile].Value = _soundFileTextBox.Text;
                _mainWin.NewMailSoundFile = _soundFileTextBox.Text;

                config.Save();
            }
            return !hadError;
        }

        #endregion Helpers
    }
}

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
Web Developer
United States United States
I have been developing .NET applications since 2001 and have been working in software development since 1989.

Comments and Discussions