Exemplo n.º 1
0
        /// <summary>
        /// Metodo responsável por iniciar os serviços do UniNFe em threads diferentes
        /// </summary>
        public void ExecutaServicos(bool updateOptions = true)
        {
            if (servicoInstaladoErodando)
            {
                Empresas.CarregaConfiguracao();

                switch (ServiceProcess.StatusService(srvName))
                {
                case System.ServiceProcess.ServiceControllerStatus.Stopped:
                    ServiceProcess.StartService(srvName, 40000);
                    break;

                case System.ServiceProcess.ServiceControllerStatus.Paused:
                    ServiceProcess.RestartService(srvName, 40000);
                    break;
                }
                if (updateOptions)
                {
                    this.updateControleDoServico();
                }
            }
            else
            {
                ThreadService.Start();
            }
        }
        /// <summary>
        /// Main method performing CoreService call to retrieve all AppData for the given item Uri
        /// </summary>
        /// <param name="process">ServiceProcee the async process to use</param>
        /// <param name="arguments">parameter object with item TcmUri to retrieve AppData for</param>
        public override void Process(ServiceProcess process, object arguments)
        {
            _data = new List <AppDataInspectorData>();

            AppDataInspectorParameters parameters = (AppDataInspectorParameters)arguments;

            process.SetCompletePercentage(10);
            process.SetStatus(Resources.ProgressStatusInitializing);

            using (var coreService = Client.GetCoreService())
            {
                process.SetCompletePercentage(20);
                process.SetStatus(Resources.AppDataInspectorRetrievingData);

                ApplicationData[] appDataList       = coreService.ReadAllApplicationData(parameters.ItemUri).OrderBy(data => data.ApplicationId).ToArray();
                double            progressIncrement = appDataList.Length == 0 ? 0 : 80 / appDataList.Length;      //nasty progress calculation
                int i = 1;

                foreach (ApplicationData appData in appDataList)
                {
                    _data.Add(new AppDataInspectorData                     // create response data object and add it to response data collection
                    {
                        ApplicationId = appData.ApplicationId,
                        Value         = ByteArrayToObject(appData).ToString(),
                        Type          = appData.TypeId
                    });

                    int progressPercentage = (int)(20 + i * progressIncrement);                     // some more nasty progress calculation
                    process.SetCompletePercentage(progressPercentage);
                    i++;
                }

                process.Complete(Resources.ProgressStatusComplete);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Metodo responsável por iniciar os serviços do UniNFe em threads diferentes
        /// </summary>
        private void ExecutaServicos()
        {
            Empresa.CarregaConfiguracao();

            if (servicoInstaladoErodando)
            {
                if (restartServico)
                {
                    ServiceProcess.StopService(srvName, 40000);
                }

                restartServico = false;

                switch (ServiceProcess.StatusService(srvName))
                {
                case System.ServiceProcess.ServiceControllerStatus.Stopped:
                    ServiceProcess.StartService(srvName, 40000);
                    break;

                case System.ServiceProcess.ServiceControllerStatus.Paused:
                    ServiceProcess.RestartService(srvName, 40000);
                    break;
                }
                this.updateControleDoServico();
            }
            else
            {
                ThreadService.Start();
            }
        }
Exemplo n.º 4
0
        private void InstallMsu(DtoClientFileHash file)
        {
            var directory = Path.Combine(DtoGobalSettings.BaseCachePath, _module.Guid) + Path.DirectorySeparatorChar;
            var pArgs     = new DtoProcessArgs();

            pArgs.RunWith          = "wusa.exe";
            pArgs.Command          = "\"" + directory + file.FileName + "\"";
            pArgs.Arguments        = "/quiet /norestart " + _module.Arguments;
            pArgs.Timeout          = _module.Timeout;
            pArgs.WorkingDirectory = directory;
            pArgs.RedirectError    = _module.RedirectError;
            pArgs.RedirectOutput   = _module.RedirectOutput;

            var result = new ServiceProcess(pArgs).RunProcess();

            Logger.Info(JsonConvert.SerializeObject(result));
            Logger.Info("Windows Update Module: " + _module.DisplayName + "Finished");

            _moduleResult.ExitCode = result.ExitCode.ToString();
            if (!_module.SuccessCodes.Contains(result.ExitCode.ToString()))
            {
                _moduleResult.Success      = false;
                _moduleResult.ErrorMessage = result.StandardError;
            }
        }
Exemplo n.º 5
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                foreach (var item in ServiceProcess.GetBatch())
                {
                    FeriadosPromaxModel result = await ServiceFeriado.FindById(item.Id);

                    if (result.NomeFeriado is not null && result.NomePais is not null)
                    {
                        var bifrostModel  = FeriadosDTO.TransferData(result);
                        var output        = OutputModel.Build(item.Timestamp, GetOperationEnum(item.Operator), "feriado", bifrostModel);
                        var resultPublish = Broker.PublishToQueue(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(output)), "PROMAX_VISITA_FERIADO");

                        if (resultPublish)
                        {
                            if (!await ServiceProcess.DeleteById(item.Id))
                            {
                                throw new Exception($"Id {item.Id} Not Found");
                            }
                        }
                    }
                }

                Task.Delay(5000).Wait();
            }
        }
Exemplo n.º 6
0
        public override void Process(ServiceProcess process, object arguments)
        {
            FieldRemoverParameters parameters = (FieldRemoverParameters)arguments;

            if (!Directory.Exists(parameters.Directory))
            {
                throw new BaseServiceException(string.Format(CultureInfo.InvariantCulture, "Directory '{0}' does not exist.", parameters.Directory));
            }

            var client = PowerTools.Common.CoreService.Client.GetCoreService();

            try
            {
                string[] files = Directory.GetFiles(parameters.Directory);
                int      i     = 0;

                foreach (string file in files)
                {
                    process.SetStatus("Importing image: " + Path.GetFileName(file));
                    process.SetCompletePercentage(++i * 100 / files.Length);
                    System.Threading.Thread.Sleep(500);                     // Temp, until it actually does something :)
                }

                process.Complete();
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
Exemplo n.º 7
0
 public void updateControleDoServico()
 {
     if (servicoInstaladoErodando)
     {
         this.tbPararServico.Enabled   = ServiceProcess.StatusService(srvName) == System.ServiceProcess.ServiceControllerStatus.Running;
         this.tbRestartServico.Enabled = ServiceProcess.StatusService(srvName) == System.ServiceProcess.ServiceControllerStatus.Stopped;
     }
 }
Exemplo n.º 8
0
 // Start is called before the first frame update
 void Start()
 {
     serviceProcess   = GameObject.FindGameObjectWithTag("DriveThruWindow").GetComponent <ServiceProcess>();
     arrivalMechanism = GameObject.FindGameObjectWithTag("CarSpawn").GetComponent <ArrivalMechanism>();
     dropDown         = GameObject.FindGameObjectWithTag("Dropdown").GetComponent <Dropdown>();
     slider           = GameObject.FindGameObjectWithTag("Slider").GetComponent <Slider>();
     serviceRate      = GameObject.FindGameObjectWithTag("ServiceRate").GetComponent <InputField>();
     arrivalRate      = GameObject.FindGameObjectWithTag("ArrivalRate").GetComponent <InputField>();
 }
Exemplo n.º 9
0
        private static void RunTestService(RunnerMode runnerMode, int parentPid, CommunicationProtocol protocol, string[] assemblyPaths)
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;

            foreach (var assemblyPath in assemblyPaths)
            {
                Console.Write($"Loading {assemblyPath}... ");
                Assembly.LoadFrom(assemblyPath);
                Console.WriteLine("Done.");
            }

            Process parentProcess = null;

            try
            {
                parentProcess = Process.GetProcessById(parentPid);
                parentProcess.EnableRaisingEvents = true;
                parentProcess.Exited += OnParentProcessExited;
            }
            catch (Exception e)
            {
                throw new Exception("Cannot open parent process.", e);
            }

            Type serviceInterface;
            Type serviceImplementation;

            GetService(runnerMode, out serviceInterface, out serviceImplementation);

            Console.WriteLine("AxoCover.Runner");
            Console.WriteLine("Copyright (c) 2016-2017 Péter Major");
            Console.WriteLine();

            Console.WriteLine($"Starting {runnerMode} service...");
            var serviceAddress = NetworkingExtensions.GetServiceAddress(protocol);
            var serviceBinding = NetworkingExtensions.GetServiceBinding(protocol);

            var serviceHost = new ServiceHost(serviceImplementation, new[] { serviceAddress });

            serviceHost.AddServiceEndpoint(serviceInterface, serviceBinding, serviceAddress);
            serviceHost.Open();
            ServiceProcess.PrintServiceStarted(serviceAddress);

            _isFinished.WaitOne();
            Console.WriteLine("Exiting...");
            try
            {
                serviceHost.Close(_closeTimeout);
            }
            catch { }

            //Make sure to kill leftover non-background threads started by tests
            Environment.Exit(0);
        }
Exemplo n.º 10
0
        public override void Process(ServiceProcess process, object arguments)
        {
            while (process.PercentComplete < 100)
            {
                process.IncrementCompletePercentage();
                process.SetStatus("Loading...");

                Random rnd = new Random(DateTime.Now.GetHashCode());
                Thread.Sleep(((int)(rnd.NextDouble() * 4) + 10) * 10);
            }
            process.Complete();
        }
Exemplo n.º 11
0
        public ServiceProcess ExecuteAsync(object arguments)
        {
            ServiceProcess       newProcess    = new ServiceProcess();
            ServiceProcessHelper storedProcess = new ServiceProcessHelper(newProcess);

            OperationContext.Current.InstanceContext.Extensions.Add(storedProcess);
            ExecuteData executeData = new ExecuteData {
                Process = storedProcess.Process, Arguments = arguments
            };

            ThreadPool.QueueUserWorkItem(WorkerThread, executeData);
            return(newProcess);
        }
Exemplo n.º 12
0
        private static void Main(string[] args)
        {
            bool debugMode = false;

            try
            {
                const int             argumentCount = 4;
                RunnerMode            runnerMode;
                int                   parentPid;
                CommunicationProtocol protocol;
                string[]              assemblyPaths;

                if (args.Length < argumentCount ||
                    !Enum.TryParse(args[0], true, out runnerMode) ||
                    !int.TryParse(args[1], out parentPid) ||
                    !Enum.TryParse(args[2], true, out protocol) ||
                    !bool.TryParse(args[3], out debugMode) ||
                    !args.Skip(argumentCount).All(p => File.Exists(p)))
                {
                    throw new Exception("Arguments are invalid.");
                }

                assemblyPaths = args.Skip(argumentCount).ToArray();

                if (debugMode)
                {
                    AppDomain.CurrentDomain.FirstChanceException += (o, e) => Console.WriteLine(e.Exception.GetDescription().PadLinesLeft("   "));
                }

                RunTestService(runnerMode, parentPid, protocol, assemblyPaths);
            }
            catch (Exception e)
            {
                if (debugMode)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    else
                    {
                        Debugger.Launch();
                    }
                }

                var crashFilePath = Path.GetTempFileName();
                var crashDetails  = JsonConvert.SerializeObject(new SerializableException(e));
                File.WriteAllText(crashFilePath, crashDetails);
                ServiceProcess.PrintServiceFailed(crashFilePath);
            }
        }
        public async Task RestartServerAsync(Context context)
        {
            if (_doNotStartService)
            {
                throw new InvalidOperationException();
            }

            await _serviceProcess.ShutdownAsync(context).ShouldBeSuccess();

            _serviceProcess.Dispose();

            _serviceProcess = new ServiceProcess(_configuration, _localContentServerConfiguration, Configuration.Scenario, WaitForServerReadyTimeoutMs, WaitForExitTimeoutMs);
            await _serviceProcess.StartupAsync(context).ShouldBeSuccess();
        }
