Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>Returns a PDF version of the specified rental agreement</remarks>
        /// <param name="id">id of RentalAgreement to obtain the PDF for</param>
        /// <response code="200">OK</response>
        public virtual IActionResult RentalagreementsIdPdfGetAsync(int id)
        {
            FileContentResult result          = null;
            RentalAgreement   rentalAgreement = _context.RentalAgreements
                                                .Include(x => x.Equipment).ThenInclude(y => y.Owner).ThenInclude(z => z.PrimaryContact)
                                                .Include(x => x.Equipment).ThenInclude(y => y.DistrictEquipmentType)
                                                .Include(x => x.Equipment).ThenInclude(y => y.EquipmentAttachments)
                                                .Include(x => x.Equipment).ThenInclude(y => y.LocalArea.ServiceArea.District.Region)
                                                .Include(x => x.Project).ThenInclude(p => p.District.Region)
                                                .Include(x => x.RentalAgreementConditions)
                                                .Include(x => x.RentalAgreementRates)
                                                .Include(x => x.TimeRecords)
                                                .FirstOrDefault(a => a.Id == id);

            if (rentalAgreement != null)
            {
                // construct the view model.

                RentalAgreementPdfViewModel rentalAgreementPdfViewModel = rentalAgreement.ToViewModel();

                // TODO: Review Global JSON Serialization Options
                string payload = JsonConvert.SerializeObject(rentalAgreementPdfViewModel, new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                    Formatting            = Formatting.Indented,
                    DateFormatHandling    = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling  = DateTimeZoneHandling.Utc
                });

                // pass the request on to the PDF Micro Service
                string pdfHost = Configuration["PDF_SERVICE_NAME"];

                string targetUrl = pdfHost + "/api/PDF/GetPDF";

                // call the microservice
                try
                {
                    HttpClient client = new HttpClient();

                    var request = new HttpRequestMessage(HttpMethod.Post, targetUrl);
                    request.Content = new StringContent(payload, Encoding.UTF8, "application/json");

                    request.Headers.Clear();
                    // transfer over the request headers.
                    foreach (var item in Request.Headers)
                    {
                        string key   = item.Key;
                        string value = item.Value;
                        request.Headers.Add(key, value);
                    }

                    Task <HttpResponseMessage> responseTask = client.SendAsync(request);
                    responseTask.Wait();

                    HttpResponseMessage response = responseTask.Result;
                    if (response.StatusCode == HttpStatusCode.OK) // success
                    {
                        var bytetask = response.Content.ReadAsByteArrayAsync();
                        bytetask.Wait();

                        result = new FileContentResult(bytetask.Result, "application/pdf");
                        result.FileDownloadName = "RentalAgreement-" + rentalAgreement.Number + ".pdf";
                    }
                }
                catch (Exception e)
                {
                    result = null;
                }

                // check that the result has a value
                if (result != null)
                {
                    return(result);
                }
                else
                {
                    return(new StatusCodeResult(400)); // problem occured
                }
            }
            else
            {
                // record not found
                return(new StatusCodeResult(404));
            }
        }
        /// <summary>
        /// Get rental agreement pdf
        /// </summary>
        /// <remarks>Returns a PDF version of the specified rental agreement</remarks>
        /// <param name="id">id of RentalAgreement to obtain the PDF for</param>
        /// <exception cref="Exception"></exception>
        /// <response code="200">OK</response>
        public virtual IActionResult RentalagreementsIdPdfGetAsync(int id)
        {
            _logger.LogInformation("Rental Agreement Pdf [Id: {0}]", id);

            RentalAgreement rentalAgreement = _context.RentalAgreements.AsNoTracking()
                                              .Include(x => x.Equipment).ThenInclude(y => y.Owner).ThenInclude(z => z.PrimaryContact)
                                              .Include(x => x.Equipment).ThenInclude(y => y.DistrictEquipmentType)
                                              .Include(x => x.Equipment).ThenInclude(y => y.EquipmentAttachments)
                                              .Include(x => x.Equipment).ThenInclude(y => y.LocalArea.ServiceArea.District.Region)
                                              .Include(x => x.Project).ThenInclude(p => p.District.Region)
                                              .Include(x => x.RentalAgreementConditions)
                                              .Include(x => x.RentalAgreementRates)
                                              .FirstOrDefault(a => a.Id == id);

            if (rentalAgreement != null)
            {
                // construct the view model
                RentalAgreementPdfViewModel rentalAgreementPdfViewModel = rentalAgreement.ToViewModel();

                string payload = JsonConvert.SerializeObject(rentalAgreementPdfViewModel, new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                    Formatting            = Formatting.Indented,
                    DateFormatHandling    = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling  = DateTimeZoneHandling.Utc
                });

                _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - Payload Length: {1}", id, payload.Length);

                // pass the request on to the Pdf Micro Service
                string pdfHost   = _configuration["PDF_SERVICE_NAME"];
                string pdfUrl    = _configuration.GetSection("Constants:RentalAgreementPdfUrl").Value;
                string targetUrl = pdfHost + pdfUrl;

                // generate pdf document name [unique portion only]
                string ownerName = rentalAgreement.Equipment.Owner.OrganizationName.Trim().ToLower();
                ownerName = CleanFileName(ownerName);
                ownerName = ownerName.Replace(" ", "");
                ownerName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(ownerName);
                string fileName = rentalAgreement.Number + "_" + ownerName;

                targetUrl = targetUrl + "/" + fileName;

                _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - HETS Pdf Service Url: {1}", id, targetUrl);

                // call the microservice
                try
                {
                    HttpClient    client        = new HttpClient();
                    StringContent stringContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");

                    _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - Calling HETS Pdf Service", id);
                    HttpResponseMessage response = client.PostAsync(targetUrl, stringContent).Result;

                    // success
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - HETS Pdf Service Response: OK", id);

                        var pdfResponseBytes = GetPdf(response);

                        // convert to string and log
                        string pdfResponse = Encoding.Default.GetString(pdfResponseBytes);

                        fileName = fileName + ".pdf";

                        _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - HETS Pdf Filename: {1}", id, fileName);
                        _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - HETS Pdf Size: {1}", id, pdfResponse.Length);

                        // return content
                        FileContentResult result = new FileContentResult(pdfResponseBytes, "application/pdf")
                        {
                            FileDownloadName = fileName
                        };

                        return(result);
                    }

                    _logger.LogInformation("Rental Agreement Pdf [Id: {0}] - HETS Pdf Service Response: {1}", id, response.StatusCode);
                }
                catch (Exception ex)
                {
                    Debug.Write("Error generating pdf: " + ex.Message);
                    return(new ObjectResult(new HetsResponse("HETS-05", ErrorViewModel.GetDescription("HETS-05", _configuration))));
                }

                // problem occured
                return(new ObjectResult(new HetsResponse("HETS-05", ErrorViewModel.GetDescription("HETS-05", _configuration))));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }