DevExpress Report with richTextBox - richtextbox

I am using WPF RichTextBox to record data and save the same in database. Now when i retrieve the same back from database and try to show the detail in a DevExpress report RichTextBox value appears as a single line of text without line break or new lines or table format. This is what i am doing
Converting FlowDocument to byte[] to save in database.
var content = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
if (content.CanSave(DataFormats.Rtf))
{
using (var stream = new MemoryStream())
{
content.Save(stream, DataFormats.Rtf);
return stream.ToArray();
}
}
Converting byte array to text to display in report
FlowDocument doc = new FlowDocument();
string rtfText = null;
using (MemoryStream stream = new MemoryStream(byteArrayValue))
{
TextRange text = new TextRange(doc.ContentStart, doc.ContentEnd);
text.Load(stream, DataFormats.Text);
rtfText = text.Text;
}

Related

Kendo Grid Export to Excel "Input string was not in a correct format"

I have used entity framework, and I am trying to export to excel. It keeps telling me that my input string is incorrect. I have them all converted to string, and I can not figure out which one it doesn't like. Could it be the header rows? and if so, how do I fix this?
private BaselineDataEntities db = new BaselineDataEntities();
public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
//Get the data representing the current grid state - page, sort and filter
IEnumerable products = db.ProductQualityFileFulls.ToDataSourceResult(request).Data;
//Create new Excel workbook
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
// //Create a header row
var headerRow = sheet.CreateRow(0);
//// Set the column names in the header row
headerRow.CreateCell(0).SetCellValue("Recent Update Status");
headerRow.CreateCell(1).SetCellValue("Marketing Rep");
headerRow.CreateCell(2).SetCellValue("Customer Name");
headerRow.CreateCell(3).SetCellValue("Opt-In Status");
headerRow.CreateCell(4).SetCellValue("Store ID");
headerRow.CreateCell(5).SetCellValue("Dealer");
headerRow.CreateCell(6).SetCellValue("DBA Name");
headerRow.CreateCell(7).SetCellValue("Class");
headerRow.CreateCell(8).SetCellValue("Act Code Desc");
headerRow.CreateCell(9).SetCellValue("Jobber");
headerRow.CreateCell(10).SetCellValue("Jobber Name");
headerRow.CreateCell(11).SetCellValue("SubJobber");
headerRow.CreateCell(12).SetCellValue("Company Op Desc");
headerRow.CreateCell(13).SetCellValue("Longitude");
headerRow.CreateCell(14).SetCellValue("Latitude");
headerRow.CreateCell(15).SetCellValue("Local Address");
headerRow.CreateCell(16).SetCellValue("Local Address 2");
headerRow.CreateCell(17).SetCellValue("Local City");
headerRow.CreateCell(18).SetCellValue("Local County");
headerRow.CreateCell(19).SetCellValue("Local State");
headerRow.CreateCell(20).SetCellValue("Local Postal");
headerRow.CreateCell(21).SetCellValue("Phone");
headerRow.CreateCell(22).SetCellValue("Establish Date");
headerRow.CreateCell(23).SetCellValue("Establish ID");
//// (Optional) freeze the header row so it is not scrolled
// sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
//Populate the sheet with values from the grid data
foreach (ProductQualityFileFull product in products)
{
//Create a new row
var row = sheet.CreateRow(rowNumber++);
//Set values for the cells
row.CreateCell(0).SetCellValue(product.RecUpdtStatus.ToString());
row.CreateCell(1).SetCellValue(product.mktRep.ToString());
row.CreateCell(2).SetCellValue(product.CustName.ToString());
row.CreateCell(3).SetCellValue(product.OptInd.ToString());
row.CreateCell(4).SetCellValue(product.StoreId.ToString());
row.CreateCell(5).SetCellValue(product.dealerNo.ToString());
row.CreateCell(6).SetCellValue(product.DBAName.ToString());
row.CreateCell(7).SetCellValue(product.Class.ToString());
row.CreateCell(8).SetCellValue(product.ActCodedesc.ToString());
row.CreateCell(9).SetCellValue(product.Jobber.ToString());
row.CreateCell(10).SetCellValue(product.JobberName.ToString());
row.CreateCell(11).SetCellValue(product.SubJobber.ToString());
row.CreateCell(12).SetCellValue(product.CompanyOpDesc.ToString());
row.CreateCell(13).SetCellValue(product.Longitude.ToString());
row.CreateCell(14).SetCellValue(product.Latitude.ToString());
row.CreateCell(15).SetCellValue(product.LocAddress.ToString());
row.CreateCell(16).SetCellValue(product.LocAddress2.ToString());
row.CreateCell(17).SetCellValue(product.LocCity.ToString());
row.CreateCell(18).SetCellValue(product.LocCounty.ToString());
row.CreateCell(19).SetCellValue(product.LocState.ToString());
row.CreateCell(20).SetCellValue(product.LocPostalCode.ToString());
row.CreateCell(21).SetCellValue(product.Phone.ToString());
row.CreateCell(22).SetCellValue(product.establish_date_time.ToString());
row.CreateCell(23).SetCellValue(product.establish_id.ToString());
}
// Write the workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);
//eturn the result to the end user
return File(output.ToArray(), //The binary data of the XLS file
"application/vnd.ms-excel", //MIME type of Excel files
"GridExcelExport.xls"); //Suggested file name in the "Save as" dialog which will be displayed to the end user
}
Well have you tried just commenting out the content and building it up piece by piece.
Without knowing how your data is built up it's difficult to say what your issue is and if you break point through the code you should be able to find out where the problem is (or debug statements)
As you are using npoi this little library may be of use for you:
Excel Helper
This is a project I built which can easily take a flatten list collection and turn it into an excel file both xls and xlsx file types. It is purely just to get data and doesn't do any of the fancy graph stuff but is great for just getting data into a sheet.

