Beispiel #1
0
        public ActionResult AddService(CreateServiceRequest createRequest, int id)
        {
            var newService     = _userRepository.AddService(createRequest.Name, createRequest.Description, createRequest.Price);
            var newUserService = _userRepository.AddUserService(id, newService.Id);

            return(Ok(newService));
        }
        /// <summary>Snippet for CreateServiceAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateServiceRequestObjectAsync()
        {
            // Create client
            ServiceManagerClient serviceManagerClient = await ServiceManagerClient.CreateAsync();

            // Initialize request argument(s)
            CreateServiceRequest request = new CreateServiceRequest
            {
                Service = new ManagedService(),
            };
            // Make the request
            Operation <ManagedService, OperationMetadata> response = await serviceManagerClient.CreateServiceAsync(request);

            // Poll until the returned long-running operation is complete
            Operation <ManagedService, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            ManagedService result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <ManagedService, OperationMetadata> retrievedResponse = await serviceManagerClient.PollOnceCreateServiceAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                ManagedService retrievedResult = retrievedResponse.Result;
            }
        }
Beispiel #3
0
        public async Task <bool> CreateServiceAsync(int laboratoryId, CreateServiceRequest request)
        {
            ResearchServiceType type;

            if (!Enum.TryParse(request.Type, true, out type))
            {
                throw new RequestError("Service type is invalid!");
            }
            if (request.Name.Length == 0)
            {
                throw new RequestError("Name can not be empty");
            }
            if (request.Name.Length > 200)
            {
                throw new RequestError("Name can not be longer than 200");
            }
            Laboratory laboratory = await unitOfWork.Laboratories.Where(l => l.Id == laboratoryId).SingleOrDefaultAsync();

            if (laboratory == default(Laboratory))
            {
                throw new RequestError("Non existing laboratory");
            }

            // AUTHORISATION CHECK
            int myId = authService.CurrentUser.Id;

            if (myId != laboratory.Coordinator.Id &&
                laboratory.Permissions.Where(p => p.UserId == myId).SingleOrDefault() == default(LaboratoryPermission))
            {
                throw new RequestError(403, "Permission denied!");
            }

            List <User> team = new List <User>();

            foreach (int teamMember in request.Persons)
            {
                var user = await unitOfWork.Users.Where(u => u.Id == teamMember).SingleOrDefaultAsync();

                if (user == default(User))
                {
                    throw new RequestError("Team member does not exist!");
                }
                team.Add(user);
            }
            ResearchService researchService = new ResearchService
            {
                Laboratory  = laboratory,
                Description = request.Description,
                Name        = request.Name,
                Type        = type
            };

            researchService.Persons = team.Select(t => new ResearchServicePerson {
                User = t, ResearchService = researchService
            }).ToList();
            laboratory.ResearchServices.Add(researchService);
            await unitOfWork.SaveAsync();

            return(true);
        }
        public CreateServiceResponse AddServiceSetting(CreateServiceRequest request)
        {
            var response = new CreateServiceResponse {
                ResponseStatus = ResponseStatus.Success
            };

            var settingsProvider = new SettingsProvider();

            try
            {
                if (request.ActionType == ActionType.Insert)
                {
                    response.isSuccessful = settingsProvider.AddService(request);
                }
                else
                {
                    response.ResponseStatus      = ResponseStatus.Failure;
                    response.ResponseDescription = "Not update action";
                }
            }
            catch (Exception ex)
            {
                response.ResponseStatus      = ResponseStatus.Failure;
                response.ResponseDescription = ex.Message;
            }
            return(response);
        }
        public async Task <GetServiceResponse> CreateServiceRequest(CreateServiceRequest dto)
        {
            var customer = await _unitOfWork.Customers.GetWithAddresses(new Guid(dto.CustomerId));

            var address = await _unitOfWork.Addresses.Get(new Guid(dto.AddressId));

            // validate
            if (customer is null)
            {
                throw new KeyNotFoundException("Customer does not exist.");
            }
            if (address is null)
            {
                throw new KeyNotFoundException("Address does not exist.");
            }
            if (!customer.CustomerAddresses.Any(ca => ca.AddressId == address.Id))
            {
                throw new AppException("Address does not belong to this customer.");
            }

            // map dto to new employee object
            var newService = _mapper.Map <ServiceRequest>(dto);

            newService.Status  = Status.New;
            newService.Created = DateTime.UtcNow;

            _unitOfWork.ServiceRequests.Add(newService);
            _unitOfWork.Commit();

            return(_mapper.Map <GetServiceResponse>(newService));
        }
        internal bool AddService(CreateServiceRequest request)
        {
            var conn           = GetConnection(ConnectionNames.CSPSqlDatabase);
            var commandWrapper = GetStoredProcCommand("dbo.Insert_Service", conn);

            AddInParameter(commandWrapper, "@ServiceName", DbType.String, request.Service.ServiceName);
            AddInParameter(commandWrapper, "@ServiceDescription", DbType.String, request.Service.ServiceDescription);
            AddInParameter(commandWrapper, "@Price", DbType.Int16, request.Service.Price);
            AddInParameter(commandWrapper, "@Type", DbType.Int16, request.Service.Type);



            AddInParameter(commandWrapper, "@ERROR", DbType.String, 1000);
            AddInParameter(commandWrapper, "@ERROR_CODE", DbType.String, 4);

            try
            {
                conn.Open();
                int results = commandWrapper.ExecuteNonQuery();

                var isProcedureSucced = Convert.ToBoolean(results);
                MakeDboLog(request.ToString(), isProcedureSucced.ToString(), "dbo.Insert_Service");

                var errorObject     = GetParameterValue(commandWrapper, "@ERROR");
                var errorCodeObject = GetParameterValue(commandWrapper, "@ERROR_CODE");

                return(Convert.ToBoolean(results));
            }
            finally
            {
                commandWrapper.Dispose();
                conn.Close();
            }
        }
        internal CreateServiceResponse CreateService(CreateServiceRequest request)
        {
            var marshaller   = new CreateServiceRequestMarshaller();
            var unmarshaller = CreateServiceResponseUnmarshaller.Instance;

            return(Invoke <CreateServiceRequest, CreateServiceResponse>(request, marshaller, unmarshaller));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the CreateService operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateService operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task <CreateServiceResponse> CreateServiceAsync(CreateServiceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new CreateServiceRequestMarshaller();
            var unmarshaller = CreateServiceResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateServiceRequest, CreateServiceResponse>(request, marshaller,
                                                                             unmarshaller, cancellationToken));
        }
        public JsonResult Save([FromBody] CreateServiceRequest model)
        {
            ActionsResult result;

            result = ApiHelper <ActionsResult> .HttpPostAsync($"{Helper.ApiUrl}api/service/save", model);

            return(Json(new { result }));
        }
Beispiel #10
0
        internal virtual CreateServiceResponse CreateService(CreateServiceRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = CreateServiceRequestMarshaller.Instance;
            options.ResponseUnmarshaller = CreateServiceResponseUnmarshaller.Instance;

            return(Invoke <CreateServiceResponse>(request, options));
        }
Beispiel #11
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateService operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateService operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateService">REST API Reference for CreateService Operation</seealso>
        public virtual Task <CreateServiceResponse> CreateServiceAsync(CreateServiceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = CreateServiceRequestMarshaller.Instance;
            options.ResponseUnmarshaller = CreateServiceResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateServiceResponse>(request, options, cancellationToken));
        }
Beispiel #12
0
        public CreateServiceRequest GetCreateServiceRequest(Service service)
        {
            var request = new CreateServiceRequest()
            {
                Service    = service,
                ActionType = Requests.ActionType.Insert
            };

            return(request);
        }
Beispiel #13
0
        public ActionResult AddService(CreateServiceRequest createRequest)
        {
            if (!_validator.Validate(createRequest))
            {
                return(BadRequest(new { error = "What Is The Name Of Your Service?" }));
            }

            var newService = _serviceRepository.AddService(createRequest.Name, createRequest.Description, createRequest.Price);

            return(Created($"api/services/{newService.Id}", newService));
        }
        //POST to add services
        public ActionResult AddService(CreateServiceRequest createRequest)
        {
            if (!_validator.Validate(createRequest))
            {
                return(BadRequest(new { error = "users must have a name for their service and a cost" }));
            }

            var newService = _serviceRepository.AddService(createRequest.Name, createRequest.Cost);

            return(Created($"api/services/{newService.Id}", newService));
        }
