Hi I'm working with crystal reports in a asp.net application with c#, my problem is
that the generated report should have a QR code that is generated with the following code
QRCode qrcode = new QRCode();
qrcode.Data = "Id Asociacion Civil:" + query.fiIdAsocCivil + "\n" + "Fecha de Registro:" + query.fdFechaReg.ToShortDateString() + "\n" + "Nombre de la AsociaciĆ³n:" + query.fcRazonSocial;
qrcode.X = 12;
// Create QR-Code and encode barcode to Jpeg format
qrcode.ImageFormat = ImageFormat.Jpeg;
if (Request.ApplicationPath == "/")
{
qrcode.drawBarcode(#"\\cjfapppba\ssac\Ejemplo1.jpg");
}
else
{
qrcode.drawBarcode((MapPath(#"~/Ejemplo1.jpg")));
}
}
catch (Exception x)
{
Label1.Text = x.Message;
Label1.Visible = true;
}
Every time I hit the button "report" to create a report the code to generate the code is executed and overwrites the last qrcode. My problem is that if I scan the qr code it ios updated correctly but in my report it doesn't. I tried adding a OLE object as other forums suggest but no success yet.
Any advice on how to achieve this?
I call the report with this code
GeneraCodigo();
switch (e.CommandName)
{
case "Registro":
var strRep = new StringBuilder();
strRep.Append("<script languaje=javascript>window.open('http://portalrpt/reportes/default.aspx?rep=SSAC/Constancia.rpt&mod=136&sf={AsocCivil.fiIdAsocCivil}=");
strRep.Append(idAC);
strRep.Append("','','width=670,height=570,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes');</script>");
ClientScript.RegisterStartupScript(Page.GetType(), "WOpen", strRep.ToString());
And method GeneraCodigo() is for generate the new qr code
You may want to adjust the approach that I suggested for rendering LaTex equations in Crystal Reports.
Related
I'm using ClosedXML library to generate a simple Excel file with 2 worksheets.
I keep getting error message whenever i try to open the file saying
"We found a problem with some content in "example.xlsx". Do you want us to try to recover as much as we can. if you trust source of this workbook, click Yes"
If i click Yes, it displays the data as expected, i don't see any
problems with it. Also if i generate only 1 worksheet this error does
not appear.
This is what my stored procedure returns, first result set is populated in sheet1 and second result set is populated in sheet2, which works as expected.
Workbook data
Here is the method i am using, it returns 2 result sets and populates both result sets in 2 different worksheets:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult POAReport(POAReportVM model)
{
POAReportVM poaReportVM = reportService.GetPOAReport(model);
using (var workbook = new XLWorkbook())
{
IXLWorksheet worksheet1 = workbook.Worksheets.Add("ProductOrderAccuracy");
worksheet1.Cell("A1").Value = "DATE";
worksheet1.Cell("B1").Value = "ORDER";
worksheet1.Cell("C1").Value = "";
var countsheet1 = 2;
for (int i = 0; i < poaReportVM.productOrderAccuracyList.Count; i++)
{
worksheet1.Cell(countsheet1, 1).Value = poaReportVM.productOrderAccuracyList[i].CompletedDate.ToString();
worksheet1.Cell(countsheet1, 2).Value = poaReportVM.productOrderAccuracyList[i].WebOrderID.ToString();
worksheet1.Cell(countsheet1, 3).Value = poaReportVM.productOrderAccuracyList[i].CompletedIndicator;
countsheet1++;
}
IXLWorksheet worksheet2 = workbook.Worksheets.Add("Summary");
worksheet2.Cell("A1").Value = "Total Orders Sampled";
worksheet2.Cell("B1").Value = "Passed";
worksheet2.Cell("C1").Value = "% Passed";
worksheet2.Cell(2, 1).Value = poaReportVM.summaryVM.TotalOrdersSampled.ToString();
worksheet2.Cell(2, 2).Value = poaReportVM.summaryVM.Passed.ToString();
worksheet2.Cell(2, 3).Value = poaReportVM.summaryVM.PassedPercentage.ToString();
//save file to memory stream and return it as byte array
using (var ms = new MemoryStream())
{
workbook.SaveAs(ms);
ms.Position = 0;
var content = ms.ToArray();
return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
}
I had similar problem. For me the cause was as mentioned in this answer:
I had this issue when I was using EPPlus to customise an existing template. For me the issue was in the template itself as it contained invalid references to lookup tables. I found this in Formula -> Name Manager.
You may find other solutions there.
Apologies as my reputation is too low to add a comment.
I was setting up a storm cluster to calculate real time trending and other statistics, however I have some problems introducing the "recovery" feature into this project, by allowing the offset that was last read by the kafka-spout (the source code for kafka-spout comes from https://github.com/apache/incubator-storm/tree/master/external/storm-kafka) to be remembered. I start my kafka-spout in this way:
BrokerHosts zkHost = new ZkHosts("localhost:2181");
SpoutConfig kafkaConfig = new SpoutConfig(zkHost, "test", "", "test");
kafkaConfig.forceFromStart = false;
KafkaSpout kafkaSpout = new KafkaSpout(kafkaConfig);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("test" + "spout", kafkaSpout, ESConfig.spoutParallelism);
The default settings should be doing this, but I think it is not doing so in my case, every time I start my project, the PartitionManager tries to look for the file with the offsets, then nothing is found:
2014-06-25 11:57:08 INFO PartitionManager:73 - Read partition information from: /storm/partition_1 --> null
2014-06-25 11:57:08 INFO PartitionManager:86 - No partition information found, using configuration to determine offset
Then it starts reading from the latest possible offset. Which is okay if my project never fails, but not exactly what I wanted.
I also looked a bit more into the PartitionManager class which uses Zkstate class to write the offsets, from this code snippet:
PartitionManeger
public void commit() {
long lastCompletedOffset = lastCompletedOffset();
if (_committedTo != lastCompletedOffset) {
LOG.debug("Writing last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
Map<Object, Object> data = (Map<Object, Object>) ImmutableMap.builder()
.put("topology", ImmutableMap.of("id", _topologyInstanceId,
"name", _stormConf.get(Config.TOPOLOGY_NAME)))
.put("offset", lastCompletedOffset)
.put("partition", _partition.partition)
.put("broker", ImmutableMap.of("host", _partition.host.host,
"port", _partition.host.port))
.put("topic", _spoutConfig.topic).build();
_state.writeJSON(committedPath(), data);
_committedTo = lastCompletedOffset;
LOG.debug("Wrote last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
} else {
LOG.debug("No new offset for " + _partition + " for topology: " + _topologyInstanceId);
}
}
ZkState
public void writeBytes(String path, byte[] bytes) {
try {
if (_curator.checkExists().forPath(path) == null) {
_curator.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, bytes);
} else {
_curator.setData().forPath(path, bytes);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I could see that for the first message, the writeBytes method gets into the if block and tries to create a path, then for the second message it goes into the else block, which seems to be ok. But when I start the project again, the same message as mentioned above shows up. No partition information can be found.
I had the same problem. Turned out I was running in local mode which uses an in memory zookeeper and not the zookeeper that Kafka is using.
To make sure that KafkaSpout doesn't use Storm's ZooKeeper for the ZkState that stores the offset, you need to set the SpoutConfig.zkServers, SpoutConfig.zkPort, and SpoutConfig.zkRoot in addition to the ZkHosts. For example
import org.apache.zookeeper.client.ConnectStringParser;
import storm.kafka.SpoutConfig;
import storm.kafka.ZkHosts;
import storm.kafka.KeyValueSchemeAsMultiScheme;
...
final ConnectStringParser connectStringParser = new ConnectStringParser(zkConnectStr);
final List<InetSocketAddress> serverInetAddresses = connectStringParser.getServerAddresses();
final List<String> serverAddresses = new ArrayList<>(serverInetAddresses.size());
final Integer zkPort = serverInetAddresses.get(0).getPort();
for (InetSocketAddress serverInetAddress : serverInetAddresses) {
serverAddresses.add(serverInetAddress.getHostName());
}
final ZkHosts zkHosts = new ZkHosts(zkConnectStr);
zkHosts.brokerZkPath = kafkaZnode + zkHosts.brokerZkPath;
final SpoutConfig spoutConfig = new SpoutConfig(zkHosts, inputTopic, kafkaZnode, kafkaConsumerGroup);
spoutConfig.scheme = new KeyValueSchemeAsMultiScheme(inputKafkaKeyValueScheme);
spoutConfig.zkServers = serverAddresses;
spoutConfig.zkPort = zkPort;
spoutConfig.zkRoot = kafkaZnode;
I think you are hitting this bug:
https://community.hortonworks.com/questions/66524/closedchannelexception-kafka-spout-cannot-read-kaf.html
And the comment from the colleague above fixed my issue. I added some newer libraries to.
I have an asp.net application, and if there is an exception in the code I catch it log some details (the stack trace, exception details etc) to a database and return a reference code to the client.
I noticed that the ASP.Net yellow screen of death shows a few lines of code around the offending line as well as the stack trace.
I want to log that "Source Error:" too. Where and how does the ASP.net get the "Source Error:" source code from?
Edit: If you want the file name and line number of the error, you can get it this way:
var exc = Server.GetLastError();
var frame = new StackTrace(exc, true).GetFrame(0);
var sourceFile = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber();
// sourceFile = c:\path\to\source\file.aspx
// lineNumber = 123
Reference: How does ASP.NET get line numbers in it's generic error handler
It looks like the code in the .NET framework responsible for getting source information is System.Web.FormatterWithFileInfo.GetSourceFileLines().
...
for (int i=1; ; i++) {
// Get the current line from the source file
string sourceLine = reader.ReadLine();
if (sourceLine == null)
break;
// If it's the error line, make it red
if (i == lineNumber)
sb.Append("<font color=red>");
// Is it in the range we want to display
if (i >= lineNumber-errorRange && i <= lineNumber+errorRange) {
fFoundLine = true;
String linestr = i.ToString("G", CultureInfo.CurrentCulture);
sb.Append(SR.GetString(SR.WithFile_Line_Num, linestr));
if (linestr.Length < 3)
sb.Append(' ', 3 - linestr.Length);
sb.Append(HttpUtility.HtmlEncode(sourceLine));
if (i != lineNumber+errorRange)
sb.Append("\r\n");
}
if (i == lineNumber)
sb.Append("</font>");
if (i>lineNumber+errorRange)
break;
}
...
Basically it does nothing more than open the source file, and find the line referenced by lineNumber in the error, along with 2 lines before and after.
Is there a library or code somewhere that does that?
Some questions suggest software like Convert a PDF to a Transparent PNG with GhostScript
I need something that's done by program. So my site, which is an asp site, should have a function
function PNGfromPDF (someFile as String) as PNGSomething
end function
Something like that.
Any open source solution for that?
Try:
PdfDocument inputDocument = PdfReader.Open(fileNames[i], PdfDocumentOpenMode.Import);
// for each page create a new PDF file and save it on the disk
for (int pageCount = 0; pageCount < inputDocument.PageCount; pageCount++)
{
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNames[i]);
fileName = string.Format("{0}\\Documents\\{1}", Session.CentralWorkingDirectory, String.Format("{0} ({1}-{2}).pdf", fileNameWithoutExtension, pageCount + 1, inputDocument.PageCount));
pdfFile = PDFFile.Open(fileName);
pdfFile.SerialNumber = Configurations.PDFVIEW_KEY;
// Get image file name
string imageFileName = string.Format("{0}.png", fileName.Remove(fileName.Length - 4));
// If thumbnail already exists delete it
if (File.Exists(imageFileName))
{
File.Delete(imageFileName);
}
// Convert page to PNG and save it.
//Bitmap pageImage = pdfFile.GetPageImage(0, 32);
Bitmap pageImage = pdfFile.GetPageImage(0, 92);
pageImage.Save(imageFileName, ImageFormat.Png);
// Cleanup resources
pageImage.Dispose();
pdfFile.Dispose();
}
Here I am using below namespace...
using PdfSharp.Drawing;
using O2S.Components.PDFRender4NET; // Thrid party components so you use PDF sharp with this componets
using System.Drawing.Imaging;
I am required to replace a word with a new word, selected from a drop-down list by user, in a PDF document in ASP.NET. I am using iTextSharp , but the new PDF that is created is all distorted as I am not able to extract the formatting/styling info of the PDF while extracting. Also, IS There a way to read a pdf line-by-line? Please help..
protected void Page_Load(object sender, EventArgs e)
{
String s = DropDownList1.SelectedValue;
Response.Write(s);
ListFieldNames(s);
}
private void CreatePDF(string text)
{
string outFileName = #"z:\TEMP\PDF\Test_abc.pdf";
Document doc = new Document();
doc.SetMargins(30f, 30f, 30f, 30f);
PdfWriter.GetInstance(doc, new FileStream(outFileName, FileMode.Create));
doc.Open();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false);
Font times = new Font(bfTimes, 12, Font.BOLDITALIC);
//Chunk ch = new Chunk(text,times);
Paragraph para = new Paragraph(text,times);
//para.SpacingAfter = 9f;
para.Alignment = Element.ALIGN_CENTER;
//para.IndentationLeft = 100;
doc.Add(para);
//doc.Add(new Paragraph(text,times));
doc.Close();
Response.Redirect(#"z:\TEMP\PDF\Test_abc.pdf",false);
}
private void ListFieldNames(string s)
{
ArrayList arrCheck = new ArrayList();
try
{
string pdfTemplate = #"z:\TEMP\PDF\abc.pdf";
//string dest = #"z:\TEMP\PDF\Test_abc.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
string pdfText = string.Empty;
string extracttext = "";
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
PdfReader reader = new PdfReader((string)pdfTemplate);
extracttext = PdfTextExtractor.GetTextFromPage(reader, page, its);
extracttext = Encoding.Unicode.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.Unicode, Encoding.Default.GetBytes(extracttext)));
pdfText = pdfText + extracttext;
pdfText = pdfText.Replace("[xyz]", s);
pdfReader.Close();
}
CreatePDF(pdfText);
}
catch (Exception ex)
{
}
finally
{
}
}
You are making one wrong assumption after the other.
You assume that the concept of "lines" exists in PDF. This is wrong. In Text State, different snippets of text are drawn on the page at absolute positions. For every "show text" operator, iText will return a TextRenderInfo object with the portion of text that was drawn and its coordinates. One line can consist of multiple text snippets. A text snippet may contain whitespace or may even be empty.
You assume that all text in a PDF keeps its natural reading order. This should be true for PDF/UA (UA stands for Universal Accessibility), but it's certainly not true for most PDFs you can find in the wild. That's why iText provides location-based text extraction (see p521 of iText in Action, Second Edition). As explained on p516, the text "Hello World" can be stored in the PDF as "ld", "Wor", "llo", "He". The LocationTextExtractionStrategy will order all the text snippets, reconstructing words if necessary. For instance: it will concatenate "He" and "llo" to "Hello", because there's not sufficient space between the "He" snippet and the "llo" snippet. However, for reasons unknown (probably ignorance), you're using the SimpleTextExtractionStrategy which doesn't order the text based on its location.
You are completely ignoring all the Graphics State operators, as well as the Text State operators that define the font, etc...
You assume that PDF is a Word processing format. This is wrong on many levels, as is your code. Please read the intro of chapter 6 of my book.
All these wrong assumptions almost make me want to vote down your question. At the risk of being voted down myself for this answer, I must tell you that you shouldn't try to "do the same". You're asking something that is very complex, and in many cases even impossible!