save form values through script file in umbraco

hello i want to save the value of umbraco form in database for this i have made script file and in this script file i have created function to save data and called this function in same script file and this script file is used in macro and i have called this macro in template of my page but it is not working will this approach is proper or i have to something else my basic aim is to save data in database without creating my usercontrol
code is
#functions
{
public void AddToCart()
{
string con = System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString();
SqlConnection OnCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString());
ItemsDataContext db = new ItemsDataContext(con);
var request = HttpContext.Current.Request;
string itemcode= request.Form["ItemCode"].ToString();
string itemname = request.Form["ItemName"].ToString();
string itemcategory = Request.Form["ItemCategory"].ToString();
string userid = "Pallavi";
db.sp_AddItems(userid, itemcode, itemcategory, itemname, 0);
HttpContext.Current.Session["UserId"] = "Pallavi";
}
}
#if (!IsPost)
{
AddToCart();
}
and called this macro on template
<umbraco:Macro Alias="Uc_Cart" runat="server"></umbraco:Macro>
You approach is wrong. You must use the methods that Umbraco provides in their API and do not try to write data into the database directly.
Try this code to create an new document from Razor code:
#using umbraco.BusinessLogic;
#using umbraco.cms.businesslogic.web;
#{
DocumentType dt = DocumentType.GetByAlias("Textpage");
User author = umbraco.BusinessLogic.User.GetUser(0);
Document doc = Document.MakeNew("My new document", dt, author, parentID);
}
The example above is for Umbraco 4.x. If you're using Umbraco v6.x you could also use the new API methods:
#{
// get an instance of the contentService
var contentService = ApplicationContext.Services.ContentService;
// create new content, the last param is the userId and is optional [default = 0]
IContent newContent = contentService.CreateContent("My new document", parentID, "Textpage", 0);
// set property values
newContent.SetValue("propertyAlias", "Value");
// save (or save and publish)
contentService.Save(newContent);
}

iTextSharp creating file in memory resulting corrupted file

I am trying to create a pdf file in MVC using iTextSharp. I do have a following simple used case. File is getting created but when I open the PDF I am getting error file is corrupted unable to open the file. Any idea/help ?
My Controller code is a follows
public FileStreamResult GetPdfMemory()
{
iTextSharp.text.Document doc = new iTextSharp.text.Document();
MemoryStream mem = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, mem);
//pdfWriter.CloseStream = false;
doc.Open();
doc.Add(new Paragraph("Charts"));
mem.Position = 0;
FileStreamResult fileStreamResult = new FileStreamResult(mem, System.Net.Mime.MediaTypeNames.Application.Pdf)
{
FileDownloadName = "chart_" + ".PDF"
};
return fileStreamResult;
}
View :
#Html.ActionLink("Pdf Memory", "GetPdfMemory", "Home", null, new { id = "download"})
FYI : When I try to use FileStream instead of MemoryStream all works fine. But I need to create PDF using memorystream.
You manipulate (mem.Position = 0) and use (new FileStreamResult(mem, ...)) the MemoryStream before signalling iTextSharp that it can finalize the document. Thus, depending on whether implicit destruction of the Document and the PdfWriter or the use of the data in the memory stream comes first, you either have a PDF missing its closing parts or the closing parts (being written after you reposition the memory stream) overwriting the start of the data.
To signal to iTextSharp that it can finalize the document, please call doc.Close() before manipulating the memory stream or alternatively use the Document in a using block, e.g.:
using (MemoryStream ms = new MemoryStream()) {
// step 1
using (Document document = new Document()) {
// step 2
PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// step 4
document.Add(new Paragraph("HelloWorldMemory"));
}
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
(shamelessly copied from the sample HelloWorldMemory.cs from the Webified iTextSharp Examples) for iText in Action — 2nd Edition)
Using using implicitly causes the Document to be closed.

