Exemple #1
0
        public void Start_ServiceAppProcessCanStartSucessfully()
        {
            ILog log = Substitute.For <ILog>();
            bool monitorMethodCalled = false;

            IProcessWrapperFactory procFactory = Substitute.For <IProcessWrapperFactory>();

            procFactory.CreateProcess().Returns(new FakeStandardProcess());

            var serviceApp = new ServiceApp {
                Name = "Test", AppVersion = new Version()
            };
            ServiceAppProcess appProcToTest = new ServiceAppProcess(serviceApp, log, procFactory);

            appProcToTest.MonitorProcessCallback = () => { monitorMethodCalled = true; };

            Task t       = appProcToTest.Start();
            bool success = t.Wait(500);

            if (!success)
            {
                Assert.Fail("Start() took too long to finish");
            }

            log.DidNotReceive().Error(Arg.Any <object>(), Arg.Any <Exception>());
            log.DidNotReceive().Warn(Arg.Any <object>(), Arg.Any <Exception>());
            Assert.IsTrue(monitorMethodCalled, "MonitorProcessCallback() not called.");
        }
Exemple #2
0
        public void ProcessError_LoggingWorksWithUnrecognizedExceptionObject()
        {
            ILog log = Substitute.For <ILog>();
            IProcessWrapperFactory procFactory = Substitute.For <IProcessWrapperFactory>();

            procFactory.CreateProcess().Returns(new FakeStandardProcess());
            var serviceApp = new ServiceApp {
                Name = "Test", AppVersion = new Version()
            };
            ServiceAppProcess appProcToTest = new ServiceAppProcess(serviceApp, log, procFactory);
            Exception         testException = new InvalidOperationException("test");

            string exceptionMessage = string.Format(@"{{ error: {{
                    details: {{
                        type: ""{0}"",
                        message: ""{1}"",
                        source: ""{2}"",
                        stackTrace: ""{3}""
                    }},
                    exception: ""xxxxx""
                }} }}",
                                                    testException.GetType().ToString(),
                                                    testException.Message,
                                                    testException.Source,
                                                    testException.StackTrace);

            bool shouldExit = appProcToTest.ProcessMessage(exceptionMessage);

            log.Received().Warn(Arg.Any <string>());
            Assert.IsFalse(shouldExit, "Process message was not meant to return true");
        }
