Пример #1
0
        private void UninstallWindow_Shown(object sender, EventArgs e)
        {
            if (
                MessageBox.Show("Uninstall Exchange DKIM Signer?", "Uninstall?", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) != DialogResult.Yes)
            {
                this.Close();
                Application.Exit();
                return;
            }

            try
            {
                lbStep.Text = "Uninstalling Exchange Agent";
                ExchangeServer.UninstallDkimTransportAgent();

                lbStep.Text = "Restarting MS Exchange Transport";
                TransportService ts = new TransportService();
                try
                {
                    ts.Do(TransportServiceAction.Restart, delegate(string msg)
                    {
                        MessageBox.Show(msg, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Couldn't restart MSExchangeTransport Service. Please restart it manually. \n" + ex.Message, "Error restarting Service", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    ts.Dispose();
                }


                lbStep.Text = "Deleting directory";

                if (
                    MessageBox.Show(this,
                                    "The directory '" + Constants.DkimSignerPath +
                                    "' will now be deleted. Please make a backup of the keys stored within this directory before continuing.\n Continue deleting?",
                                    "Delete directory?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        Directory.Delete(Constants.DkimSignerPath, true);
                    }
                    catch (Exception)
                    {
                        //ignore exception. Delete directory on reboot
                        if (!NativeMethods.MoveFileEx(Constants.DkimSignerPath, null, MoveFileFlags.DelayUntilReboot))
                        {
                            MessageBox.Show(
                                "Unable to schedule '" + Constants.DkimSignerPath + "' for deletion on next reboot.",
                                "Delete error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }

                lbStep.Text = "Removing registry entry";
                CplControl.Unregister();
                UninstallerRegistry.Unregister();

                /*if (MessageBox.Show(this, "Transport Agent removed from Exchange. Would you like me to remove all the settings for Exchange DKIM Signer?'", "Remove settings?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                 * {
                 *  if (File.Exists(Path.Combine(Constants.DKIM_SIGNER_PATH, "settings.xml")))
                 *      File.Delete(Path.Combine(Constants.DKIM_SIGNER_PATH, "settings.xml"));
                 * }*/
                /*if (MessageBox.Show(this, "Transport Agent removed from Exchange. Would you like me to remove the folder '" + Constants.DKIM_SIGNER_PATH + "' and all its content?\nWARNING: All your settings and keys will be deleted too!", "Remove files?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                 * {
                 *  var dir = new DirectoryInfo(Constants.DKIM_SIGNER_PATH);
                 *  dir.Delete(true);
                 * }*/
                lbStep.Text             = "Uninstall complete";
                progressUninstall.Style = ProgressBarStyle.Continuous;
                progressUninstall.Value = 100;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Uninstall error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btClose.Enabled = true;
        }
Пример #2
0
        private void Install()
        {
            progressInstall.Style            = ProgressBarStyle.Continuous;
            btClose.Enabled                  = false;
            gbSelectVersionToInstall.Enabled = false;
            gbInstallStatus.Enabled          = true;
            Refresh();

            // ###########################################
            // ### IS Exchange version supported?      ###
            // ###########################################

            string agentExchangeVersionPath = "";

            foreach (KeyValuePair <string, string> entry in Constants.DkimSignerVersionDirectory)
            {
                if (exchangeVersion.StartsWith(entry.Key))
                {
                    agentExchangeVersionPath = entry.Value;
                    break;
                }
            }

            if (agentExchangeVersionPath == "")
            {
                MessageBox.Show(this, "Your Microsoft Exchange version isn't supported by the DKIM agent: " + exchangeVersion, "Version not supported", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                lbDownloadFiles.Enabled = true;
            }

            // path which is the base for copying the files. Should be the root of the downloaded .zip file.
            string extractPath;

            if (zipUrl != null)
            {
                // ###########################################
                // ### Download files                      ###
                // ###########################################

                string zipFile = "";

                if (Uri.IsWellFormedUriString(zipUrl, UriKind.RelativeOrAbsolute))
                {
                    zipFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip");

                    DownloadProgressWindow oDpw = new DownloadProgressWindow(zipUrl, zipFile);
                    try
                    {
                        if (oDpw.ShowDialog(this) == DialogResult.OK)
                        {
                            lbExtractFiles.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "Couldn't initialize download progress window:\n" + ex.Message, "Error showing download progress", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        oDpw.Dispose();
                    }
                }
                else
                {
                    if (File.Exists(zipUrl) && Path.GetExtension(zipUrl) == ".zip")
                    {
                        zipFile = zipUrl;
                        lbExtractFiles.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show(this, "The URL or the path to the ZIP file is invalid. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                picDownloadFiles.Image = lbExtractFiles.Enabled ? statusImageList.Images[0] : statusImageList.Images[1];
                progressInstall.Value  = 1;
                Refresh();

                // ###########################################
                // ### Extract files                       ###
                // ###########################################

                string zipDirName = Path.GetDirectoryName(zipFile);
                if (zipDirName == null)
                {
                    MessageBox.Show(this, "Invaild Zip path", "Could not extract directory from zip path: " + zipFile,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }

                extractPath = Path.Combine(zipDirName, Path.GetFileNameWithoutExtension(zipFile));

                if (lbExtractFiles.Enabled)
                {
                    if (!Directory.Exists(extractPath))
                    {
                        Directory.CreateDirectory(extractPath);
                    }

                    try
                    {
                        ZipFile.ExtractToDirectory(zipFile, extractPath);

                        // copy root directory is one directory below extracted zip:
                        string[] contents = Directory.GetDirectories(extractPath);
                        if (contents.Length == 1)
                        {
                            extractPath           = Path.Combine(extractPath, contents[0]);
                            lbStopService.Enabled = true;
                        }
                        else
                        {
                            MessageBox.Show(this, "Downloaded .zip is invalid. Please try again.", "Invalid download", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, "ZIP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                picExtractFiles.Image = lbStopService.Enabled ? statusImageList.Images[0] : statusImageList.Images[1];
                progressInstall.Value = 2;
                Refresh();
            }
            else
            {
                // the files are already downloaded and in the same directory as this .exe file

                // the executable is within: \Src\Configuration.DkimSigner\bin\Release so we need to go up a few directories
                DirectoryInfo dir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
                if (dir == null)
                {
                    MessageBox.Show(this, "Could not get directory info for: " + Assembly.GetExecutingAssembly().Location, "Directory error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string[] expectedDirs = { "Release", "bin", "Configuration.DkimSigner", "Src" };
                bool     sanityFail   = false;

                foreach (string str in expectedDirs)
                {
                    if (dir == null || !dir.Name.Equals(str))
                    {
                        sanityFail = true;
                        break;
                    }
                    dir = dir.Parent;
                }
                if (dir == null)
                {
                    sanityFail = true;
                }

                lbDownloadFiles.Enabled = !sanityFail;
                lbExtractFiles.Enabled  = !sanityFail;
                lbStopService.Enabled   = !sanityFail;

                if (sanityFail)
                {
                    picDownloadFiles.Image = statusImageList.Images[1];
                    picExtractFiles.Image  = statusImageList.Images[1];

                    Refresh();
                    MessageBox.Show(this, "Failed to determine copy root directory.\nThis executable is expected to be in the subpath: \\Src\\Configuration.DkimSigner\\bin\\Release", "ZIP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    btClose.Enabled = true;
                    return;
                }

                picDownloadFiles.Image = statusImageList.Images[0];
                picExtractFiles.Image  = statusImageList.Images[0];
                progressInstall.Value  = 2;
                Refresh();

                extractPath = dir.FullName;
            }


            // ###########################################
            // ### Stop Microsoft Transport service    ###
            // ###########################################

            if (lbStopService.Enabled)
            {
                if (transportService.GetStatus() != "Stopped")
                {
                    transportServiceSuccessStatus = "Stopped";
                    transportService.Do(TransportServiceAction.Stop, delegate(string msg)
                    {
                        MessageBox.Show(msg, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    });
                    lbCopyFiles.Enabled = transportServiceActionCompleted.WaitOne();
                }
                else
                {
                    lbCopyFiles.Enabled = true;
                }
            }

            picStopService.Image  = lbCopyFiles.Enabled ? statusImageList.Images[0] : statusImageList.Images[1];
            progressInstall.Value = 3;
            Refresh();

            // ###########################################
            // ### Copy required files                 ###
            // ###########################################

            if (lbCopyFiles.Enabled)
            {
                List <string> filesToCopy = new List <string>();
                filesToCopy.Add(Path.Combine(extractPath, @"Src\Configuration.DkimSigner\bin\Release"));
                filesToCopy.Add(Path.Combine(extractPath, Path.Combine(@"Src\Exchange.DkimSigner\bin\" + agentExchangeVersionPath)));

                // IF the directory "C:\Program Files\Exchange DkimSigner" doesn't exist, create it
                if (!Directory.Exists(Constants.DkimSignerPath))
                {
                    Directory.CreateDirectory(Constants.DkimSignerPath);
                }

                // Generate list of source files
                string[] sourceFiles = new string[0];
                foreach (string sourcePath in filesToCopy)
                {
                    string[] asTemp = Directory.GetFiles(sourcePath);

                    Array.Resize(ref sourceFiles, sourceFiles.Length + asTemp.Length);
                    Array.Copy(asTemp, 0, sourceFiles, sourceFiles.Length - asTemp.Length, asTemp.Length);
                }

                // Generate list of destinations files
                string[] destinationFiles = new string[sourceFiles.Length];
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    string sFile = Path.GetFileName(sourceFiles[i]);
                    destinationFiles[i] = Path.Combine(Constants.DkimSignerPath, sFile);
                }

                bool bAnyOperationsAborted;
                bool bReturn = FileOperation.CopyFiles(Handle, sourceFiles, destinationFiles, true, "Copy files", out bAnyOperationsAborted);

                lbInstallAgent.Enabled = bReturn && !bAnyOperationsAborted;
            }

            // register Control Panel Applet
            if (lbInstallAgent.Enabled)
            {
                try
                {
                    CplControl.Register();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Could not create applet in control panel:\n" + ex.Message + "\nThe installation will be successful anyways but you won't be able to open the DKIM Configurator from the Control Panel", "Error creating applet", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                try
                {
                    UninstallerRegistry.Register();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Could not create uninstall entry in Program and Files:\n" + ex.Message + "\nThe installation will be successful anyways but you won't be able to open the DKIM Configurator from the Control Panel", "Error creating applet", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            picCopyFiles.Image    = lbInstallAgent.Enabled ? statusImageList.Images[0] : statusImageList.Images[1];
            progressInstall.Value = 4;
            Refresh();

            // ############################################
            // ### Install DKIM Signer Exchange Agent   ###
            // ############################################

            if (lbInstallAgent.Enabled)
            {
                try
                {
                    // First make sure the following Registry key exists HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\Exchange DKIM
                    if (EventLog.SourceExists(Constants.DkimSignerEventlogSource))
                    {
                        // Make sure we recreate the event log source to fix messageResourceFile from versions previous to 2.0.0
                        RegistryKey key = Registry.LocalMachine.OpenSubKey(Constants.DkimSignerEventlogRegistry, false);
                        if (key == null || key.GetValue("EventMessageFile") == null)
                        {
                            // Delete the event source for the custom event log
                            EventLog.DeleteEventSource(Constants.DkimSignerEventlogSource);

                            // Create a new event source for the custom event log
                            EventSourceCreationData mySourceData = new EventSourceCreationData(Constants.DkimSignerEventlogSource, "Application");
                            mySourceData.MessageResourceFile = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll";
                            EventLog.CreateEventSource(mySourceData);
                        }
                    }
                    else
                    {
                        // Create a new event source for the custom event log
                        EventSourceCreationData mySourceData = new EventSourceCreationData(Constants.DkimSignerEventlogSource, "Application");
                        mySourceData.MessageResourceFile = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll";
                        EventLog.CreateEventSource(mySourceData);
                    }

                    // Install DKIM Transport Agent in Microsoft Exchange
                    ExchangeServer.InstallDkimTransportAgent();

                    lbStartService.Enabled = true;
                }
                catch (ExchangeServerException ex)
                {
                    MessageBox.Show(this, "Could not install DKIM Agent:\n" + ex.Message, "Error installing agent", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            picInstallAgent.Image = lbStartService.Enabled ? statusImageList.Images[0] : statusImageList.Images[1];
            progressInstall.Value = 5;
            Refresh();

            // ###########################################
            // ### Start Microsoft Transport service   ###
            // ###########################################

            if (lbStartService.Enabled)
            {
                transportServiceSuccessStatus = "Running";
                transportService.Do(TransportServiceAction.Start, delegate(string msg)
                {
                    MessageBox.Show(msg, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
                picStartService.Image = transportServiceActionCompleted.WaitOne() ? statusImageList.Images[0] : statusImageList.Images[1];
            }
            else
            {
                picStartService.Image = statusImageList.Images[1];
            }

            progressInstall.Value = 6;
            Refresh();

            btClose.Enabled = true;
        }