I am trying to create a xtrareport with xml in asp.net using c#. I created xml and reference to xtrareport. I have also selected data source schmema and data member on xtrareport design and put fields to labels. I have also debugged dataset and it is not empty. But I can't see data on my report page.
SqlConnection conn = new SqlConnection(#"blabla");
SqlCommand select = new SqlCommand(#"select * from table",conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(select);
DataSet ds = new DataSet();
da.Fill(ds);
//ds.WriteXmlSchema(#"C:\dataset.xml");
XtraReport1 rpr = new XtraReport1();
rpr.DataSource = ds;
rpr.PrintingSystem.SetCommandVisibility(PrintingSystemCommand.ClosePreview, DevExpress.XtraPrinting.CommandVisibility.None);
rpr.CreateDocument(true);`
personally I create extensions to load and save xml Layout of reports.
I create them with an win application or whatever then save the xml layout:
public static void RestoreFromXmlXtraReportLayout(this DevExpress.XtraReports.UI.XtraReport report, string xmlXtraReportLayout)
{
if (!string.IsNullOrEmpty(xmlXtraReportLayout))
{
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".repx";
System.IO.File.WriteAllText(fileName, xmlXtraReportLayout);
report.LoadLayout(fileName);
System.IO.File.Delete(fileName);
}
}
public static string GetXmlXtraReportLayout(this DevExpress.XtraReports.UI.XtraReport report)
{
string tmpFileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".repx";
report.SaveLayout(tmpFileName);
string xmlXtraReportLayout = System.IO.File.ReadAllText(tmpFileName);
System.IO.File.Delete(tmpFileName);
return xmlXtraReportLayout;
}
using Memory Stream ( but it dosn't works fine, some data are lost, but you can try it )
public static void RestoreLayoutFromNavigationItem(this DevExpress.XtraReports.UI.XtraReport report, string xmlXtraReportLayout)
{
if (!string.IsNullOrEmpty(xmlXtraReportLayout))
{
using (Stream xmlStream = new System.IO.MemoryStream())
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlXtraReportLayout);
xDoc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position = 0;
report.LoadLayoutFromXml(xmlStream);
}
}
}
and to load the report I use a web page that contains a ASPxDocumentViewer :
<body>
<form id="formDocumentViewer" runat="server">
<div>
<dx:ASPxDocumentViewer ID="mainDocumentViewer" runat="server">
</dx:ASPxDocumentViewer>
</div>
</form>
in the page Load:
protected void Page_Load(object sender, EventArgs e)
{
report.DataSource = "your data source";
string xmlXtraReportLayout = "load it from the saved file";
report.RestoreFromXmlXtraReportLayout(xmlXtraReportLayout);
this.mainDocumentViewer.SettingsSplitter.SidePaneVisible = false;
this.mainDocumentViewer.Report = report;
}
but first you have to create your report with the report designer , load it in win application , use GetXmlXtraReportLayout to save the layout into a file.
Related
I am working with RDLC reports and currently I have a sub report with its properties and parameters within a main report. After trying to generate the report, the below error is shown at the UI :
"Data retrieval failed for the subreport, 'Subreport1', located at: [C:/filepath]"
There is nothing error shown at Visual studio, so I thing the error may not cause by the code.
I think the error comes from the parameters at rdlc not being able to pass into the sub report via the main report . Below is my code:
public ReportViewer Main_Report(string path, ProgressReportFilter item, DataTable dt)
{
ReportViewer reportViewer = new ReportViewer();
try
{
var user = UserAccess.GetCurrentUser();
reportViewer.ProcessingMode = ProcessingMode.Local;
//reportViewer.LocalReport.ReportPath = #"Reports/Main_Report.rdlc";
reportViewer.LocalReport.ReportPath = path;
reportViewer.SizeToReportContent = true;
reportViewer.Width = Unit.Percentage(100);
reportViewer.Width = Unit.Percentage(100);
reportViewer.LocalReport.SetParameters(new Microsoft.Reporting.WebForms.ReportParameter("Year", item.yyyy));
reportViewer.LocalReport.SetParameters(new
Microsoft.Reporting.WebForms.ReportParameter("Month", item.mm));
ReportDataSource ds = new ReportDataSource("Main_DataSet", dt);
reportViewer.LocalReport.DataSources.Add(ds);
reportViewer.LocalReport.SubreportProcessing += new
SubreportProcessingEventHandler(Detail_Alco);
reportViewer.LocalReport.Refresh();
}
catch (Exception e)
{}
return reportViewer;
}
void Detail_Alco(object sender, SubreportProcessingEventArgs e)
{
Helper.log.Info("para is " + e.Parameters[0].Values[0]);
string serial = e.Parameters["serial"].Values[0].ToString();
//Helper.log.Info("serial is " + serial);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("#serial", serial);
string spName1 = "SP_Report_MRS_Detail_Breakdown_Report_Sub_Alco";
SUSDB susdb = new SUSDB();
DataTable dtAlco = ReportHelp.ToDataTable(susdb.DetailBreakdownReport_SubReport_Alco(spName1, parameters));
ReportDataSource ds = new ReportDataSource("Detail_Breakdown_Alco", dtAlco);
e.DataSources.Add(ds);
}
Any help would be appreciated, many thanks
I want to generate a PDF using windows form in the desktop application. I have readymade pdf design and I just want to feed data from database in that blank section of pdf for each user. (One type of receipt). Please guide me. I have searched but most of the time there is the solution in asp.net for the web application. I want to do in the desktop app. Here is my code I am able to fatch data from database and print in pdf. But main problem is trhat I have already designed pdf and I want to place data exactly at same field (ie name, Amount, date etc.)
using System;
using System.Windows.Forms;
using System.Diagnostics;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace printPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
int yPoint = 0;
string pubname = null;
string city = null;
string state = null;
connetionString = "Data Source=EEVO-SALMAN\\MY_PC;Initial Catalog=;User ID=s***;Password=******";
// var connectionString = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
sql = "select NAME,NAME,uid from tblumaster";
connection = new SqlConnection(connetionString);
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
connection.Close();
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = "Database to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Regular );
yPoint = yPoint + 100;
for (i = 0; i <=ds.Tables[0].Rows.Count-1; i++)
{
pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString ();
city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
state = ds.Tables[0].Rows[i].ItemArray[2].ToString();
graph.DrawString(pubname, font, XBrushes.Black, new XRect(10, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(city, font, XBrushes.Black, new XRect(200, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
graph.DrawString(state, font, XBrushes.Black, new XRect(400, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
yPoint = yPoint + 40;
}
string pdfFilename = "dbtopdf.pdf";
pdf.Save(pdfFilename);
Process.Start(pdfFilename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Instead of modifying the document, please create a new document and copy the pages from the old document to new document
sample code can be found here,
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637
Because modifying pdf is not recommended using 'PdfSharp' library. if you still want to edit you can use 'ISharp' library which needs a license.
Here is some VB.Net code I use to fill PDF forms. You need a PDF fillable form with form control names matching the SQL record field names.
It calls a routine Gen.GetDataTable() that just builds a typical DataTable. You could re-code to accept a pre-built Datatable as a parameter. Only the top row is processed. The code can be modified to work with a DataRow (.Table.Columns for column reference) or a DataReader.
Public Function FillPDFFormSQL(pdfMasterPath As String, pdfFinalPath As String, SQL As String, Optional FlattenForm As Boolean = True, Optional PrintPDF As Boolean = False, Optional PrinterName As String = "", Optional AllowMissingFields As Boolean = False) As Boolean
' case matters SQL <-> PDF Form Field Names
Dim pdfFormFields As AcroFields
Dim pdfReader As PdfReader
Dim pdfStamper As PdfStamper
Dim s As String = ""
Try
If pdfFinalPath = "" Then pdfFinalPath = pdfMasterPath.Replace(".pdf", "_Out.pdf")
Dim newFile As String = pdfFinalPath
pdfReader = New PdfReader(pdfMasterPath)
pdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
pdfReader.Close()
pdfFormFields = pdfStamper.AcroFields
Dim dt As DataTable = Gen.GetDataTable(SQL)
For i As Integer = 0 To dt.Columns.Count - 1
s = dt.Columns(i).ColumnName
If AllowMissingFields Then
If pdfFormFields.Fields.ContainsKey(s) Then
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
Else
Debug.WriteLine($"Missing PDF Field: {s}")
End If
Else
pdfFormFields.SetField(s, dt.Rows(0)(i).ToString.Trim)
End If
Next
' flatten the form to remove editing options
' set it to false to leave the form open for subsequent manual edits
If My.Computer.Keyboard.CtrlKeyDown Then
pdfStamper.FormFlattening = False
Else
pdfStamper.FormFlattening = FlattenForm
End If
pdfStamper.Close()
If Not newFile.Contains("""") Then newFile = """" & newFile & """"
If Not PrintPDF Then
Process.Start(newFile)
Else
Dim sPDFProgramPath As String = INI.GetValue("OISForms", "PDFProgramPath", "C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")
If Not IO.File.Exists(sPDFProgramPath) Then MsgBox("PDF EXE not found:" & vbNewLine & sPDFProgramPath) : Exit Function
If PrinterName.Length > 0 Then
Process.Start(sPDFProgramPath, "/t " & newFile & " " & PrinterName)
Else
Process.Start(sPDFProgramPath, "/p " & newFile)
End If
End If
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
Finally
pdfStamper = Nothing
pdfReader = Nothing
End Try
End Function
In my asp.net application we generating pdf using ITextSharp.dll
Now my problem is every time same pdf is opening(not refreshing) unless until clear my browser history it is same. I am using chrome browser.
Here is my code
private void fillForm() {
try {
string Phone = "", Physical = "";
string formFile = Server.MapPath("~\\Inspection.pdf");
string newFile = Server.MapPath("~\\InspectionPrint.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
PdfContentByte d = new PdfContentByte(stamper.Writer);
//getting values from DB
SqlCommand comd = new SqlCommand("usp_PrintInspection", QMSConn);
QMSConn.Open();
comd.CommandType = CommandType.StoredProcedure;
comd.Parameters.Add("#QuoteNumber", SqlDbType.VarChar);
comd.Parameters["#QuoteNumber"].Value = Session["CurrQuoteNumber"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlAdapter.SelectCommand = comd;
sqlAdapter.Fill(ds, "Table");
if (ds.Tables[0].Rows.Count > 0) {
// set form fields
string Name = ds.Tables[0].Rows[0]["NAME"].ToString();
string Address1 = ds.Tables[0].Rows[0]["Address1"].ToString();
string CompanyID = ds.Tables[0].Rows[0]["CompanyID"].ToString();
string PolicyNumber = ds.Tables[0].Rows[0]["PolicyNumber"].ToString();
fields.SetField("Name", Name);
fields.SetField("Address1", Address1);
fields.SetField("CompanyID ", CompanyID);
fields.SetField("PolicyNumber", PolicyNumber);
stamper.FormFlattening = false;
stamper.Close();
string file = "InspectionPrint";
string Url = "../" + file + ".pdf";
String js = #"WindowPopup('" + Url + "');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Key", js, true);
}
else {
showalert("No Record Available For This Quote");
}
}
catch(exception ex) {
}
}
as you are saying it is working in the Localhost but not in the production server, most likely it seems to me as an URL/Path issue.
1. after observing your code, you are creating one more string Url variable without using the existing String formFile variable.
as you should provide the valid path you need to use the formFile instead of Url as you have created formFile using Server.MapPath()
Try This:
/*string Url = "../" + file + ".pdf";*/ //comment or remove
String js = #"WindowPopup('" + formFile + "');";//use formFile instead of Url
I'm writing a program for manage all customers we have in our company. I have a DataGridView where every single customer should display. And right to the DataGridView I got some textboxes, for displaying the details of every customer and for add a new customer. And I got a button "Add Customer". So if I type in some random text in textboxes and click on "Add Customer" it should add the new customer to the DataGridView. And if I restart the program, every customer should still be saved. So I save the details of every customer to a .xml file.
Can someone help me or give me a hint how I can add customers to DataGridView by clicking button? I got this code for saving to xml file:
public partial class Form1 : Form
{
const string folder = #"C:\Users\Römel\Desktop\Save";
const string basename = "save.xml";
string filename = folder + "\\" + basename;
public Form1()
{
InitializeComponent();
if (Directory.Exists(folder))
{
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
dataGridKunden.Columns["KundenNr"].Visible = false;
dataGridKunden.Columns["Adresse"].Visible = false;
dataGridKunden.Columns["Ort"].Visible = false;
dataGridKunden.Columns["Telefon"].Visible = false;
dataGridKunden.Columns["Mail"].Visible = false;
dataGridKunden.ScrollBars = ScrollBars.None;
}
}
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
File.Create(filename);
}
XmlTextWriter xwriter = new XmlTextWriter(filename, Encoding.Unicode);
xwriter.WriteStartDocument();
xwriter.WriteStartElement("Kundenverwaltung");
xwriter.WriteStartElement("KundenNr");
xwriter.WriteString(txtKundenNr.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Nachname");
xwriter.WriteString(txtKundeNachname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Vorname");
xwriter.WriteString(txtKundeVorname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Adresse");
xwriter.WriteString(txtKundeAdresse.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Ort");
xwriter.WriteString(txtKundeOrt.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Telefon");
xwriter.WriteString(txtKundeTel.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Mail");
xwriter.WriteString(txtKundeMail.Text);
xwriter.WriteEndElement();
xwriter.WriteEndDocument();
xwriter.Close();
}
}
The button "Add Customer" is called "btnAddKunde".
Thanks in advance.
Cheers
Add These line of code in your button click event in last:
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
However, your version of XmlTextWriter will overwrite the xml file. Thus, when you click on button you will see only the latest added row. Instead you can use below code in your button click event:
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
using (File.Create(filename))
{}
}
XElement xmlNode = new XElement("Kundenverwaltung",
new XElement("KundenNr", txtKundenNr.Text),
new XElement("Nachname", txtKundeNachname.Text),
new XElement("Vorname", txtKundeVorname.Text),
new XElement("Adresse", txtKundeAdresse.Text),
new XElement("Ort", txtKundeOrt.Text),
new XElement("Telefon", txtKundeTel.Text),
new XElement("Mail", txtKundeMail.Text)
);
XElement xmlFile;
try
{
xmlFile = XElement.Load(filename);
xmlFile.Add(xmlNode);
}
catch (XmlException)
{
xmlFile = new XElement("Customers", xmlNode);
}
xmlFile.Save(filename);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
you need to use XMLDocument class to retrieve data from xml file
do something like this :
XDocument xmlDoc = XDocument.Load("People.xml");
xmlDoc.Element("employee").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));
Are you lookin for an example for retrieving data from xml or just add string array retrieved from xml??
Here's how you add a string array..
string[] s = new string[4];
s[0] = "Salim";
s[1] = "9388938813"
s[2] = "s/10 santhi Nagar, Dpo road, Palakkad"
s[3] = "Kerala"
datagridView1.Rows.Add(s);
dataGridKunden.Rows.Add(new string[] {surname.text, forename.text, address.text .... });
// add as much as you want.
How can I dynamically insert images when user uploads an image file to SQL Server 2005 with C# in ASP.NET? This is to let users upload their profile photos in my web app. Is it very different from how it is done for windows app with C#?
There is a metric ton of examples on the web on this one:
http://aspalliance.com/138
https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx
http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/
You should be able to follow any of those to accomplish what you want.
The same way as in in WinForms. Get byte[] and same to image column. But i strongly recommend to use file system to store pictures. DB is for relational data, File System for raw bytes.
http://msdn.microsoft.com/en-us/library/aa479405.aspx
Here is a sample of the code behind for inserting an image into a database in C#. You will of coarse need supporting table the picture should be a byte field and keep the picture type so you can retrieve the image later to display it. In addition to that you need to put a file input box on your page along with a submit button.
public void AddImage(object sender, EventArgs e)
{
int intImageSize;
String strImageType;
Stream ImageStream;
FileStream fs = File.OpenRead(Request.PhysicalApplicationPath + "/Images/default_image.png");
Byte[] ImageContent;
if (PersonImage.PostedFile.ContentLength > 0)
{
intImageSize = PersonImage.PostedFile.ContentLength;
strImageType = PersonImage.PostedFile.ContentType;
ImageStream = PersonImage.PostedFile.InputStream;
ImageContent = new Byte[intImageSize];
int intStatus;
intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
}
else
{
strImageType = "image/x-png";
ImageContent = new Byte[fs.Length];
fs.Read(ImageContent, 0, ImageContent.Length);
}
SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand objCmd;
string strCmd;
strCmd = "INSERT INTO ImageTest (Picture, PictureType) VALUES (#Picture, #PictureType)";
objCmd = new SqlCommand(strCmd, objConn);
SqlParameter prmPersonImage = new SqlParameter("#Picture", SqlDbType.Image);
prmPersonImage.Value = ImageContent;
objCmd.Parameters.Add(prmPersonImage);
objCmd.Parameters.AddWithValue("#PictureType", strImageType);
lblMessage.Visible = true;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
lblMessage.Text = "ImageAdded!";
}
catch
{
lblMessage.Text = "Error occured the image has not been added to the database!";
}
}