public IActionResult GetMonthlyReport(string reportId) { try { var filter = $"adoxio_cannabismonthlyreportid eq {reportId}"; MicrosoftDynamicsCRMadoxioCannabismonthlyreport monthlyReport = _dynamicsClient.Cannabismonthlyreports.Get(filter: filter).Value.FirstOrDefault(); if (monthlyReport != null && CurrentUserHasAccessToMonthlyReportOwnedBy(monthlyReport._adoxioLicenseeidValue)) { return(new JsonResult(monthlyReport.ToViewModel(_dynamicsClient, true))); } } catch (HttpOperationException ex) { _logger.LogError(ex, "Error getting cannabis monthly report"); } return(new NotFoundResult()); }
public static MonthlyReport ToViewModel(this MicrosoftDynamicsCRMadoxioCannabismonthlyreport dynamicsMonthlyReport, IDynamicsClient dynamicsClient) { if (dynamicsMonthlyReport == null) { return(null); } MonthlyReport monthlyReportVM = new MonthlyReport() { licenseId = dynamicsMonthlyReport._adoxioLicenceidValue, licenseNumber = dynamicsMonthlyReport.AdoxioLicencenumber, reportingPeriodMonth = dynamicsMonthlyReport.AdoxioReportingperiodmonth, reportingPeriodYear = dynamicsMonthlyReport.AdoxioReportingperiodyear, statusCode = dynamicsMonthlyReport.Statuscode, employeesManagement = dynamicsMonthlyReport.AdoxioEmployeesmanagement, employeesAdministrative = dynamicsMonthlyReport.AdoxioEmployeesadministrative, employeesSales = dynamicsMonthlyReport.AdoxioEmployeessales, employeesProduction = dynamicsMonthlyReport.AdoxioEmployeesproduction, employeesOther = dynamicsMonthlyReport.AdoxioEmployeesother, inventorySalesReports = new List <InventorySalesReport>() }; monthlyReportVM.monthlyReportId = dynamicsMonthlyReport.AdoxioCannabismonthlyreportid; // fetch the establishment and get name and address Guid?adoxioEstablishmentId = null; if (!string.IsNullOrEmpty(dynamicsMonthlyReport._adoxioEstablishmentidValue)) { adoxioEstablishmentId = Guid.Parse(dynamicsMonthlyReport._adoxioEstablishmentidValue); } if (adoxioEstablishmentId != null) { var establishment = dynamicsClient.Establishments.GetByKey(adoxioEstablishmentId.ToString()); monthlyReportVM.establishmentName = establishment.AdoxioName; monthlyReportVM.establishmentAddressCity = establishment.AdoxioAddresscity; monthlyReportVM.establishmentAddressPostalCode = establishment.AdoxioAddresspostalcode; } IEnumerable <MicrosoftDynamicsCRMadoxioCannabisinventoryreport> inventoryReports = dynamicsClient.GetInventoryReportsForMonthlyReport(dynamicsMonthlyReport.AdoxioCannabismonthlyreportid); foreach (var inventoryReport in inventoryReports) { MicrosoftDynamicsCRMadoxioCannabisproductadmin product = dynamicsClient.Cannabisproductadmins.GetByKey(inventoryReport._adoxioProductidValue); InventorySalesReport inv = new InventorySalesReport() { product = product.AdoxioName, ProductDescription = product.AdoxioDescription, ProductDisplayOrder = product.AdoxioDisplayorder, inventoryReportId = inventoryReport.AdoxioCannabisinventoryreportid, openingInventory = inventoryReport.AdoxioOpeninginventory, domesticAdditions = inventoryReport.AdoxioQtyreceiveddomestic, returnsAdditions = inventoryReport.AdoxioQtyreceivedreturns, otherAdditions = inventoryReport.AdoxioQtyreceivedother, domesticReductions = inventoryReport.AdoxioQtyshippeddomestic, returnsReductions = inventoryReport.AdoxioQtyshippedreturned, destroyedReductions = inventoryReport.AdoxioQtydestroyed, lostReductions = inventoryReport.AdoxioQtyloststolen, otherReductions = inventoryReport.AdoxioOtherreductions, closingNumber = inventoryReport.AdoxioClosinginventory, closingValue = (inventoryReport.AdoxioValueofclosinginventory != null) ? inventoryReport.AdoxioValueofclosinginventory.Value : 0, totalSalesToConsumerQty = Convert.ToInt32(inventoryReport.AdoxioPackagedunitsnumber), totalSalesToConsumerValue = (inventoryReport.AdoxioTotalvalue != null) ? inventoryReport.AdoxioTotalvalue.Value : 0, totalSalesToRetailerQty = Convert.ToInt32(inventoryReport.AdoxioPackagedunitsnumberretailer), totalSalesToRetailerValue = (inventoryReport.AdoxioTotalvalueretailer != null) ? inventoryReport.AdoxioTotalvalueretailer.Value : 0 }; if (product.AdoxioName != "Seeds" && product.AdoxioName != "Vegetative Cannabis") { inv.closingWeight = (inventoryReport.AdoxioWeightofclosinginventory != null) ? inventoryReport.AdoxioWeightofclosinginventory.Value : 0; } if (product.AdoxioName == "Seeds") { inv.totalSeeds = inventoryReport.AdoxioTotalnumberseeds; } monthlyReportVM.inventorySalesReports.Add(inv); } return(monthlyReportVM); }
/// <summary> /// Generate a csv with the federal tracking report for a given reporting period /// </summary> /// <returns></returns> public async Task GenerateFederalTrackingReport(PerformContext hangfireContext) { try { MicrosoftDynamicsCRMadoxioCannabismonthlyreport previousReport = _dynamicsClient.Cannabismonthlyreports.Get(top: 1, orderby: new List <string> { "adoxio_csvexportid desc" }).Value.FirstOrDefault(); int currentExportId = (previousReport != null && previousReport.AdoxioCsvexportid != null) ? (int)previousReport.AdoxioCsvexportid + 1 : 1; // Submitted reports string filter = $"statuscode eq {(int)MonthlyReportStatus.Submitted}"; var dynamicsMonthlyReports = _dynamicsClient.Cannabismonthlyreports.Get(filter: filter); List <FederalReportingMonthlyExport> monthlyReports = new List <FederalReportingMonthlyExport>(); foreach (MicrosoftDynamicsCRMadoxioCannabismonthlyreport report in dynamicsMonthlyReports.Value) { FederalReportingMonthlyExport export = new FederalReportingMonthlyExport() { ReportingPeriodMonth = report.AdoxioReportingperiodmonth, ReportingPeriodYear = report.AdoxioReportingperiodyear, RetailerDistributor = report.AdoxioRetailerdistributor?.ToString() ?? "1", CompanyName = report.AdoxioEstablishmentnametext, SiteID = report.AdoxioSiteidnumber, City = report.AdoxioCity, PostalCode = report.AdoxioPostalcode, ManagementEmployees = report.AdoxioEmployeesmanagement ?? 0, AdministrativeEmployees = report.AdoxioEmployeesadministrative ?? 0, SalesEmployees = report.AdoxioEmployeessales ?? 0, ProductionEmployees = report.AdoxioEmployeesproduction ?? 0, OtherEmployees = report.AdoxioEmployeesother ?? 0 }; filter = $"_adoxio_monthlyreportid_value eq {report.AdoxioCannabismonthlyreportid}"; var invResp = _dynamicsClient.Cannabisinventoryreports.Get(filter: filter); foreach (MicrosoftDynamicsCRMadoxioCannabisinventoryreport inventoryReport in invResp.Value) { MicrosoftDynamicsCRMadoxioCannabisproductadmin product = _dynamicsClient.Cannabisproductadmins.GetByKey(inventoryReport._adoxioProductidValue); export.PopulateProduct(inventoryReport, product); } monthlyReports.Add(export); MicrosoftDynamicsCRMadoxioCannabismonthlyreport patchRecord = new MicrosoftDynamicsCRMadoxioCannabismonthlyreport() { AdoxioCsvexportdate = DateTime.UtcNow, AdoxioCsvexportid = currentExportId, Statuscode = (int)MonthlyReportStatus.Closed }; _dynamicsClient.Cannabismonthlyreports.Update(report.AdoxioCannabismonthlyreportid, patchRecord); } hangfireContext.WriteLine($"Found {monthlyReports.Count} monthly reports to export."); _logger.LogInformation($"Found {monthlyReports.Count} monthly reports to export."); if (monthlyReports.Count > 0) { string filePath = ""; using (var mem = new MemoryStream()) using (var writer = new StreamWriter(mem)) using (var csv = new CsvWriter(writer)) { csv.Configuration.RegisterClassMap <FederalReportingMonthlyExportMap>(); csv.WriteRecords(monthlyReports); writer.Flush(); mem.Position = 0; string filename = $"{currentExportId.ToString("0000")}_{DateTime.Now.ToString("yyy-MM-dd")}-CannabisTrackingReport.csv"; string sharepointFilename = await _sharepoint.UploadFile(filename, DOCUMENT_LIBRARY, "", mem, "text/csv"); string url = _sharepoint.GetServerRelativeURL(DOCUMENT_LIBRARY, ""); } hangfireContext.WriteLine($"Successfully exported Federal Reporting CSV {currentExportId}."); _logger.LogInformation($"Successfully exported Federal Reporting CSV {currentExportId}."); } } catch (HttpOperationException httpOperationException) { hangfireContext.WriteLine("Error creating federal tracking CSV"); _logger.LogError(httpOperationException, "Error creating federal tracking CSV"); } catch (SharePointRestException e) { hangfireContext.WriteLine("Error saving csv to sharepoint"); _logger.LogError(e, "Error saving csv to sharepoint"); } }
public IActionResult UpdateMonthlyReport([FromBody] MonthlyReport item, string id) { if (item != null && id != item.monthlyReportId) { return(BadRequest()); } // get the current user. UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor); Guid monthlyReportId = new Guid(id); string filter = $"adoxio_cannabismonthlyreportid eq {id}"; var monthlyReportResp = _dynamicsClient.Cannabismonthlyreports.Get(filter: filter); if (monthlyReportResp.Value.Count < 1 || !CurrentUserHasAccessToMonthlyReportOwnedBy(monthlyReportResp.Value[0]._adoxioLicenseeidValue)) { return(new NotFoundResult()); } try { // Update monthly report MicrosoftDynamicsCRMadoxioCannabismonthlyreport monthlyReport = new MicrosoftDynamicsCRMadoxioCannabismonthlyreport { AdoxioEmployeesmanagement = item.employeesManagement, AdoxioEmployeesadministrative = item.employeesAdministrative, AdoxioEmployeessales = item.employeesSales, AdoxioEmployeesproduction = item.employeesProduction, AdoxioEmployeesother = item.employeesOther, Statuscode = item.statusCode }; _dynamicsClient.Cannabismonthlyreports.Update(item.monthlyReportId, monthlyReport); // Update inventory reports if (item.inventorySalesReports != null && item.inventorySalesReports.Count > 0) { foreach (InventorySalesReport invReport in item.inventorySalesReports) { MicrosoftDynamicsCRMadoxioCannabisinventoryreport updateReport = new MicrosoftDynamicsCRMadoxioCannabisinventoryreport { AdoxioOpeninginventory = invReport.openingInventory == null ? 0 : invReport.openingInventory, AdoxioQtyreceiveddomestic = invReport.domesticAdditions == null ? 0 : invReport.domesticAdditions, AdoxioQtyreceivedreturns = invReport.returnsAdditions == null ? 0 : invReport.returnsAdditions, AdoxioQtyreceivedother = invReport.otherAdditions == null ? 0 : invReport.otherAdditions, AdoxioQtyshippeddomestic = invReport.domesticReductions == null ? 0 : invReport.domesticReductions, AdoxioQtyshippedreturned = invReport.returnsReductions == null ? 0 : invReport.returnsReductions, AdoxioQtydestroyed = invReport.destroyedReductions == null ? 0 : invReport.destroyedReductions, AdoxioQtyloststolen = invReport.lostReductions == null ? 0 : invReport.lostReductions, AdoxioOtherreductions = invReport.otherReductions == null ? 0 : invReport.otherReductions, AdoxioClosinginventory = invReport.closingNumber == null ? 0 : invReport.closingNumber, AdoxioValueofclosinginventory = invReport.closingValue == null ? 0 : invReport.closingValue, AdoxioPackagedunitsnumber = invReport.totalSalesToConsumerQty == null ? 0 : invReport.totalSalesToConsumerQty, AdoxioTotalvalue = invReport.totalSalesToConsumerValue == null ? 0 : invReport.totalSalesToConsumerValue, AdoxioPackagedunitsnumberretailer = invReport.totalSalesToRetailerQty == null ? 0 : invReport.totalSalesToRetailerQty, AdoxioTotalvalueretailer = invReport.totalSalesToRetailerValue == null ? 0 : invReport.totalSalesToRetailerValue }; if (invReport.product == "Seeds") { updateReport.AdoxioTotalnumberseeds = invReport.totalSeeds == null ? 0 : invReport.totalSeeds; } else if (invReport.product == "Extracts - Other" || invReport.product == "Other") { updateReport.AdoxioOtherdescription = invReport.otherDescription; } if (invReport.product != "Vegetative Cannabis") { updateReport.AdoxioWeightofclosinginventory = invReport.closingWeight == null ? 0 : invReport.closingWeight; } _dynamicsClient.Cannabisinventoryreports.Update(invReport.inventoryReportId, updateReport); } } } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error updating monthly report"); // fail if we can't update. throw (httpOperationException); } return(GetMonthlyReport(id)); }
/// <summary> /// Update entity in adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioCannabismonthlyreportid'> /// key: adoxio_cannabismonthlyreportid of adoxio_cannabismonthlyreport /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this ICannabismonthlyreports operations, string adoxioCannabismonthlyreportid, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(adoxioCannabismonthlyreportid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioCannabismonthlyreportid'> /// key: adoxio_cannabismonthlyreportid of adoxio_cannabismonthlyreport /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this ICannabismonthlyreports operations, string adoxioCannabismonthlyreportid, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body) { operations.UpdateAsync(adoxioCannabismonthlyreportid, body).GetAwaiter().GetResult(); }
/// <summary> /// Update entity in adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioCannabismonthlyreportid'> /// key: adoxio_cannabismonthlyreportid of adoxio_cannabismonthlyreport /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this ICannabismonthlyreports operations, string adoxioCannabismonthlyreportid, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(adoxioCannabismonthlyreportid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Add new entity to adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse <MicrosoftDynamicsCRMadoxioCannabismonthlyreport> CreateWithHttpMessages(this ICannabismonthlyreports operations, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null) { return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Add new entity to adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MicrosoftDynamicsCRMadoxioCannabismonthlyreport> CreateAsync(this ICannabismonthlyreports operations, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Add new entity to adoxio_cannabismonthlyreports /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMadoxioCannabismonthlyreport Create(this ICannabismonthlyreports operations, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, string prefer = "return=representation") { return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_cannabismonthlyreports /// </summary> /// <param name='adoxioCannabismonthlyreportid'> /// key: adoxio_cannabismonthlyreportid of adoxio_cannabismonthlyreport /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioCannabismonthlyreportid, MicrosoftDynamicsCRMadoxioCannabismonthlyreport body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioCannabismonthlyreportid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioCannabismonthlyreportid"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("adoxioCannabismonthlyreportid", adoxioCannabismonthlyreportid); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_cannabismonthlyreports({adoxio_cannabismonthlyreportid})").ToString(); _url = _url.Replace("{adoxio_cannabismonthlyreportid}", System.Uri.EscapeDataString(adoxioCannabismonthlyreportid)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.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 = null; if (body != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task ExportFederalReports(PerformContext hangfireContext) { // Get any new exports that have been created string filter = "adoxio_exportcompleted eq null"; MicrosoftDynamicsCRMadoxioFederalreportexportCollection exports = _dynamicsClient.Federalreportexports.Get(filter: filter); if (exports.Value.Count > 0) { MicrosoftDynamicsCRMadoxioFederalreportexport export = exports.Value.FirstOrDefault(); string exportId = export.AdoxioFederalreportexportid; MicrosoftDynamicsCRMadoxioFederalreportexport patchExport = new MicrosoftDynamicsCRMadoxioFederalreportexport(); patchExport.AdoxioExporttriggered = DateTime.UtcNow; _dynamicsClient.Federalreportexports.Update(exportId, patchExport); try { // Gather submitted reports filter = $"statuscode eq {(int)MonthlyReportStatus.Submitted}"; var dynamicsMonthlyReports = _dynamicsClient.Cannabismonthlyreports.Get(filter: filter); List <FederalReportingMonthlyExport> monthlyReports = new List <FederalReportingMonthlyExport>(); hangfireContext.WriteLine($"Found {dynamicsMonthlyReports.Value.Count} monthly reports to export."); _logger.LogInformation($"Found {dynamicsMonthlyReports.Value.Count} monthly reports to export."); foreach (MicrosoftDynamicsCRMadoxioCannabismonthlyreport report in dynamicsMonthlyReports.Value) { FederalReportingMonthlyExport exportVM = new FederalReportingMonthlyExport() { ReportingPeriodMonth = report.AdoxioReportingperiodmonth, ReportingPeriodYear = report.AdoxioReportingperiodyear, RetailerDistributor = report.AdoxioRetailerdistributor?.ToString() ?? "1", CompanyName = report.AdoxioEstablishmentnametext, SiteID = report.AdoxioSiteidnumber, City = report.AdoxioCity, PostalCode = report.AdoxioPostalcode, ManagementEmployees = report.AdoxioEmployeesmanagement ?? 0, AdministrativeEmployees = report.AdoxioEmployeesadministrative ?? 0, SalesEmployees = report.AdoxioEmployeessales ?? 0, ProductionEmployees = report.AdoxioEmployeesproduction ?? 0, OtherEmployees = report.AdoxioEmployeesother ?? 0 }; // Get inventory reports for those submitted reports filter = $"_adoxio_monthlyreportid_value eq {report.AdoxioCannabismonthlyreportid}"; var invResp = _dynamicsClient.Cannabisinventoryreports.Get(filter: filter); foreach (MicrosoftDynamicsCRMadoxioCannabisinventoryreport inventoryReport in invResp.Value) { MicrosoftDynamicsCRMadoxioCannabisproductadmin product = _dynamicsClient.Cannabisproductadmins.GetByKey(inventoryReport._adoxioProductidValue); exportVM.PopulateProduct(inventoryReport, product); } monthlyReports.Add(exportVM); MicrosoftDynamicsCRMadoxioCannabismonthlyreport patchRecord = new MicrosoftDynamicsCRMadoxioCannabismonthlyreport() { AdoxioFederalReportExportIdODateBind = _dynamicsClient.GetEntityURI("adoxio_federalreportexports", exportId), Statuscode = (int)MonthlyReportStatus.Closed }; _dynamicsClient.Cannabismonthlyreports.Update(report.AdoxioCannabismonthlyreportid, patchRecord); } if (monthlyReports.Count > 0) { string filename = $"{export.AdoxioExportnumber}_{DateTime.Now.ToString("yyy-MM-dd")}-CannabisTrackingReport.csv"; Regex illegalInFileName = new Regex(@"[#%*<>?{}~¿""]"); filename = illegalInFileName.Replace(filename, ""); illegalInFileName = new Regex(@"[&:/\\|]"); filename = illegalInFileName.Replace(filename, "-"); using (var mem = new MemoryStream()) using (var writer = new StreamWriter(mem)) using (var csv = new CsvWriter(writer)) { csv.Configuration.RegisterClassMap <FederalReportingMonthlyExportMap>(); csv.WriteRecords(monthlyReports); writer.Flush(); mem.Position = 0; string folderName = null; MicrosoftDynamicsCRMsharepointdocumentlocation?documentLocation = null; if (export.AdoxioFederalreportexportSharePointDocumentLocations != null) { documentLocation = export.AdoxioFederalreportexportSharePointDocumentLocations.FirstOrDefault(); folderName = documentLocation.Relativeurl; } if (folderName == null) { folderName = export.GetDocumentFolderName(); await CreateFederalReportDocumentLocation(export, DOCUMENT_LIBRARY, folderName); } byte[] data = mem.ToArray(); //call the web service var uploadRequest = new Services.FileManager.UploadFileRequest() { ContentType = "text/csv", Data = ByteString.CopyFrom(data), EntityName = "federal_report", FileName = filename, FolderName = folderName }; bool folderResult = CreateFolder(folderName); if (folderResult) { var uploadResult = _fileManagerClient.UploadFile(uploadRequest); } else { hangfireContext.WriteLine($"Failed to create sharepoint folder for federal report."); _logger.LogInformation($"Failed to create sharepoint folder for federal report."); } } hangfireContext.WriteLine($"Successfully exported Federal Reporting CSV {export.AdoxioExportnumber}."); _logger.LogInformation($"Successfully exported Federal Reporting CSV {export.AdoxioExportnumber}."); } patchExport.AdoxioExportcompleted = DateTime.UtcNow; _dynamicsClient.Federalreportexports.Update(exportId, patchExport); } catch (HttpOperationException httpOperationException) { hangfireContext.WriteLine("Error creating federal tracking CSV"); _logger.LogError(httpOperationException, "Error creating federal tracking CSV"); } } }