Exemplo n.º 14
0
 public void PararServicos(bool fechaServico)
 {
     if (servicoInstaladoErodando)
     {
         if (fechaServico)
         {
             ServiceProcess.StopService(srvName, 40000);
         }
     }
     else
     {
         ThreadService.Stop();
     }
 }
Exemplo n.º 15
0
        public override void Process(ServiceProcess process, object arguments)
        {
            PagePublisherParameters parameters = (PagePublisherParameters)arguments;

            process.SetCompletePercentage(0);
            process.SetStatus("Initializing");

            using (var coreService = Client.GetCoreService())
            {
                _pagePublisherData = new PagePublisherData();
                // get a list of the items from the core service
                ItemsFilterData filter  = GetFilter(parameters);
                XElement        listXml = coreService.GetListXml(parameters.LocationId, filter);

                // Get the page id's that will be published
                string[] pageIds      = GetPageIds(listXml);
                int      batchSize    = 5;
                int      currentBatch = 0;

                // Publish pages
                try
                {
                    double ratio      = pageIds.Count() / batchSize;
                    double percentage = 100 / ratio;
                    double currperc   = 0;
                    while (currentBatch * batchSize < pageIds.Count())
                    {
                        string[] nextBatch = pageIds.Skip(currentBatch * batchSize)
                                             .Take(batchSize).ToArray();
                        coreService.Publish(nextBatch, GetPublishInstructionData(parameters), parameters.TargetUri, parameters.Priority, new ReadOptions());
                        currentBatch++;
                        currperc += percentage;
                        if (currperc >= 1)
                        {
                            process.IncrementCompletePercentage();
                            currperc = 0;
                        }
                    }
                    _pagePublisherData.SuccessMessage = string.Format("{0} Pages published successfully", pageIds.Length.ToString());
                }
                catch (Exception ex)
                {
                    //process.Complete(string.Format("Failed to publish, reason: {0}", ex.Message));
                    _pagePublisherData.FailedMessage = string.Format("Page publishing failed, reason {0}", ex.Message);
                }

                process.Complete("done");
            }
        }
        public TestServiceClientContentStore(
            ILogger logger,
            IAbsFileSystem fileSystem,
            ServiceClientContentStoreConfiguration configuration,
            TimeSpan?heartbeatInterval,
            ServiceConfiguration serviceConfiguration,
            LocalServerConfiguration localContentServerConfiguration = null)
            : base(logger, fileSystem, configuration)
        {
            _logger = logger;

            _localContentServerConfiguration = localContentServerConfiguration;
            _serviceProcess    = new ServiceProcess(_configuration, localContentServerConfiguration, configuration.Scenario, WaitForServerReadyTimeoutMs, WaitForExitTimeoutMs);
            _configuration     = serviceConfiguration;
            _heartbeatInterval = heartbeatInterval;
        }
Exemplo n.º 17
0
 /// <summary>
 /// Stop the test driver, and shutdown the sqltoolsservice executable
 /// </summary>
 public async Task Stop()
 {
     if (IsCoverageRun)
     {
         // Kill all the processes in the list
         foreach (Process p in serviceProcesses.Where(p => !p.HasExited))
         {
             p.Kill();
         }
         ServiceProcess?.WaitForExit();
     }
     else
     {
         await this.protocolClient.Stop();
     }
 }
Exemplo n.º 18
0
        public override void Process(ServiceProcess process, object arguments)
        {
            DecommissionParameters parameters = (DecommissionParameters)arguments;

            using (var coreService = Client.GetCoreService())
            {
                process.SetCompletePercentage(25);
                try
                {
                    coreService.DecommissionPublicationTarget(parameters.ItemUri);
                    process.Complete();
                }
                catch (Exception e)
                {
                    process.SetStatus(e.Message);
                    process.Failed = true;
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Contains actual processing logic: instantiates a CoreService client, queries for item list,
        /// then sets the actual response counts data object, while updating the progress all along.
        /// </summary>
        /// <param name="process">the current ServiceProcess</param>
        /// <param name="arguments">CountItemsParameters arguments</param>
        public override void Process(ServiceProcess process, object arguments)
        {
            CountItemsParameters parameters = (CountItemsParameters)arguments;

            process.SetCompletePercentage(25);
            process.SetStatus("Initializing");

            using (var coreService = Client.GetCoreService())
            {
                ItemsFilterData filter = GetFilter(parameters);
                process.SetCompletePercentage(50);
                process.SetStatus("Retrieving count data");

                XElement listXml = coreService.GetListXml(parameters.OrgItemUri, filter);
                process.SetCompletePercentage(75);
                process.SetStatus("Extracting item counts");

                ProcessCounts(listXml);
                process.Complete("Done");
            }
        }
Exemplo n.º 20
0
        private void tbRestartServico_Click(object sender, EventArgs e)
        {
            FormWait fw = new FormWait();

            fw.Show();
            try
            {
                fw.DisplayMessage("Reiniciando o serviço do UniNFe");
                ServiceProcess.RestartService(srvName, 40000);
                this.updateControleDoServico();
                fw.StopMarquee();
                MessageBox.Show("Serviço do UniNFe reiniciado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                fw.Dispose();
            }
        }
Exemplo n.º 21
0
        public override void Process(ServiceProcess process, object arguments)
        {
            MarkUnpublishedParameters parameters = (MarkUnpublishedParameters)arguments;

            if (string.IsNullOrEmpty(parameters.OrgItemURI))
            {
                throw new BaseServiceException(string.Format(CultureInfo.InvariantCulture, "parameters.OrgItemURI is null or empty"));
            }

            var client = PowerTools.Common.CoreService.Client.GetCoreService();

            try
            {
                process.Complete();
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
Exemplo n.º 22
0
        private async Task RunServerTestAsync(Context context, Func <Context, ServiceConfiguration, Task> funcAsync)
        {
            using (var directory = new DisposableDirectory(FileSystem))
            {
                var storeConfig = CreateStoreConfiguration();
                await storeConfig.Write(FileSystem, directory.Path).ConfigureAwait(false);

                var serviceConfig = CreateServiceConfiguration(directory.Path, PortExtensions.GetNextAvailablePort(), Guid.NewGuid().ToString());

                using (var server = new ServiceProcess(serviceConfig, LocalContentServerConfiguration, Scenario, WaitForServerReadyTimeoutMs, WaitForExitTimeoutMs))
                {
                    BoolResult r = await server.StartupAsync(context).ConfigureAwait(false);

                    r.ShouldBeSuccess();

                    await funcAsync(context, serviceConfig);

                    r = await server.ShutdownAsync(context);

                    r.ShouldBeSuccess();
                }
            }
        }
        public override void Process(ServiceProcess process, object arguments)
        {
            CompSyncParameters parameters = (CompSyncParameters)arguments;

            if (parameters.SelectedUrIs == null)
            {
                throw new BaseServiceException(string.Format(CultureInfo.InvariantCulture, "List '{0}' is null.", parameters.SelectedUrIs));
            }

            var client = Client.GetCoreService();

            try
            {
                int           i = 0;
                ComponentData ReferenceComponentData = client.Read(parameters.ReferenceComponentUri, new ReadOptions()) as ComponentData;

                foreach (string uri in parameters.SelectedUrIs)
                {
                    ComponentData currentComponent = client.Read(uri, new ReadOptions()) as ComponentData;
                    process.SetStatus("Synchronizing: " + currentComponent.Title);
                    _processedItems.Add(uri);
                    process.SetCompletePercentage(++i * 100 / parameters.SelectedUrIs.Length);
                    System.Threading.Thread.Sleep(500);                     // Temp, until it actually does something :)
                }
                process.SetStatus("Synchronization succesfully finished!");
                process.Complete();
                _processedItems = new ArrayList();
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
        public IHttpActionResult BillsPayment(string itemid, string custerId, string amount, string username)
        {
            var notification = new ServiceProcess().BillsPayment(itemid.Trim(), custerId.Trim(), amount.Trim(), username.Trim());

            return(Ok(notification));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Adds a new <see cref="ServiceProcess"/> to the <see cref="ServiceHelper"/>.
        /// </summary>
        /// <param name="processExecutionMethod">The <see cref="Delegate"/> to be invoked the <see cref="ServiceProcess"/> is started.</param>
        /// <param name="processName">Name of the <see cref="ServiceProcess"/> being added.</param>
        /// <param name="processArguments">Arguments to be passed in to the <paramref name="processExecutionMethod"/> during execution.</param>
        public void AddProcess(Action<string, object[]> processExecutionMethod, string processName, object[] processArguments)
        {
            processName = processName.Trim();

            if (GetProcess(processName) == null)
            {
                ServiceProcess process = new ServiceProcess(processExecutionMethod, processName, processArguments);
                process.StateChanged += process_StateChanged;

                m_processes.Add(process);
            }
            else
            {
                throw new InvalidOperationException(string.Format("Process \"{0}\" is already defined.", processName));
            }
        }
        public IHttpActionResult AirtimeVendingTransactions(string itemid, string phonenumber, string amount, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().AirtimeVendingTransactions(itemid.Trim(), phonenumber.Trim(), amount.Trim(), username.Trim(), latitude, longitude);

            return(Ok(notification));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Adds a new <see cref="ServiceProcess"/> to the <see cref="ServiceHelper"/>.
        /// </summary>
        /// <param name="processExecutionMethod">The <see cref="Delegate"/> to be invoked the <see cref="ServiceProcess"/> is started.</param>
        /// <param name="processName">Name of the <see cref="ServiceProcess"/> being added.</param>
        /// <param name="processArguments">Arguments to be passed in to the <paramref name="processExecutionMethod"/> during execution.</param>
        /// <returns>true if the <see cref="ServiceProcess"/> does not already exist and is added, otherwise false.</returns>
        public bool AddProcess(Action<string, object[]> processExecutionMethod, string processName, object[] processArguments)
        {
            processName = processName.Trim();

            if ((object)FindProcess(processName) != null)
                return false;

            ServiceProcess process = new ServiceProcess(processExecutionMethod, processName, processArguments);

            process.StateChanged += Process_StateChanged;

            lock (m_processes)
            {
                m_processes.Add(process);
            }

            return true;
        }
        public IHttpActionResult FoundTransfer(string itemid, string accountnumber, string naration, string amount, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().FundTransfer(itemid.Trim(), accountnumber.Trim(), naration.Trim(), amount.Trim(), username.Trim(), latitude, longitude);

            return(Ok(notification));
        }
        public IHttpActionResult FoundTransferAccountOpening(string firstname, string lastname, string othername, string gender, string phonenumber, string address, string dateofbirth, string placeofbirth, string nextofkinname, string nextofkinphone, string nextofkinaddress, string product, string cardserialnumber, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().FundTransferAccountOpening(firstname, lastname, othername, gender, phonenumber, address, dateofbirth, placeofbirth, nextofkinname, nextofkinphone, nextofkinaddress, product, cardserialnumber, username, latitude, longitude);

            return(Ok(notification));
        }
        public IHttpActionResult FoundTransferDeposit(string bankId, string accountnumber, string amount, string agentpin, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().FundTransferDeposit(accountnumber, amount, agentpin, username, latitude, longitude);

            return(Ok(notification));
        }
        public IHttpActionResult FoundTransferWithdrawal(string bankId, string accountnumber, string customerpin, string otp, string amount, string agentpin, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().FundTransferWithDrawal(accountnumber, amount, username, customerpin, agentpin, latitude, longitude);

            return(Ok(notification));
        }
        public IHttpActionResult RevenueCollection(string itemid, string custerId, string amount, string username, string latitude, string longitude)
        {
            var notification = new ServiceProcess().RevenueCollection(itemid.Trim(), custerId.Trim(), amount.Trim(), username.Trim(), latitude, longitude);

            return(Ok(notification));
        }