Exemple #1
0
        public virtual IActionResult Start([FromBody] StartRequest request, [FromRoute] string name)
        {
            try
            {
                _behavior.Init(request.GameId, request.Height, request.Width);

                // Если имя змейки не передали в параметрах, то берем из конфигов
                name = string.IsNullOrEmpty(name) ? _options.Value.Name : name;

                return(Ok(new StartResponse
                {
                    Name = name,
                    Color = _options.Value.Color,
                    HeadType = _options.Value.HeadType,
                    HeadUrl = _options.Value.HeadUrl,
                    SecondaryColor = _options.Value.SecondaryColor,
                    TailType = _options.Value.TailType,
                    Taunt = _options.Value.Taunt
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ошибка при вызове Start => {ex.Message}");
                return(Ok());
            }
        }
        public StartResponse Start(StartRequest request)
        {
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Start:\n  VM: {0}", request.Vm);
            if (request.__isset.snapshot)
                message.AppendFormat("\n  Snapshot: {0}", request.Snapshot);
            log.Info(message.ToString());

            string output;
            int exitCode;

            if (request.__isset.snapshot)
            {
                exitCode = ExecuteVBoxCommand("VBoxManage.exe",
                    string.Format("snapshot \"{0}\" restore \"{1}\"", request.Vm, request.Snapshot),
                    TimeSpan.FromSeconds(30),
                    out output);
                if (exitCode != 0)
                {
                    throw OperationFailed("Failed to restore the snapshot.", output);
                }

                // Wait a bit before starting the VM.  May help work around problems where
                // the VM will not start due to VBOX_E_INVALID_OBJECT_STATE.
                Thread.Sleep(10000);
            }

            Retry((lastRetry) =>
            {
                exitCode = ExecuteVBoxCommand("VBoxManage.exe",
                    string.Format("startvm \"{0}\"", request.Vm),
                    TimeSpan.FromSeconds(30),
                    out output);

                if (exitCode != 0
                    || output.Contains("E_FAIL")
                    || output.Contains("VBOX_E_INVALID_OBJECT_STATE"))
                {
                    // Sometimes VirtualBox hangs with a VM in a saved state but not completely
                    // powered off.  When this happens, we need to forcibly kill the VM process.
                    if (! lastRetry)
                    {
                        Status status = GetVmStatus(request.Vm, false);
                        if (status == Status.SAVED || status == Status.OFF)
                        {
                            if (KillHungVm(request.Vm))
                                return false;
                        }
                    }
                
                    throw OperationFailed(
                        "Failed to start the virtual machine.", 
                        ErrorDetails(exitCode, output));
                }
                
                return true;
            });

            return new StartResponse();
        }
Exemple #3
0
        /// <summary>
        /// Start processes which are in 'price checked' status
        /// </summary>
        /// <param name="token">Login Token, aquire a login token by invoking by using `CopyleaksIdentityApi.LoginAsync`</param>
        /// <param name="model">A model with the list of scan id's to start and error handeling defenition in case one or more scans have a starting error</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result contains a list of successfully started scans and a list of scans that have failed starting</returns>
        public async Task <StartResponse> StartAsync(StartRequest model, string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Token is mandatory", nameof(token));
            }

            if (model.Trigger == null)
            {
                throw new ArgumentException("Trigger is mandatory.", nameof(model.Trigger));
            }

            var                method     = new HttpMethod("PATCH");
            string             requestUri = $"{this.CopyleaksApiServer}{this.ApiVersion}/scans/start";
            HttpRequestMessage msg        = new HttpRequestMessage(method, requestUri);

            msg.SetupHeaders(token);
            msg.Content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");

            using (var stream = new MemoryStream())
                using (var streamContent = new StreamContent(stream))
                    using (var response = await Client.SendAsync(await msg.CloneAsync(stream, streamContent).ConfigureAwait(false)).ConfigureAwait(false))
                    {
                        if (!response.IsSuccessStatusCode)
                        {
                            throw new CopyleaksHttpException(response);
                        }
                        return(await response.ExtractJsonResultsAsync <StartResponse>().ConfigureAwait(false));
                    }
        }
        public async IAsyncEnumerable <OneOf <string, int> > StartAsync(string experimentName, int cycleCount)
        {
            var request = new StartRequest {
                ExperimentName = experimentName, CycleCount = cycleCount
            };

            using var call = client.Start(request, new CallOptions().WithDeadline(DateTime.MaxValue)); // настройка времени ожидания
            while (await call.ResponseStream.MoveNext())
            {
                var message = call.ResponseStream.Current;
                switch (message.ContentCase)
                {
                case StartResponse.ContentOneofCase.Plate:
                    yield return(message.Plate.ExperimentalData);

                    break;

                case StartResponse.ContentOneofCase.Status:
                    yield return(message.Status.PlateTemperature);

                    break;

                default:
                    break;
                }
                ;
            }
        }
Exemple #5
0
        public async Task Handle(StartRequest <VSTSRelease_v1> request, CancellationToken cancellationToken)
        {
            var dialog = new ConfirmationDialog($"Are you sure you want to create a new release of {request.DataContext.Name}?");

            var result = _dialogService.ShowDialog(dialog);

            if (result != DialogResult.Yes)
            {
                return;
            }

            if (!request.DataContext.ReleaseId.HasValue)
            {
                throw new InvalidOperationException("Release id was not set.");
            }

            _logger.Info($"Creating a new release of \"{request.DataContext.Name}\"...");

            var client = new AnyStatus.VSTS();

            request.DataContext.MapTo(client);

            var body = new
            {
                definitionId = request.DataContext.ReleaseId
            };

            await client.Send("release/releases?api-version=4.1-preview.6", body, true).ConfigureAwait(false);

            request.DataContext.State = State.Queued;

            _logger.Info($"Release \"{request.DataContext.Name}\" has been queued.");
        }
Exemple #6
0
        public async Task Handle(StartRequest <ReleaseEnvironmentWidget> request, CancellationToken cancellationToken)
        {
            var dialog = new ConfirmationDialog($"Are you sure you want to start {request.DataContext.Name}?");

            if (_dialogService.ShowDialog(dialog) != DialogResult.Yes)
            {
                return;
            }

            if (request.DataContext.Parent is ReleaseWidget parent)
            {
                var api = new AzureDevOpsApi(parent.ConnectionSettings);

                var response = await api.GetReleasesAsync(parent.Project, parent.DefinitionId, 1, cancellationToken).ConfigureAwait(false);

                if (response.Count == 0)
                {
                    throw new Exception("Release not found.");
                }

                var release = response.Value.First();

                await api.DeployAsync(parent.Project, release.Id, request.DataContext.DeploymentId, cancellationToken).ConfigureAwait(false);

                request.DataContext.State = State.Queued;
            }
        }
Exemple #7
0
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public override CommandResult Execute(IClient sender, string[] args)
        {
            // generate command expects exactly 3 parameters

            if (args.Length != 3)
            {
                return(new CommandResult(false, Command.Start, "Usage: start <name> <rows> <cols>", true));
            }

            string name;
            int    rows, cols;

            name = args[0];
            if (!int.TryParse(args[1], out rows))
            {
                return(new CommandResult(false, Command.Start, "Bad <rows> field.", true));
            }

            if (!int.TryParse(args[2], out cols))
            {
                return(new CommandResult(false, Command.Start, "Bad <cols> field.", true));
            }

            StartRequest request = new StartRequest(sender, new GenerateRequest(name, rows, cols));

            try
            {
                _model.CreateGame(request);
                return(new CommandResult(true, Command.Start, "A game was created, please wait for your opponent to connect...", true));
            }
            catch (Exception e)
            {
                return(new CommandResult(false, Command.Start, e.Message, true));
            }
        }
        public StartResponse Start(
            string url,
            string name,
            string lastName,
            string secondLastName,
            string rut,
            string serviceId,
            string finalUrl,
            decimal maxAmount,
            string phone,
            string cellPhone,
            string patpassName,
            string personEmail,
            string commerceEmail,
            string address,
            string city
            )
        {
            // set culture to es-CL, since webpay only works with clp we are forcing to anyone to use clp currency standard.
            CultureInfo myCiIntl = new CultureInfo("es-CL", false);
            string      mAmount  = maxAmount <= 0 ? "" : maxAmount.ToString(myCiIntl);

            return(ExceptionHandler.Perform <StartResponse, InscriptionStartException>(() =>
            {
                var request = new StartRequest(
                    url, name, lastName, secondLastName, rut, serviceId, finalUrl,
                    Options.CommerceCode, mAmount, phone, cellPhone,
                    patpassName, personEmail, commerceEmail, address, city
                    );
                return _requestService.Perform <StartResponse, InscriptionStartException>(request, Options, _headers);
            }));
        }
Exemple #9
0
 public override Task <StartResponse> Start(StartRequest request,
                                            ServerCallContext context)
 {
     mutex             = new Mutex();
     latencies         = new List <long>();
     received_messages = new List <MessageIdentifier>();
     try {
         client = SimpleSubscriber.CreateAsync(
             new SubscriptionName(request.Project,
                                  request.PubsubOptions.Subscription)
             ).Result;
         Console.WriteLine("Client created successfully.");
     } catch (Exception e) {
         Console.WriteLine("Error starting client: " + e.ToString());
     }
     client.StartAsync((msg, ct) =>
     {
         long now       = CurrentTimeMillis();
         var identifier = new MessageIdentifier();
         mutex.WaitOne();
         latencies.Add(now - long.Parse(msg.Attributes["sendTime"]));
         identifier.PublisherClientId =
             long.Parse(msg.Attributes["clientId"]);
         identifier.SequenceNumber =
             int.Parse(msg.Attributes["sequenceNumber"]);
         received_messages.Add(identifier);
         mutex.ReleaseMutex();
         return(Task.FromResult(SimpleSubscriber.Reply.Ack));
     });
     return(Task.FromResult(new StartResponse()));
 }
Exemple #10
0
        public RegisterStartAck OnRegisterStart(RegisterStartReq msg)
        {
            if (!IsValidEmail(msg.email))
            {
                return(new RegisterStartAck(RegisterStartAck.Result.EMAIL_NOT_FOUND));
            }
            DropExpiredCodes();
            StartRequest req = GetRequestByEmail(msg.email);

            if (req != null)
            {
                req.createdTime = DateTime.Now;
            }
            else if (!IsUserRegistred(msg))
            {
                req             = new StartRequest();
                req.msg         = msg;
                req.createdTime = DateTime.Now;
                req.code        = GenerateCode();
                requests.Add(req);
            }
            if (req != null)
            {
                try
                {
                    SendCode(req.msg.email, req.code);
                }
                catch
                {
                    return(new RegisterStartAck(RegisterStartAck.Result.BAD_REQUEST));
                }
                return(new RegisterStartAck(RegisterStartAck.Result.OK));
            }
            return(new RegisterStartAck(RegisterStartAck.Result.NON_UNIQUE_EMAIL));
        }
Exemple #11
0
        public RegisterFinishAck OnRegisterFinish(RegisterFinishReq msg)
        {
            DropExpiredCodes();
            StartRequest request = null;

            foreach (StartRequest startRequest in requests)
            {
                if (msg.code == startRequest.code)
                {
                    request = startRequest;
                    break;
                }
            }
            if (request == null)
            {
                return(new RegisterFinishAck(RegisterFinishAck.Result.FAIL));
            }
            QueryBase query = null;

            if (msg.type == 0)
            {
                query = new QueryInsertClient(ConverterUser.MakeClient(request.msg),
                                              DBUtils.GetDBConnection(),
                                              null);
            }
            else if (msg.type == 1)
            {
                query = new QueryInsertSaler(ConverterUser.MakeSaler(request.msg),
                                             DBUtils.GetDBConnection(),
                                             null);
            }
            query.Execute();
            requests.Remove(request);
            return(new RegisterFinishAck(RegisterFinishAck.Result.OK));
        }
Exemple #12
0
        public async Task DeployVstsRelease()
        {
            var release = new VSTSRelease_v1
            {
                Account   = Account,
                Project   = Project,
                Password  = Token,
                ReleaseId = 11
            };

            var env = new VSTSReleaseEnvironment
            {
                EnvironmentId = 1149
            };

            release.Add(env);

            var request = StartRequest.Create(env);

            var dlg = Substitute.For <IDialogService>();

            dlg.ShowDialog(Arg.Any <ConfirmationDialog>()).Returns(_ => DialogResult.Yes);

            var handler = new DeployVstsRelease(dlg, Substitute.For <ILogger>());

            await handler.Handle(request, CancellationToken.None).ConfigureAwait(false);

            Assert.AreEqual(State.Queued, release.State);
        }
Exemple #13
0
        public async Task Handle(StartRequest <VSTSBuild_v1> request, CancellationToken cancellationToken)
        {
            var dialog = new ConfirmationDialog($"Are you sure you want to start {request.DataContext.Name}?");

            var result = _dialogService.ShowDialog(dialog);

            if (result != DialogResult.Yes)
            {
                return;
            }

            _logger.Info($"Starting \"{request.DataContext.Name}\"...");

            var client = new VstsClient(new VstsConnection());

            request.DataContext.MapTo(client.Connection);

            if (request.DataContext.DefinitionId == null)
            {
                var definition = await client.GetBuildDefinitionAsync(request.DataContext.DefinitionName).ConfigureAwait(false);

                request.DataContext.DefinitionId = definition.Id;
            }

            await client.QueueNewBuildAsync(request.DataContext.DefinitionId.Value).ConfigureAwait(false);

            _logger.Info($"Build \"{request.DataContext.Name}\" has been triggered.");
        }
Exemple #14
0
 public override Task <StartReply> StartRecording(StartRequest request, ServerCallContext context)
 {
     _spindelService.StartAsync(request.Id);
     return(Task.FromResult(new StartReply()
     {
         Rc = true
     }));
 }
Exemple #15
0
        internal static void Start(StartRequest req)
        {
            var response = Send(Constants.Endpoints.RTM.Start, req);
            var serResp  = JsonConvert.DeserializeObject <StartResponse>(response);

            // The start response gives us a load of information about the context
            MapToContext(serResp);
        }
        public async Task API_StartTest()
        {
            var widget  = new TestWidget();
            var handler = new Start();
            var request = StartRequest.Create(widget);

            await handler.Handle(request, CancellationToken.None);
        }
Exemple #17
0
 public OperationInfo(
     Operation operation,
     StartRequest request,
     IReadOnlyList <KeyValuePair <string, Uri> > sourceResourceUris)
 {
     Operation          = operation;
     Request            = request;
     SourceResourceUris = sourceResourceUris;
 }
        private void HandleStartRequest(StartRequest request)
        {
            this.StopServingApi();

            this.api = Context
                       .ActorOf(ApiActor.Props, ApiActor.Name);

            Context.Sender.Tell(new ApiResponse(request, success: true));
        }
        public IActionResult Start(StartRequest request)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            return(this.Ok());
        }
    void StartCompetition()
    {
        StartRequest rq = new StartRequest();

        rq.id = GameManager.mainPlayerUid;
        string jsonData = SimpleJson.SimpleJson.SerializeObject(rq);

        NetworkManager.StarXService.Notify("Room.StartCompetition", Encoding.UTF8.GetBytes(jsonData));
    }
Exemple #21
0
        public async Task Handle(StartRequest <VSTSReleaseEnvironment> request, CancellationToken cancellationToken)
        {
            var dialog = new ConfirmationDialog($"Are you sure you want to deploy to {request.DataContext.Name}?");

            var result = _dialogService.ShowDialog(dialog);

            if (result != DialogResult.Yes)
            {
                return;
            }

            _logger.Info($"Starting deployment to \"{request.DataContext.Name}\"...");

            var client = new AnyStatus.VSTS();

            if (request.DataContext.Parent is VSTSRelease_v1 release)
            {
                release.MapTo(client);
            }
            else
            {
                throw new InvalidOperationException("Release environment is not associated with a release.");
            }

            if (!release.ReleaseId.HasValue)
            {
                throw new InvalidOperationException("Release id was not set.");
            }

            var lastRelease = await client
                              .GetLastReleaseAsync(release.ReleaseId.Value)
                              .ConfigureAwait(false);

            if (lastRelease == null)
            {
                request.DataContext.State = State.Failed;

                _logger.Error("VSTS release definition was not released.");

                return;
            }

            var body = new
            {
                status = "inProgress"
            };

            var url = $"release/releases/{lastRelease.Id}/environments/{request.DataContext.EnvironmentId}?api-version=4.1-preview.5";

            await client.Send(url, body, true, true).ConfigureAwait(false);

            request.DataContext.State = State.Queued;

            _logger.Info($"Deployment to \"{request.DataContext.Name}\" has been queued.");
        }
        public IActionResult StartVerification([FromBody] StartRequest request)
        {
            var verification = VerificationResource.Create(
                to: $"+{request.CountryCode}{request.PhoneNumber}",
                channel: request.Channel,
                locale: request.Locale,
                pathServiceSid: _options.VerifyServiceSid
                );

            return(Ok(verification));
        }
Exemple #23
0
        public static StartResponse Start(string userName, string email,
                                          string responseUrl, Options options)
        {
            return(ExceptionHandler.Perform <StartResponse, InscriptionStartException>(() =>
            {
                var startRequest = new StartRequest(userName, email, responseUrl);
                var response = RequestService.Perform <InscriptionStartException>(
                    startRequest, options);

                return JsonConvert.DeserializeObject <StartResponse>(response);
            }));
        }
Exemple #24
0
        public async Task HasExpectedType(string method, string url, OperationType?type)
        {
            var request = new StartRequest(method, url);
            var sources = new List <string> {
                NuGetSourceUrl
            };
            var context = await OperationParserContext.CreateAsync(sources);

            var operationInfo = OperationParser.Parse(context, request);

            Assert.Equal(type, operationInfo.Operation?.Type);
        }
Exemple #25
0
        private void OnRequestListenerEvent(JToken obj)
        {
            var t = obj?["fname"]?["value"]?.ToString();

            if (t == "RequestListener.onStartRequest")
            {
                StartRequest?.Invoke(this, obj);
            }
            else if (t == "RequestListener.onStopRequest")
            {
                StopRequest?.Invoke(this, obj);
            }
        }
Exemple #26
0
        public Task Handle(StartRequest <IISApplicationPool> request, CancellationToken cancellationToken)
        {
            using (var iis = ServerManager.OpenRemote(request.DataContext.Host))
            {
                var appPool = iis.ApplicationPools[request.DataContext.ApplicationPoolName];

                appPool.Start();

                request.DataContext.State = appPool.State == ObjectState.Started ? State.Ok : State.Failed;

                return(Task.CompletedTask);
            }
        }
Exemple #27
0
        public async Task Handle(StartRequest <ReleaseWidget> request, CancellationToken cancellationToken)
        {
            var dialog = new ConfirmationDialog($"Are you sure you want to create a new release of {request.DataContext.Name}?");

            if (_dialogService.ShowDialog(dialog) != DialogResult.Yes)
            {
                return;
            }

            var api = new AzureDevOpsApi(request.DataContext.ConnectionSettings);

            await api.CreateReleaseAsync(request.DataContext.Project, request.DataContext.DefinitionId, cancellationToken).ConfigureAwait(false);
        }
Exemple #28
0
        /// <summary>
        /// Store SignedService objects
        /// </summary>
        /// <param name="smpSignedServiceUrl"></param>
        /// <returns>Stored SignedService object ready for deserialization</returns>
        public SignedServiceMetadata GetSignedService(string smpSignedServiceUrl)
        {
            StartRequest _startRequest = new StartRequest();

            try
            {
                string        signedServiceContent = _startRequest.GetContent(smpSignedServiceUrl).Replace("ns3:SignedServiceMetadataType", "ns3:SignedServiceMetadata");
                StringReader  stringReader         = new StringReader(signedServiceContent);
                XmlSerializer xmlSerializer        = new XmlSerializer(typeof(SignedServiceMetadata));
                return((SignedServiceMetadata)xmlSerializer.Deserialize(stringReader));
            }
            catch (Exception)
            { return(null); }
        }
Exemple #29
0
        /// <summary>
        /// Store SMP Service Group objects
        /// </summary>
        /// <param name="smpUrl"></param>
        /// <returns>Stored ServiceGroup object ready for deserialization</returns>
        public ServiceGroup GetServiceGroup(string smpUrl)
        {
            StartRequest _startRequest = new StartRequest();

            try
            {
                string        serviceGroupContent = _startRequest.GetContent(smpUrl).Replace("ns2:ServiceGroupType", "ns2:ServiceGroup");
                StringReader  stringReader        = new StringReader(serviceGroupContent);
                XmlSerializer xmlSerializer       = new XmlSerializer(typeof(ServiceGroup));
                return((ServiceGroup)xmlSerializer.Deserialize(stringReader));
            }
            catch (Exception)
            { return(null); }
        }
        private static bool TryParseStartRequest(string line, Dictionary <string, string> stringToString, out StartRequest startRequest)
        {
            var match = StartRequestRegex.Match(line);

            if (match.Success)
            {
                startRequest = new StartRequest(
                    DedupeString(stringToString, match.Groups["Method"].Value),
                    DedupeString(stringToString, match.Groups["Url"].Value.Trim()));
                return(true);
            }

            startRequest = null;
            return(false);
        }
        public async Task <string> StartPeerConnection(Jsep answer, long handleId)
        {
            var request = new StartRequest()
            {
                Jsep     = answer,
                HandleId = handleId,
                Body     = new StartRequestBody
                {
                    Room = 1234
                }
            };
            var result = await SendJanusRequest <StartResponse>(request, false);

            return(result.Plugindata.Data.Started);
        }
Exemple #32
0
        public void Start()
        {
            CheckProfileHasMaster();
            CheckProfileHasVM();

            if (profile.Snapshot != null)
            {
                Log(string.Format("Starting VM '{0}' snapshot '{1}'.", profile.VM, profile.Snapshot));
                StartRequest request = new StartRequest() { Vm = profile.VM, Snapshot = profile.Snapshot };
                GetMasterClient().Start(request);
            }
            else
            {
                Log(string.Format("Starting VM '{0}'.", profile.VM));
                StartRequest request = new StartRequest() { Vm = profile.VM };
                GetMasterClient().Start(request);
            }
        }