/// <summary> /// 导出报表的每一个页面到一个EMF文件 /// </summary> /// <param name="report">ReportViewer.LocalReport</param> /// <param name="PageName">页面设置</param> private void Export(LocalReport report, string PageName) { string deviceInfo = ""; if (PageName != "")//单据名称 { deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>7cm</PageWidth>" + " <PageHeight>3cm</PageHeight>" + " <MarginTop>0.1cm</MarginTop>" + " <MarginLeft>0.1cm</MarginLeft>" + " <MarginRight>0.1cm</MarginRight>" + " <MarginBottom>0.1cm</MarginBottom>" + "</DeviceInfo>"; } else { deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>" + PageWidth + "</PageWidth>" + " <PageHeight>" + PageHeight + "</PageHeight>" + " <MarginTop>" + MarginTop + "</MarginTop>" + " <MarginLeft>" + MarginLeft + "</MarginLeft>" + " <MarginRight>" + MarginRight + "</MarginRight>" + " <MarginBottom>" + MarginBottom + "</MarginBottom>" + "</DeviceInfo>"; } Warning[] warnings; m_streams = new List <Stream>(); try { //report.DisplayName = PageName;// //将报表的内容按照deviceInfo指定的格式输出到CreateStream函数提供的Stream中。 report.Render("Image", deviceInfo, CreateStream, out warnings); report.Dispose(); } catch (Exception ex) { Exception innerEx = ex.InnerException;//取内异常。因为内异常的信息才有用,才能排除问题。 while (innerEx != null) { MessageBox.Show(innerEx.Message); innerEx = innerEx.InnerException; } } foreach (Stream stream in m_streams) { stream.Position = 0; } }
public void Dispose() { _localReport?.Dispose(); if (_subReports?.Count > 0) { foreach (var sr in _subReports) { sr.Value?.Dispose(); } } }
private void ExportReportToStreams(LocalReport report, string deviceInfo) { Warning[] warnings; _streams = new List <MemoryStream>(); report.Render("Image", deviceInfo, CreateStream, out warnings); report.Dispose(); foreach (Stream stream in _streams) { stream.Position = 0; } }
public void PrintGoodsTransport(CmcsGoodsTransport entity) { #region 备份 DataTable table = new DataTable(); table.Columns.Add("SerialNumber", typeof(string)); table.Columns.Add("TareTime", typeof(string)); table.Columns.Add("CarNumber", typeof(string)); table.Columns.Add("FuelKindName", typeof(string)); table.Columns.Add("SupplierName", typeof(string)); table.Columns.Add("Remark", typeof(string)); table.Columns.Add("GrossWeight", typeof(string)); table.Columns.Add("TareWeight", typeof(string)); table.Columns.Add("SuttleWeight", typeof(string)); table.Columns.Add("DeductWeight", typeof(string)); table.Columns.Add("CreateUser", typeof(string)); table.Columns.Add("Type", typeof(string)); decimal GrossWeight = entity.FirstWeight, TareWeight = entity.SecondWeight; if (entity.FirstWeight < entity.SecondWeight) { GrossWeight = entity.SecondWeight; TareWeight = entity.FirstWeight; } table.Rows.Add(entity.SerialNumber, entity.SecondTime.ToString("yyyy年MM月dd日 HH:mm"), entity.CarNumber, entity.GoodsTypeName, entity.SupplyUnitName, entity.ReceiveUnitName, GrossWeight, TareWeight, entity.SuttleWeight, 0, CommonDAO.GetInstance().GetNameByAccount(entity.CreateUser)); LocalReport report = new LocalReport(); //设置需要打印的报表的文件名称。 report.ReportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TransportReport.rdlc"); //创建要打印的数据源 ReportDataSource source = new ReportDataSource(); source.Name = "Transport"; source.Value = table; report.DataSources.Add(source); ////刷新报表中的需要呈现的数据 //report.Refresh(); PrintDocument(source, report); Dispose(); report.Dispose(); #endregion }
private MemoryStream GetExportedContent(string reportRenderType, string deviceInfo) { MemoryStream toRet; LocalReport localReport = new LocalReport(); try { byte[] reportData = ProcessReport(localReport, reportRenderType, deviceInfo); toRet = new MemoryStream(reportData); } finally { localReport.Dispose(); } return(toRet); }
protected void Page_LoadComplete(object sender, EventArgs e) { Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; SqlDataSource sql = new SqlDataSource(); sql.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DeLoreanConnectionString"].ConnectionString; sql.SelectCommand = "sp_GetReportStudentLogs"; sql.SelectCommandType = SqlDataSourceCommandType.StoredProcedure; if (Request["search"] != null) { sql.SelectParameters.Add("Search", null); } if (Request["accountID"] != null) { sql.SelectParameters.Add("AccountID", null); } if (Request["dateTimeStart"] != null) { sql.SelectParameters.Add("DateTimeStart", Request["dateTimeStart"]); } if (Request["dateTimeEnd"] != null) { sql.SelectParameters.Add("DateTimeEnd", Request["dateTimeEnd"]); } LocalReport lrpt = ReportViewer1.LocalReport; //ReportViewer1.LocalReport.ReportPath = Server.MapPath(@"StudentLogs.rdlc"); //ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("StudentLogDataSet", sql)); lrpt.ReportPath = Server.MapPath(@"StudentLogs.rdlc"); lrpt.DataSources.Add(new ReportDataSource("StudentLogDataSet", sql)); string filepath = System.IO.Path.GetTempFileName().Replace(".tmp", ".pdf"); Export(lrpt, filepath); lrpt.Dispose(); }
public void PrintLabel(char type, int id) { LocalReport report = new LocalReport(); // Set report path (*) report.ReportPath = Properties.Settings.Default.LabelReportFile; // Set report parameters (*) ReportParameter input1 = new ReportParameter("Type", "1"); ReportParameter input2 = new ReportParameter("Id", "1"); report.SetParameters(new ReportParameter[] { input1, input2 }); // Hook everything up and render the report. DataSet data = this.GetJewelryLabelReportDataSource(type, id); report.DataSources.Add(new ReportDataSource(report.GetDataSourceNames()[0], data.Tables[0])); // Set printer page settings (*) string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>2.3125in</PageWidth>" + " <PageHeight>4in</PageHeight>" + " <MarginTop>0in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0in</MarginBottom>" + "</DeviceInfo>"; ExportReportToStreams(report, deviceInfo); _currentPage = 0; Print(Properties.Settings.Default.LabelPrinterName); report.Dispose(); data.Dispose(); }
/// <summary> /// Prints a local report wihthout ReportViewer when the "Print Local Report" button is pressed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPrintLocal_Click(object sender, EventArgs e) { LocalReport report = null; DataSet dataSet = null; ReportPrintDocument printdoc = null; try { // Create a LocalReport object directly report = new LocalReport(); report.ReportPath = @"..\..\Report1.rdlc"; // Add report data sources dataSet = new DataSet(); dataSet.ReadXml(@"..\..\data.xml"); report.DataSources.Add(new ReportDataSource(report.GetDataSourceNames()[0], dataSet.Tables[0])); // Print the report using the ReportPrintDocument class (see ReportPrintDocument.cs) printdoc = new ReportPrintDocument(report); printdoc.Print(); } finally { if (report != null) { report.Dispose(); } if (dataSet != null) { dataSet.Dispose(); } if (printdoc != null) { printdoc.Dispose(); } } }
public void PrintPurchasePoliceReport(int purchaseid) { LocalReport report = new LocalReport(); // Set report path (*) report.ReportPath = Properties.Settings.Default.PurchasePoliceReportFile; // Set report parameters (*) ReportParameter input1 = new ReportParameter("PurchaseId", "1"); report.SetParameters(new ReportParameter[] { input1 }); // Hook everything up and render the report. DataSet data = this.GetPurchaseReportDataSource(purchaseid); report.DataSources.Add(new ReportDataSource(report.GetDataSourceNames()[0], data.Tables[0])); // Set printer page settings (*) string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>5.5in</PageHeight>" + " <MarginTop>0in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0in</MarginBottom>" + "</DeviceInfo>"; ExportReportToStreams(report, deviceInfo); _currentPage = 0; Print(Properties.Settings.Default.PolicePrinterName); report.Dispose(); data.Dispose(); }
public JsonResult GenerateReportForSearchResult(int sellsPointId, DateTime fromDate, DateTime toDate) { try { List <DAL.ViewModel.VM_Product> productList = unitOfWork.CustomRepository.sp_ProductSell(fromDate, toDate, sellsPointId); decimal totalAmount = 0; var newProductList = new List <VM_Product>(); foreach (var product in productList) { VM_Product newProduct = new VM_Product(); newProduct.ProductName = product.ProductName; newProduct.UnitPrice = product.UnitPrice; newProduct.Unit = product.Unit; newProduct.Quantity = product.Quantity; newProduct.TotalPrice = product.TotalPrice; newProductList.Add(newProduct); } totalAmount = productList.Select(s => s.TotalPrice).Sum(); string StoreName = unitOfWork.StoreRepository.GetByID(sellsPointId).store_name; int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());; string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/ProductSellReport.rdlc"); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("StoreName", StoreName)); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); ReportDataSource reportDataSource = new ReportDataSource("ProductSellDataSet", newProductList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Product Report generated.", result = productList, TotalAmount = totalAmount }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public JsonResult GenerateReportForSearchResult(int routeId) { try { List <DAL.ViewModel.VM_BusInformation> busInfoList = unitOfWork.CustomRepository.sp_BusInformationListForABusRoute((routeId)); var newBusInfoList = new List <DAL.ViewModel.VM_BusInformation>(); foreach (var busInfo in busInfoList) { DAL.ViewModel.VM_BusInformation newBusInfo = new DAL.ViewModel.VM_BusInformation(); newBusInfo.RegistrationNo = busInfo.RegistrationNo; newBusInfo.ModelNo = busInfo.ModelNo; newBusInfo.ChassisNo = busInfo.ChassisNo; newBusInfoList.Add(newBusInfo); } int workShopId = Int32.Parse(SessionManger.WorkShopOfLoggedInUser(Session).ToString()); string workShopName = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Name; string workShopAddress = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Address; string routerName = unitOfWork.RouteRepository.GetByID(routeId).RouteName; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/BusInfornationListForSpecificBusRouteReport.rdlc"); localReport.SetParameters(new ReportParameter("RouterName", routerName.ToString())); localReport.SetParameters(new ReportParameter("WorkShopName", workShopName)); localReport.SetParameters(new ReportParameter("WorkShopAddress", workShopAddress)); ReportDataSource reportDataSource = new ReportDataSource("BusInfornationListForSpecificBusRouteDataSet", newBusInfoList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.1in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Report generated successfully.", result = busInfoList }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public JsonResult GenerateReportForSearchResult(int?id) { try { double totalAmount = 0; var storeInfo = unitOfWork.StoreRepository.Get().Where(s => s.StoreId == id).FirstOrDefault(); var partsId = unitOfWork.PartsTransferRepository.Get().Where(a => a.StoreId == storeInfo.StoreId).DistinctBy(a => a.tblPartsInfo.PartsId).ToList(); var partsList = new List <Vm_PartsTransfetToBusRegistrationNoFromStore>(); foreach (var aParts in partsId) { if (aParts != null) { Vm_PartsTransfetToBusRegistrationNoFromStore newParts = new Vm_PartsTransfetToBusRegistrationNoFromStore(); var partsInfo = unitOfWork.PartsInfoRepository.GetByID(aParts.PartsId); if (partsInfo != null) { int partsIn = (int)unitOfWork.PartsTransferRepository.Get().Where(x => x.isIn == true && x.PartsId == partsInfo.PartsId).Select(x => x.Quantity).Sum(); int partsOut = (int)unitOfWork.PartsTransferRepository.Get().Where(x => x.isOut == true && x.PartsId == partsInfo.PartsId).Select(x => x.Quantity).Sum(); int getProductAvilableQty = partsIn - partsOut; if (getProductAvilableQty > 0) { newParts.PartsId = partsInfo.PartsId; newParts.PartsName = partsInfo.PartsName; newParts.UnitPrice = Convert.ToInt32(partsInfo.BasePrice); newParts.AvailableQuatity = getProductAvilableQty; newParts.Price = newParts.AvailableQuatity * newParts.UnitPrice; totalAmount += newParts.Price; partsList.Add(newParts); } } } } int workShopId = Int32.Parse(SessionManger.WorkShopOfLoggedInUser(Session).ToString()); string workShopName = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Name; string workShopAddress = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Address; string storeName = unitOfWork.StoreRepository.GetByID(id).StoreName; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/PartsStatusInStoreReport.rdlc"); localReport.SetParameters(new ReportParameter("StoreName", storeName)); localReport.SetParameters(new ReportParameter("WorkShopName", workShopName)); localReport.SetParameters(new ReportParameter("WorkShopAddress", workShopAddress)); ReportDataSource reportDataSource = new ReportDataSource("PartsStatusInStoreDataSet", partsList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Report generated successfully.", result = partsList, TotalAmount = totalAmount }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public void Run() { ProgressDlg prg = new ProgressDlg(); var d = new voidCaller(() => { //display wait msg prg.m_descr = "Load view data ..."; LocalReport report = new LocalReport(); //long time work DataSet ds = new DataSet(); int step = 50 / m_sqls.Count; foreach (var pair in m_sqls) { DataTable dt; dt = loadData(pair.Value); //after load data complete m_iWork += step; dt.TableName = pair.Key; ds.Tables.Add(dt); report.ReportPath = m_rdlcPath; report.DataSources.Add(new ReportDataSource(pair.Key, dt)); } //add report params List <ReportParameter> rpParams = getReportParam(); report.SetParameters(rpParams); report.Refresh(); //display wait msg prg.m_descr = "Exporting ..."; //long time work Export(report); m_iWork = 100; ds.Clear(); ds.Dispose(); report.Dispose(); }); var t = d.BeginInvoke(null, null); m_iWork = 0; prg.m_endPos = 100; prg.m_cursor = this; prg.m_param = t; prg.ShowDialog(); prg.Dispose(); //print #if false byte[] bytes = report.Render("PDF"); FileStream fs = new FileStream(m_pdfPath, FileMode.Create); fs.Seek(0, SeekOrigin.Begin); fs.Write(bytes, 0, bytes.Length); fs.Close(); #else Print(); #endif }
//public JsonResult GenerateReportForSearchResult(int? storeId, int shiftId, DateTime fromDate) public JsonResult GenerateReportForSearchResult(int storeId, int shiftId, DateTime fromDate) { try { var date = DateTime.Parse(fromDate.ToString()); var printInfo = string.Format("{0:yyyy-MM-dd}", date); //IEnumerable<VM_Product> sellsPointProductList = (from a in unitOfWork.ProductRepository.Get().Where(a => a.ProductTypeId == (int)ProductType.SellTypeProduct || a.ProductTypeId == (int)ProductType.PurchaseAndSellTypeProduct) // select new VM_Product() // { // ProductId = a.ProductId, // ProductName = a.ProductName, // Unit = a.Unit, // UnitPrice = (decimal)a.UnitPrice // }).ToList(); List <DAL.ViewModel.VM_Product> products; string groupName; decimal totalAmount = 0; decimal totalOtherExpense = 0; double netCash = 0; //List<VM_Product> products = new List<VM_Product>(); if (shiftId == 1) { groupName = unitOfWork.GroupAndShiftMappingRepository.Get() .Where(x => x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) .Select(a => a.Day) .FirstOrDefault(); //foreach (VM_Product aProduct in sellsPointProductList) //{ // var product = // unitOfWork.ProductTransferRepository.Get() // .Where(x => x.ProductId == aProduct.ProductId && x.StoreId == storeId) // .ToList(); // decimal ProductIn = (decimal)product.Where(x => x.isIn == true && x.TransferDate < fromDate).Select(x => x.Quantity).Sum(); // decimal ProductOut = (decimal)product.Where(x => x.isOut == true && x.TransferDate < fromDate).Select(x => x.Quantity).Sum(); // decimal getProductAvilableQty = ProductIn - ProductOut; // aProduct.OpeningProduct = getProductAvilableQty; // decimal issue = (decimal)product.Where(x => x.isIn == true && x.ShiftId == shiftId && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // aProduct.InProduct = issue; // aProduct.TotalProduct = aProduct.OpeningProduct + aProduct.InProduct; // decimal SellproductSelectDate = (decimal)product.Where(x => x.isOut == true && x.ShiftId == shiftId && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // aProduct.SellProduct = SellproductSelectDate; // aProduct.ClosingProduct = aProduct.TotalProduct - aProduct.SellProduct; // aProduct.TotalPrice = aProduct.UnitPrice * aProduct.SellProduct; // totalAmount += aProduct.TotalPrice; // if (getProductAvilableQty > 0 || issue > 0 || SellproductSelectDate > 0) // { // products.Add(aProduct); // } //} products = unitOfWork.CustomRepository.sp_ProductSellHistoryWithOpeningProductForDayShift(storeId, shiftId, fromDate).ToList(); if (products.Any()) { totalAmount = products.Select(x => x.TotalPrice).Sum(); } } else { groupName = unitOfWork.GroupAndShiftMappingRepository.Get() .Where(x => x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) .Select(a => a.Night) .FirstOrDefault(); //foreach (VM_Product aProduct in sellsPointProductList) //{ // var product = // unitOfWork.ProductTransferRepository.Get() // .Where(x => x.ProductId == aProduct.ProductId && x.StoreId == storeId) // .ToList(); // decimal ProductIn = (decimal)product.Where(x => x.isIn == true && x.TransferDate < fromDate).Select(x => x.Quantity).Sum(); // decimal ProductOut = (decimal)product.Where(x => x.isOut == true && x.TransferDate < fromDate).Select(x => x.Quantity).Sum(); // decimal getProductAvilableQty = ProductIn - ProductOut; // decimal issueForDay = (decimal)product.Where(x => x.isIn == true && x.ShiftId == 1 && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // decimal totalProductForDay = getProductAvilableQty + issueForDay; // decimal SellproductSelectDateForDay = (decimal)product.Where(x => x.isOut == true && x.ShiftId == 1 && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // decimal closingProductForDay = totalProductForDay - SellproductSelectDateForDay; // aProduct.OpeningProduct = closingProductForDay; // decimal issue = (decimal)product.Where(x => x.isIn == true && x.ShiftId == shiftId && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // aProduct.InProduct = issue; // aProduct.TotalProduct = aProduct.OpeningProduct + aProduct.InProduct; // decimal SellproductSelectDate = (decimal)product.Where(x => x.isOut == true && x.ShiftId == shiftId && x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)).Select(x => x.Quantity).Sum(); // aProduct.SellProduct = SellproductSelectDate; // aProduct.ClosingProduct = aProduct.TotalProduct - aProduct.SellProduct; // aProduct.TotalPrice = aProduct.UnitPrice * aProduct.SellProduct; // totalAmount += aProduct.TotalPrice; // if (closingProductForDay > 0 || issue > 0 || SellproductSelectDate > 0) // { // products.Add(aProduct); // } //} products = unitOfWork.CustomRepository.sp_ProductSellHistoryWithOpeningProductForNightShift(storeId, shiftId, fromDate).ToList(); if (products.Any()) { totalAmount = products.Select(x => x.TotalPrice).Sum(); } } //decimal less = (decimal) // unitOfWork.OtherExpenseRepository.Get() // .Where( // x => // x.StoreId == storeId && x.ShiftId == shiftId && // x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) // .Select(x => x.Less) // .Sum(); //decimal due = (decimal) // unitOfWork.OtherExpenseRepository.Get() // .Where( // x => // x.StoreId == storeId && x.ShiftId == shiftId && // x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) // .Select(x => x.Due) // .Sum(); //decimal complimen = (decimal) // unitOfWork.OtherExpenseRepository.Get() // .Where( // x => // x.StoreId == storeId && x.ShiftId == shiftId && // x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) // .Select(x => x.Compliment) // .Sum(); //decimal damage = (decimal) // unitOfWork.OtherExpenseRepository.Get() // .Where( // x => // x.StoreId == storeId && x.ShiftId == shiftId && // x.TransferDate.Value.Date == Convert.ToDateTime(printInfo)) // .Select(x => x.Damage) // .Sum(); decimal less = unitOfWork.CustomRepository.sp_OtherExpenseAmountForSellReportWithOpeningProduct(storeId, shiftId, fromDate).Select(a => a.Less).FirstOrDefault(); decimal due = unitOfWork.CustomRepository.sp_OtherExpenseAmountForSellReportWithOpeningProduct(storeId, shiftId, fromDate).Select(a => a.Due).FirstOrDefault(); decimal complimen = unitOfWork.CustomRepository.sp_OtherExpenseAmountForSellReportWithOpeningProduct(storeId, shiftId, fromDate).Select(a => a.Compliment).FirstOrDefault(); decimal damage = unitOfWork.CustomRepository.sp_OtherExpenseAmountForSellReportWithOpeningProduct(storeId, shiftId, fromDate).Select(a => a.Damage).FirstOrDefault(); totalOtherExpense = less + due + complimen + damage; netCash = (double)(totalAmount - totalOtherExpense); int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString()); string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; string storeName = unitOfWork.StoreRepository.GetByID(storeId).store_name; //string groupName = unitOfWork.GroupForShiftRepository.GetByID(groupId).GroupName; string shiftName = unitOfWork.ShiftRepository.GetByID(shiftId).ShiftName; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/ProductSellHistoryWithOpeningProductReport.rdlc"); localReport.SetParameters(new ReportParameter("Date", printInfo)); localReport.SetParameters(new ReportParameter("StoreName", storeName.ToString())); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); localReport.SetParameters(new ReportParameter("GroupName", groupName)); localReport.SetParameters(new ReportParameter("ShiftName", shiftName)); localReport.SetParameters(new ReportParameter("Less", less.ToString())); localReport.SetParameters(new ReportParameter("Due", due.ToString())); localReport.SetParameters(new ReportParameter("Complimen", complimen.ToString())); localReport.SetParameters(new ReportParameter("Damage", damage.ToString())); localReport.SetParameters(new ReportParameter("TotalOtherExpense", totalOtherExpense.ToString())); localReport.SetParameters(new ReportParameter("NetCash", netCash.ToString())); ReportDataSource reportDataSource = new ReportDataSource("ProductSellHistoryWithOpeningProductDataSet", products); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Product Report generated.", result = products, TotalAmount = totalAmount, Less = less, Due = due, Complimen = complimen, Damage = damage, TotalOtherExpense = totalOtherExpense, NetCash = netCash }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
private void SupplierProductToStoreReport(int SupplierId, int StoreId, List <VM_ProductToStore> productList) { var newProductList = new List <VM_ProductToStore>(); foreach (var product in productList) { VM_ProductToStore newProduct = new VM_ProductToStore(); newProduct.StoreId = StoreId; newProduct.StoreName = unitOfWork.StoreRepository.GetByID(StoreId).store_name; newProduct.SupplierId = SupplierId; newProduct.SupplierName = product.SupplierName; newProduct.ProductName = product.ProductName; newProduct.Quantity = product.Quantity; newProduct.Unit = product.Unit; newProduct.UnitPrice = product.UnitPrice; newProductList.Add(newProduct); } int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());; string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/SupplierProductToStoreReport.rdlc"); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); ReportDataSource reportDataSource = new ReportDataSource("SupplierProductToStoreDataSet", newProductList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var fileName = RenameReportFile(SupplierId, StoreId, DateTime.Now, "Sup", "Main"); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); //var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var saveAs = path + "\\" + fileName + ".pdf"; var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } tblChalanReport report = new tblChalanReport() { ToStore = Convert.ToString(StoreId), Supplier = Convert.ToString(SupplierId), Date = DateTime.Now, ReportName = fileName }; SaveToDatabase(report); localReport.Dispose(); }
public JsonResult SendReport( reportModel data, List <reportParm> parms, List <reportParm> extensionParms = null ) { MSGReturnModel <string> result = new MSGReturnModel <string>(); result.RETURN_FLAG = false; Treasury.WebUtility.FileRelated.createFile(Server.MapPath("~/Temp/")); try { var fileLocation = Server.MapPath("~/Temp/"); string title = "報表名稱"; if (data.className.IsNullOrWhiteSpace()) { result.DESCRIPTION = "寄送報表錯誤請聯絡IT人員"; //result.DESCRIPTION = MessageType.parameter_Error.GetDescription(null, "無呼叫的className"); return(Json(result)); } if (!data.title.IsNullOrWhiteSpace()) { title = data.title; } object obj = Activator.CreateInstance(Assembly.Load("Treasury.Web").GetType($"Treasury.Web.Report.Data.{data.className}")); MethodInfo[] methods = obj.GetType().GetMethods(); MethodInfo mi = methods.FirstOrDefault(x => x.Name == "GetData"); if (mi == null) { //檢查是否有實作資料獲取 result.DESCRIPTION = "寄送報表錯誤請聯絡IT人員"; return(Json(result)); } DataSet ds = (DataSet)mi.Invoke(obj, new object[] { parms }); List <reportParm> eparm = (List <reportParm>)(obj.GetType().GetProperty("extensionParms").GetValue(obj)); var lr = new LocalReport(); lr.ReportPath = Server.MapPath($"~/Report/Rdlc/{data.className}.rdlc"); lr.DataSources.Clear(); List <ReportParameter> _parm = new List <ReportParameter>(); _parm.Add(new ReportParameter("Title", title)); if (extensionParms != null) { _parm.AddRange(extensionParms.Select(x => new ReportParameter(x.key, x.value))); } if (eparm.Any()) { _parm.AddRange(eparm.Select(x => new ReportParameter(x.key, x.value))); } if (_parm.Any()) { lr.SetParameters(_parm); } for (int i = 0; i < ds.Tables.Count; i++) { lr.DataSources.Add(new ReportDataSource("DataSet" + (i + 1).ToString(), ds.Tables[i])); } string _DisplayName = title; if (_DisplayName != null) { _DisplayName = _DisplayName.Replace("(", "-").Replace(")", ""); var _name = _parm.FirstOrDefault(x => x.Name == "vJobProject"); if (_name != null) { _DisplayName = $"{_DisplayName}_{_name.Values[0]}"; } } lr.DisplayName = _DisplayName; lr.Refresh(); string mimeType, encoding, extension; Warning[] warnings; string[] streams; var renderedBytes = lr.Render ( "PDF", null, out mimeType, out encoding, out extension, out streams, out warnings ); var saveAs = string.Format("{0}.pdf", Path.Combine(fileLocation, _DisplayName)); var idx = 0; while (Directory.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(fileLocation, _DisplayName), idx); } //using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) //{ // stream.Write(renderedBytes, 0, renderedBytes.Length); // stream.Close(); //} lr.Dispose(); #region 寄信 //存許項目 string vitemIdName = extensionParms.FirstOrDefault(x => x.key == "vJobProject")?.value; //庫存日期 string aplyDt = parms.FirstOrDefault(x => x.key == "APLY_DT_From")?.value; MAIL_TIME MT = new MAIL_TIME(); MAIL_CONTENT MC = new MAIL_CONTENT(); //List<Tuple<string, string>> _mailTo = new List<Tuple<string, string>>() { new Tuple<string, string>("*****@*****.**", "測試帳號-glsisys") }; List <Tuple <string, string> > _mailTo = new List <Tuple <string, string> >(); List <Tuple <string, string> > _ccTo = new List <Tuple <string, string> >(); using (TreasuryDBEntities db = new TreasuryDBEntities()) { //季追蹤庫存表 抓5 MT = db.MAIL_TIME.AsNoTracking().FirstOrDefault(x => x.MAIL_TIME_ID == "5" && x.IS_DISABLED != "Y"); var _MAIL_CONTENT_ID = MT?.MAIL_CONTENT_ID; MC = db.MAIL_CONTENT.AsNoTracking().FirstOrDefault(x => x.MAIL_CONTENT_ID == _MAIL_CONTENT_ID && x.IS_DISABLED != "Y"); var _MAIL_RECEIVE = db.MAIL_RECEIVE.AsNoTracking(); var _CODE_ROLE_FUNC = db.CODE_ROLE_FUNC.AsNoTracking(); var _CODE_USER_ROLE = db.CODE_USER_ROLE.AsEnumerable(); var _CODE_USER = db.CODE_USER.AsNoTracking(); var emps = comm.GetEmps(); using (DB_INTRAEntities dbINTRA = new DB_INTRAEntities()) { //存許項目 string vitemId = parms.FirstOrDefault(x => x.key == "vJobProject")?.value; //Bianco 20190326 原參數 vjobProject //權責部門 string vdept = parms.FirstOrDefault(x => x.key == "vdept")?.value; //Bianco 20190326 原參數 CHARGE_DEPT_ID //權責科別 string vsect = parms.FirstOrDefault(x => x.key == "vsect")?.value; //Bianco 20190326 原參數 CHARGE_SECT_ID var _VW_OA_DEPT = dbINTRA.VW_OA_DEPT.AsNoTracking(); var _V_EMPLY2 = dbINTRA.V_EMPLY2.AsNoTracking(); var _ITEM_CHARGE_UNIT = db.ITEM_CHARGE_UNIT.AsNoTracking() .Where(x => x.ITEM_ID == vitemId, vitemId != null) .Where(x => x.CHARGE_DEPT == vdept, vdept != "All") .Where(x => x.CHARGE_SECT == vsect, vsect != "All") .Where(x => x.IS_DISABLED == "N") .AsEnumerable() .Select(x => new ITEM_CHARGE_UNIT() { CHARGE_DEPT = x.CHARGE_DEPT, CHARGE_SECT = x.CHARGE_SECT, CHARGE_UID = x.CHARGE_UID, IS_MAIL_SECT_MGR = x.IS_MAIL_SECT_MGR, IS_MAIL_DEPT_MGR = x.IS_MAIL_DEPT_MGR }).ToList(); _ITEM_CHARGE_UNIT.ForEach(x => { //經辦 var _CHARGE_NAME = _V_EMPLY2.FirstOrDefault(y => y.USR_ID == x.CHARGE_UID); if (_CHARGE_NAME != null && !_mailTo.Any(y => y.Item1 == _CHARGE_NAME.EMAIL)) { _mailTo.Add(new Tuple <string, string>(_CHARGE_NAME.EMAIL, _CHARGE_NAME.EMP_NAME)); } if (x.IS_MAIL_SECT_MGR == "Y") { //科主管員編 var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.DPT_HEAD; //人名 EMAIl var _EMP_NAME = _V_EMPLY2.FirstOrDefault(y => y.EMP_NO == _VW_OA_DEPT_DPT_HEAD); if (_EMP_NAME != null && !_mailTo.Any(y => y.Item1 == _EMP_NAME.EMAIL)) { _mailTo.Add(new Tuple <string, string>(_EMP_NAME.EMAIL, _EMP_NAME.EMP_NAME)); } } if (x.IS_MAIL_DEPT_MGR == "Y") { //部主管員編 //var _UP_DPT_CD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.UP_DPT_CD; //var _UP_DPT_CD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.UP_DPT_CD; //var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == _UP_DPT_CD)?.DPT_HEAD; var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_DEPT)?.DPT_HEAD; //人名 EMAIl var _EMP_NAME = _V_EMPLY2.FirstOrDefault(y => y.EMP_NO == _VW_OA_DEPT_DPT_HEAD); if (_EMP_NAME != null && !_ccTo.Any(y => y.Item1 == _EMP_NAME.EMAIL) && !_mailTo.Any(y => y.Item1 == _EMP_NAME.EMAIL)) { _ccTo.Add(new Tuple <string, string>(_EMP_NAME.EMAIL, _EMP_NAME.EMP_NAME)); } } }); if (MC != null) { var _FuncId = _MAIL_RECEIVE.Where(x => x.MAIL_CONTENT_ID == MC.MAIL_CONTENT_ID).Select(x => x.FUNC_ID); var _RoleId = _CODE_ROLE_FUNC.Where(x => _FuncId.Contains(x.FUNC_ID)).Select(x => x.ROLE_ID); var _UserId = _CODE_USER_ROLE.Where(x => _RoleId.Contains(x.ROLE_ID)).Select(x => x.USER_ID).Distinct(); List <string> _userIdList = new List <string>(); _userIdList.AddRange(_CODE_USER.Where(x => _UserId.Contains(x.USER_ID) && x.IS_MAIL == "Y").Select(x => x.USER_ID).ToList()); if (_userIdList.Any()) { //人名 EMAIl var _EMP = emps.Where(x => _userIdList.Contains(x.USR_ID)).ToList(); if (_EMP.Any()) { _EMP.ForEach(x => { if (!_ccTo.Any(y => y.Item1 == x.EMAIL) && !_mailTo.Any(y => y.Item1 == x.EMAIL)) { _ccTo.Add(new Tuple <string, string>(x.EMAIL, x.EMP_NAME)); } }); } } } } } string passwordZip = getPassWord(); Dictionary <string, Stream> attachment = new Dictionary <string, Stream>(); //attachment.Add(string.Format("{0}.pdf", _DisplayName), new MemoryStream(renderedBytes)); using (ZipFile zip = new ZipFile(System.Text.Encoding.Default)) { var memSteam = new MemoryStream(); var streamWriter = new StreamWriter(memSteam); ZipEntry e = zip.AddEntry(string.Format("{0}.pdf", _DisplayName), new MemoryStream(renderedBytes)); e.Password = passwordZip; e.Encryption = EncryptionAlgorithm.WinZipAes256; var ms = new MemoryStream(); ms.Seek(0, SeekOrigin.Begin); zip.Save(ms); ms.Seek(0, SeekOrigin.Begin); ms.Flush(); attachment.Add(string.Format("{0}.zip", _DisplayName), ms); } string str = MC?.MAIL_CONTENT1 ?? string.Empty; str = str.Replace("@_DATE_", aplyDt); str = str.Replace("@_ITEM_", vitemIdName); StringBuilder sb = new StringBuilder(); sb.AppendLine(str); try { var sms = new SendMail.SendMailSelf(); sms.smtpPort = 25; sms.smtpServer = Properties.Settings.Default["smtpServer"]?.ToString(); sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString(); sms.mailPwd = Properties.Settings.Default["mailPwd"]?.ToString(); sms.Mail_Send( new Tuple <string, string>(sms.mailAccount, "金庫管理系統"), _mailTo, _ccTo, MC?.MAIL_SUBJECT ?? "季追蹤庫存表", sb.ToString(), false, attachment ); } catch (Exception ex) { result.DESCRIPTION = $"Email 發送失敗請人工通知。"; return(Json(result)); } //寄密碼 try { var sms = new SendMail.SendMailSelf(); sms.smtpPort = 25; sms.smtpServer = Properties.Settings.Default["smtpServer"]?.ToString(); sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString(); sms.mailPwd = Properties.Settings.Default["mailPwd"]?.ToString(); sms.Mail_Send( new Tuple <string, string>(sms.mailAccount, "金庫管理系統"), _mailTo, _ccTo, "季追蹤庫存表-密碼", $"密碼:{passwordZip}", false, null ); } catch (Exception ex) { result.DESCRIPTION = $"Email 密碼發送失敗。"; return(Json(result)); } #endregion result.RETURN_FLAG = true; result.DESCRIPTION = "已寄送追蹤報表!"; } catch (Exception ex) { result.DESCRIPTION = ex.exceptionMessage(); } return(Json(result)); }
public JsonResult GenerateReportForSearchResult(string registrationNo, string fromDate, string toDate) { try { List <DAL.ViewModel.VM_CostForBusRegistrationNo> totalCostInfoList = unitOfWork.CustomRepository.sp_totalCostHistoryFromDateToDateForBusRegistrationNoFullFinal(registrationNo, Convert.ToDateTime(fromDate), Convert.ToDateTime(toDate)); double totalAmount = 0; var newTotalCostInfoList = new List <DAL.ViewModel.VM_CostForBusRegistrationNo>(); foreach (var totalCostInfo in totalCostInfoList) { DAL.ViewModel.VM_CostForBusRegistrationNo newtotalCostInfo = new DAL.ViewModel.VM_CostForBusRegistrationNo(); newtotalCostInfo.CompanyName = totalCostInfo.CompanyName; newtotalCostInfo.PartsName = totalCostInfo.PartsName; newtotalCostInfo.Other = totalCostInfo.Other; newtotalCostInfo.Quantity = totalCostInfo.Quantity; newtotalCostInfo.UnitPrice = totalCostInfo.UnitPrice; newtotalCostInfo.Price = totalCostInfo.Price; newtotalCostInfo.StoreName = totalCostInfo.StoreName; newTotalCostInfoList.Add(totalCostInfo); } totalAmount = totalCostInfoList.Select(s => s.Price).Sum(); int workShopId = Int32.Parse(SessionManger.WorkShopOfLoggedInUser(Session).ToString()); string workShopName = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Name; string workShopAddress = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/TotalCostHistoryFromDateToDateForABusRegistrationNoReport.rdlc"); localReport.SetParameters(new ReportParameter("RegistrationNo", registrationNo)); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("WorkShopName", workShopName)); localReport.SetParameters(new ReportParameter("WorkShopAddress", workShopAddress)); ReportDataSource reportDataSource = new ReportDataSource("TotalCostHistoryFromDateToDateForABusRegistrationNoDataSet", newTotalCostInfoList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Report generated successfully.", result = totalCostInfoList, TotalAmount = totalAmount }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
private void GenerateReport(IEnumerable data, String path, String ExportFormat) { try { LocalReport report = new LocalReport(); ReportDataSource ds = new ReportDataSource("CaseListDataSet", data); report.DataSources.Add(ds); report.ReportPath = path; report.SetBasePermissionsForSandboxAppDomain(new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted)); Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtention; if (ExportFormat == "PDF") { //export report to PDF byte[] bytes = report.Render( "PDF", null, out mimeType, out encoding, out filenameExtention, out streamids, out warnings); using (FileStream fs = new FileStream("Report.pdf", FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } PDFHolder pf = new PDFHolder(); System.Windows.Forms.Integration.WindowsFormsHost wh = new System.Windows.Forms.Integration.WindowsFormsHost(); wh.Child = pf; Window pdfWin = new Window(); pdfWin.Content = wh; pdfWin.Show(); pf.LoadPDF("Report.pdf"); } else if (ExportFormat == "Export") { SaveFileDialog saveFileDlg = new SaveFileDialog(); saveFileDlg.FileName = "Report"; saveFileDlg.Filter = "Excel Worksheets|*.xls"; saveFileDlg.DefaultExt = ".xls"; Nullable <bool> result = saveFileDlg.ShowDialog(); if (result == true) { //export report to excel worksheet byte[] bytes = report.Render( "Excel", null, out mimeType, out encoding, out filenameExtention, out streamids, out warnings); using (FileStream fs = new FileStream(saveFileDlg.FileName, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } } } report.Dispose(); } catch (Exception exp) { log.PrintInfoLine("GenerateReport Exception: " + exp); } }
/// <summary> /// /// </summary> /// <param name="folderPath"></param> /// <param name="strPP">chuoi pp</param> /// <param name="typeExport"></param> private void SaveAll(string folderPath, string strPP, string typeExport) { try { currentExport = 0; if (dataMaster == null) { return; } string path = ""; //1.xuat detail ///var source = dataMaster.Items.Skip(exportFrom-1).Take(1000).ToList(); LocalReport localReport = new LocalReport(); foreach (var item in dataMaster.Items) { localReport.DataSources.Clear(); currentExport++; if (item.Items.Count == 0) { continue; } Vcpmc.Mis.ViewModels.Mis.Distribution.Quarter.Distribution exportS = (Vcpmc.Mis.ViewModels.Mis.Distribution.Quarter.Distribution)item.Clone(); //Vcpmc.Mis.ViewModels.Mis.Distribution.Quarter.Distribution exportS = new ViewModels.Mis.Distribution.Quarter.Distribution(); if (typeExport == "PDF") { path = $"{folderPath}\\{item.NameFile}.pdf"; SaveAll(localReport, exportS, path, strPP, typeExport); } else { path = $"{folderPath}\\{item.NameFile}.xls"; SaveAll(localReport, exportS, path, strPP, typeExport); } exportS.Items.Clear(); exportS.Items = null; exportS = null; //localReport.ReleaseSandboxAppDomain(); } //if(exportTo>= dataMaster.Items.Count) //{ if (typeExport != "PDF") { MakeLink(folderPath, dataMaster, year, quarter, regions); } //} statusMain.Invoke(new MethodInvoker(delegate { //lbOperation.Text = $"Export from {exportFrom} to {exportFrom}, total: {currentExport}"; lbOperation.Text = $"Export, total: {currentExport}"; })); localReport.Dispose(); localReport = null; GC.Collect(); } catch (Exception ex) { pcloader.Invoke(new MethodInvoker(delegate { pcloader.Visible = false; })); MessageBox.Show(ex.ToString()); } }