Prevent ActionResult from posting to a new page?

My project is very similar to NerdDinner and I'm generating a pdf-document using PdfSharp.
In my view I'm using this:
<%: Html.ActionLink("Pdf", "GeneratePdf1", "Persons")%>
Calling this ActionResult:
public ActionResult GeneratePdf1()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document...
const string filename = "HelloWorld.pdf";
document.Save(filename);
Process.Start(filename);
return View();
}
A few questions/problems on this:
I don't want the link to post. When you click the link it should just open the file, but I don't know what to return to prevent it from posting.
I'd also like the "save/open" dialog to appear. Right now the pdf file is displayed directly.
You want to return a FileResult not an ActionResult. Also, I would save it to a MemoryStream and return the byte array, not use a file. Full solution below.
public FileResult GeneratePdf1()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
return File(stream.ToArray(), "application/pdf");
}
you should replace these lines:
Process.Start(filename);
return View();
with
return File(filename, "application/pdf");
You may also have a third param with the downloaded filename, if it should be different to the action name.
return File(filename, "application/pdf", "myGeneratedPdf.pdf");
Also be sure the filename is unique per request or use a MemoryStream like it is suggested by Chris Kooken.
Btw: Process.Start(filename) will run the file on the server machine. that may work on your development machine, but on a live server the pdf will open on the server!!!

Open xml replace text from word file and return memory stream using MVC

I have an word file that contain my specified pattern text {pattern} and I want to replace those pattern with new my string which was read from database. So I used open xml read stream from my docx template file the replace my pattern string then returned to stream which support to download file without create a temporary file. But when I opened it generated me error on docx file. Below is my example code
public ActionResult SearchAndReplace(string FilePath)
{
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(FilePath));
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
//Instead using this code below to write text back the original file. I write new string back to memory stream and return to a stream download file
//using (StreamWriter sw = new //StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
//{
// sw.Write(docText);
//}
using (StreamWriter sw = new StreamWriter(mem))
{
sw.Write(docText);
}
}
mem.Seek(0, SeekOrigin.Begin);
return File(mem, "application/octet-stream","download.docx"); //Return to download file
}
Please suggest me any solutions instead read a text from a word file and replace those expected pattern text then write data back to the original file. Are there any solutions replace text with WordprocessingDocument libary? How can I return to memory stream with validation docx file format?
The approach you are taking is not correct. If, by chance, the pattern you are searching for matches some Open XML markup, you will corrupt the document. If the text you are searching for is split over multiple runs, your search/replace code will not find the text and will not operate correctly. If you want to search and replace text in a WordprocessingML document, there is a fairly easy algorithm that you can use:
Break all runs into runs of a single
character. This includes runs that
have special characters such as a
line break, carriage return, or hard
tab.
It is then pretty easy to find a
set of runs that match the characters
in your search string.
Once you have identified a set of runs that match,
then you can replace that set of runs
with a newly created run (which has
the run properties of the run
containing the first character that
matched the search string).
After replacing the single-character runs
with a newly created run, you can
then consolidate adjacent runs with
identical formatting.
I've written a blog post and recorded a screen-cast that walks through this algorithm.
Blog post: http://openxmldeveloper.org/archive/2011/05/12/148357.aspx
Screen cast: http://www.youtube.com/watch?v=w128hJUu3GM
-Eric
string sourcepath = HttpContext.Server.MapPath("~/File/Form/s.docx");
string targetPath = HttpContext.Server.MapPath("~/File/ExportTempFile/" + DateTime.Now.ToOADate() + ".docx");
System.IO.File.Copy(sourcepath, targetPath, true);
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(targetPath, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
byte[] byteArray = Encoding.UTF8.GetBytes(docText);
MemoryStream stream = new MemoryStream(byteArray);
wordDocument.MainDocumentPart.FeedData(stream);
}
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(targetPath));
return File(mem, "application/octet-stream", "download.docx");
Writing directly to the word document stream will indeed corrupt it.
You should instead write to the MainDocumentPart stream, but you should first truncate it.
It looks like MainDocumentPart.FeedData(Stream sourceStream) method will do just that.
I haven't tested it but this should work.
public ActionResult SearchAndReplace(string FilePath)
{
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(FilePath));
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
{
sw.Write(docText);
}
ms.Seek(0, SeekOrigin.Begin);
wordDoc.MainDocumentPart.FeedData(ms);
}
}
mem.Seek(0, SeekOrigin.Begin);
return File(mem, "application/octet-stream","download.docx"); //Return to download file
}

Resources