public async Task <IHttpActionResult> SetDetails(long id, [FromBody] BicyclePolicyDetailDTO details)
        {
            long?tokenId = User.Identity.GetPolicyIdFromToken();

            if (tokenId != id)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                Policy policy = await _service.SetDetails(id, details);

                return(Ok(_service.ConvertToDto(policy)));
            }
            catch (BadRequestException)
            {
                return(BadRequest());
            }
            catch (Exception)
            {
                return(NotFound());
            }
        }
        protected BicyclePolicyDetail CreateDetailModelFromDto(BicyclePolicyDetailDTO details)
        {
            BicyclePolicyDetail detail = new BicyclePolicyDetail()
            {
                Make      = details.Make,
                Model     = details.Model,
                Type      = details.Type,
                Year      = details.Year,
                CreatedAt = DateTime.UtcNow
            };

            return(detail);
        }
        public async Task <Policy> Create(BicyclePolicyDetailDTO policyDto)
        {
            using (InsuranceDbContext ctx = ContextFactory.CreateContext())
            {
                Policy policy = new Policy()
                {
                    State       = PolicyState.Quote,
                    Description = "Bicycle Insurance",
                    CreatedAt   = DateTime.UtcNow,
                    Detail      = CreateDetailModelFromDto(policyDto)
                };

                policy.Option = await CalculatePolicyOption(policy);

                ctx.Policies.Add(policy);
                await ctx.SaveChangesAsync();

                policy.PolicyNumber = $"QTE{policy.Id:D9}";
                await ctx.SaveChangesAsync();

                return(policy);
            }
        }
        public async Task <Policy> SetDetails(long id, BicyclePolicyDetailDTO details)
        {
            if (details == null)
            {
                throw new BadRequestException();
            }

            using (InsuranceDbContext ctx = ContextFactory.CreateContext())
            {
                Policy policy = await ctx.Policies.SingleAsync(x => x.Id == id);

                if (policy.IsIssued)
                {
                    throw new BadRequestException("Cannot update an issued Policy.");
                }

                policy.Detail = CreateDetailModelFromDto(details);
                policy.Option = await CalculatePolicyOption(policy);

                await ctx.SaveChangesAsync();

                return(policy);
            }
        }
        public async Task <IHttpActionResult> Create([FromBody] BicyclePolicyDetailDTO details)
        {
            Policy policy = await _service.Create(details);

            return(Ok(_service.ConvertToDto(policy)));
        }
示例#6
0
        /// <param name='details'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <HttpOperationResponse <PolicyDTO> > CreateWithHttpMessagesAsync(BicyclePolicyDetailDTO details, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (details == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "details");
            }
            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("details", details);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var baseUrl = this.Client.BaseUri.AbsoluteUri;
            var url     = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "api/BicyclePolicies").ToString();
            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();

            httpRequest.Method     = new HttpMethod("POST");
            httpRequest.RequestUri = new Uri(url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(header.Key))
                    {
                        httpRequest.Headers.Remove(header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // Serialize Request
            string requestContent = JsonConvert.SerializeObject(details, this.Client.SerializationSettings);

            httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
            httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                ex.Request  = httpRequest;
                ex.Response = httpResponse;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }
            // Create Result
            var result = new HttpOperationResponse <PolicyDTO>();

            result.Request  = httpRequest;
            result.Response = httpResponse;
            // Deserialize Response
            if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                result.Body = JsonConvert.DeserializeObject <PolicyDTO>(responseContent, this.Client.DeserializationSettings);
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return(result);
        }
示例#7
0
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='id'>
        /// </param>
        /// <param name='details'>
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <PolicyDTO> SetDetailsAsync(this IBicyclePolicies operations, long?id, BicyclePolicyDetailDTO details, CancellationToken cancellationToken = default(CancellationToken))
        {
            HttpOperationResponse <PolicyDTO> result = await operations.SetDetailsWithHttpMessagesAsync(id, details, null, cancellationToken).ConfigureAwait(false);

            return(result.Body);
        }
示例#8
0
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='id'>
 /// </param>
 /// <param name='details'>
 /// </param>
 public static PolicyDTO SetDetails(this IBicyclePolicies operations, long?id, BicyclePolicyDetailDTO details)
 {
     return(Task.Factory.StartNew(s => ((IBicyclePolicies)s).SetDetailsAsync(id, details), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }