.NET MVC FileResult equivalent in Web Forms - asp.net

I'm using FileResult as a return value for a function in MVC that returns a PDF file.
What return type should I use in Web Forms?
Thanks
public FileResult PrintPDFVoucher(object sender, EventArgs e)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
outputDoc.Save(memory, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
var result = new FileContentResult(memory.GetBuffer(), "text/pdf");
result.FileDownloadName = "file.pdf";
return result;
}

In ASP.NET Webforms you'll need to write the file to the Response stream manually. There is no result abstraction in webforms.
Response.ContentType = "Application/pdf";
//Write the generated file directly to the response stream
Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download
Response.End();
This code is not tested, but this should get you in the general direction.

Classic ASP.NET doesn't have the idea of a return type. The way to approach this would be to create an custom .ashx page/handler to serve up the file.
Your code behind for this file should look something similar to:
public class Download : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
Response.ContentType = ""text/pdf"";
Response.AppendHeader("Content-Disposition","attachment; filename=File.pdf");
outputDoc.Save(Response.OutputStream, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Related

How to use Tempdata to display the list

I have did the excel upload in dotnet core .I had to use tempdata to retrieve the details of the excel in list.Instead in my below code i had used Static object to retrieve the list.My code works as like this ,when i click on upload button it will display the details in the excel sheet.and when click on save it will save it to database and i need to edit in grid view using ajax call also .Help me out
My Action in controller is
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
using (var stream = new FileStream(path, FileMode.Create))
{
await excelfile.CopyToAsync(stream);
}
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
employeesListObject.EmpModelList = employeesViewModelList;
return View(employeesListObject);
}
}
catch(Exception ex)
{
TempData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
Try this, using your own list.
List<string> SomeList = new List<string>();
TempData["MyList"] = SomeList;
//then to get data just do
SomeList = TempData["MyList"] as List<string>; //This converts back to List<T>
Once you add the list to the TempData, you can retrive it from any Action or View in the same controller

Xamarin iOS: How can I open a pdf file using a standard reader

I need to open a pdf file using a default reader, android works, but for iOS i can not. And I do not have a solid experience with C # only 2 months
public void SaveOpen(string filename, MemoryStream stream)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, filename);
//Create a file and write the stream into it.
FileStream fileStream = File.Open(filePath, FileMode.Create);
stream.Position = 0;
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Close();
UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (currentController.PresentedViewController != null)
currentController = currentController.PresentedViewController;
UIView currentView = currentController.View;
}
To open a pdf file from a filePath:
public void OpenPDF(string filePath)
{
FileInfo fi = new FileInfo(filePath);
QLPreviewController previewController = new QLPreviewController();
previewController.DataSource = new PreviewControllerDataSource(fi.FullName, fi.Name);
UINavigationController controller = FindNavigationController();
if (controller != null)
controller.PresentViewController(previewController, true, null);
}
private UINavigationController FindNavigationController()
{
foreach (var window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController.NavigationController != null)
{
return window.RootViewController.NavigationController;
}
var value = CheckSubs(window.RootViewController.ChildViewControllers);
if (value != null)
return value;
}
return null;
}
private UINavigationController CheckSubs(UIViewController[] controllers)
{
foreach (var controller in controllers)
{
if (controller.NavigationController != null)
{
return controller.NavigationController;
}
var value = CheckSubs(controller.ChildViewControllers);
return value;
}
return null;
}
So, in your code, after saving it, just call OpenPDF with the correct path.

print preview is not working in godady

I have a web application developed in ASP.NET. I am using rdlc to do the reporting. Everything seems to work fine on my development machine, but not when I upload the application to the hosting service (GoDaddy.com). The reports show up as preview (ReportViewer Control). But when I click on Print it is not showing the preview.
public void print()
{
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
//Open exsisting pdf
Document document = new Document(PageSize.A4);
PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
//Getting a instance of new pdf wrtiter
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
int i = 0;
int p = 0;
int n = reader.NumberOfPages;
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
//Add Page to new document
while (i < n)
{
document.NewPage();
p++;
i++;
PdfImportedPage page1 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page1, 0, 0);
}
//Attach javascript to the document
PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
writer.AddJavaScript(jAction);
document.Close();
//Attach pdf to the iframe
frmPrint.Attributes["src"] = "Print.pdf";
}
catch (Exception ex)
{
Response.Write("<script>alert('Error Occured')</script>");
}
}
I am using the above code for print..

How to get image from HTTP URL in Windows Phone?

How do I get image from http url, my url is like:
"http://accd.com/abc.htm",
how do I get image from it?
So
public static BitmapImage Base64StringToBitmap(string source)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
return img;
}
You can use the web client like this :
var webClient = new WebClient();
webClient.DownloadStringAsync(new Uri("http://accd.com/abc.htm"));
webClient.DownloadStringCompleted += (sender, eventArgs) => (eventArgs.Result); //Here is your base 64 image code, you can use the Base64StringToBitmap function
May be with using a webclient
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("your http url"), wc);
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
imgLogoData.Source = bitmapImage;
imgLogoData.Height = 200;
}
catch (Exception ex)
{
MessageBox.Show(AppResources.resErrorOccured);
ExceptionHelper.WriteLog(ex);
}
}
And to convert a Base64 string to BitmapImage just follow this method
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So that, for an Image declared in xaml like this
Add an image to your XAML, such as this:
<Image x:Name="imgLogoData" Height="50" Width="50" />
You can then set the source, like this:
imgLogoData.Source = base64image(yourBase64string);

Compressing viewstate is adding another hidden field with same id as __VIEWSTATE

I am trying to compress viewstate in ASP.Net 4.0, so the page loads more quickly for heavily bloated viewstate pages.
However, when I view source of page in browser, I am finding 2 hidden fields with same name and id of '__VIEWSTATE'.
My code is as below. How can I compress the view state but let it be stored in its original hidden field without creating another duplicate hidden field?
protected override void SavePageStateToPersistenceMedium(object viewState)
{
byte[] viewStateArray;
using (MemoryStream memoryStream = new MemoryStream())
{
_objectStateFormatter.Serialize(memoryStream, viewState);
viewStateArray = memoryStream.ToArray();
}
ClientScript.RegisterHiddenField("__VIEWSTATE",
Convert.ToBase64String(GZip.Compress(viewStateArray)));
}
using System.IO;
using System.IO.Compression;
using System.Web.UI;
public class PageCompressed : System.Web.UI.Page
{
private ObjectStateFormatter _formatter = new ObjectStateFormatter();
protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__CVIEWSTATE", Convert.ToBase64String(_Compress(viewStateArray)));
}
protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__CVIEWSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = _DeCompress(bytes);
return _formatter.Deserialize(Convert.ToBase64String(bytes));
}
private byte[] _Compress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Compress, true);
zip.Write(inputBytes, 0, inputBytes.Length);
zip.Close();
return m.ToArray();
}
private byte[] _DeCompress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream(inputBytes);
MemoryStream mout = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Decompress, true);
do
{
byte[] bBuffer = new byte[4097];
int iRead = zip.Read(bBuffer, 0, bBuffer.Length);
if (iRead > 0)
{
mout.Write(bBuffer, 0, iRead);
}
else
{
break;
}
} while (true);
zip.Close();
return mout.ToArray();
}
}
you can use this Interface Class to compress viewstate by inheriting from it like this in code behind for every page
public partial class Default : PageCompressed

Resources