public async Task <FileResult> GenerateFingerReport([FromBody] ReportInput input) { var data = await _userAppService.GenerateFingerReport(input); var query = from s in data group s by s.UserId into g select g.ToList(); var result = query.ToList(); string cusomtSwitches = string.Format("--header-html \"{0}\" --footer-center \" Created Date: " + DateTime.Now.Date.ToString("dd/MM/yyyy") + " Page: [page]/[toPage]\"" + " --footer-line --footer-font-size \"12\" --footer-spacing 1 --footer-font-name \"Segoe UI\"", Url.Action("Header", "Report", new HeaderModel { ReportName = " تقرير البصمات " }, "https")); var report = new ViewAsPdf("FingerReport") { PageMargins = { Left = 5, Bottom = 20, Right = 5, Top = 30 }, Model = result, PageSize = Rotativa.AspNetCore.Options.Size.A4, CustomSwitches = cusomtSwitches }; var bytes = await report.BuildFile(this.ControllerContext); return(File(bytes, "application/pdf", "test.pdf")); }
/// <summary> /// Function to generate and return the report binaries /// </summary> /// <param name="reportData">Report data containing date range, format, and report name</param> /// <returns>The HttpResponse from the report server</returns> public async Task <HttpResponseMessage> GenerateReport(ReportInput reportData) { HttpResponseMessage resp = null; string format, reportName; format = GetFormat(reportData); reportName = GetReportName(reportData); if (!reportName.Equals("Invalid")) { string startDate = reportData.StartDate.ToString("MM/dd/yyyy"); string endDate = reportData.EndDate.ToString("MM/dd/yyyy"); HttpClientHandler handler = new HttpClientHandler { PreAuthenticate = true, Credentials = new NetworkCredential(userName, password) }; var client = new HttpClient(handler); resp = await client.GetAsync(BuildUrl(ssrsBaseURL, reportName, format, startDate, endDate)); return(resp); } else { Exception e = new Exception("Error, Report Type is not valid"); throw e; } }
public async Task <List <TEntity> > GetReportAsync(string aRequestUri, ReportInput aObj) { try { string sSerialisedObj = JsonSerializer.Serialize(aObj); var vRequestMessage = new HttpRequestMessage(HttpMethod.Post, aRequestUri); var vAccessToken = await LocalStorageSvc.GetItemAsync <string>(AppConstants.AccessKey); vRequestMessage.Headers.Authorization = new AuthenticationHeaderValue(AppConstants.BearerKey, vAccessToken); vRequestMessage.Content = new StringContent(sSerialisedObj); vRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(AppConstants.JsonMediaTypeHeader); var vServiceResponse = await ServiceClient.SendAsync(vRequestMessage); if (vServiceResponse.IsSuccessStatusCode) { var vResponseBody = await vServiceResponse.Content.ReadAsStreamAsync(); return(await JsonSerializer.DeserializeAsync <List <TEntity> >(vResponseBody, JsonOptions)); } else { return(null); } } catch (Exception ex) { throw ex; } }
public IActionResult PdfReport(ReportInput input) { var globalSettings = new GlobalSettings { ColorMode = ColorMode.Color, Orientation = Orientation.Portrait, PaperSize = PaperKind.A4, Margins = new MarginSettings { Top = 10 }, DocumentTitle = "PDF Report" }; var objectSettings = new ObjectSettings { PagesCount = true, HtmlContent = Report.GetHTMLString(input), WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") }, HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true }, FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" } }; var pdf = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings } }; var file = _converter.Convert(pdf); return(File(file, "application/pdf", "Report.pdf")); }
private void InitReport() { reportInput = new ReportInput(); DateTime now = DateTime.Now; DateTime lastWeek = now.AddDays(-(int)now.DayOfWeek - 7); reportInput.StartDate = lastWeek; reportInput.EndDate = DateTime.Now; }
/// <summary> /// 新增或修改报表信息 /// </summary> /// <param name="report"></param> /// <returns></returns> public bool InsertOrUpdateReport(ReportInput report) { if (report != null) { if (_reportRepository.GetAll().Any(p => p.Id != report.Id && (p.Name == report.Name || p.Code == report.Code))) { throw new System.Exception("报表名称或编码重复"); } // var ent = AutoMapper.Mapper.Map<Report>(report); var ent = _reportRepository.GetAll().FirstOrDefault(x => x.Id == report.Id) ?? new Report(); ent = Fun.ClassToCopy(report, ent, (new string[] { "Id" }).ToList()); //var currReport = _reportRepository.InsertOrUpdate(ent); //更新主报表(基础信息) var reportId = _reportRepository.InsertOrUpdateAndGetId(ent); //更新子报表信息 if (report.ChildReportListJson != null && report.ChildReportListJson.Length > 0) { var reportList = JSON.EncodeToEntity <List <ChildReportModel> >(report.ChildReportListJson); if (reportList != null && reportList.Count > 0) { foreach (var rp in reportList) { //表格式报表保存逻辑 if (rp.ChildReportType == (short)ReportEnum.ReportType.KeyValue || rp.ChildReportType == (short)ReportEnum.ReportType.Table) { //调用表格报表的保存逻辑 _tbReportApp.SaveTbReport(rp, reportId, report.Code); } //RDLC报表保存逻辑 if (rp.ChildReportType == (short)ReportEnum.ReportType.Rdlc) { //调用RDLC报表保存逻辑 _rdlcReportApp.SaveRdlcReport(rp, reportId, report.Code); } //图形报表保存 else if (rp.ChildReportType == (short)ReportEnum.ReportType.Chart) { _chartReportApp.SaveChartReport(rp, reportId, report.Code); } } } } return(true); } else { throw new UserFriendlyException("传入信息为空!"); } }
public void Report(ReportInput input) { var bill = _workOrderManager.Get(input.BillId); var archive = _equipmentArchiveAppService.GetArchiveBySerialNo(bill.SerialNo); if (bill.ServiceType.Equals(ServiceType.Install)) { if (archive != null) { throw new UserFriendlyException("序列号已存在"); } } else { if (archive == null) { throw new UserFriendlyException("序列号不存在"); } } //记录修改回单活动 if (bill.BillStatus == BillStatus.Dispatch) { var user = AsyncHelper.RunSync(() => UserManager.GetUserByIdAsync(UserManager.AbpSession.UserId.Value)); var reportActivity = new Activity() { Bill = bill, Operater = user, Name = "修改回单", Log = string.Format("【{0}】修改了回单信息。", user.Name) }; _workOrderManager.AddActivity(reportActivity); } //回单基本信息 bill.SerialNo = input.SerialNo; bill.Office = input.Office; bill.OfficeMobile = input.OfficeMobile; bill.OfficePerson = input.OfficePerson; bill.OfficePosition = input.OfficePosition; bill.OfficeTel = input.OfficeTel; bill.Warrenty = input.Warrenty; bill.ServiceTime = input.ServiceTime; bill.Dealfa = input.Dealfa; bill.GuaranteedState = input.GuaranteedState; bill.TrafficLong = input.TrafficLong; bill.TrafficUrban = input.TrafficUrban; bill.Supply = input.Supply; bill.OtherEx = input.OtherEx; bill.HotelEx = input.HotelEx; //处理图片 PhotoProcess(input, bill); }
/// <summary> /// Helper function to return the name of the report to generate /// </summary> /// <param name="reportInput"></param> /// <returns></returns> private string GetReportName(ReportInput reportInput) { switch (reportInput.ReportName) { case ReportName.LaborHoursByJob: return("LaborHoursByJob"); case ReportName.LaborHoursByJobAndEmployee: return("LaborHoursByJobAndEmployee"); case ReportName.IncentiveReport: return("IncentiveReport"); } return("Invalid"); }
/// <summary> /// Endpoint to run the selected report /// </summary> /// <param name="reportData"></param> /// <returns></returns> public async Task <JsonResult> RunReport(ReportInput reportData) { try { Authorize(); } catch (HttpResponseException e) { return(Json(new { newUrl = Url.Action("Error", Utility.CreateHttpErrorView(e, "401 Unauthorized")) })); } HttpResponseMessage resp = null; try { ReportGenerator rg = new ReportGenerator(); resp = await rg.GenerateReport(reportData); var content = resp.Content; var bytes = await resp.Content.ReadAsByteArrayAsync(); return(Json(new { content = content, data = bytes })); } catch (HttpResponseException e) { string guid = ExceptionReporter.DumpException(e); ServerErrorViewModel error = await Utility.CreateServerErrorView(e); return(Json(new { newUrl = Url.Action("ServerError", error) })); } catch (Exception e) { string guid = ExceptionReporter.DumpException(e); return(Json(new { newUrl = Url.Action("Error", Utility.CreateBasicExceptionView(e, guid)) })); } }
/// <summary> /// Helper function to get the format of the report /// </summary> /// <param name="reportInput"></param> /// <returns>extension of the desired format</returns> private string GetFormat(ReportInput reportInput) { switch (reportInput.ReportFormat) { case ReportFormat.PDF: return("pdf"); case ReportFormat.CSV: return("csv"); //case ReportFormat.DOCX: // return "docx"; default: return("csv"); } }
public async Task <List <EmployeeReportOutput> > CalculateDaysReport(ReportInput input) { try { var formattedQuery = $"exec CalculateDays '{input.FromDate.ToString("yyyy-MM-dd")}','{input.ToDate.ToString("yyyy-MM-dd")}' , '{input.Type}','{input.DaysCount}'"; var result = await CurrentUnitOfWork.GetDbContext <AttendanceDbContext>().EmployeeReportCore.FromSqlRaw(formattedQuery).ToListAsync(); var output = ObjectMapper.Map <List <EmployeeReportOutput> >(result); return(output); } catch (Exception ex) { throw; } }
public async Task <List <FingerReportOutput> > GenerateFingerReport(ReportInput input) { try { var formattedQuery = $"exec SP_Transaction_Rpt_Emp_Machine '{input.FromDate.ToString("yyyy-MM-dd")}','{input.ToDate.ToString("yyyy-MM-dd")}','{string.Join(",", input.UserIds)}' , '{GetCurrentUser().Id}',''"; var result = await CurrentUnitOfWork.GetDbContext <AttendanceDbContext>().FingerReportCore.FromSqlRaw(formattedQuery).ToListAsync(); var output = ObjectMapper.Map <List <FingerReportOutput> >(result); return(output); } catch (Exception ex) { throw; } }
public async Task <List <InOutReportOutput> > GenerateInOutReport(ReportInput input) { try { var formattedQuery = $"exec SP_InOut_Summary_ByDate '{input.FromDate.ToString("yyyy-MM-dd")}','{input.ToDate.ToString("yyyy-MM-dd")}','{string.Join(",", input.UserIds)}'"; var result = await CurrentUnitOfWork.GetDbContext <AttendanceDbContext>().InOutReportOutputCore.FromSqlRaw(formattedQuery).ToListAsync(); var output = ObjectMapper.Map <List <InOutReportOutput> >(result); return(output); } catch (Exception ex) { throw; } }
public ActionResult MonthlyStats(ReportInput reportInput) { // Refactor this to make it async controller var issueManagement = new IssueManagement(UserSession.Connection); var statistics = new Cell[reportInput.Months]; for (int i = 0; i < reportInput.Months; i++) { var month = i < 10 ? String.Format("0{0}", i + 1) : i + 1.ToString(); var range = String.Format("{0}-{1}-01 .. {0}-{1}-{2}", reportInput.Year, month, DateTime.DaysInMonth(reportInput.Year, i + 1)); statistics[i] = new Cell { FilterName1 = // project: resharper #fixed resolved date: issueManagement.GetIssueCount( string.Format("{0} {1}", reportInput.FilterExpression1, range)), // project: resharper created by: resharper-developers created: FilterName2 = issueManagement.GetIssueCount( string.Format("{0} {1}", reportInput.FilterExpression2, range)), // project: resharper created by: -resharper-developers created: FilterName3= issueManagement.GetIssueCount( string.Format("{0} {1}", reportInput.FilterExpression3, range)), }; } var stastics = ConvertToArray(statistics, reportInput.Months); var reportResult = new ReportResult() { FilterName1 = reportInput.FilterName1, FilterName2 = reportInput.FilterName2, FilterName3 = reportInput.FilterName3, Statistics = stastics }; return View(reportResult); }
void UpdateOutputReport() { if (IsConnected) { if (SendByOutputReport) { if (USB.SpecifiedDevice.OutputReportLength > 0) { ReportOutput.Clear(); for (UInt16 i = 0; i < USB.SpecifiedDevice.OutputReportLength; i++) { ReportOutput.Add(new ReportByte()); } } else { ReportOutput.Clear(); } } else { if (USB.SpecifiedDevice.FeatureReportLength > 0) { ReportOutput.Clear(); for (UInt16 i = 0; i < USB.SpecifiedDevice.FeatureReportLength; i++) { ReportOutput.Add(new ReportByte()); } } else { ReportOutput.Clear(); } } } else { ReportInput.Clear(); ReportOutput.Clear(); } }
private void PhotoProcess(ReportInput input, WorkOrderBill bill) { for (int i = bill.Photos.Count - 1; i >= 0; i--) { WorkOrderPhoto photo = bill.Photos.ElementAt(i); //删除分录 _workOrderPhotoRepository.Delete(photo); // i--; } if (input.Photos == null) { return; } foreach (var photo in input.Photos) { var newPhoto = new WorkOrderPhoto() { FilePath = photo, Bill = bill }; _workOrderPhotoRepository.Insert(newPhoto); } }
public async Task GenerateReportTest() { ReportInput reportInput = new ReportInput(); reportInput.ReportName = ReportName.LaborHoursByJob; reportInput.ReportFormat = ReportFormat.PDF; reportInput.StartDate = DateTime.Today; reportInput.EndDate = DateTime.Today; var result = rg.GenerateReport(reportInput); Assert.IsNotNull(result); reportInput.ReportName = ReportName.LaborHoursByJob; reportInput.ReportFormat = ReportFormat.PDF; reportInput.StartDate = DateTime.Today; reportInput.EndDate = DateTime.Today; result = rg.GenerateReport(reportInput); Assert.IsNotNull(result); reportInput.ReportName = ReportName.LaborHoursByJob; reportInput.ReportFormat = ReportFormat.PDF; reportInput.StartDate = DateTime.Today; reportInput.EndDate = DateTime.Today; result = rg.GenerateReport(reportInput); Assert.IsNotNull(result); reportInput.ReportName = ReportName.LaborHoursByJob; reportInput.ReportFormat = ReportFormat.PDF; reportInput.StartDate = DateTime.Today; reportInput.EndDate = DateTime.Today; result = rg.GenerateReport(reportInput); Assert.IsNotNull(result); }
static void Main(string[] args) { var logger = LogManager.GetCurrentClassLogger(); var input = new ReportInput(); input.EmailListToNotify = new string[1] { "*****@*****.**" }; input.CPF = "000.000.000-00"; // provide here a CPF input.Protocol = "000000000000000000000"; // provide here a protocol input.BirthDate = new DateTime(); // provide here a birth date input.UF = "SP"; try { var config = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); var servicesProvider = BuildDi(config); using (servicesProvider as IDisposable) { servicesProvider.GetRequiredService <IAppointmentsAvailbilityReportGenerator>().Generate(input).Wait(); } } catch (Exception ex) { logger.Error(ex, "Stopped program because an exception occured"); throw; } finally { LogManager.Shutdown(); } }
public static string SendEmail(ReportInput Obj) { var root = System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ExcelPath"]); var StatusList = StatusMasterDAL.GetData(Obj.SessionData); Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(System.Reflection.Missing.Value); Microsoft.Office.Interop.Excel.Worksheet ws = wb.ActiveSheet; ws.Cells[1, 1] = "Group Name"; ws.Cells[1, 1].Font.Bold = true; for (int i = 0; i < StatusList.Count; i++) { ws.Cells[1, i + 2] = StatusList[i].StatusName; ws.Cells[1, i + 2].Font.Bold = true; //ws.Cells[1, i + 2].Text.Align= } ws.Cells[1, StatusList.Count + 2] = "Total"; ws.Cells[1, StatusList.Count + 2].Font.Bold = true; int cell = 2; foreach (var item in Obj.ContractorWiseReport) { int j = 1; ws.Cells[cell, j] = item.ContractorName; j++; foreach (var Status in item.StatusList) { ws.Cells[cell, j] = Status.JobCards; j++; } ws.Cells[cell, j] = item.Total; cell++; } string file = "GroupWiseReport_" + DateTime.Now.ToString("MM-dd-yyyy_hh_mm_ss") + ".xlsx"; string ExportPath = root + "" + file; wb.SaveAs(ExportPath); wb.Close(); Marshal.ReleaseComObject(wb); xla.Quit(); Marshal.FinalReleaseComObject(xla); // Function calling for Email MailAddressCollection toEmail = new MailAddressCollection(); MailAddressCollection ccEmail = new MailAddressCollection(); MailAddressCollection frmEmail = new MailAddressCollection(); using (var DbContext = new BSSDBEntities()) { var EmailList = DbContext.TblEmailMasters.Where(x => x.AccountId == Obj.SessionData.AccountId && x.DealerId == Obj.SessionData.DealerID).ToList(); foreach (var id in EmailList) { toEmail.Add(id.Email_ID); } } string MailBody = ReportsDAL.GenerateHtml(Obj.SessionData); //ccEmail.Add("*****@*****.**"); //toEmail.Add("*****@*****.**"); string MailStatus = Email.sendEmail("BodyShop_Report_" + DateTime.Now.ToString("MM-dd-yyyy"), "*****@*****.**", toEmail, ccEmail, ExportPath, MailBody); return(MailStatus); }
public string SendEmail(ReportInput Obj) { return(ReportsDAL.SendEmail(Obj)); }
public void RunReport(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn) { string ClassName = Data["ClassName"].ToString(); if (ClassName == "") { throw new Exception("ClassName Not Set!"); } Assembly assembly = Assembly.Load("MESReport"); Type ReportType = assembly.GetType(ClassName); if (ReportType == null) { throw new Exception($@"Can Not Create {ClassName}!"); } ReportBase Report = (MESReport.ReportBase)assembly.CreateInstance(ClassName); Report.DBPools = this.DBPools; Report.Init(); //循環加載input for (int i = 0; i < Report.Inputs.Count; i++) { ReportInput input = Report.Inputs[i]; bool match = false; int mIndex = 0; for (int j = 0; j < Data["Report"]["Inputs"].Count(); j++) { if (Data["Report"]["Inputs"][j]["Name"].ToString() == input.Name) { match = true; mIndex = j; break; } } if (!match) { //input.Value = null; //input.ValueForUse = null; continue; } try { if (input.InputType == "DateTime") { //input.Value = Data["Report"]["Inputs"][mIndex]["Value"]?.ToObject<DateTime>(); input.Value = Data["Report"]["Inputs"][mIndex]["Value"]?.ToString().Replace("%20", " "); if (input.Value != null) { input.Value = Convert.ToDateTime(input.Value); } input.ValueForUse = Data["Report"]["Inputs"][mIndex]["ValueForUse"]?.ToObject <List <DateTime> >(); } else { input.Value = Data["Report"]["Inputs"][mIndex]["Value"]?.ToObject <string>(); input.ValueForUse = Data["Report"]["Inputs"][mIndex]["ValueForUse"]?.ToObject <List <string> >(); } input.Enable = Data["Report"]["Inputs"][mIndex]["Enable"]?.ToObject <bool>(); } catch { } } Report.Run(); StationReturn.Data = Report; StationReturn.Message = ""; StationReturn.Status = StationReturnStatusValue.Pass; }
public async Task Generate(ReportInput input, IReadOnlyCollection <DPFCity> overrideDPFCities = null, string overrideUf = null, bool noDelaysExpected = false) { Dictionary <DPFCity, List <Tuple <DPFOffice, IReadOnlyCollection <string> > > > dictionaryResult = new Dictionary <DPFCity, List <Tuple <DPFOffice, IReadOnlyCollection <string> > > >(); logInfo($"Starting report generation"); var cities = await this._dpfGateway.GetAvailbleCities(input.CPF, input.Protocol, input.BirthDate); if (overrideDPFCities?.Count > 0) { cities.Data = overrideDPFCities; } if (!String.IsNullOrEmpty(overrideUf)) { input.UF = overrideUf; } logInfo($"{cities.Data.Count} cities found"); foreach (var city in cities.Data.OrderBy(a => a.Id)) { await randomDelay(noDelaysExpected); logInfo($"Checking city {city.Id}-{city.Name}"); var offices = await this._dpfGateway.GetAvailbleOffices(cities.SessionData, city.Id); logInfo($"{offices.Data.Count} offices found"); foreach (var office in offices.Data) { logInfo($"Checking office {office.Id}-{office.Name}"); if (office.IsAppointmentMandatory) { logInfo($"Office with appointment mandatory."); } IReadOnlyCollection <string> appointmentAlerts = null; if (office.HaveAlerts) { logInfo($"Office with alerts '{office.Alerts}'."); } else if (office.IsAppointmentMandatory) { await randomDelay(noDelaysExpected); appointmentAlerts = (await this._dpfGateway.GetAppointmentAlertsFromOffice(cities.SessionData, input.UF, city.Id, office.Id)).Data; if (appointmentAlerts.Count > 0) { logInfo($"Office with appoitment alerts '{appointmentAlerts.FirstOrDefault()}'."); } } registerReport(dictionaryResult, city, office, appointmentAlerts); logInfo($"Office {office.Id}-{office.Name} checked"); } logInfo($"City {city.Id}-{city.Name} checked"); } var emailSent = this._appointmentsAvailbilityReportSender.Send(input.EmailListToNotify, dictionaryResult); logInfo($"Report generation finished, email sent={emailSent}"); }
public async Task HaveOfficesWithOutAlerts_ShouldBePresentInFinalDictionary() { // Arrange var sessionData = new Model.SessionData() { Cookie = Guid.NewGuid().ToString() }; var cities = new List <Model.DPFCity>() { new Model.DPFCity() { Id = "1", Name = "SÃO PAULO" } }; var input = new ReportInput(); var offices = new List <Model.DPFOffice>() { new Model.DPFOffice() { Id = "2025", Name = "SÃO PAULO OFFICE A", IsAppointmentMandatory = true }, new Model.DPFOffice() { Id = "2026", Name = "SÃO PAULO OFFICE B", IsAppointmentMandatory = false, Alerts = "Closed" }, new Model.DPFOffice() { Id = "2027", Name = "SÃO PAULO OFFICE C", IsAppointmentMandatory = true } }; List <Tuple <Model.DPFOffice, IReadOnlyCollection <string> > > officesTuple = new List <Tuple <DPFOffice, IReadOnlyCollection <string> > >(); var alerts = new List <string>() { "No dates availble" }; this.dpfGatewayMock .Setup(a => a.GetAvailbleCities(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>())) .Returns(Task.FromResult( new Model.DPFResponse <IReadOnlyCollection <Model.DPFCity> >(cities, sessionData) )); this.dpfGatewayMock .Setup(a => a.GetAvailbleOffices(It.IsAny <Model.SessionData>(), It.IsAny <string>())) .Returns(Task.FromResult( new Model.DPFResponse <IReadOnlyCollection <Model.DPFOffice> >(offices, sessionData) )); this.dpfGatewayMock .Setup(a => a.GetAppointmentAlertsFromOffice(It.IsAny <Model.SessionData>(), It.IsAny <string>(), It.IsAny <string>(), offices.FirstOrDefault().Id)) .Returns(Task.FromResult( new Model.DPFResponse <IReadOnlyCollection <string> >(new List <string>(), sessionData) )); this.dpfGatewayMock .Setup(a => a.GetAppointmentAlertsFromOffice(It.IsAny <Model.SessionData>(), It.IsAny <string>(), It.IsAny <string>(), offices.LastOrDefault().Id)) .Returns(Task.FromResult( new Model.DPFResponse <IReadOnlyCollection <string> >(alerts, sessionData) )); Dictionary <Model.DPFCity, List <Tuple <Model.DPFOffice, IReadOnlyCollection <string> > > > result = null; this.appointmentsAvailbilityReportSenderMock .Setup(a => a.Send(It.IsAny <string[]>(), It.IsAny <Dictionary <Model.DPFCity, List <Tuple <Model.DPFOffice, IReadOnlyCollection <string> > > > >())) .Callback <string[], Dictionary <Model.DPFCity, List <Tuple <Model.DPFOffice, IReadOnlyCollection <string> > > > >((emails, obj) => result = obj) .Returns(true); offices.ForEach(a => officesTuple.Add(new Tuple <DPFOffice, IReadOnlyCollection <string> >(a, a.Id == offices.LastOrDefault().Id ? alerts : a.IsAppointmentMandatory ? new List <string>() : null))); Dictionary <DPFCity, List <Tuple <DPFOffice, IReadOnlyCollection <string> > > > expected = generateExpectedDictionary(cities, officesTuple); // Act await this.appointmentsAvailbilityReportGenerator.Generate(input, null, null, true); // Assert result.Should().BeEquivalentTo(expected); }
private string GetSecureNotice(EventHandlerEnvironment env) { ReportInput input = new ReportInput(); Writelog(env.Input + "GetSecureNotice :"); try { input = JsonConvert.DeserializeObject <ReportInput>(env.Input); } catch (Exception ex) { Writelog(env.Input + "GetSecureNotice error:" + ex.Message); return(JsonConvert.SerializeObject("-1", Formatting.None)); } #region search issuenotice var conditions = new SearchConditions(); { var condition = new SearchCondition(); condition.ConditionType = MFConditionType.MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass; condition.TypedValue.SetValueToLookup(new Lookup { Item = ClassSecureNotice.ID }); conditions.Add(-1, condition); } { var condition = new SearchCondition(); condition.ConditionType = MFConditionType.MFConditionTypeGreaterThanOrEqual; condition.Expression.DataPropertyValuePropertyDef = PropCheckDate.ID; condition.TypedValue.SetValue(MFDataType.MFDatatypeDate, input.startDate); conditions.Add(-1, condition); } { var condition = new SearchCondition(); condition.ConditionType = MFConditionType.MFConditionTypeLessThanOrEqual; condition.Expression.DataPropertyValuePropertyDef = PropCheckDate.ID; condition.TypedValue.SetValue(MFDataType.MFDatatypeDate, input.endDate); conditions.Add(-1, condition); } if (input.principal != 0) { var condition = new SearchCondition(); condition.ConditionType = MFConditionType.MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = PropPrincipal.ID; condition.TypedValue.SetValueToLookup(new Lookup { Item = input.principal }); conditions.Add(-1, condition); } if (input.receiver != 0) { var condition = new SearchCondition(); condition.ConditionType = MFConditionType.MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = PropSecureReceiver.ID; condition.TypedValue.SetValueToLookup(new Lookup { Item = input.receiver }); conditions.Add(-1, condition); } var allwork = env.Vault.ObjectSearchOperations.SearchForObjectsByConditionsEx(conditions, MFSearchFlags.MFSearchFlagNone, false, 0, 0).GetAsObjectVersions(); #endregion search issuenotice var templatefile = GetTemplateFile(env); if (string.IsNullOrEmpty(templatefile)) { return(JsonConvert.SerializeObject("-2", Formatting.None)); } try { var app = new Microsoft.Office.Interop.Word.Application(); var unknow = Type.Missing; // var msocoding = MsoEncoding.msoEncodingSimplifiedChineseGB18030; var doc = app.Documents.Open(templatefile, ref unknow, false, ref unknow, ref unknow, ref unknow, // ref unknow, ref unknow, ref unknow, ref unknow, msocoding, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow); //var num = 0; //foreach (Table table in doc.Tables) //{ // Writelog(string.Format("table[{0}],Columns[{1}],,Rows[{2}]", num, table.Columns.Count, table.Rows.Count)); // for (int i = 0; i < table.Columns.Count; i++) // { // for (int j = 0; j < table.Rows.Count; j++) // { // try // { // var text = table.Cell(j, i).Range.Text; // Writelog(string.Format("table[{0}],Columns[{1}],Rows[{2}],text[{3}]", num, i, j, text)); // } // catch (Exception ex) // { // Writelog(string.Format("table[{0}],Columns[{1}],Rows[{2}],message[{3}]", num, i, j, ex.Message)); // } // } // } // num++; //} //Writelog("num=" + num); var page = 0; var tableindex = 0; var temppath = System.IO.Path.GetTempPath(); doc.Tables[1].Range.Copy(); var issuename = string.Empty; var secureissuename = string.Empty; foreach (ObjectVersion objectVersion in allwork) { if (page > 0) { doc.Content.InsertParagraphAfter(); doc.Content.InsertAfter(" "); object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行; var movedown = app.Selection.MoveDown(ref WdLine, 21); //移动焦点 Writelog(string.Format(" before paste table num=[{0}],count=[{1}],down==[{2}]", doc.Tables.Count.ToString(), movedown)); app.Selection.Paste(); } var onepvs = env.Vault.ObjectPropertyOperations.GetProperties(objectVersion.ObjVer); page++; tableindex++; issuename = onepvs.SearchForProperty(0).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(4, 2).Range.Text = issuename; doc.Tables[tableindex].Cell(4, 4).Range.Text = DateTime.Now.ToShortDateString(); doc.Tables[tableindex].Cell(4, 6).Range.Text = page.ToString(); doc.Tables[tableindex].Cell(0, 1).Range.Text = "整改期限:" + onepvs.SearchForProperty(PropZhengGaiQiXin.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 2).Range.Text = "接收人:" + onepvs.SearchForProperty(PropSecureReceiver.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 3).Range.Text = "检查负责人:" + onepvs.SearchForProperty(PropPrincipal.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 4).Range.Text = "复查人:" + onepvs.SearchForProperty(PropFuChaRen.ID).GetValueAsLocalizedText(); var serial = 1; var lus = onepvs.SearchForProperty(PropSecureIssues.ID).Value.GetValueAsLookups(); foreach (Lookup lookup in lus) { var rowindex = 6 + serial; var objid = new ObjID(); objid.SetIDs(OtSecureIssue.ID, lookup.Item); var issuepvs = env.Vault.ObjectOperations.GetLatestObjectVersionAndProperties(objid, true).Properties; secureissuename = issuepvs.SearchForProperty(0).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 1).Range.Text = serial.ToString(); doc.Tables[tableindex].Cell(rowindex, 2).Range.Text = secureissuename; doc.Tables[tableindex].Cell(rowindex, 3).Range.Text = issuepvs.SearchForProperty(PropAdjustMeasure.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 4).Range.Text = issuepvs.SearchForProperty(PropAdjustMan.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(rowindex, 5).Range.Text = issuepvs.SearchForProperty(PropSecureAdjustDate.ID).GetValueAsLocalizedText(); var beforepictures = issuepvs.SearchForProperty(PropBeforePictures.ID).Value.GetValueAsLookups(); foreach (Lookup beforepicture in beforepictures) { var objver = env.Vault.ObjectOperations.GetLatestObjVer( new ObjID { ID = beforepicture.Item, Type = beforepicture.ObjectType }, true); var files = env.Vault.ObjectFileOperations.GetFiles(objver); foreach (ObjectFile objectFile in files) { var apicture = temppath + objectFile.GetNameForFileSystem(); env.Vault.ObjectFileOperations.DownloadFile(objectFile.ID, objectFile.Version, apicture); object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory; object nothing = System.Reflection.Missing.Value; // doc.Content.InsertParagraphAfter(); doc.Content.InsertAfter(string.Format("{3}安全隐患整改名称:{0},{3}安全问题名称:{1},{3}整改前照片名称:{2}{3}", issuename, secureissuename, beforepicture.DisplayValue, Environment.NewLine)); app.Selection.EndKey(ref unite, ref nothing);//将光标移至文末 object LinkToFile = false; object SaveWithDocument = true; object Anchor = app.Selection.Range; doc.InlineShapes.AddPicture(apicture, ref LinkToFile, ref SaveWithDocument, ref Anchor); } } var afterpictures = issuepvs.SearchForProperty(PropAfterPictures.ID).Value.GetValueAsLookups(); foreach (Lookup after in afterpictures) { var objver = env.Vault.ObjectOperations.GetLatestObjVer( new ObjID { ID = after.Item, Type = after.ObjectType }, true); var files = env.Vault.ObjectFileOperations.GetFiles(objver); foreach (ObjectFile objectFile in files) { var apicture = temppath + objectFile.GetNameForFileSystem(); env.Vault.ObjectFileOperations.DownloadFile(objectFile.ID, objectFile.Version, apicture); object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory; object nothing = System.Reflection.Missing.Value; // doc.Content.InsertParagraphAfter(); doc.Content.InsertAfter(string.Format("{3}安全隐患整改名称:{0},{3}安全问题名称:{1},{3}复查现场照片名称:{2}{3}", issuename, secureissuename, after.DisplayValue, Environment.NewLine)); app.Selection.EndKey(ref unite, ref nothing);//将光标移至文末 object LinkToFile = false; object SaveWithDocument = true; object Anchor = app.Selection.Range; doc.InlineShapes.AddPicture(apicture, ref LinkToFile, ref SaveWithDocument, ref Anchor); } } serial++; if (serial > 12) { doc.Content.InsertParagraphAfter(); doc.Content.InsertAfter(" "); object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行; var movedown = app.Selection.MoveDown(ref WdLine, 21); //移动焦点 Writelog(string.Format(" before paste table num=[{0}],count=[{1}],down==[{2}]", doc.Tables.Count.ToString(), movedown)); app.Selection.Paste(); page++; tableindex++; doc.Tables[tableindex].Cell(4, 2).Range.Text = "project name"; doc.Tables[tableindex].Cell(4, 4).Range.Text = DateTime.Now.ToShortDateString(); doc.Tables[tableindex].Cell(4, 6).Range.Text = page.ToString(); doc.Tables[tableindex].Cell(0, 1).Range.Text = "整改期限:" + onepvs.SearchForProperty(PropZhengGaiQiXin.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 2).Range.Text = "接收人:" + onepvs.SearchForProperty(PropSecureReceiver.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 3).Range.Text = "检查负责人:" + onepvs.SearchForProperty(PropPrincipal.ID).GetValueAsLocalizedText(); doc.Tables[tableindex].Cell(0, 4).Range.Text = "复查人:" + onepvs.SearchForProperty(PropFuChaRen.ID).GetValueAsLocalizedText(); } } } doc.Close(); app.Quit(); } catch (Exception ex) { Writelog(ex.Message); } var pvs = new PropertyValues(); var pv = new PropertyValue(); pv.PropertyDef = 0; pv.Value.SetValue(MFDataType.MFDatatypeText, "securenoticereport"); pvs.Add(-1, pv); pv.PropertyDef = 100; pv.Value.SetValueToLookup(new Lookup { Item = ClassSecureReport }); pvs.Add(-1, pv); var file = new SourceObjectFile(); file.Title = "report"; file.SourceFilePath = templatefile; file.Extension = "docx"; var t = env.Vault.ObjectOperations.CreateNewSFDObject(0, pvs, file, true); var f = env.Vault.ObjectFileOperations.GetFiles(t.ObjVer); var rpd = new ReportPrintData(); rpd.objid = t.ObjVer.ID; rpd.objtype = t.ObjVer.Type; rpd.objversion = t.ObjVer.Version; rpd.fileid = f[1].FileVer.ID; rpd.fileversion = f[1].FileVer.Version; return(JsonConvert.SerializeObject(rpd, Formatting.None)); }
/// <summary> /// Maps result types from TRX into instance of drop models with configuration /// </summary> /// <param name="source">Instance of test results from deserialised TRX input</param> /// <param name="destination">Instance to map and merge results into</param> /// <param name="inputConfiguration">User configured input for current source</param> public static void Map(TestRunType source, TestRunDrop destination, ReportInput inputConfiguration = null) { var times = source.Times.FirstOrDefault(); var started = DateTimeOffset.Parse(times.Start); var finished = DateTimeOffset.Parse(times.Finish); if (destination.Started is null || destination.Started > started) { destination.Started = started; } if (destination.Finished is null || destination.Finished < finished) { destination.Finished = finished; } var definitions = source.TestDefinitions.SelectMany(x => x.UnitTest).ToDictionary(k => k.Id, v => v); var unitTestResultsGroup = source.Results .SelectMany(r => r.UnitTestResult) .Select(r => (result: r, definition: definitions[r.TestId])) .GroupBy(t => inputConfiguration?.GroupTitle ?? StringFilters.PathSplit(t.definition.TestMethod.CodeBase).Last()) // Group by codebase if no title is provided .ToList(); foreach (var resultGroup in unitTestResultsGroup) { TestResultSetDrop drop; if (destination.ResultSets.TryGetValue(resultGroup.Key, out var existingDrop)) { drop = existingDrop; } else { drop = new TestResultSetDrop { Source = resultGroup.Key, Results = new List <TestResultDrop>(), }; destination.ResultSets.Add(drop); } foreach (var(result, definition) in resultGroup) { foreach (var unitTestResults in ExtractTestResults(result)) { var testCase = new TestCaseDrop { Source = definition.TestMethod.CodeBase, DisplayName = string.IsNullOrEmpty(inputConfiguration?.TestSuffix) ? unitTestResults.TestName : $"{unitTestResults.TestName}{inputConfiguration.TestSuffix}", FullyQualifiedName = $"{definition.TestMethod.ClassName}.{definition.TestMethod.Name}", Id = Guid.Parse(definition.Id), ExecutorUri = definition.TestMethod.AdapterTypeName, }; var startTime = DateTimeOffset.Parse(unitTestResults.StartTime); var endTime = DateTimeOffset.Parse(unitTestResults.EndTime); var duration = (endTime - startTime); var outcome = MapOutcome(unitTestResults.Outcome, drop, destination.TestRunStatistics); var resultDrop = new TestResultDrop { StartTime = startTime, EndTime = endTime, Duration = duration, Outcome = outcome, TestCase = testCase, ComputerName = unitTestResults.ComputerName, AttachmentSets = new List <AttachmentSetDrop>(unitTestResults.CollectorDataEntries.Select(rf => new AttachmentSetDrop { Attachments = new List <AttachmentDrop>(rf.Collector.Select(c => new AttachmentDrop { Description = c.CollectorDisplayName, Uri = c.Uri })) })), DisplayName = definition.TestMethod.Name }; MapOutputToResult(unitTestResults.Output, resultDrop); destination.TestRunStatistics.ExecutedTestsCount++; destination.ElapsedTimeInRunningTests += duration; drop.Duration += duration; drop.ExecutedTestsCount++; drop.Results.Add(resultDrop); } } } }
/// <summary> /// Maps result types from JUnit into instance of drop models with configuration /// </summary> /// <param name="source">Instance of test results from deserialised JUnit input</param> /// <param name="destination">Instance to map and merge results into</param> /// <param name="inputConfiguration">User configured input for current source</param> public static void Map(Testsuites source, TestRunDrop destination, ReportInput inputConfiguration = null) { foreach (var testsuite in source.Testsuite) { var started = DateTimeOffset.Parse(testsuite.Timestamp); var finished = started + TimeSpan.FromMilliseconds(double.Parse(testsuite.Time)); if (destination.Started is null || destination.Started > started) { destination.Started = started; } if (destination.Finished is null || destination.Finished < finished) { destination.Finished = finished; } var key = inputConfiguration?.GroupTitle ?? testsuite.Package; foreach (var testCase in testsuite.Testcase) { TestResultSetDrop drop; if (destination.ResultSets.TryGetValue(key, out var existingDrop)) { drop = existingDrop; } else { drop = new TestResultSetDrop { Source = key, Results = new List <TestResultDrop>(), }; destination.ResultSets.Add(drop); } var testCaseDrop = new TestCaseDrop { Source = testsuite.Package, DisplayName = string.IsNullOrEmpty(inputConfiguration?.TestSuffix) ? testCase.Name : $"{testCase.Name}{inputConfiguration.TestSuffix}", FullyQualifiedName = $"{testCase.Classname}.{testCase.Classname}", Id = null, ExecutorUri = null, }; var duration = TimeSpan.FromMilliseconds(double.Parse(testCase.Time)); var outcome = MapOutcome(testCase, drop, destination.TestRunStatistics); var resultDrop = new TestResultDrop { StartTime = null, EndTime = null, Duration = duration, Outcome = outcome, TestCase = testCaseDrop, ComputerName = testsuite.Hostname, AttachmentSets = null, DisplayName = testCase.Name }; MapOutputToResult(testCase, resultDrop); destination.TestRunStatistics.ExecutedTestsCount++; destination.ElapsedTimeInRunningTests += duration; drop.Duration += duration; drop.ExecutedTestsCount++; drop.Results.Add(resultDrop); } } }