public void TestGetById() { //Get a house by a specified id using (var context = new ReportContext(options)) { HouseController houseController = new HouseController(context, AUTH_SERVICE); // Get houses with database-specified ids House selection1 = context.House.Where(x => x.Address == houseAddresses[0]).Single(); House selection2 = context.House.Where(x => x.Address == houseAddresses[1]).Single(); OkObjectResult result1 = houseController.GetById(selection1.Id) as OkObjectResult; House retrievedHouse1 = result1.Value as House; OkObjectResult result2 = houseController.GetById(selection1.Id) as OkObjectResult; House retrievedHouse2 = result1.Value as House; // Check if houses actually exist Assert.IsNotNull(retrievedHouse1); Assert.IsNotNull(retrievedHouse2); // Check that houses contain the completed field Assert.IsNotNull(retrievedHouse1.Completed); Assert.IsNotNull(retrievedHouse2.Completed); // Check that house 1 feature in category 1 has a valid grade. Feature validFeature = new Feature { Name = featureNames[3], Comments = featureNotes, Grade = 2, }; Category newCategory = new Category { Name = "random category", Count = 1, Features = new List <Feature> { validFeature }, }; retrievedHouse1.Categories.Add(newCategory); Assert.AreEqual(2, retrievedHouse1.Categories.ElementAt(2).Features.ElementAt(0).Grade); // Check if sub-elements are still there Assert.AreEqual(houseAddresses[0], retrievedHouse1.Address); Assert.AreEqual(3, retrievedHouse1.Categories.Count); Assert.AreEqual(1, retrievedHouse1.Categories.ElementAt(0).Features.Count); } }
/// <summary> /// Salva o relatorio que está aberto no banco /// </summary> /// <param name="reportDesigner"></param> /// <param name="report"></param> public ReportImage SaveReport(XRDesignMdiController reportDesigner, ReportImage report) { try { using (var ctx = new ReportContext()) { //objeto designer do relatório var xtraReport = reportDesigner.ActiveDesignPanel.Report; //nome setado no relatório //report.DefaultName = xtraReport.Name; //gera um nome aleatorio utilizando o nome setado no dashboard string reportPath = generatePath(report, ctx); using (MemoryStream ms = new MemoryStream()) { //salva o relatorio reportDesigner.ActiveDesignPanel.SaveReport(reportPath); //salva o layout em memoria xtraReport.SaveLayout(ms); xtraReport.SaveLayoutToXml(reportPath + ".xml"); //salva o relatorio no disco em formato repx xtraReport.SaveLayout(reportPath); //obtem os bytes do relatorio var bytes = ms.GetBuffer(); //gerar os bytes do arquivo report.ReportImageData = bytes; if (ctx.ReportImageDao.Save(report)) { return(report); } } } } catch (Exception ex) { XMessageIts.Advertencia("Houve um erro ao salvar relatório.\n\n" + ex.Message); LoggerUtilIts.GenerateLogs(ex); } return(null); }
public TodoController(ReportContext context, UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager) { _context = context; _userManager = userManager; _signInManager = signInManager; if (_context.TodoItems.Count() == 0) { _context.TodoItems.Add(new TodoItem { Name = "Hello World!" }); _context.SaveChanges(); } }
public string GetChannelContent(string channelValue = "news") { string result = string.Empty; using (var context = new ReportContext()) { var entity = context.ChannelContents.FirstOrDefault(c => c.ChannelValue == channelValue); if (entity != null) { result = entity.Content; } } return(result); }
public ReportImage FindReportByName(string rptName) { using (var ctx = new ReportContext()) { try { return(ctx.ReportImageDao.Where(r => r.ReportName == rptName).First()); } catch (Exception ex) { throw new Exception("Relatório \"" + rptName + "\"\n\n" + ex.Message); } } }
async Task <ReportInfo> GetReportInfo(String url, String id, ExpandoObject prms) { var rc = new ReportContext() { UserId = UserId, TenantId = TenantId, }; if (_baseController.Host.IsMultiCompany) { rc.CompanyId = CompanyId; } return(await _reportHelper.GetReportInfo(rc, url, id, prms)); }
async Task <ReportInfo> GetReportInfoDesktop(DesktopReport dr, String url, ExpandoObject prms) { var rc = new ReportContext() { UserId = dr.UserId, TenantId = dr.TenantId, }; if (_baseController.Host.IsMultiCompany) { rc.CompanyId = dr.CompanyId; } return(await _reportHelper.GetReportInfo(rc, url, dr.Id, prms)); }
public void Report(ReportContext context) { var series = ( IFigureSeries )context.ProvideValue(Source) ?? FigureSeries.Empty; var caption = Caption ?? series.Name; if (InMillions) { caption += " (in Mio.)"; } var chart = new Chart(); chart.Title = caption; chart.Width = 200; chart.Height = 200; chart.BorderThickness = new Thickness(0); var style = new Style(typeof(Legend)); style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 0d)); style.Setters.Add(new Setter(FrameworkElement.HeightProperty, 0d)); chart.LegendStyle = style; style = new Style(typeof(Title)); style.Setters.Add(new Setter(Title.FontSizeProperty, 14d)); style.Setters.Add(new Setter(Title.HorizontalAlignmentProperty, HorizontalAlignment.Center)); chart.TitleStyle = style; var chartSeries = new ColumnSeries(); chartSeries.ItemsSource = series .OrderBy(i => i.Period) .ToList(); chartSeries.IndependentValueBinding = new Binding("Period") { Converter = new PeriodChartConverter() }; chartSeries.DependentValueBinding = new Binding("Value") { Converter = new InMillionsConverter() { InMillions = InMillions } }; chart.Series.Add(chartSeries); context.Document.Blocks.Add(new BlockUIContainer(chart)); }
private void InitComponent() { List <string> columns = new List <string>(); columns.Add("FileName"); columns.Add("FilePath"); var table = CommonUtility.CreateMemoryTable(columns); Session["tempTable"] = table; DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0); DateTime endDate = startDate.AddDays(1); using (var context = new ReportContext()) { var newsCount = context.Articles.Count(a => a.AddDate >= startDate && a.AddDate <= endDate); this.ltlNewsCount.Text = newsCount.ToString(); var reportsCount = context.Reports.Count(); this.ltlReportsCount.Text = reportsCount.ToString(); var referencesCount = context.ReferenceReports.Count(); this.ltlReferencesCount.Text = referencesCount.ToString(); } using (var context = new PaperContext()) { var articlesCount = context.Papers.Count(p => p.AddDate >= startDate && p.AddDate <= endDate); this.ltlArticlesCount.Text = articlesCount.ToString(); } this.ltlBarChart.Text = BasicColumnBarChart(); string userId = User.Identity.GetUserId(); if (userId != null) { var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = manager.FindById(userId); if (user.CanWriteEmail == true) { this.send_email_div.Visible = true; } else { this.send_email_div.Visible = false; } } InitRepeater1(); InitRepeater2(); cblReceiveUser_GetData(); InitRepeater4(); ddlParentGroupID_GetData(); InitRepeater5(); }
/// <summary> /// Cria um XtraReport a partir do nome do relatório salvo no banco. /// </summary> /// <param name="reportName"></param> /// <param name="showParams"></param> /// <returns></returns> public static XtraReport CreateReportByName(string reportName, bool showParams = true) { using (var ctx = new ReportContext()) { try { var current = ctx.ReportImageDao.First(r => r.ReportName == reportName); string dir = Path.GetTempPath().Replace("Temp", "Reports"); FileManagerIts.CreateDirectory(dir); string path = Path.Combine(dir, current.ReportName + ".repx"); //salva o report no disco FileManagerIts.WriteBytesToFile(path, current.ReportImageData); //carregue a estrutura do relatório XtraReport report = XtraReport.FromFile(path, true); if (showParams == false) { //nao exibe foreach (var p in report.Parameters) { p.Visible = false; } } //objeto para chamar a tela de parametros ReportPrintTool reportPrintTool = new ReportPrintTool(report); ReportUtil.SetParamDataSource(report.DataSource as SqlDataSource, AppConfigManager.Configuration.AppConfig); //criar o documento report.CreateDocument(); //libera memoria da ferramenta reportPrintTool.Dispose(); //retorna o relatorio return(report); } catch (Exception ex) { XMessageIts.ExceptionMessageDetails(ex, "Impossível gerar relatório !", "Falha ao gerar relatório"); LoggerUtilIts.GenerateLogs(ex); return(null); } } }
public ServiceOutageSummaryRepository( IRepository <ServiceOutageSummary> repository, IServiceSlaService serviceSlaService, IRefundSupportTicketRepository refundSupportTicketRepository, ReportContext context, ILogger <ServiceOutageSummaryRepository> logger, IApiIdentity apiIdentity) : base(context, apiIdentity) { _repository = repository; _serviceSlaService = serviceSlaService; _refundSupportTicketRepository = refundSupportTicketRepository; _context = context; _logger = logger; }
public byte[] CreateReport(DublinCore citation, List <RepositoryItemMetadata> items, RepositoryClientBase client) { // Get identification for all the DDI variables in the item list. var variableIDs = items .Where(x => x.ItemType == DdiItemType.Variable) .Select(x => x.CompositeId) .ToIdentifierCollection(); // Fetch all the variables. var allVariables = client.GetItems(variableIDs) .OfType <Variable>(); // Use the Colectica.Reporting MigraDoc helper to create a PDF that // simply lists all variables with their names, labels, and types. var document = new Document(); document.Info.Title = "Sample Variable Summary"; // Add a title. var section = document.AddSection(); var paragraph = section.AddParagraph(citation.Title.Best); paragraph.Format.Font.Bold = true; // Create the report helper. ReportContext context = new ReportContext(); var builder = new ItemBuilderBase(document, context); // Make a list with one item for each variable. builder.DefineList(); foreach (var variable in allVariables) { string lineText = $"{variable.ItemName.Best} - {variable.Label.Best} - {variable.RepresentationType}"; builder.AddListItem(lineText); } // Render the PDF and return it. var pdfRenderer = new PdfDocumentRenderer(true); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); using (var stream = new MemoryStream()) { pdfRenderer.Save(stream, true); var fileContents = stream.ToArray(); return(fileContents); } }
private ReportContext ResetContext(ReportContext context) { if (context == null) { // builds an aggregate of virtual user counts by status. Func <IList <VirtualUserDto> > getUsers = () => statuses .Select(s => new VirtualUserDto { Status = s, Count = users.Count(u => u.State == s) }) .ToList(); // extracts all profiled results for the current period. Func <IList <ProfileItem> > snapshot = () => { ProfileItem item; IList <ProfileItem> items = new List <ProfileItem>(); while (period.TryTake(out item)) { items.Add(item); } return(items); }; // extracts all profile pending. Func <IList <RequestItem> > pending = () => { return(periodPending.Values.ToList()); }; context = new ReportContext { RequestFactory = this, Total = totalRequests, Users = getUsers, Snapshot = snapshot, Pending = pending }; } context.InternalId++; context.LastReportedPosition = context.Position; context.Duration = TimeSpan.Zero; context.Started = DateTime.UtcNow; context.Stopwatch = Stopwatch.StartNew(); return(context); }
public Report GenerateReport() { var workerReports = Workers.Select(t => new FormDayReport(t, Log, Date.Date)).Cast <IFormReport>().ToList(); IFormReport bossReport = new FormDayReport(Boss, Log, Date.Date); workerReports.Add(bossReport); Report = new Report(workerReports); using ReportContext db = new ReportContext(); db.Reports.Add(Report); return(Report); }
private void btnEditConsulta_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { var selectedSource = gridView1.GetFocusedRow <ReportDataSource>(); if (selectedSource != null) { using (var ctx = new ReportContext()) { var queryFull = ctx.SqlQueryItsDao .Where(q => q.CodigoQuery == selectedSource.Consulta.CodigoQuery).FirstOrDefault(); FormsUtil.ShowDialog(new XFrmAddConsultaSQL(queryFull)); } } }
public string GetCustomerName(int customerId) { using (var context = new ReportContext()) { var entity = context.Customers.Find(customerId); if (entity != null) { return(entity.Name); } else { return(string.Empty); } } }
public string GetCustomerNameByID(int CustomerID) { using (var context = new ReportContext()) { var entity = context.Customers.FirstOrDefault(c => c.ID == CustomerID); if (entity != null) { return(entity.Name); } else { return(""); } } }
private void InitRepeater(int currentPageIndex = 1, int customerId = 0) { using (var context = new ReportContext()) { var entities = context.SendPorts.Select(a => a); if (customerId != 0) { entities = entities.Where(s => s.CustomerID == customerId); } this.AspNetPager1.RecordCount = entities.Count(); this.AspNetPager1.CurrentPageIndex = currentPageIndex; this.Repeater1.DataSource = entities.OrderByDescending(a => a.ID).Skip((this.AspNetPager1.CurrentPageIndex - 1) * this.AspNetPager1.PageSize).Take(this.AspNetPager1.PageSize).ToList(); this.Repeater1.DataBind(); } }
static async Task Main(string[] args) { var connectionString = ""; var csvPath = @"C:\Temp\trade_history.csv"; var fileContent = File.ReadAllLines(csvPath); var batch = new List <TradeEntity>(); var page = 100; for (var i = 1; i < fileContent.Length; i++) { var line = fileContent[i]; var trade = Parse(line); batch.Add(trade); if (i % page == 0 || i == fileContent.Length - 1) { using var context = new ReportContext(connectionString); foreach (var tradeEntity in batch) { context.Trades.Add(tradeEntity); } try { await context.SaveChangesAsync(); } catch (Exception e) { Console.WriteLine(e); throw; } batch.Clear(); Console.WriteLine($"Saved {i} trades"); } } Console.WriteLine("Done!"); }
public Report GenerateReport() { var Report = new Report(); foreach (var infos in Log.Where(infos => infos.Person == WhoWorkingAllDay && infos.LastEditTime == Date.Date)) { Report.report.Add(infos); } using (ReportContext db = new ReportContext()) { db.Reports.Add(Report); } return(Report); }
/// <summary> /// Remove um relatório do spool /// </summary> /// <param name="idSpool"></param> /// <returns></returns> public bool RemoveRelatorioFromSpool(Int32 idSpool) { using (var ctx = new ReportContext()) { try { var reportDelete = ctx.ReportSpoolDao.Find(idSpool); return(ctx.ReportSpoolDao.Delete(reportDelete)); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(false); } } }
protected void lnkDelete_Command(object sender, CommandEventArgs e) { string id = e.CommandArgument.ToString(); using (var context = new ReportContext()) { var entity = context.SendPorts.Find(int.Parse(id)); if (entity != null) { context.SendPorts.Remove(entity); context.SaveChanges(); InitRepeater(this.AspNetPager1.CurrentPageIndex, int.Parse(this.ddlCustomer.SelectedValue)); ScriptManager.RegisterStartupScript(this.UpdatePanel1, GetType(), "a", "alert('发送端口删除成功')", true); } } }
public void ReportTableNames() { using (var ctx = new ReportContext()) { var tableName = ctx.GetTableName(typeof(Period)); Assert.AreEqual("Some.Complex_Schema Name", tableName.Schema); Assert.AreEqual("Period", tableName.Name); tableName = ctx.GetTableName(typeof(SummaryReportFROMTableASExtent)); Assert.AreEqual(nameof(SummaryReportFROMTableASExtent), tableName.Name); tableName = ctx.GetTableName(typeof(DetailReportWithFROM)); Assert.AreEqual("In # Some.Complex_Schema @Name", tableName.Schema); Assert.AreEqual("SELECT WORSE FROM NAMES AS Extent1", tableName.Name); } }
protected void btnEdit_Command(object sender, CommandEventArgs e) { string id = e.CommandArgument.ToString(); using (var context = new ReportContext()) { var entity = context.QuestionCategories.Find(int.Parse(id)); if (entity != null) { this.txtQuestionName.Text = entity.Name; this.txtQuestionSummary.Text = entity.Summary; this.hideAction.Value = "edit"; this.hideQuestionID.Value = id; } } }
private string generatePath(DashboardImage dash, ReportContext ctx) { //acompanha o Pk do dashboard que nunca se repete if (dash.IdReport != 0) { dash.ReportName = "Dashboard" + dash.IdReport; } else { dash.ReportName = "Dashboard" + (ctx.DashboardImageDao.FindAll().Count + 1); } var path = string.Format("{0}\\{1}{2}", _dashboardDir, dash.ReportName, ".xml"); return(path); }
protected void lnkDeleteReport_Command(object sender, CommandEventArgs e) { int id = e.CommandArgument.ToInt32(); using (var context = new ReportContext()) { var entity = context.Reports.Find(id); if (entity != null) { context.Reports.Remove(entity); context.SaveChanges(); InitRepeater1(this.AspNetPager1.CurrentPageIndex, int.Parse(this.ddlCustomer.SelectedValue), this.ddlReportType.SelectedValue, this.txtDate.Value); MessageBox.ShowAndRedirect(this, "alert('专报删除成功')", Request.RawUrl); } } }
public static async Task InitializeAsync(ReportContext context, IServiceProvider service) { var roleManager = service.GetRequiredService <RoleManager <IdentityRole> >(); var roleNames = new[] { "Teacher", "Admin", "FacultyAdmin", "DepartmentAdmin" }; IdentityResult roleResult; foreach (var roleName in roleNames) { var roleExists = await roleManager.RoleExistsAsync(roleName); if (!roleExists) { roleResult = await roleManager.CreateAsync(new IdentityRole(roleName)); } } }
public ExportController(ReportContext context, IAuthorizeService authorizeService, IImageService imageService, IEmailService emailService) { _context = context; _imageService = imageService; _authorizeService = authorizeService; _emailService = emailService; _imageHandler = new ImageHandler(); _largeRegularFont = new XFont("Arial", 20, XFontStyle.Bold); _medRegularFont = new XFont("Arial", 13, XFontStyle.Regular); _medBoldFont = new XFont("Arial", 13, XFontStyle.Bold); _smallRegularFont = new XFont("Arial", 8, XFontStyle.Regular); _smallBoldFont = new XFont("Arial", 8, XFontStyle.Bold); _document = new PdfDocument(); _color = new XSolidBrush(XColor.FromArgb(179, 204, 204)); _text = new ReportText(); }
/// <summary> /// Atualiza o dashboard existente no banco /// </summary> /// <param name="dashboardDesigner">Designer do dashboard</param> /// <param name="dash">Dashboard a ser persistido</param> /// <returns>O Dashboard persistido no banco ou null</returns> public bool UpdateDashboard(DashboardDesigner dashboardDesigner, DashboardImage dash) { try { using (var ctx = new ReportContext()) { //nome padrão dash.DefaultName = dashboardDesigner.ActiveControl.Name; //gera um nome aleatorio utilizando o nome setado no dashboard string dashPath = generatePath(dash, ctx); // using (MemoryStream ms = new MemoryStream()) //objeto designer do dashboard var designer = dashboardDesigner.Dashboard; FileManagerIts.DeleteFile(dashPath); //salva o layout em memoria //designer.SaveToXml(ms); //salva o dashboard no disco em formato xml designer.SaveToXml(dashPath); var bytes = FileManagerIts.GetBytesFromFile(dashPath); //ms.GetBuffer(); //passando objeto pro contexto var current = ctx.DashboardImageDao.Find(dash.IdReport); //atualiza o dashboard current.Update(dash); //garante a atualização current.ReportImageData = bytes; //efetiva no banco return(ctx.DashboardImageDao.Update(current)); } } catch (Exception ex) { XMessageIts.Advertencia("Houve um erro na atualização do dashboard.\n\n" + ex.Message); LoggerUtilIts.GenerateLogs(ex); return(false); } }
/// <summary> /// Salva o dashboard no banco /// </summary> /// <param name="dashboardDesigner">Designer do dashboard</param> /// <param name="dash">Dashboard a ser persistido</param> /// <returns>O Dashboard persistido no banco ou null</returns> public DashboardImage SaveDashboard(DashboardDesigner dashboardDesigner, DashboardImage dash) { try { using (var ctx = new ReportContext()) { //nome informado no dashboard dash.DefaultName = dashboardDesigner.ActiveControl.Name; //gera um nome aleatorio utilizando o nome setado no dashboard string dashPath = generatePath(dash, ctx); using (MemoryStream ms = new MemoryStream()) { //objeto designer do dashboard var designer = dashboardDesigner.Dashboard; //salva o layout em memoria designer.SaveToXml(ms); //salva o dashboard no disco em formato xml designer.SaveToXml(dashPath); //obtem os bytes do dashboard var bytes = ms.GetBuffer(); //passa os bytes do dashboard pro objeto dashboard dash.ReportImageData = bytes; //persiste o objeto no banco if (ctx.DashboardImageDao.Save(dash)) { return(dash); } } } } catch (Exception ex) { XMessageIts.Advertencia("Houve um erro ao salvar o dashboard.\n\n" + ex.Message); LoggerUtilIts.GenerateLogs(ex); } return(null); }