Beispiel #15
0
        public async Task <IActionResult> Post([FromBody] CreateServiceRequest request)
        {
            var command = new CreateServiceCommand(request.Name, request.AllowHalfTime);
            var result  = await createServiceService.Process(command);

            return(Ok(new ApiReturnItem <ServiceResult>
            {
                Item = result,
                Success = true
            }));
        }
Beispiel #16
0
        public async Task CreateService_Should_Succeed()
        {
            var request = new CreateServiceRequest
            {
                ServiceName = "testservice"
            };

            var res = await _namingClient.CreateServiceAsync(request);

            Assert.True(res);
        }
Beispiel #17
0
 /// <summary>Snippet for CreateService</summary>
 public void CreateService_RequestObject()
 {
     // Snippet: CreateService(CreateServiceRequest,CallSettings)
     // Create client
     ServiceMonitoringServiceClient serviceMonitoringServiceClient = ServiceMonitoringServiceClient.Create();
     // Initialize request argument(s)
     CreateServiceRequest request = new CreateServiceRequest
     {
         ParentAsProjectName = new ProjectName("[PROJECT]"),
         Service             = new Service(),
     };
     // Make the request
     Service response = serviceMonitoringServiceClient.CreateService(request);
     // End snippet
 }
        public IActionResult CreateService([FromBody] CreateServiceRequest requestBody)
        {
            var service = requestBody.ToService();

            if (_servicesManager.GetService(service.Slug) != null)
            {
                return(BadRequest(new
                {
                    message = "A service with this slug already exists."
                }));
            }

            service = _servicesManager.CreateService(service);
            return(Ok(service));
        }
Beispiel #19
0
        /// <summary>
        /// 创建服务
        /// </summary>
        /// <param name="req"><see cref="CreateServiceRequest"/></param>
        /// <returns><see cref="CreateServiceResponse"/></returns>
        public CreateServiceResponse CreateServiceSync(CreateServiceRequest req)
        {
            JsonResponseModel <CreateServiceResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "CreateService");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <CreateServiceResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
Beispiel #20
0
        /// <summary>Snippet for CreateServiceAsync</summary>
        public async Task CreateServiceAsync_RequestObject()
        {
            // Snippet: CreateServiceAsync(CreateServiceRequest,CallSettings)
            // Additional: CreateServiceAsync(CreateServiceRequest,CancellationToken)
            // Create client
            ServiceMonitoringServiceClient serviceMonitoringServiceClient = await ServiceMonitoringServiceClient.CreateAsync();

            // Initialize request argument(s)
            CreateServiceRequest request = new CreateServiceRequest
            {
                ParentAsProjectName = new ProjectName("[PROJECT]"),
                Service             = new Service(),
            };
            // Make the request
            Service response = await serviceMonitoringServiceClient.CreateServiceAsync(request);

            // End snippet
        }
        public async Task <IActionResult> CreateService([FromBody] CreateServiceRequest serviceRequest)
        {
            var user = this.GetUser();

            var service = new Api
            {
                Title       = serviceRequest.Title,
                Description = serviceRequest.Description,
            };
            var model = await _service.CreateServiceAsync(service, await user);

            var response = new WebServiceResponse
            {
                Code    = "success",
                Message = "service.create.success",
                Data    = service
            };

            return(Ok(response));
        }
Beispiel #22
0
        private threadingTask.Task CreateService()
        {
            throw new NotImplementedException("Services should be created and configured manually for now.");

            var request = new CreateServiceRequest
            {
                Cluster        = DefaultSettings.General.ClusterName,
                LaunchType     = LaunchType.FindValue(DefaultSettings.General.ServiceLaunchType),
                DesiredCount   = DefaultSettings.General.ServiceNumberOfTasks,
                ServiceName    = DefaultSettings.General.ServiceName,
                TaskDefinition = TaskDefenition.TaskDefinitionArn,
                LoadBalancers  = new List <LoadBalancer>
                {
                    new LoadBalancer {
                        LoadBalancerName = DefaultSettings.General.ServiceName,
                    }
                }
            };

            return(ECSClient.CreateServiceAsync(request));
        }
Beispiel #23
0
        public async Task <ActionResult> Post([FromBody] CreateServiceRequest req)
        {
            string serviceRequestAggregateId = "";
            ServiceRequestAggregate serviceRequestAggregate;

            try
            {
                // 1. Try to create the aggregate
                string user = ""; // Pull this out of auth or something
                string guid = Guid.NewGuid().ToString();
                serviceRequestAggregate = new ServiceRequestAggregate(
                    guid,
                    req.buildingCode,
                    req.description,
                    (int)ServiceRequestStatus.Created,
                    req.createdBy,
                    DateTime.Now,
                    user,
                    DateTime.Now
                    );

                // 2. Persist aggregate
                serviceRequestAggregateId = await _repo.CreateAsync(serviceRequestAggregate);
            }
            catch (ServiceRequestDomainException ex)
            {
                return(BadRequest(ex.Message));
            }

            try
            {
                // 3. Sideaffects
                SendEmail(serviceRequestAggregate);
            }
            catch (Exception ex)
            {
                // log
            }
            return(Created($"api/servicerequest/{serviceRequestAggregateId}", serviceRequestAggregate));
        }
