private void RunResolveProblems(MonitoringData monitoringData, List <TroubleshooterCheck> checkList, List <TroubleshooterCheck> failedCheckList)
 {
     if (failedCheckList.Count == 0)
     {
         ExchangeServer exchangeServer = (ExchangeServer)base.Fields["ExchangeServer"];
         monitoringData.Events.Add(new MonitoringEvent(AssistantTroubleshooterBase.EventSource, 5000, EventTypeEnumeration.Information, Strings.TSNoProblemsDetected(exchangeServer.Name)));
         using (List <TroubleshooterCheck> .Enumerator enumerator = checkList.GetEnumerator())
         {
             while (enumerator.MoveNext())
             {
                 TroubleshooterCheck         troubleshooterCheck         = enumerator.Current;
                 AssistantTroubleshooterBase assistantTroubleshooterBase = troubleshooterCheck as AssistantTroubleshooterBase;
                 if (assistantTroubleshooterBase != null)
                 {
                     monitoringData.PerformanceCounters.Add(assistantTroubleshooterBase.GetCrashDumpCountPerformanceCounter());
                     break;
                 }
             }
             return;
         }
     }
     if (this.ResolveProblems.IsPresent)
     {
         foreach (TroubleshooterCheck troubleshooterCheck2 in failedCheckList)
         {
             troubleshooterCheck2.Resolve(monitoringData);
         }
     }
 }
        private async void btExchangeVersion_Click(object sender, EventArgs e)
        {
            string version = "Unknown";

            btExchangeVersion.Enabled = false;
            ExchangeServerException ex = null;
            await Task.Run(() => { try { version = ExchangeServer.GetInstalledVersion(); } catch (ExchangeServerException exe) { ex = exe; } });

            btExchangeVersion.Enabled = true;
            if (ex != null)
            {
                ShowMessageBox("Exchange Version Error", "Couldn't determine installed Exchange Version: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            char[] values = version.ToCharArray();
            string result = "";

            foreach (char letter in values)
            {
                // Get the integral value of the character.
                int value = Convert.ToInt32(letter);
                // Convert the decimal value to a hexadecimal value in string form.
                string hexOutput = String.Format("{0:X}", value);
                result += "'" + letter + "'" + " -> " + hexOutput + "\n";
            }

            string configVersion = Version.Parse(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion).ToString().Substring(0, 5);


            result = "My version: " + configVersion + "\nExchange\n" + result;

            ShowMessageBox("Exchange Version Debug", result, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 protected void StartAssistantService(ExchangeServer server, MonitoringData monitoringData)
 {
     try
     {
         using (ServiceController serviceController = new ServiceController("MsExchangeMailboxAssistants", server.Fqdn))
         {
             serviceController.Start();
             serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMinutes(5.0));
             monitoringData.Events.Add(new MonitoringEvent(AssistantTroubleshooterBase.EventSource, 5002, EventTypeEnumeration.Information, Strings.MailboxAssistantsServiceStarted(this.ExchangeServer.Name)));
         }
     }
     catch (System.ServiceProcess.TimeoutException ex)
     {
         this.SendWatsonForAssistantProcess(ex, false);
         monitoringData.Events.Add(this.MailboxAssistantsServiceCouldNotBeStarted(this.ExchangeServer.Name, ex.Message));
     }
     catch (InvalidOperationException ex2)
     {
         monitoringData.Events.Add(this.MailboxAssistantsServiceCouldNotBeStarted(this.ExchangeServer.Name, ex2.Message));
     }
     catch (Win32Exception ex3)
     {
         monitoringData.Events.Add(this.MailboxAssistantsServiceCouldNotBeStarted(this.ExchangeServer.Name, ex3.Message));
     }
 }
Esempio n. 4
0
        public IHttpActionResult Create(CreateAppointmentRequest request)
        {
            var service     = ExchangeServer.Open();
            var appointment = new Appointment(service);

            // Set the properties on the appointment object to create the appointment.
            appointment.Subject = request.Subject;
            appointment.Body    = request.Body;
            appointment.Start   = DateTime.Parse(request.Start);
            //appointment.StartTimeZone = TimeZoneInfo.Local;
            appointment.End = DateTime.Parse(request.End);
            //appointment.EndTimeZone = TimeZoneInfo.Local;
            appointment.Location = request.Location;
            //appointment.ReminderDueBy = DateTime.Now;

            foreach (var email in request.Recipients)
            {
                appointment.RequiredAttendees.Add(email);
            }

            // Save the appointment to your calendar.
            appointment.Save(SendInvitationsMode.SendOnlyToAll);

            // Verify that the appointment was created by using the appointment's item ID.
            Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));

            var response = new CreateAppointmentResponse
            {
                Message   = "Appointment created: " + item.Subject,
                AppointId = appointment.Id.ToString()
            };

            return(Ok(response));
        }
Esempio n. 5
0
        public IHttpActionResult Availability(AvailabilityRequest request)
        {
            List <AttendeeInfo> attendees = new List <AttendeeInfo>();

            foreach (var user in request.Users)
            {
                attendees.Add(new AttendeeInfo()
                {
                    SmtpAddress  = user,
                    AttendeeType = MeetingAttendeeType.Required
                });
            }

            // Specify availability options.
            AvailabilityOptions myOptions = new AvailabilityOptions();

            myOptions.MeetingDuration       = request.DurationMinutes;
            myOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

            // Return a set of free/busy times.
            var service = ExchangeServer.Open();

            var startTime = DateTime.Parse(request.Start);
            var endTime   = DateTime.Parse(request.End);
            GetUserAvailabilityResults freeBusyResults = service.GetUserAvailability(attendees,
                                                                                     new TimeWindow(startTime, endTime),
                                                                                     AvailabilityData.FreeBusy,
                                                                                     myOptions);

            var response = new AvailabilityResponse
            {
                AvailabilityResult = new List <AvailabilityUser>()
            };


            foreach (AttendeeAvailability availability in freeBusyResults.AttendeesAvailability)
            {
                var user  = new AvailabilityUser();
                var avail = new List <TimeBlock>();

                foreach (CalendarEvent calendarItem in availability.CalendarEvents)
                {
                    var block = new TimeBlock
                    {
                        Start      = calendarItem.StartTime,
                        End        = calendarItem.EndTime,
                        StatusEnum = calendarItem.FreeBusyStatus,
                        Status     = calendarItem.FreeBusyStatus.ToString()
                    };

                    avail.Add(block);
                }
                user.Availability = avail;
                response.AvailabilityResult.Add(user);
            }

            return(Ok(response));
        }
Esempio n. 6
0
 protected override void WriteResult(IConfigurable dataObject)
 {
     TaskLogger.LogEnter(new object[]
     {
         dataObject.Identity,
         dataObject
     });
     if (this.Domain == null || (this.Domain != null && ((Server)dataObject).Domain.Equals(this.Domain, StringComparison.InvariantCultureIgnoreCase)))
     {
         ExchangeServer exchangeServer = new ExchangeServer((Server)dataObject);
         if (this.Status && exchangeServer.IsProvisionedServer)
         {
             this.WriteWarning(Strings.StatusSpecifiedForProvisionedServer);
         }
         if (this.Status && !exchangeServer.IsReadOnly && !((Server)dataObject).IsProvisionedServer)
         {
             if (string.IsNullOrEmpty(exchangeServer.Fqdn))
             {
                 this.WriteWarning(Strings.ErrorInvalidObjectMissingCriticalProperty(typeof(Server).Name, exchangeServer.Identity.ToString(), ServerSchema.Fqdn.Name));
             }
             else
             {
                 Exception ex = null;
                 string[]  array;
                 string[]  array2;
                 string    staticConfigDomainController;
                 string[]  array3;
                 bool?     errorReportingEnabled;
                 GetExchangeServer.GetConfigurationFromRegistry(exchangeServer.Fqdn, out array, out array2, out staticConfigDomainController, out array3, out errorReportingEnabled, out ex);
                 if (ex != null)
                 {
                     this.WriteWarning(Strings.ErrorAccessingRegistryRaisesException(exchangeServer.Fqdn, ex.Message));
                 }
                 exchangeServer.StaticDomainControllers         = array;
                 exchangeServer.StaticGlobalCatalogs            = array2;
                 exchangeServer.StaticConfigDomainController    = staticConfigDomainController;
                 exchangeServer.StaticExcludedDomainControllers = array3;
                 exchangeServer.ErrorReportingEnabled           = errorReportingEnabled;
                 if (exchangeServer.IsExchange2007OrLater)
                 {
                     try
                     {
                         exchangeServer.RefreshDsAccessData();
                     }
                     catch (ADTransientException ex2)
                     {
                         this.WriteWarning(Strings.ErrorADTopologyServiceNotAvailable(exchangeServer.Fqdn, ex2.Message));
                     }
                 }
                 exchangeServer.ResetChangeTracking();
             }
         }
         base.WriteResult(exchangeServer);
     }
     TaskLogger.LogExit();
 }
Esempio n. 7
0
        /// <summary>
        /// 构造函数
        /// </summary>
        private Controller()
        {
            Args               = SystemArgs.GetInstance();
            strUnitCode        = Args.args.UnitCode;
            strUnitName        = Args.args.UnitName;
            SharkHandsInterval = Args.args.SharkHandsInterval;

            us = new UploadServer();
            es = new ExchangeServer();
            bs = new BServer();
            gs = new GServer();
        }
Esempio n. 8
0
        /// <summary>
        /// Check the Microsoft Exchange Transport Service Status
        /// </summary>
        private async void CheckExchangeInstalled()
        {
            progressInstall.Style = ProgressBarStyle.Marquee;
            await Task.Run(() => exchangeVersion = ExchangeServer.GetInstalledVersion());

            lblExchangeVersionWait.Hide();
            btInstall.Enabled = IsBtInstallEnabled();

            // If the source for install have been specified in command line
            if (zipUrl != null || performInstall)
            {
                Install();
            }
        }
        protected override void InternalBeginProcessing()
        {
            TaskLogger.LogEnter();
            base.InternalBeginProcessing();
            Server         server         = this.GetServer();
            ExchangeServer exchangeServer = new ExchangeServer(server);

            base.Fields["ExchangeServer"] = exchangeServer;
            if (this.ResolveProblems.IsPresent && this.IncludeCrashDump.IsPresent && !StringComparer.OrdinalIgnoreCase.Equals(exchangeServer.Name, Environment.MachineName))
            {
                throw new TSCrashDumpsOnlyAvailableOnLocalMachineException();
            }
            TaskLogger.LogExit();
        }
 private void Initialize(Server server, string processName)
 {
     if (server != null)
     {
         this.serverGuid    = new Guid?(server.Guid);
         this.serverName    = server.Name;
         this.serverVersion = server.AdminDisplayVersion;
         this.serverRole    = ExchangeServer.ConvertE15ServerRoleToOutput(server.CurrentServerRole).ToString();
     }
     else
     {
         this.serverName = NativeHelpers.GetLocalComputerFqdn(false);
     }
     this.processName = processName;
 }
Esempio n. 11
0
        internal static string GetDefaultEdbFolderPath(ExchangeServer ownerServer, string databaseName)
        {
            string      text        = Path.Combine(ownerServer.DataPath.PathName, LocalLongFullPath.ConvertInvalidCharactersInFileName(databaseName));
            string      path        = string.Format("{0}{1}{2}", databaseName, "0000", ".edb");
            EdbFilePath edbFilePath = null;

            if (!EdbFilePath.TryParse(Path.Combine(text, path), out edbFilePath))
            {
                text = ownerServer.DataPath.PathName;
                if (!EdbFilePath.TryParse(Path.Combine(text, path), out edbFilePath))
                {
                    text = EdbFilePath.DefaultEdbFilePath;
                }
            }
            return(text);
        }
Esempio n. 12
0
        public IHttpActionResult Send(SendEmailRequest request)
        {
            // Send Email
            var email = new EmailMessage(ExchangeServer.Open());

            email.ToRecipients.AddRange(request.Recipients);

            email.Subject = request.Subject;
            email.Body    = new MessageBody(request.Body);


            email.Send();
            return(Ok(new SendEmailResponse {
                Recipients = request.Recipients
            }));
        }
Esempio n. 13
0
        /// <summary>
        /// Thread safe function for the thread DkimSignerInstalled
        /// </summary>
        private async void CheckDkimSignerInstalled()
        {
            Version oDkimSignerInstalled = null;

            // Check if DKIM Agent is in C:\Program Files\Exchange DkimSigner and get version of DLL
            await Task.Run(() =>
            {
                try
                {
                    oDkimSignerInstalled = Version.Parse(FileVersionInfo.GetVersionInfo(Path.Combine(Constants.DkimSignerPath, Constants.DkimSignerAgentDll)).ProductVersion);
                }
                catch (Exception)
                {
                    // ignored
                }
            });

            // Check if DKIM agent have been load in Exchange
            if (oDkimSignerInstalled != null)
            {
                bool isDkimAgentTransportInstalled = false;

                await Task.Run(() =>
                {
                    try
                    {
                        isDkimAgentTransportInstalled = !ExchangeServer.IsDkimAgentTransportInstalled();
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                });

                if (isDkimAgentTransportInstalled)
                {
                    oDkimSignerInstalled = null;
                }
            }

            txtDkimSignerInstalled.Text         = (oDkimSignerInstalled != null ? oDkimSignerInstalled.ToString() : "Not installed");
            btConfigureTransportService.Enabled = (oDkimSignerInstalled != null);
            dkimSignerInstalled = oDkimSignerInstalled;

            SetUpgradeButton();
        }
Esempio n. 14
0
        /// <summary>
        /// 构造函数
        /// </summary>
        private Controller()
        {
            Args = SystemArgs.GetInstance();
            us   = new UploadServer();
            es   = new ExchangeServer();
            bs   = new BServer();
            gs   = new GServer();

            //Get all unit info
            dicUnit = new Dictionary <string, TUnit>();
            //TUnit unit = new TUnit();
            //unit.UnitCode = "001000";
            //unit.UnitName = "xx县120急救中心";
            //unit.UnitXZBM = "510112";

            //dicUnit.Add("001000", unit);
        }
Esempio n. 15
0
        private void btUninstall_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "Do you really want to UNINSTALL the DKIM Exchange Agent?\n", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    ExchangeServer.UninstallDkimTransportAgent();
                    RefreshTransportServiceAgents();
                    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();
                    }
                    MessageBox.Show(this, "Transport Agent unregistered from Exchange. Please remove the folder manually: '" + Constants.DkimSignerPath + "'\nWARNING: If you remove the folder, keep a backup of your settings and keys!", "Uninstalled", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    /*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);
                     * }*/
                }
                catch (ExchangeServerException ex)
                {
                    MessageBox.Show(this, ex.Message, "Uninstall error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 16
0
        public IHttpActionResult GetDetails(GetAppointmentsRequest request)
        {
            var startDate = DateTime.Parse(request.Start);
            var endDate   = DateTime.Parse(request.End);
            // Assuming 8 max per day * 5 (days/week) * 4 (weeks/month)
            const int NUM_APPTS = 160;
            var       calendar  = CalendarFolder.Bind(ExchangeServer.Open(), WellKnownFolderName.Calendar, new PropertySet());
            var       cView     = new CalendarView(startDate, endDate, NUM_APPTS);

            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.TimeZone);



            FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView);

            var response = new GetAppointmentsResponse();
            var list     = new List <Interview>();

            foreach (var app in appointments)
            {
                var appointment = Appointment.Bind(ExchangeServer.Open(), app.Id);

                var attendees = new List <RequiredAttendees>();
                foreach (var required in appointment.RequiredAttendees)
                {
                    attendees.Add(new RequiredAttendees
                    {
                        Name     = required.Name,
                        Email    = required.Address,
                        Response = required.ResponseType.ToString()
                    });
                }

                list.Add(new Interview {
                    Start = app.Start, End = app.End, TimeZone = app.TimeZone, Attendees = attendees, Subject = app.Subject
                });
            }
            response.Appointments = list;
            return(Ok(response));
        }
        // ##########################################################
        // ################# Internal functions #####################
        // ##########################################################

        private void RefreshTransportServiceAgents()
        {
            installedAgentsList = null;

            try
            {
                installedAgentsList = ExchangeServer.GetTransportServiceAgents();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error reading transport agents. " + ex.Message, "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            dgvTransportServiceAgents.Rows.Clear();

            if (installedAgentsList != null)
            {
                foreach (TransportServiceAgent oAgent in installedAgentsList)
                {
                    dgvTransportServiceAgents.Rows.Add(oAgent.Priority, oAgent.Name, oAgent.Enabled);
                    if (oAgent.Name == Constants.DkimSignerAgentName)
                    {
                        currentAgentPriority = oAgent.Priority;
                    }
                }
            }
            foreach (DataGridViewRow row in dgvTransportServiceAgents.Rows)
            {
                row.Selected = row.Cells["dgvcName"].Value.ToString().Equals(Constants.DkimSignerAgentName);
            }

            bool isDkimAgentTransportInstalled = ExchangeServer.IsDkimAgentTransportInstalled();
            bool isDkimAgentTransportEnabled   = isDkimAgentTransportInstalled && ExchangeServer.IsDkimAgentTransportEnabled();

            btDisable.Text = (isDkimAgentTransportEnabled ? "Disable" : "Enable");
            RefreshMoveButtons(true);
        }
Esempio n. 18
0
        private void btDisable_Click(object sender, EventArgs e)
        {
            try
            {
                if (btDisable.Text == "Disable")
                {
                    ExchangeServer.DisableDkimTransportAgent();
                }
                else
                {
                    ExchangeServer.EnableDkimTransportAgent();
                }

                RefreshTransportServiceAgents();
                RefreshMoveButtons(true);

                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();
                }
            }
            catch (ExchangeServerException ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Check the Microsoft Exchange Transport Service Status
        /// </summary>
        private async void CheckExchangeInstalled()
        {
            string version = "Unknown";

            ExchangeServerException ex = null;
            await Task.Run(() => { try { version = ExchangeServer.GetInstalledVersion(); } catch (ExchangeServerException e) { ex = e; } });

            if (ex != null)
            {
                ShowMessageBox("Exchange Version Error", "Couldn't determine installed Exchange Version: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            txtExchangeInstalled.Text = version;

            // Uptade Microsft Exchange Transport Service stuatus
            btConfigureTransportService.Enabled = (version != null && version != "Not installed");
            if (!btConfigureTransportService.Enabled)
            {
                txtExchangeStatus.Text = "Unavailable";
            }

            SetUpgradeButton();
        }
Esempio n. 20
0
        public void Initialize()
        {
            var dataProcessor = new DataProcessor(logger, this);

            emercitService = new EmercitAdapterService(serviceUrl);

            int value = 0;

            if (int.TryParse(sendingDataTimeout, out value))
            {
                sendingTimeout = value;
            }
            else
            {
                logger.LogError("Проблема при считывании таймаута отправки данных из конфига. Установлено значение 3600 секунд.");
                sendingTimeout = 3600;
            }

            int controllerValue = 0;

            if (int.TryParse(reconnectControllersTimeout, out controllerValue))
            {
                reconnectTimeout = controllerValue;
            }
            else
            {
                logger.LogError("Проблема при считывании таймаута переподключения контроллеров. Установлено значение 3600 секунд.");
                reconnectTimeout = 3600;
            }

            int portValue = 0;

            if (int.TryParse(controllerPort, out portValue))
            {
                port = portValue;
            }
            else
            {
                logger.LogError("Проблема при считывании порта контроллеров. Установлен порт 8081.");
                port = 8081;
            }

            int q = 0;

            if (int.TryParse(queue, out q))
            {
                queueSize = q;
            }
            else
            {
                logger.LogError("Проблема при считывании количества контроллеров в очереди. Установлено значение 5.");
                queueSize = 5;
            }

            sendingDataTimer = new Timer(Callback, null, TimeSpan.FromSeconds(sendingTimeout), Timeout.InfiniteTimeSpan);

            //Cоздание загрузчика и хранилища обновлений. При добавлении/удалении файлов обновлений в указанную
            //директорию автоматически будет выполенено добавление или удаление данного обновления в хранилище.
            //Это позволяет выполнять добавление файла обновления не перезапуская сервис.
            //const string updatesPath = @"C:\";

            FilesFirmwaresStore store = null;

            try
            {
                store = new FilesFirmwaresStore(new FirmwaresWatcher(logger, NotifyFilters.FileName, updatesPath), new FileLoader(), logger);
                logger.LogInformation($"Обновление загружено. Версии в store:");
                foreach (var s in store.GetVersions)
                {
                    logger.LogInformation(s.ToString());
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Ошибка при обновлении. {ex.Message}. Путь из конфига: {updatesPath}");
            }

            if (store == null)
            {
                logger.LogInformation($"По указанному пути обновления не найдены, проверка директории С:.");
                updatesPath = @"C:\";
                store       = new FilesFirmwaresStore(new FirmwaresWatcher(logger, NotifyFilters.FileName, updatesPath), new FileLoader(), logger);
            }

            //Создание экземпляра класса сервера (прослушивание всех интерфейсов и TCP порта 4090, размер очереди
            //подключения контроллеров равен 5
            var exchangeServer =
                ExchangeServer.CreateInstance(dataProcessor, store, new IPEndPoint(IPAddress.Any, port), queueSize);

            logger.LogInformation("Добавление контроллеров в хранилище");

            try
            {
                controllers = DatabaseWorker.GetInstance(connectionString, logger).ReadData(read_sqlQuery);

                foreach (var controller in controllers)
                {
                    exchangeServer.KeyStore.AddOrUpdate(controller.Id, controller.Key, false);
                    logger.LogInformation($"Контроллер {controller.Key} добавлен.");
                }
                logger.LogInformation("Запуск сервера");
            }
            catch (Exception ex)
            {
                logger.LogError($"Проблема при добавлении контроллеров в Exchange Server. {ex.Message}");
            }
            exchangeServer.Start();


            Console.WriteLine("Нажмите клавишу Enter для выхода...");
            Console.ReadLine();
            logger.LogInformation("Останов сервера");

            try
            {
                Dispose();

                exchangeServer.Stop();
            }
            catch (Exception ex)
            {
                logger.LogError($"Ошибка при остановке сервера. {ex.Message}. {ex.InnerException}");
            }
        }
Esempio n. 21
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;
        }
 // Token: 0x060008C9 RID: 2249 RVA: 0x0001ED1B File Offset: 0x0001CF1B
 public ServerIdParameter(ExchangeServer exServer) : base(exServer.Id)
 {
 }
Esempio n. 23
0
        private void OnMessageChange(object obj)
        {
            try
            {
                ExchangeServer es   = Controller.GetInstance().es;
                string         Name = obj.GetType().Name;
                string         xml  = "";
                switch (Name)
                {
                case "MonitorData":
                    MonitorData md = obj as MonitorData;
                    xml = XmlUtil.Serializer(md.GetType(), md);
                    es.SendMessage(xml);
                    break;

                case "DispatchTaskSelectData":
                    DispatchTaskSelectData SelectData = obj as DispatchTaskSelectData;
                    xml = XmlUtil.Serializer(SelectData.GetType(), SelectData);
                    es.SendMessage(xml);
                    break;

                case "DispatchTaskNoAnswer":
                    DispatchTaskNoAnswer NoAnswer = obj as DispatchTaskNoAnswer;
                    xml = XmlUtil.Serializer(NoAnswer.GetType(), NoAnswer);
                    es.SendMessage(xml);
                    break;

                case "SubCenterState":
                    SubCenterState State = obj as SubCenterState;
                    xml = XmlUtil.Serializer(State.GetType(), State);
                    //es.SendNotLogMessage(xml);
                    break;

                case "CommonInterface":
                    CommonInterface Common = obj as CommonInterface;
                    xml = XmlUtil.Serializer(Common.GetType(), Common);
                    es.SendMessage(xml);
                    break;

                case "GetVehiclePositionResp":
                    GetVehiclePositionResp PositionResp = obj as GetVehiclePositionResp;
                    xml = XmlUtil.Serializer(PositionResp.GetType(), PositionResp);
                    es.SendMessage(xml);
                    break;

                case "ShakeHand":
                    ShakeHand ShakeHand = obj as ShakeHand;
                    xml = XmlUtil.Serializer(ShakeHand.GetType(), ShakeHand);
                    // es.SendNotLogMessage(xml);
                    break;

                case "DispatchTaskRequestReinforcementResp":
                    DispatchTaskRequestReinforcementResp Resp = obj as DispatchTaskRequestReinforcementResp;
                    xml = XmlUtil.Serializer(Resp.GetType(), Resp);
                    es.SendMessage(xml);
                    break;

                case "VehicleStatus":
                    VehicleStatus Status = obj as VehicleStatus;
                    xml = XmlUtil.Serializer(Status.GetType(), Status);
                    es.SendMessage(xml);
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex) { throw ex; }
        }
Esempio n. 24
0
 public ClientAccessServerOrArrayIdParameter(ExchangeServer exServer) : base(exServer.Id)
 {
 }
Esempio n. 25
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;
        }