Compressing viewstate is adding another hidden field with same id as __VIEWSTATE - asp.net

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

Related

What is the Most simple way to store image in Data base in MVC

ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>
Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image

getting directed to ASP.NET home page on browser

I am trying to run the following HTTP POST API Call using ASP.NET on Visual studio 2013. I created a new web application project as mentioned here
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateNewAPICall("test api abc");
}
private object CreateNewAPICall(string apiDesc)
{
object result = null;
var accessKey = "myaccesskey";
var secretKey = "mysecretkey";
var uRLapiList = "http://myurl.com";
byte[] bytes = Encoding.UTF8.GetBytes("apiListDesc=" + apiDesc);
var method = "POST";
var timeString = DateTime.UtcNow.GetDateTimeFormats()[104];
var signature = GetSignature(secretKey, method, timeString);
var authorization = accessKey + ":" + signature;
HttpWebRequest request = CreateWebRequest(uRLapiList, "POST", bytes.Length, timeString, authorization);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseReader = new StreamReader(request.GetResponse().GetResponseStream());
// Return List api Data
result = responseReader.ReadToEnd();
}
}
return result;
}
private HttpWebRequest CreateWebRequest(string endPoint, string method, Int32 contentLength, string timeString, string authorization)
{
// Some code here
}
private string GetSignature(string secretKey, string method, string timeString)
{
// Some code here
}
private byte[] HMAC_SHA1(string signKey, string signMessage)
{
// Some code here
}
private string CreateSignature(string stringIn, string scretKey)
{
// Some code here
}
}
Right now, I am confused as to where to put this file in the "Solution Explorer" in order to
run the file and get the output on my browser?
Right now I have this code inside "Models-->Class1.cs" directory as shown in the image below:
So, when I press F-5 key, I am getting directed to the home page of the ASP.NET with the URL http://localhost:4439/
Do I need to make any changes here?

How to pass image to Eval method from handler.ashx to imageurl?

I want to retrieve image from database and display in an aspx page. I use Linq to SQL. And a Generic handler.
Handler2.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
int id;
string sid = context.Request.QueryString["id"];
if (int.TryParse(sid, out id))
{
Stream strm = getImage(id);
byte[] buffer = new byte[4096];
int i = strm.Read(buffer, 0, 4096);
while (i > 0)
{
context.Response.OutputStream.Write(buffer, 0, 4096);
i = strm.Read(buffer, 0, 4096);
}
}
else
{
//
}
}
}
public Stream getImage(int id)
{
using (DummyDBEntities cntx = new DummyDBEntities())
{
var db = from c in cntx.Images
where c.imageId == id
select c.imageData;
MemoryStream ms = new MemoryStream();
byte[] byteArray = new byte[db.ToArray().Length];
ms.Write(byteArray, 0, db.ToArray().Length);
return new MemoryStream(byteArray);
}
}
And a button control in Default.aspx page when I click, redirects to handler1.ashx. Gets the id of image from database and supposed to Show it in Default.aspx asp:image control
protected void btnGetID_Click(object sender, EventArgs e)
{
int id=Convert.ToInt32(txtGetID.Text);
Response.Redirect("Handler2.ashx?id="+id);
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
}
How do i supposed to write Eval method and the querystring to pass the image to imageurl?
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
Please help, thanks.
I hope I understood your problem right.
You want to display the image from your handler in the Image1. For that you can just do the following
Image1.ImageUrl = ResolveUrl("~/Handler2.ashx?id=" + id);

Pdf's fields should remain editable using itextsharp in asp.net

I have a fillable pdf. In which i have few textboxes.
I fill these fields by using following code(itextsharp).
DataTable dt = new DataTable();
String pdfPath1 = Server.MapPath("pdfs\\transmittal2.pdf");
if (File.Exists(pdfPath1))
{
dt = objClsTransmittal.GetTransmittal(jobid, cid);
String comment = "Correspondence generated for " + dt.Rows[0]["Recipient"].ToString();
var formfield = PDFHelper.GetFormFieldNames(pdfPath1);
formfield["DocDate"] = DateTime.Now.ToLongDateString();
formfield["Address1"] = dt.Rows[0]["Company"].ToString();
formfield["Address2"] = dt.Rows[0]["Address1"].ToString();
formfield["PropertyAddress"] = dt.Rows[0]["PropertyAddress"].ToString();
formfield["Job"] = dt.Rows[0]["JobID"].ToString();
formfield["Name"] = dt.Rows[0]["Recipient"].ToString();
formfield["CityStateZip"] = dt.Rows[0]["address2"].ToString();
formfield["E-mail"] = dt.Rows[0]["Email"].ToString();
var pdfcontent = PDFHelper.GeneratePDF(pdfPath1, formfield);
PDFHelper.ReturnPDF(pdfcontent, "Transmittal.pdf");
}
Currently its downloded as read only pdf.
when this pdf gets downloaded, i want that all fields still remain fillable, with the text i have filled in pdf. So that i can edit the text.
I'm looking forward for your replies.
Thanks.
EDIT
PdfHelper is my custom class. In which i have used following code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
Your code line
stamper.FormFlattening = true;
instructs iTextSharp to flatten the form fields, i.e. to integrate them into the page content and remove the form field annotations.
As you want to keep the form fields as editable fields, don't flatten the form.
Error: Cannot convert type in PDFHelper.cs
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields) //ERROR: 'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'
{
fields.Add(entry.Key.ToString(), string.Empty);
}
reader.Close();
return fields;
}
'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'

.NET MVC FileResult equivalent in Web Forms

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;
}
}
}

Resources