Beispiel #24
0
        public async Task CreateServiceAsync2()
        {
            Mock <ServiceMonitoringService.ServiceMonitoringServiceClient> mockGrpcClient = new Mock <ServiceMonitoringService.ServiceMonitoringServiceClient>(MockBehavior.Strict);
            CreateServiceRequest request = new CreateServiceRequest
            {
                ParentAsProjectName = new ProjectName("[PROJECT]"),
                Service             = new Service(),
            };
            Service expectedResponse = new Service
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
                DisplayName = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.CreateServiceAsync(request, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <Service>(Task.FromResult(expectedResponse), null, null, null, null));
            ServiceMonitoringServiceClient client = new ServiceMonitoringServiceClientImpl(mockGrpcClient.Object, null);
            Service response = await client.CreateServiceAsync(request);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Beispiel #25
0
        public async Task <ActionsResult> Save(CreateServiceRequest request)
        {
            var service = new Service()
            {
                Description = request.Description,
                Price       = request.Price,
                ServiceId   = request.ServiceId,
                ServiceName = request.ServiceName,
                IsDelete    = request.IsDelete
            };
            var createServiceResult = await serviceRepository.Save(service);

            if (createServiceResult.Id != 0)
            {
                _ = serviceImageRepository.Save(new UploadServiceImagesRequest()
                {
                    ServiceId = createServiceResult.Id,
                    Images    = request.Images
                });
            }
            return(createServiceResult);
        }
Beispiel #26
0
        public void CreateService2()
        {
            Mock <ServiceMonitoringService.ServiceMonitoringServiceClient> mockGrpcClient = new Mock <ServiceMonitoringService.ServiceMonitoringServiceClient>(MockBehavior.Strict);
            CreateServiceRequest request = new CreateServiceRequest
            {
                ParentAsProjectName = new ProjectName("[PROJECT]"),
                Service             = new Service(),
            };
            Service expectedResponse = new Service
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
                DisplayName = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.CreateService(request, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            ServiceMonitoringServiceClient client = new ServiceMonitoringServiceClientImpl(mockGrpcClient.Object, null);
            Service response = client.CreateService(request);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public Task CreateService()
        {
            _context.Logger.WriteLine("CreateService");

            var request = new CreateServiceRequest
            {
                Cluster        = _cluster.Name,
                DesiredCount   = 2,
                ServiceName    = _task.Name,
                Role           = "ecsServiceRole",
                TaskDefinition = $"{_task.Name}:1",
                LoadBalancers  =
                {
                    new LoadBalancer
                    {
                        ContainerName    = _task.Name,
                        ContainerPort    = _task.ContainerPort,
                        LoadBalancerName = _task.Name
                    }
                }
            };

            return(_client.CreateServiceAsync(request));
        }
Beispiel #28
0
 public bool Validate(CreateServiceRequest requestToValidate)
 {
     return(!(string.IsNullOrEmpty(requestToValidate.Name) ||
              (double.IsNaN(requestToValidate.Cost))));
 }
        public virtual MachineLearningServiceCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string workspaceName, string serviceName, CreateServiceRequest properties, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (workspaceName == null)
            {
                throw new ArgumentNullException(nameof(workspaceName));
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException(nameof(serviceName));
            }
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            using var scope = _clientDiagnostics.CreateScope("MachineLearningServiceOperations.StartCreateOrUpdate");
            scope.Start();
            try
            {
                var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, workspaceName, serviceName, properties, cancellationToken);
                return(new MachineLearningServiceCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, workspaceName, serviceName, properties).Request, originalResponse));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
Beispiel #30
0
        private async Task CreateOrUpdateService(string ecsCluster, string ecsService, string taskDefinitionArn, string ecsContainer)
        {
            try
            {
                var describeServiceResponse = await this.ECSClient.DescribeServicesAsync(new DescribeServicesRequest
                {
                    Cluster  = ecsCluster,
                    Services = new List <string> {
                        ecsService
                    }
                });

                var desiredCount                    = this.GetIntValueOrDefault(this.DeployServiceProperties.DesiredCount, ECSDefinedCommandOptions.ARGUMENT_ECS_DESIRED_COUNT, false);
                var deploymentMaximumPercent        = this.GetIntValueOrDefault(this.DeployServiceProperties.DeploymentMaximumPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MAXIMUM_PERCENT, false);
                var deploymentMinimumHealthyPercent = this.GetIntValueOrDefault(this.DeployServiceProperties.DeploymentMinimumHealthyPercent, ECSDefinedCommandOptions.ARGUMENT_DEPLOYMENT_MINIMUM_HEALTHY_PERCENT, false);


                var launchType = this.GetStringValueOrDefault(this.ClusterProperties.LaunchType, ECSDefinedCommandOptions.ARGUMENT_LAUNCH_TYPE, true);
                NetworkConfiguration networkConfiguration = null;
                if (IsFargateLaunch(this.ClusterProperties.LaunchType))
                {
                    if (describeServiceResponse.Services.Count != 0)
                    {
                        networkConfiguration = describeServiceResponse.Services[0].NetworkConfiguration;
                    }
                    else
                    {
                        networkConfiguration = new NetworkConfiguration();
                    }

                    await ECSUtilities.SetupAwsVpcNetworkConfigurationAsync(this, networkConfiguration);
                }

                DeploymentConfiguration deploymentConfiguration = null;
                if (deploymentMaximumPercent.HasValue || deploymentMinimumHealthyPercent.HasValue)
                {
                    deploymentConfiguration = new DeploymentConfiguration();
                    if (deploymentMaximumPercent.HasValue)
                    {
                        deploymentConfiguration.MaximumPercent = deploymentMaximumPercent.Value;
                    }
                    if (deploymentMinimumHealthyPercent.HasValue)
                    {
                        deploymentConfiguration.MinimumHealthyPercent = deploymentMinimumHealthyPercent.Value;
                    }
                }

                if (describeServiceResponse.Services.Count == 0 || describeServiceResponse.Services[0].Status == "INACTIVE")
                {
                    this.Logger?.WriteLine($"Creating new service: {ecsService}");
                    var request = new CreateServiceRequest
                    {
                        ClientToken             = Guid.NewGuid().ToString(),
                        Cluster                 = ecsCluster,
                        ServiceName             = ecsService,
                        TaskDefinition          = taskDefinitionArn,
                        DesiredCount            = desiredCount.HasValue ? desiredCount.Value : 1,
                        DeploymentConfiguration = deploymentConfiguration,
                        LaunchType              = launchType,
                        NetworkConfiguration    = networkConfiguration
                    };

                    if (IsFargateLaunch(this.ClusterProperties.LaunchType))
                    {
                        await this.AttemptToCreateServiceLinkRoleAsync();
                    }
                    else
                    {
                        request.PlacementConstraints = ECSUtilities.ConvertPlacementConstraint(this.GetStringValuesOrDefault(this.DeployServiceProperties.PlacementConstraints, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_CONSTRAINTS, false));
                        request.PlacementStrategy    = ECSUtilities.ConvertPlacementStrategy(this.GetStringValuesOrDefault(this.DeployServiceProperties.PlacementStrategy, ECSDefinedCommandOptions.ARGUMENT_PLACEMENT_STRATEGY, false));
                    }

                    var elbTargetGroup = this.GetStringValueOrDefault(this.DeployServiceProperties.ELBTargetGroup, ECSDefinedCommandOptions.ARGUMENT_ELB_TARGET_GROUP_ARN, false);
                    if (!this.OverrideIgnoreTargetGroup && !string.IsNullOrWhiteSpace(elbTargetGroup))
                    {
                        if (!IsFargateLaunch(this.ClusterProperties.LaunchType))
                        {
                            request.Role = this.GetStringValueOrDefault(this.DeployServiceProperties.ELBServiceRole, ECSDefinedCommandOptions.ARGUMENT_ELB_SERVICE_ROLE, false);
                        }

                        var port = this.GetIntValueOrDefault(this.DeployServiceProperties.ELBContainerPort, ECSDefinedCommandOptions.ARGUMENT_ELB_CONTAINER_PORT, false);
                        if (!port.HasValue)
                        {
                            port = 80;
                        }
                        request.LoadBalancers.Add(new LoadBalancer
                        {
                            TargetGroupArn = elbTargetGroup,
                            ContainerName  = ecsContainer,
                            ContainerPort  = port.Value
                        });
                    }

                    try
                    {
                        await this.ECSClient.CreateServiceAsync(request);
                    }
                    catch (Amazon.ECS.Model.InvalidParameterException e)
                    {
                        if (e.Message.StartsWith("The target group") && !string.IsNullOrEmpty(elbTargetGroup) && string.IsNullOrEmpty(this.DeployServiceProperties.ELBTargetGroup))
                        {
                            request.LoadBalancers.Clear();
                            request.Role = null;

                            var defaultFile = string.IsNullOrEmpty(this.ConfigFile) ? ECSToolsDefaults.DEFAULT_FILE_NAME : this.ConfigFile;
                            this.Logger?.WriteLine($"Warning: ELB Target Group ARN specified in config file {defaultFile} does not exist.");
                            await this.ECSClient.CreateServiceAsync(request);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    this.Logger?.WriteLine($"Updating new service: {ecsService}");
                    var updateRequest = new UpdateServiceRequest
                    {
                        Cluster                 = ecsCluster,
                        Service                 = ecsService,
                        TaskDefinition          = taskDefinitionArn,
                        DeploymentConfiguration = deploymentConfiguration,
                        NetworkConfiguration    = networkConfiguration
                    };

                    if (desiredCount.HasValue)
                    {
                        updateRequest.DesiredCount = desiredCount.Value;
                    }

                    await this.ECSClient.UpdateServiceAsync(updateRequest);
                }
            }
            catch (DockerToolsException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new DockerToolsException($"Error updating ECS service {ecsService} on cluster {ecsCluster}: {e.Message}", DockerToolsException.ECSErrorCode.FailedToUpdateService);
            }
        }