Generate Media RSS (MRSS) feed in ASP.NET 3.5 - asp.net

IN .NET 3.5 I know of the System.ServiceModel.Syndication classes which can create Atom 1.0 and RSS 2.0 rss feeds. Does anyone know of a way to easily generate yahoo's Media RSS in ASP.Net? I am looking for a free and fast way to generate an MRSS feed.

Here a simplified solution I ended up using within a HttpHandler (ashx):
public void GenerateRss(HttpContext context, IEnumerable<Media> medias)
{
context.Response.ContentType = "application/rss+xml";
XNamespace media = "http://search.yahoo.com/mrss";
List<Media> videos2xml = medias.ToList();
XDocument rss = new XDocument(
new XElement("rss", new XAttribute("version", "2.0"),
new XElement("channel",
new XElement("title", ""),
new XElement("link", ""),
new XElement("description", ""),
new XElement("language", ""),
new XElement("pubDate", DateTime.Now.ToString("r")),
new XElement("generator", "XLinq"),
from v in videos2xml
select new XElement("item",
new XElement("title", v.Title.Trim()),
new XElement("link", "",
new XAttribute("rel", "alternate"),
new XAttribute("type", "text/html"),
new XAttribute("href", String.Format("/Details.aspx?vid={0}", v.ID))),
new XElement("id", NotNull(v.ID)),
new XElement("pubDate", v.PublishDate.Value.ToLongDateString()),
new XElement("description",
new XCData(String.Format("<a href='/Details.aspx?vid={1}'> <img src='/Images/ThumbnailHandler.ashx?vid={1}' align='left' width='120' height='90' style='border: 2px solid #B9D3FE;'/></a><p>{0}</p>", v.Description, v.ID))),
new XElement("author", NotNull(v.Owner)),
new XElement("link",
new XAttribute("rel", "enclosure"),
new XAttribute("href", String.Format("/Details.aspx?vid={0}", v.ID)),
new XAttribute("type", "video/wmv")),
new XElement(XName.Get("title", "http://search.yahoo.com/mrss"), v.Title.Trim()),
new XElement(XName.Get("thumbnail", "http://search.yahoo.com/mrss"), "",
new XAttribute("url", String.Format("/Images/ThumbnailHandler.ashx?vid={0}", v.ID)),
new XAttribute("width", "320"),
new XAttribute("height", "240")),
new XElement(XName.Get("content", "http://search.yahoo.com/mrss"), "a",
new XAttribute("url", String.Format("/Details.aspx?vid={0}", v.ID)),
new XAttribute("fileSize", Default(v.FileSize)),
new XAttribute("type", "video/wmv"),
new XAttribute("height", Default(v.Height)),
new XAttribute("width", Default(v.Width))
)
)
)
)
);
using (XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
{
try
{
rss.WriteTo(writer);
}
catch (Exception ex)
{
Log.LogError("VideoRss", "GenerateRss", ex);
}
}
}

Step 1: Convert your data into XML:
So, given a List photos:
var photoXml = new XElement("photos",
new XElement("album",
new XAttribute("albumId", albumId),
new XAttribute("albumName", albumName),
new XAttribute("modified", DateTime.Now.ToUniversalTime().ToString("r")),
from p in photos
select
new XElement("photo",
new XElement("id", p.PhotoID),
new XElement("caption", p.Caption),
new XElement("tags", p.StringTags),
new XElement("albumId", p.AlbumID),
new XElement("albumName", p.AlbumName)
) // Close element photo
) // Close element album
);// Close element photos
Step 2: Run the XML through some XSLT:
Then using something like the following, run that through some XSLT, where xslPath is the path to your XSLT, current is the current HttpContext:
var xt = new XslCompiledTransform();
xt.Load(xslPath);
var ms = new MemoryStream();
if (null != current){
var xslArgs = new XsltArgumentList();
var xh = new XslHelpers(current);
xslArgs.AddExtensionObject("urn:xh", xh);
xt.Transform(photoXml.CreateNavigator(), xslArgs, ms);
} else {
xt.Transform(photoXml.CreateNavigator(), null, ms);
}
// Set the position to the beginning of the stream.
ms.Seek(0, SeekOrigin.Begin);
// Read the bytes from the stream.
var byteArray = new byte[ms.Length];
ms.Read(byteArray, 0, byteArray.Length);
// Decode the byte array into a char array
var uniEncoding = new UTF8Encoding();
var charArray = new char[uniEncoding.GetCharCount(
byteArray, 0, byteArray.Length)];
uniEncoding.GetDecoder().GetChars(
byteArray, 0, byteArray.Length, charArray, 0);
var sb = new StringBuilder();
sb.Append(charArray);
// Returns the XML as a string
return sb.ToString();
I have those two bits of code sitting in one method "BuildPhotoStream".
The class "XslHelpers" contains the following:
public class XslHelpers{
private readonly HttpContext current;
public XslHelpers(HttpContext currentContext){
current = currentContext;
}
public String ConvertDateTo822(string dateTime){
DateTime original = DateTime.Parse(dateTime);
return original.ToUniversalTime()
.ToString("ddd, dd MMM yyyy HH:mm:ss G\"M\"T");
}
public String ServerName(){
return current.Request.ServerVariables["Server_Name"];
}
}
This basically provides me with some nice formatting of dates that XSLT doens't give me.
Step 3: Render the resulting XML back to the client application:
"BuildPhotoStream" is called by "RenderHelpers.Photos" and "RenderHelpers.LatestPhotos", which are responsible for getting the photo details from the Linq2Sql objects, and they are called from an empty aspx page (I know now that this should really be an ASHX handler, I've just not gotten around to fixing it):
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/rss+xml";
ResponseEncoding = "UTF-8";
if (!string.IsNullOrEmpty(Request.QueryString["AlbumID"]))
{
Controls.Add(new LiteralControl(RenderHelpers
.Photos(Server.MapPath("/xsl/rssPhotos.xslt"), Context)));
}
else
{
Controls.Add(new LiteralControl(RenderHelpers
.LatestPhotos(Server.MapPath("/xsl/rssLatestPhotos.xslt"), Context)));
}
}
At the end of all that, I end up with this:
http://www.doodle.co.uk/Albums/Rss.aspx?AlbumID=61
Which worked in Cooliris/PicLens when I set it up, however now seems to render the images in the reflection plane, and when you click on them, but not in the wall view :(
In case you missed it above, the XSLT can be found here:
http://www.doodle.co.uk/xsl/rssPhotos.xslt
You'll obviously need to edit it to suit your needs (and open it in something like Visual Studio - FF hides most of the stylesheet def, including xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss").

I was able to add the media namespace to the rss tag by doing the following:
XmlDocument feedDoc = new XmlDocument();
feedDoc.Load(new StringReader(xmlText));
XmlNode rssNode = feedDoc.DocumentElement;
// You cant directly set the attribute to anything other then then next line. So you have to set the attribute value on a seperate line.
XmlAttribute mediaAttribute = feedDoc.CreateAttribute("xmlns", "media", "http://www.w3.org/2000/xmlns/");
mediaAttribute.Value = "http://search.yahoo.com/mrss/";
rssNode.Attributes.Append(mediaAttribute);
return feedDoc.OuterXml;

Just to add another option for future reference:
I created a library that leverages the SyndicationFeed classes in .NET and allows you to read and write media rss feeds.
http://mediarss.codeplex.com

Related

Report localization in Telerik self hosted service (.trdx)

I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)
I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values

Crystal report method not found

I made a feedback project. I made it on ASP.NET MVC 5 it also has crystal reports. reports were working fine, but suddenly they stopped to work. I don't what happened with them. but since last week I tried hard to find solution but unfortunately could not get the right one who solved the solution. I downloaded different run times but all went vain. this is the bottom line of error.
"Method not found: 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag CrystalDecisions.ReportAppServer.ReportDefModel.ISCRExportOptions.get_ExportOptionsEx()'"
this is the code:
public CrystalReportFeedback UserFeedbackDateWise(FeedbackReport be){
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
return new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
Init of the report :
public CrystalReportFeedback(string reportPath, FeedbackReport be)//, object dataSet)
{
//int[] array;
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
//reportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "C:\report.pdf");
_contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
}
Export method :
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.ApplicationInstance.Response;
response.Clear();
response.Buffer = false;
response.ClearContent();
response.ClearHeaders();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = "application/pdf";
using (var stream = new MemoryStream(_contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
private static byte[] StreamToBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Hope that I will get my solution at earliest.
this is modified code:
[HttpGet]
public FileResult UserFeedbackDateWise(FeedbackReport be)
{
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
Stream stream = reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
//new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
This isn't a coding issue, it's a runtime issue. The version of the crystal runtime or the bitness of your application.
One thing to try first is to upgrade both your development version and ensure you're running the same version in production. See https://apps.support.sap.com/sap/support/knowledge/public/en/2148492 for more details
It says:
Compile your application either to 'X86 mode' or 'X64 mode'
Install the particular versions of runtimes on deployment machine.
i.e. If the application is compiled as 32 bit, then install the 32bit runtimes.
I'll try my best to help you exporting your report, but your post is not very clear. For your next post try to be very specific and provide as much information as you can.
I currently made a MVC project and export a crystalreport report from my controller to my client.
I think that your ExecuteResult method can work, but working with the httpcontext is useless, Crystalreport and .NET provide some useful methods to do the same.
So i'll show you how i create and export my report so you can copy / paste and modify your code.
Here is my controller method, called from a button :
[HttpGet]
public FileResult InitReport()
{
//I create my report here
FileImportReport rptH = new FileImportReport();
// Some configuration on the report, datasource, databaselogon .. etc
...
//
//Then I export my report to a pdf stream like that :
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
}
My method is called from a button but it can work like you want, or the file can be saved in any known path.
You can test to reproduce my code, in your CrystalReportFeedback method use my code with your reportDocument object, you don't need to use your StreamToBytes method.
Regards,
EDIT : Useful links with your error :
Crystal Reports exception in Visual Studio 2013
https://www.arcanadev.com/support/kb/K00000499.aspx

The most straightforward way to download a file in mvc

I am currently saving an excel file like so on my c drive.
public ActionResult Export()
{
try
{
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add(System.Reflection.Missing.Value);
Excel.Worksheet worksheet = workbook.ActiveSheet;
var people = db.People.ToList();
worksheet.Cells[1, 1] = "Last Name";
worksheet.Cells[1, 2] = "First Name";
int row = 2;
foreach (var person in people)
{
worksheet.Cells[row, 1] = person.PersonFName;
worksheet.Cells[row, 2] = person.PersonLName;
row++;
}
workbook.SaveAs("c:\\test\\worksheet.xls");
workbook.Close();
Marshal.ReleaseComObject(workbook);
application.Quit();
Marshal.FinalReleaseComObject(application);
ViewBag.Result = "Done";
}
catch(Exception ex)
{
ViewBag.Result = ex.Message;
}
return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");
// return View("Success");
}
I can go to c:\\test\workseet.xls and it exists there I can do what ever with it...
I am wanting to transform my method from return a view to return a file download...
I figured that it was as simple as this:
return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");
However when I do this method and click the link to download, it gives me this error.
The process cannot access the file 'c:\test\workseet.xls' because it is being used by another process.
This duplicate question is just one of those that show how to use EPPlus to generate Excel files on the server side in a scaleable manner. It's actually a lot easier than using Excel interop and a lot faster. You don't even have to save the file to the disk.
public ActionResult ExportData()
{
//Somehow, load data to a DataTable
using (ExcelPackage package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("My Sheet");
//true generates headers
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
//Save the workbook to a stream
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "myfilename.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
You can use LoadFromDataTable to fill a sheet from a data table or LoadFromCollection to load data from a collection, eg List<Sale>.
Both methods return an ExcelRange object (a range of cells) that you can use to format individual cells, rows, and columns. You can also create tables from a range and apply themes.
The duplicate goes even farther and shows how you can avoid even the MemoryStream

Fill pdf forms and send them as one merged http response in output stream [duplicate]

I currently have a PdfReader and a PdfStamper that I am filling out the acrofields with. I now have to copy another pdf to the end of that form I have been filling out and when I do I lose the acrofield on the new form I copy over. Here is the code.
public static void addSectionThirteenPdf(PdfStamper stamper, Rectangle pageSize, int pageIndex){
PdfReader reader = new PdfReader(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/documents/Section13.pdf"));
AcroFields fields = reader.getAcroFields();
fields.renameField("SecurityGuidancePage3", "SecurityGuidancePage" + pageIndex);
stamper.insertPage(pageIndex, pageSize);
stamper.replacePage(reader, 1, pageIndex);
}
The way that I am creating the original document is like this.
OutputStream output = FacesContext.getCurrentInstance().getExternalContext().getResponseOutputStream();
PdfReader pdfTemplate = new PdfReader(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/documents/dd254.pdf"));
PdfStamper stamper = new PdfStamper(pdfTemplate, output);
stamper.setFormFlattening(true);
AcroFields fields = stamper.getAcroFields();
Is there a way to merge using the first piece of code and merge both of the acrofields together?
Depending on what you want exactly, different scenarios are possible, but in any case: you are doing it wrong. You should use either PdfCopy or PdfSmartCopy to merge documents.
The different scenarios are explained in the following video tutorial.
You can find most of the examples in the iText sandbox.
Merging different forms (having different fields)
If you want to merge different forms without flattening them, you should use PdfCopy as is done in the MergeForms example:
public void createPdf(String filename, PdfReader[] readers) throws IOException, DocumentException {
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
copy.setMergeFields();
document.open();
for (PdfReader reader : readers) {
copy.addDocument(reader);
}
document.close();
for (PdfReader reader : readers) {
reader.close();
}
}
In this case, readers is an array of PdfReader instances containing different forms (with different field names), hence we use PdfCopy and we make sure that we don't forget to use the setMergeFields() method, or the fields won't be copied.
Merging identical forms (having identical fields)
In this case, we need to rename the fields, because we probably want different values on different pages. In PDF a field can only have a single value. If you merge identical forms, you have multiple visualizations of the same field, but each visualization will show the same value (because in reality, there is only one field).
Let's take a look at the MergeForms2 example:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
copy.setMergeFields();
document.open();
List<PdfReader> readers = new ArrayList<PdfReader>();
for (int i = 0; i < 3; ) {
PdfReader reader = new PdfReader(renameFields(src, ++i));
readers.add(reader);
copy.addDocument(reader);
}
document.close();
for (PdfReader reader : readers) {
reader.close();
}
}
public byte[] renameFields(String src, int i) throws IOException, DocumentException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, baos);
AcroFields form = stamper.getAcroFields();
Set<String> keys = new HashSet<String>(form.getFields().keySet());
for (String key : keys) {
form.renameField(key, String.format("%s_%d", key, i));
}
stamper.close();
reader.close();
return baos.toByteArray();
}
As you can see, the renameFields() method creates a new document in memory. That document is merged with other documents using PdfSmartCopy. If you'd use PdfCopy here, your document would be bloated (as we'll soon find out).
Merging flattened forms
In the FillFlattenMerge1, we fill out the forms using PdfStamper. The result is a PDF file that is kept in memory and that is merged using PdfCopy. While this example is fine if you'd merge different forms, this is actually an example on how not to do it (as explained in the video tutorial).
The FillFlattenMerge2 shows how to merge identical forms that are filled out and flattened correctly:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
document.open();
ByteArrayOutputStream baos;
PdfReader reader;
PdfStamper stamper;
AcroFields fields;
StringTokenizer tokenizer;
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
while ((line = br.readLine()) != null) {
// create a PDF in memory
baos = new ByteArrayOutputStream();
reader = new PdfReader(SRC);
stamper = new PdfStamper(reader, baos);
fields = stamper.getAcroFields();
tokenizer = new StringTokenizer(line, ";");
fields.setField("name", tokenizer.nextToken());
fields.setField("abbr", tokenizer.nextToken());
fields.setField("capital", tokenizer.nextToken());
fields.setField("city", tokenizer.nextToken());
fields.setField("population", tokenizer.nextToken());
fields.setField("surface", tokenizer.nextToken());
fields.setField("timezone1", tokenizer.nextToken());
fields.setField("timezone2", tokenizer.nextToken());
fields.setField("dst", tokenizer.nextToken());
stamper.setFormFlattening(true);
stamper.close();
reader.close();
// add the PDF to PdfCopy
reader = new PdfReader(baos.toByteArray());
copy.addDocument(reader);
reader.close();
}
br.close();
document.close();
}
These are three scenarios. Your question is too unclear for anyone but you to decide which scenario is the best fit for your needs. I suggest that you take the time to learn before you code. Watch the video, try the examples, and if you still have doubts, you'll be able to post a smarter question.

How to retrieve all key-value pairs in a resource file located in App_GlobalResources

In my ASP.NET MVC application, I manage localized texts in .resx files located in App_GlobalResources folder. I am able to retrieve any text value in any file knowing its key.
Now, I want to retrieve all key/value pairs in a particular resource file in order to write the result to some JavaScript. A search revealed that I might be able to use ResXResourceReader class and iterate through the pairs; however the class is unfortunately located in the System.Windows.Forms.dll and I don't want to wire that dependency to my web app. Is there any other way I can implement this feature?
I've found the solution. Now no need to reference Forms.dll.
public class ScriptController : BaseController
{
private static readonly ResourceSet ResourceSet =
Resources.Controllers.Script.ResourceManager.GetResourceSet(CurrentCulture, true, true);
public ActionResult GetResources()
{
var builder = new StringBuilder();
builder.Append("var LocalizedStrings = {");
foreach (DictionaryEntry entry in ResourceSet)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}
Okay, no other answer. Seems like referencing Forms.dll is the only way right now. Here's the code I came up with.
public class ScriptController : BaseController
{
private const string ResxPathTemplate = "~/App_GlobalResources/script{0}.resx";
public ActionResult GetResources()
{
var resxPath = Server.MapPath(string.Format(ResxPathTemplate, string.Empty));
var resxPathLocalized = Server.MapPath(string.Format(ResxPathTemplate,
"." + CurrentCulture));
var pathToUse = System.IO.File.Exists(resxPathLocalized)
? resxPathLocalized
: resxPath;
var builder = new StringBuilder();
using (var rsxr = new ResXResourceReader(pathToUse))
{
builder.Append("var resources = {");
foreach (DictionaryEntry entry in rsxr)
{
builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
}
builder.Append("};");
}
Response.ContentType = "application/x-javascript";
Response.ContentEncoding = Encoding.UTF8;
return Content(builder.ToString());
}
}

Resources