File Encryption in mvc5 - encryption

var graphids = from o in db.OfflineCarts
join i in db.Graphs on o.ItemId equals i.ItemUserID
select i;
GridView gv = new GridView();
gv.DataSource = graphids.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=GraphTable.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Encryption();
public void Encryption()
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = "/Users/Neeraj/Downloads/UserFilesEncrypt.xls";
FileStream fsCrypt = new FileStream(cryptFile, FileMode.CreateNew);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream rs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Read);
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
string inputFile = "/Users/Neeraj/Downloads/GraphTable.xls";
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
I am encrypting the file just instantaneously after it is downloaded by grid view in mvc5 but i am getting 0 byte encrypted file and when i am re downloading the file than i am getting proper encrypted file Can Anybody tell me what is wrong with the code or i have to delay encryption function after download for sometime

use System.Security
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);

Related

ASP.Net Open office XML Set the values of a cell

I am using ASP.Net and Open office XML and I have been able to set the headers of the excel file.
However, I want to set the value to cells from say D2 to D1000 in a drop down fashion i.e. that the user can only select from a predefined list of values as in a drop down list.
How do I accomplish this?
The code for creating the excel is
List<ExcelExport> mpList = new List<ExcelExport>();
DataTable dt = ListToDataTable(mpList);
string attachment = string.Format("attachment;filename={0}-{1}.xlsx", ddlHealthFacility.SelectedItem.Text + " Excel export ", " ");
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monthly Plan");
ws.Cells["A1"].LoadFromDataTable(dt, true);
Byte[] fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
Response.BinaryWrite(fileBytes);
Response.End();
}

Add background watermark logo to PDF file

I have rendered my aspx page to pdf successfully using ITextSharp.
Now i want to add watermark logo in background off PDF file please help me out i have been stuck into this.
Following is my code for export to pdf
private void ShowPdf(string s)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + s);
Response.ContentType = "application/pdf";
Response.WriteFile(s);
Response.Flush();
Response.Clear();
}
public void PrepareControlForPDF()
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
divApplicantDetails.RenderControl(myWriter);
myWriter.Flush();
// myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
//CreatePDFDocument(strmRdr);
//strmRdr.Dispose();
///mem.Dispose();
CreatePDFDocument(pageContent);
//writer.Write(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string filename = ""+System.DateTime.Now.Day+"AppLetter.pdf";
// if (System.IO.File.Exists(Server.MapPath("../Pdf") + "/" + filename))
// {
// System.IO.File.Delete(Server.MapPath("../Pdf") + "/" + filename);
// }
string strFileName = Server.MapPath("../Pdf") + "/" + filename;
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
MemoryStream ms = new MemoryStream();
ms.Write(System.Text.Encoding.ASCII.GetBytes(strHtml), 0, System.Text.Encoding.ASCII.GetBytes(strHtml).Length);
//ms.Position = 0;
StreamReader sr = new StreamReader(new MemoryStream(new System.Text.ASCIIEncoding().GetBytes(strHtml)));
sr.BaseStream.Position = 0;
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
}
finally
{
document.Close();
}
}
I think you can achieve by creating a new class and implementing the IPdfPageEvent interface... refer here

Passing a grid to a function used to export to excel

I have a method that is used to export the data to excel.Till now I have been passing table to the method.But now I wish to pass the grid data so that I do not have to call the procedures for different instances for getting different filtered data sets.
is there a way to do so?
public void ExportToExcel(DataSet ds)
{
if (ds.Tables[0].Rows.Count > 0)
{
string filename = ds.Tables[1].Rows[0]["filename"].ToString() + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = ds.Tables[0];
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.AddHeader("content-disposition", String.Concat("attachment;filename=", filename));
Response.AddHeader("Cache-Control", "max-age=0");
Response.ContentType = "application/vnd.xls";
// this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
This is the method that I am using to export to excel.

Unable to get the Content of the text file saved in the Database(My-Sql)

In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell
if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.

Avoid saving new file on the disk

I am using ASP.NET 3.5 with iTextSharp and I have the following code:
var templatePath = Server.MapPath(#"~/Templates/template1.pdf");
var newFilePath = Server.MapPath(#"~/TempFiles/new.pdf");
PdfReader pdfReader = new PdfReader(templatePath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("Box1", "007");
pdfFormFields.SetField("Box2", "123456");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=new.pdf"));
Response.WriteFile(newFilePath);
Response.End();
The above code fills out a pdf file and saves the new file to the TempFiles folder. It then prompts the user to either save or open the file. Can I achieve the same functionality without saving the file to the TempFiles location?
Yes, you can write directly to the output stream of the response. I haven't used PdfStamper, but here's how I do it when generating new PDFs:
doc = new iTextSharp.text.Document(PageSize.A4);
writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, Response.OutputStream);
writer.SetFullCompression();
doc.Open();
It looks like you pass a stream into the PdfStamper constructor, so the following should work:
var templatePath = Server.MapPath(#"~/Templates/template1.pdf");
PdfReader pdfReader = new PdfReader(templatePath);
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=new.pdf"));
PdfStamper pdfStamper = new PdfStamper(pdfReader, Response.OutputStream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("Box1", "007");
pdfFormFields.SetField("Box2", "123456");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
Response.End();

Resources