Exemple #3
0
        /// <summary>
        /// Sends the telecontrol command.
        /// </summary>
        public void SendCommand(ServiceApp serviceApp, TeleCommand cmd)
        {
            // initialize command ID and timestamp
            DateTime utcNow = DateTime.UtcNow;

            if (cmd.CommandID == 0)
            {
                cmd.CommandID = ScadaUtils.GenerateUniqueID(utcNow);
            }

            if (cmd.CreationTime == DateTime.MinValue)
            {
                cmd.CreationTime = utcNow;
            }

            // upload command
            using (MemoryStream stream = new MemoryStream())
            {
                cmd.Save(stream);
                stream.Position = 0;

                string fileName = string.Format("cmd_{0}.dat", cmd.CommandID);
                UploadFile(stream, new RelativePath(serviceApp, AppFolder.Cmd, fileName), out bool fileAccepted);

                if (!fileAccepted)
                {
                    throw new ScadaException(Locale.IsRussian ?
                                             "Команда отклонена Агентом." :
                                             "Command rejected by Agent.");
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Shows the service app details.
        /// </summary>
        /// <param name="serviceApp">The service app.</param>
        /// <param name="isReadOnly">If set to <c>true</c> show the details as read only.</param>
        private void ShowServiceAppDetails(ServiceApp serviceApp, bool isReadOnly)
        {
            if (serviceApp == null)
            {
                serviceApp = new Models.ServiceApp
                {
                    StartupTypeEnum = Enums.StartupType.NotSet,
                    Schedule        = string.Empty
                };
            }

            this.ServiceAppNameLabel.Content = this.ServiceAppNameTextBox.Text = serviceApp.Name;
            this.MessageLabel.Text           = serviceApp.LastMessage;

            this.StartServiceAppButton.IsEnabled = serviceApp.CanStart && isReadOnly;
            this.StopServiceAppButton.IsEnabled  = serviceApp.CanStop && isReadOnly;
            this.RunButton.IsEnabled             = serviceApp.CanRun && isReadOnly;

            this.StartupTypeLabel.Text             = serviceApp.StartupTypeEnum.GetName();
            this.StartupTypeComboBox.SelectedValue = serviceApp.StartupTypeEnum;
            this.ServiceAppDescriptionLabel.Text   = this.DescriptionTextBox.Text = serviceApp.Description;
            this.ServiceAppEnvironmentLabel.Text   = this.ServiceAppEnvironmentTextBox.Text = serviceApp.Environment;
            this.ServiceAppParameterLabel.Text     = this.ParameterTextBox.Text = serviceApp.Parameters;
            this.AppFilePathLabel.Text             = this.AppFilePathTextBox.Text = serviceApp.AppFilePath;
            this.AppFilePathViewButton.IsEnabled   = !string.IsNullOrWhiteSpace(serviceApp.AppFilePath);
            this.SendSuccessCheckBox.IsChecked     = serviceApp.SendSuccessNotification;
            this.IdentityLabel.Text       = this.IdentityLabel.Text = serviceApp.Username;
            this.PasswordHiddenLabel.Text = serviceApp.Password;
            this.ScheduleLabel.Text       = ScheduleUtility.GetFullDescription(serviceApp.Schedule);
            this.ScheduleHiddenLabel.Text = serviceApp.Schedule;

            this.EditServiceAppButton.IsEnabled = !serviceApp.CanRun;
            this.EditMessageTextBlock.Text      = serviceApp.CanRun ? "Stop the app before making changes" : null;
        }
Exemple #5
0
        /// <summary>
        /// Starts the underlying process for the service app.
        /// </summary>
        private void StartProcess()
        {
            // only add the password when it's time to start the process.
            _process.StartInfo.Password = ServiceApp.Password.DecryptString(EntropyValue);
            bool hasError = false;

            try
            {
                // Update the version info here so that any issues with the app start are grouped together
                ServiceApp.RefreshAppVersion();
                AddMessage("Starting service app", ServiceAppState.Unknown);
                _process.Start();
            }
            catch (Exception e)
            {
                _log.Error(string.Format("Error starting service app {0}", ServiceApp.Name), e);
                AddMessage(e.Message, ServiceAppState.NotLoaded);
                hasError = true;
            }

            if (!hasError)
            {
                MonitorProcessCallback();
            }
        }
        /// <summary>
        /// Writes contents of the varchar type.
        /// </summary>
        private void WriteVarcharContents(string tableName, ServiceApp app, string path, string contents)
        {
            string sql =
                $"INSERT INTO {tableName} (app_id, path, contents, write_time) " +
                "VALUES (@appID, @path, @contents, @writeTime) " +
                "ON CONFLICT (app_id, path) DO UPDATE SET contents = @contents, write_time = @writeTime";

            NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);

            cmd.Parameters.AddWithValue("appID", (int)app);
            cmd.Parameters.AddWithValue("path", NormalizePath(path));
            cmd.Parameters.AddWithValue("writeTime", DateTime.UtcNow);
            cmd.Parameters.AddWithValue("contents",
                                        string.IsNullOrEmpty(contents) ? (object)DBNull.Value : contents);

            try
            {
                Monitor.Enter(conn);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            finally
            {
                conn.Close();
                Monitor.Exit(conn);
            }
        }
Exemple #7
0
        /// <summary>
        /// Casts to service app.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns></returns>
        internal static ServiceApp CastToServiceApp(XElement element)
        {
            if (element == null || element.Name != "serviceApp")
            {
                return(null);
            }

            bool sendSuccess = false;

            bool.TryParse(element.Attribute("sendSuccess").EmptyIfNull("sendSuccess").Value, out sendSuccess);

            ServiceApp app = new ServiceApp
            {
                Name                    = element.Attribute("name").Value,
                Description             = element.Attribute("description").Value,
                Environment             = element.Attribute("environment").Value,
                AppFilePath             = element.Attribute("appFilePath").Value,
                Parameters              = element.Attribute("parameters").EmptyIfNull("parameters").Value,
                SendSuccessNotification = sendSuccess,
                StartupTypeEnum         = EnumHelper.Parse <StartupType>(element.Attribute("startupType").Value),
                Schedule                = element.Attribute("schedule").Value,
                Username                = element.Attribute("username").EmptyIfNull("username").Value,
                Password                = element.Attribute("password").EmptyIfNull("password").Value
            };

            return(app);
        }
        /// <summary>
        /// Gets the current status of the specified service asynchronously.
        /// </summary>
        private async Task GetServiceStatusAsync(IAgentClient client, ServiceApp serviceApp, TextBox statusTextBox)
        {
            await Task.Run(() =>
            {
                if (client == null)
                {
                    return;
                }

                try
                {
                    lock (client)
                    {
                        bool statusOK = client.GetServiceStatus(serviceApp, out ServiceStatus status);

                        if (connected)
                        {
                            statusTextBox.Text = statusOK
                                ? status.ToString(Locale.IsRussian)
                                : CommonPhrases.UndefinedSign;
                            txtUpdateTime.Text = DateTime.Now.ToLocalizedString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (connected)
                    {
                        statusTextBox.Text = ex.Message;
                        txtUpdateTime.Text = DateTime.Now.ToLocalizedString();
                    }
                }
            });
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Console.WriteLine("Hello!");
            Console.WriteLine(args[0]);
            XmlConfigurator.Configure(new System.IO.FileInfo(args[0]));
            IDictionary <String, string> props = new SortedList <String, String>();

            props.Add("ConnectionString", GetConnectionStringByName("labDB"));
            RepoDbContestant   repoDbContestant   = new RepoDbContestant(props);
            RepoDbOfficePers   repoDbOffice       = new RepoDbOfficePers(props);
            RepoDbRace         repoDbRace         = new RepoDbRace(props);
            RepoDbRegistration repoDbRegistration = new RepoDbRegistration(props);

            ServiceApp service = new ServiceApp(repoDbContestant, repoDbOffice, repoDbRace, repoDbRegistration);
            //repoTests repo1 = new repoTests();
            //repo1.test();

            Login login = new Login();

            login.Service = service;
            Application.Run(login);
        }
        public void Start(string[] args)
        {
            var basepath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            application = new ServiceApp(basepath, args);
            appTask     = application.Start();
        }
Exemple #11
0
        /// <summary>
        /// Persists the service app.
        /// </summary>
        /// <param name="app">The application.</param>
        public void PersistServiceApp(ServiceApp app)
        {
            var appElement = this.AppListDoc.Root.Element("collection").Elements().FirstOrDefault(e => e.Attribute("name").Value == app.Name);

            if (appElement == null)
            {
                appElement = new XElement("serviceApp");
                this.AppListDoc.Root.Element("collection").Add(appElement);
            }

            bool isBackedUp = this.TryBackupXmlFile(app, TryCastToServiceApp(appElement));

            appElement.ReplaceAttributes(
                new XAttribute("name", app.Name),
                new XAttribute("description", app.Description),
                new XAttribute("environment", app.Environment),
                new XAttribute("appFilePath", app.AppFilePath),
                new XAttribute("parameters", app.Parameters ?? string.Empty),
                new XAttribute("startupType", app.StartupType),
                new XAttribute("sendSuccess", app.SendSuccessNotification),
                new XAttribute("schedule", app.Schedule),
                new XAttribute("username", app.Username),
                new XAttribute("password", app.Password));

            if (this._isLoadFromFile && isBackedUp)
            {
                this.AppListDoc.Save(Path.GetFullPath(ApplicationSettings.Current.AppListLocation));
            }
        }
        public bool CheckAuth(string appId, long timestamp, string path, string sign)
        {
            ServiceApp serviceApp = this._repository.GetServiceAppById(appId);

            if (serviceApp == null)
            {
                return(false);
            }

            if (serviceApp.LockoutEnd != null && serviceApp.LockoutEnd.Value > DateTime.Now)
            {
                throw new AuthException($"The appid {appId} is locked. ", null)
                      {
                          Code = (int)HttpStatusCode.NotAcceptable,
                      };
            }

            string matchedSign = HashUtils.OpenApiSign(appId, serviceApp.AppSecret, timestamp, path);

            if (matchedSign.Equals(sign, StringComparison.InvariantCultureIgnoreCase))
            {
                return(true);
            }

            return(false);
        }
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceAppSuccessEventArgs"/> class.
 /// </summary>
 /// <param name="serviceApp">The service app to create the success data from.</param>
 /// <param name="finishTime">The time the service app finished executing.</param>
 public ServiceAppSuccessEventArgs(ServiceApp serviceApp, DateTime finishTime)
 {
     this.Name = serviceApp.Name;
     this.SendSuccessNotification = serviceApp.SendSuccessNotification;
     this.Environment             = serviceApp.Environment;
     this.FinishTime = finishTime;
 }
Exemple #14
0
        /// <summary>
        /// Управлять службой
        /// </summary>
        public bool ControlService(ServiceApp serviceApp, ServiceCommand command)
        {
            try
            {
                string batchFileName = Path.Combine(Settings.Directory,
                                                    DirectoryBuilder.GetDirectory(serviceApp), GetServiceBatchFile(command));

                if (File.Exists(batchFileName))
                {
                    Process.Start(new ProcessStartInfo()
                    {
                        FileName        = batchFileName,
                        UseShellExecute = false
                    });
                    return(true);
                }
                else
                {
                    log.WriteError(string.Format(Localization.UseRussian ?
                                                 "Не найден файл для управления службой {0}" :
                                                 "File {0} for service control not found", batchFileName));
                    return(false);
                }
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при управлении службой" :
                                   "Error controlling service");
                return(false);
            }
        }
        /// <summary>
        /// Reads contents of the varchar type.
        /// </summary>
        private string ReadVarcharContents(string tableName, ServiceApp app, string path)
        {
            string        sql = $"SELECT contents FROM {tableName} WHERE app_id = @appID AND path = @path LIMIT 1";
            NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);

            cmd.Parameters.AddWithValue("appID", (int)app);
            cmd.Parameters.AddWithValue("path", NormalizePath(path));

            try
            {
                Monitor.Enter(conn);
                conn.Open();

                using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                {
                    if (reader.Read())
                    {
                        return(reader.IsDBNull(0) ? "" : reader.GetString(0));
                    }
                }
            }
            finally
            {
                conn.Close();
                Monitor.Exit(conn);
            }

            throw new FileNotFoundException(string.Format(CommonPhrases.NamedFileNotFound, path));
        }
        /// <summary>
        /// Sends the command to the service.
        /// </summary>
        private static void ControlService(IAgentClient client, ServiceApp serviceApp, ServiceCommand command)
        {
            if (client == null)
            {
                return;
            }

            try
            {
                bool commandResult;
                lock (client)
                {
                    commandResult = client.ControlService(serviceApp, command, 0);
                }

                if (commandResult)
                {
                    ScadaUiUtils.ShowInfo(AppPhrases.ControlServiceSuccessful);
                }
                else
                {
                    ScadaUiUtils.ShowError(AppPhrases.UnableControlService);
                }
            }
            catch (Exception ex)
            {
                ScadaUiUtils.ShowError(ex.BuildErrorMessage(AppPhrases.ControlServiceError));
            }
        }
        private void btn_remove_Click(object sender, EventArgs e)
        {
            Apps       apps       = QuickConfig.Common.setXml.getConfig(ConfigName).Apps;
            ServiceApp serviceapp = apps.ServiceAppList.Find((ServiceApp gx) => gx.Name == this.Name);

            setBAT.AppServiceRemove(serviceapp.Path, serviceapp.Removebat, true);
            this.service_state.Text = Common.getServiceState(serviceapp.Servicename);
        }
Exemple #18
0
        /// <summary>
        /// Gets the current status of the specified service.
        /// </summary>
        public bool GetServiceStatus(ServiceApp serviceApp, out ServiceStatus serviceStatus)
        {
            RestoreConnection();
            bool result = client.GetServiceStatus(out serviceStatus, sessionID, serviceApp);

            RegisterActivity();
            return(result);
        }
Exemple #19
0
        /// <summary>
        /// Sends the command to the service.
        /// </summary>
        public bool ControlService(ServiceApp serviceApp, ServiceCommand command)
        {
            RestoreConnection();
            bool result = client.ControlService(sessionID, serviceApp, command);

            RegisterActivity();
            return(result);
        }
        private void btn_stop_Click(object sender, EventArgs e)
        {
            Apps       apps       = QuickConfig.Common.setXml.getConfig(ConfigName).Apps;
            ServiceApp serviceapp = apps.ServiceAppList.Find((ServiceApp gx) => gx.Name == this.Name);

            setBAT.ServiceStop(Common.getToolsFolder(), Common.getToolsTempFolder(), serviceapp.Label, serviceapp.Servicename, true);
            this.service_state.Text = Common.getServiceState(serviceapp.Servicename);
        }
Exemple #21
0
 /// <summary>
 /// Selects the specified service app, or deselects if null is passed in
 /// </summary>
 /// <param name="serviceApp">The service app.</param>
 /// <param name="isReadOnly">If the service should be shown as read-only. Default is true.</param>
 public void SelectServiceApp(ServiceApp serviceApp, bool isReadOnly = true)
 {
     this._inEditMode = !isReadOnly;
     this.UpdateInputFieldsVisibility(!isReadOnly);
     this._selectedServiceApp = serviceApp;
     this.ShowServiceAppDetails(this._selectedServiceApp, isReadOnly);
     _currentEntropyValue = null; // Important to reset this when selecting any service app.
 }
Exemple #22
0
 /// <summary>
 /// Prevents a default instance of the <see cref="ServiceAppProcess"/> class from being created.
 /// </summary>
 private ServiceAppProcess()
 {
     // For use by tests. I'm sure there's a better way, but at the time I didn't
     // want to be concerned with the workings of the process wrapper in the tests that relied
     // on this (and was too lazy to create an abstraction and change usage all over)
     ServiceApp = new ServiceApp {
         Name = "__Test"
     };
 }
Exemple #23
0
 public void SetValue(ServiceApp serviceApp)
 {
     this._name = serviceApp.Name;
     this.service_label.Text      = serviceApp.Label;
     this.service_folderPath.Text = serviceApp.Path;
     this._configFolder           = serviceApp.ConfigFolder;
     this.service_ip.Text         = serviceApp.Ip;
     this.service_port.Text       = serviceApp.Port;
 }
Exemple #24
0
        /// <summary>
        /// Получить статус службы
        /// </summary>
        public bool GetServiceStatus(ServiceApp serviceApp, out ServiceStatus status)
        {
            try
            {
                status = ServiceStatus.Undefined;
                string statusFileName = Path.Combine(Settings.Directory,
                                                     DirectoryBuilder.GetDirectory(serviceApp),
                                                     DirectoryBuilder.GetDirectory(AppFolder.Log),
                                                     GetServiceStatusFile(serviceApp));

                if (File.Exists(statusFileName))
                {
                    string[] lines = File.ReadAllLines(statusFileName, Encoding.UTF8);

                    foreach (string line in lines)
                    {
                        if (line.StartsWith("State", StringComparison.Ordinal) ||
                            line.StartsWith("Состояние", StringComparison.Ordinal))
                        {
                            int colonInd = line.IndexOf(':');

                            if (colonInd > 0)
                            {
                                string statusStr = line.Substring(colonInd + 1).Trim();

                                if (statusStr.Equals("normal", StringComparison.OrdinalIgnoreCase) ||
                                    statusStr.Equals("норма", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Normal;
                                }
                                else if (statusStr.Equals("stopped", StringComparison.OrdinalIgnoreCase) ||
                                         statusStr.Equals("остановлен", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Stopped;
                                }
                                else if (statusStr.Equals("error", StringComparison.OrdinalIgnoreCase) ||
                                         statusStr.Equals("ошибка", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Error;
                                }
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при получении статуса службы" :
                                   "Error getting service status");
                status = ServiceStatus.Undefined;
                return(false);
            }
        }
Exemple #25
0
        static void Main(string[] args)
        {
            EchoClientApp.InitCodes();

            ServiceApp.RegisterApp <EchoClientApp>("client");
            ServiceApp.RegisterApp <EchoServerApp>("server");

            string[] args2 = (new string[] { "echo.exe" }).Union(args).ToArray();
            Native.dsn_run(args2.Length, args2, true);
        }
Exemple #26
0
        /// <summary>
        /// Handles the Click event of the SaveServiceAppButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void SaveServiceAppButton_Click(object sender, RoutedEventArgs e)
        {
            ServiceApp serviceApp = this.BuildServiceAppFromInput();

            if (serviceApp != null)
            {
                this._presenter.UpdateServiceApp(serviceApp);
                this._inEditMode = false;
                this.UpdateInputFieldsVisibility(false);
            }
        }
Exemple #27
0
 public bool ControlService(long sessionID, ServiceApp serviceApp, ServiceCommand command)
 {
     if (TryGetScadaInstance(sessionID, out var scadaInstance))
     {
         return(scadaInstance.ControlService(serviceApp, command));
     }
     else
     {
         return(false);
     }
 }
Exemple #28
0
        static void Main(string[] args)
        {
            echoHelper.InitCodes();

            ServiceApp.RegisterApp <echoServerApp>("server");
            ServiceApp.RegisterApp <echoClientApp>("client");
            //ServiceApp.RegisterApp<echoPerfTestClientApp>("client.echo.perf.test");

            var args2 = (new string[] { "echo" }).Union(args).ToArray();

            Native.dsn_run(args2.Length, args2, true);
        }
Exemple #29
0
 public bool GetServiceStatus(long sessionID, ServiceApp serviceApp, out ServiceStatus status)
 {
     if (TryGetScadaInstance(sessionID, out var scadaInstance))
     {
         return(scadaInstance.GetServiceStatus(serviceApp, out status));
     }
     else
     {
         status = ServiceStatus.Undefined;
         return(false);
     }
 }
Exemple #30
0
        /// <summary>
        /// Starts the service application.
        /// </summary>
        /// <param name="serviceApp">The service app to start.</param>
        public void StartServiceApp(ServiceApp serviceApp)
        {
            this.TryExecute(
                () =>
            {
                IServiceAppClient client = this.factory.Create <IServiceAppClient>();
                client.StartServiceApp(serviceApp.Name);
            },
                true);

            this.LoadServiceApps();
        }