Try to open twice a document, only on server, with office documents - c#

I got an issue with my aspx page, that open one document.
The problem is when I click on open, of the dialog box open, it will open the document, and the same document a second time in read only.
And this happened only when i run my silverlight application on a server, not localhost.
THe code calling the aspx(silverlight page behind code) :
ub = (new Uri(HtmlPage.Document.DocumentUri, "ViewDocument.aspx?&connexion=" + connexion + ";&id=" + id.ToString()));
if (HtmlPage.IsPopupWindowAllowed)
{
HtmlPopupWindowOptions opt = new HtmlPopupWindowOptions();
HtmlPage.PopupWindow(ub, "file", opt);
}
else
{
HtmlPage.Window.Navigate(ub);
}
HtmlPage.Window.Navigate(ub);
And the aspx page :
OracleConnection conn = new OracleConnection(vChaineConnexion);
conn.Open();
string v_requete = "";
if (id != null)
{
v_requete = "SELECT doc, extension " +
"FROM t_doc " +
"WHERE id= "+ id.ToString();
}
//si la requête n'est pas vide
if (!String.IsNullOrEmpty(v_requete))
{
OracleCommand cmd = new OracleCommand(v_requete, conn);
OracleDataAdapter da = new OracleDataAdapter(cmd);
OracleCommandBuilder ocb = new OracleCommandBuilder(da);
DataSet dataset = new DataSet();
if (id != null)
{
da.Fill(dataset, "Extension");
}
//retrieving binary data of pdf from dataset to byte array
byte[] blob = (byte[])dataset.Tables[0].Rows[0].ItemArray[0];
string extension = dataset.Tables[0].Rows[0].ItemArray[1].ToString();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
if(extension.equals(".doc"))
{
HttpContext.Current.Response.ContentType = "application/msword";
}
if (id != null)
{
HttpContext.Current.Response.AddHeader("content-disposition", "Attachment; filename=" + id.ToString() + extension);
}
HttpContext.Current.Response.AddHeader("content-length", blob.Length.ToString());
HttpContext.Current.Response.BinaryWrite(blob);
if (HttpContext.Current.Response.IsClientConnected)
{
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest(); //instead of Response.End()
//HttpContext.Current.Response.End();
}
}
I don't understand, why it tried to open the document two times, only on servers, while it works fine on localhost.
I go through my method, calling the aspx only one time, and at the moment I click open on the popupWindow, it open twice the document.
And it seems, this happened with word, but not with a pdf..
Correction : all office documents... (office 2010 on my desk)
See a error message quickly : online services smartscreen unavailable
I think this is the probleme but I don't understant why.
Why?

Related

Error code 0x800704CD when generating PDF to zip

I know this question was asked & answered before, but the solutions don't work for me. I have to dynamically create a list of PDFs, and each row has a checkbox. You check the PDFs you want to download, whose ID get passed to a function to create the PDF. I store those PDF's in a list, which gets passed to the Zip function (DotNetZip). Problem is, when first generating a PDF, I get that error somewhere in the middle of creating it, about halfway through, when adding a new page in the PDF. Usually it's the same spot but occasionally it changes where it crashes. Could anyone look at my code and point out where I'm messing up?
protected void Download_PDF_Click(object sender, EventArgs e)
{
Response.Clear();
Response.BufferOutput = false;
HttpContext c = HttpContext.Current;
String archiveName = "Arhiva Inspectii.zip";
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=\"" + archiveName + "\"");
int nr_rows = tbl_inspectii.Rows.Count - 1;
foreach (String id_chbx in ID_Checkbox)
{
CheckBox chbx = tbl_inspectii.FindControl(id_chbx) as CheckBox;
String PDF_id = "";
if(chbx != null)
{
if(chbx.Checked)
{
PDF_id = chbx.ID.Replace("ChBx", string.Empty);
Create_PDF(PDF_id);
}
}
}
string destdir = Server.MapPath("~/Zip/") + archiveName;
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(PDF_list, destdir);
zip.Save(destdir);
}
}
protected byte[] Create_PDF(String id_insp_max)
{
using (MemoryStream ms = new MemoryStream())
{
Document brosura = new Document(PageSize.A4);
brosura.SetMargins(40, 40, 40, 40);
PdfWriter wri = PdfWriter.GetInstance(brosura, ms);//new FileStream(Server.MapPath("Pdf/") + titlu_pdf + ".pdf", FileMode.Create)
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=\"" + titlu_pdf + ".pdf\"");
PdfWriter.GetInstance(brosura, HttpContext.Current.Response.OutputStream);
brosura.Open();
//lots of SQL, and brosura.Add();
//at some point, a brosura.Add() has the error halfway through the pdf
brosura.Close();
PDF_list.Add(titlu_pdf);
wri.Close();
return ms.ToArray();
}
}
Try to move the Response block after you closed the Document.
And try to add Response.End();
And why are you return the Array in Create_PDF but does not using it?

Download multiple files in same record from a database table

I have this table to store Purchase Order data, it can hold up to 3 files (first file is required, second and third is optional) which their column names are highlighted in the picture.
I have already done the Upload page, which save all the data entered and uploaded by user to the database, it is working fine, I can see all the saved file names and bytes in the table.
I am working on the View page, which retrieve data from database and display it to the webpage and have problem of retrieving the files.
The idea is to display the file name to the page (which is working fine) and when user click onto the file name, they can save it to the computer (or open/run etc depend on web browser prompt windows), problem here is that: I can only save the first file, when clicking on the second and third file name, nothing happened although when in debugging mode they (name, type and data of file2 and file3) do exist but the prompt windows to save file is not appeared
Any idea how to fix this or if anyone have better method of how to download these files please help.
Here is my code (please ignore the unrelated codes or please let me know if you want to know what they do):
The View.aspx to display file names
<asp:LinkButton ID="lbtPOFile" runat="server" OnClick="lbtPOFile_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtPOFile2" runat="server" OnClick="lbtPOFile2_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtPOFile3" runat="server" OnClick="lbtPOFile3_Click"></asp:LinkButton>
C# behind: the DownloadFile() method has 3 parameters, they are just column names in the database table, corresponding to the file1, file2 or file3, it supposes to retrieve the file when user click onto the file name (called in the click events below)
protected void DownloadFile(string fileNameColumn, string fileTypeColumn, string fileDataColumn)
{
string guid = !string.IsNullOrEmpty(Request.QueryString["guid"]) ? Request.QueryString["guid"] : Guid.Empty.ToString();
string id = !string.IsNullOrEmpty(Request.QueryString["id"]) ? Request.QueryString["id"] : "0";
if (requestDAL.ValidatePODetailLink(guid, Convert.ToInt32(id)))
{
byte[] bytes = null;
string fileName = "";
string contentType = "";
DataTable PODetail = requestDAL.GetPODetail(guid, Convert.ToInt32(id));
foreach (DataRow row in PODetail.Rows)
{
bytes = (byte[])row[fileDataColumn];
contentType = row[fileTypeColumn].ToString();
fileName = row[fileNameColumn].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
else
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>Invalid file or an error has occurred while connecting to the database. Please try again later!</b>";
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName", "poFileContentType", "poFileData");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile2_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName2", "poFileContentType2", "poFileData2");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile3_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName3", "poFileContentType3", "poFileData3");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
Some related functions in case you need it:
// Validate link for employee (link format is View.aspx?guid=xxx&id=xxx)
public static bool ValidatePODetailLink(string guid, int poID)
{
using (SqlConnection con = new SqlConnection(CS))
{
string query = "SELECT COUNT(*) FROM PO WHERE poID = #poID AND poGUID = #guid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#guid", guid);
cmd.Parameters.AddWithValue("#poID", poID);
con.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i == 1) return true;
else return false;
}
}
//Get po request details for employee
public static DataTable GetPODetail(string guid, int poID)
{
using (SqlConnection con = new SqlConnection(CS))
{
string query = "SELECT * FROM PO WHERE poID = #poID AND poGUID = #guid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#guid", guid);
cmd.Parameters.AddWithValue("#poID", poID);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
PROBLEM FOUND:
I use UpdatePanel and only put <Triggers> <asp:PostBackTrigger ControlID="lbtPOFile" /> </Triggers> hence it was missing PostBackTrigger for lbtPOFile2 and lbtPOFile3. Added those 2 lines and it works.
I would suggest the following approach.
Revert your code to the "known good" state (where it can only handle the download of one file, but does so correctly)
Refactor this code so that it still supports a single file download. Take the code that streams the file contents into the response; move it into a separate function (perhaps call this SendFile); call that function from your click handler; recompile and confirm that everything is still working.
Now modify SendFile so that it accepts input parameters that determine whether it will return file 1, file 2, or file 3. Modify the click handler so that it passes the parameters that indicate file 1. Recompile and test again, make sure it still works.
Now add two additional click handlers for your other two link buttons. Should be identical to your existing click handler except for the arguments that are passed to SendFile. Recompile and test with all three files.

attached .doc is opening properly in pc but in mobile its not opening properly while sending by smtp in .net

im creating .doc file and sending mail. in pc dowloaded file from
attachment is opening properly but in mobile its not opening
properly. only html tags are displaying in smart phones.can u
tell me how to render this .doc file so that in mobile also attached
file can be displayed ?
attached file is not supporting in smartphones .only html tags are
displaying.
can anyone tell in my code how to use docX library in my code?
protected void btnMail_Click(object sender, EventArgs e)
{
DisplayProgressBar();
Response.Clear();
try
{
if (Session["Projectname"] != null && Session["Projectname"].ToString() != string.Empty)
{
string Projname = Session["Projectname"].ToString();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
design.RenderControl(htmlWrite);
string strBuilder = stringWrite.ToString();
string strPath = Request.PhysicalApplicationPath + "\\Temp\\WeeklyReport of " + Projname + ".doc";
LblNoteMsg.Text = strPath;
//code changed to send mails
if (File.Exists(strPath))
{
var counter = 1;
strPath = strPath.Replace(".doc", " (" + counter + ").doc");
while (File.Exists(strPath))
{
strPath = strPath.Replace("(" + counter + ").doc", "(" + (counter + 1) + ").doc");
counter++;
}
}
using (var fStream = File.Create(strPath))
{
fStream.Close();
fStream.Dispose();
}
using(StreamWriter sWriter = new StreamWriter(strPath))
{
sWriter.Write(strBuilder);
sWriter.Close();
sWriter.Dispose();
Response.Clear();
}
DateTime input = DateTime.Now;
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime dats = DateTime.Now.AddDays(delta);
//this week
DateTime monday = input.AddDays(delta);
string MonDate = monday.ToShortDateString();
DateTime sat = monday.AddDays(5);
string SatDate = sat.ToShortDateString();
StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
string body = r.ReadToEnd();
MailMessage Msg = new MailMessage();
string MailId = txtMailId.Text;
foreach (string ss in MailId.Split(",".ToCharArray()))
{
if (string.IsNullOrEmpty(ss) == false)
{
Msg.To.Add(new MailAddress(ss));
}
}
Msg.Bcc.Add(new MailAddress("support#sunlightit.com"));
body = body.Replace("<%MonDate%>", MonDate);
body = body.Replace("<%SatDate%>", SatDate);
Msg.Subject = "Weekly status Report of " + Projname + "," + DateTime.Now.ToShortDateString() + "";
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.Attachments.Add(new Attachment(strPath));
SmtpClient MailServer = new SmtpClient();
try
{
MailServer.Send(Msg);
string reply = (Msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess).ToString();
if (reply == "OnSuccess")
{
txtMailId.Text = "";
tblMail.Visible = false;
lblMsg.ForeColor = System.Drawing.Color.Green;
lblMsg.Text = "Mail has send succesfully";
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Mail delivery unsuccessfull";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "clentscript", "alert('It is being used by another process.Please Try after sometime ');", true);
}
}
You did not make a proper .doc file. A .doc file is not composed of HTML. Word on your computer does know HTML so it will open the file, but likely the program you're using on the mobile devices will just treat it as a corrupted .doc file.
Instead, you should build a proper Word document. There's plenty of libraries for generating .docx Open Office XML Document (Word 2007) files. Find one that works for you needs, and use it.
Write the file on the server path and pass the link to user make the download:
Example:
http://yourapp.com/files/download/051651203210.doc

Upload and download files on SQL Server from a C# application

I have a C# application that is uploading files to a sql server, I use this code to get the pdf file and then I change it to "bytes" for upload on the SQL Server database.
private void mButtonAddCV_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files | *.pdf";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openFileDialog1.FileName.Length > 0)
{
pathCV = openFileDialog1.FileName;
}
}
// Read the file and convert it to Byte Array
string filePath = pathCV;
string contenttype = String.Empty;
contenttype = "application/pdf";
if (contenttype != String.Empty)
{
Stream fs = File.OpenRead(filePath);
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
}
I use the code below to upload the file:
if (!mConnector.Update("INSERT INTO **** (***, ***, CV) " +
"VALUES ('" + *** + "', '" + *** + "', '" + bytes + "')"))
{
Messages.errorMessageBox("This CV already exists.");
}
else
{
ChangeScreen(ActiveScreen, ActiveScreens.ActiveScreen_CVList);
}
But now I don't know how to download this file and how to make a pdf file with the data stored on the database to see it. Can anyone help me?
Thanks!
First off, let's change the way you are forming your insert statement so you aren't opening up your system to sql injection. This will also make the insert statement easier to work with
var command = new SqlCommand("INSERT INTO myTable (x, y, z) VALUES (#a, #b, #c)", sqlConnection);
command.Parameters.Add(new SqlParameter("#a", bytes));
command.Parameters.Add(new SqlParameter("#b", bValue));
command.Parameters.Add(new SqlParameter("#c", bValue));
var resultingRows = command.ExecuteNonQuery();
To read the data out, use ExecuteReader, then the File object to save it to the disk.
var command = new SqlCommand("Select a from myTable", sqlConnection);
var reader = command.ExecuteReader();
reader.Read();
var pdfBinaryBuffer = (byte[])reader[0];
// Save file to disk
var file = File.Create("myFile.pdf", pdfBinaryBuffer.Length);
file.Write(pdfBinaryBuffer, 0, pdfBinaryBuffer.Length);
file.Close();
I suggest you to insert your byte data using SqlParameters...
see Inserting a byte array into sql server
Then, read the record using SqlDataReader's GetBytes(...) function see here.
I suggest you to upload pdf and save it in separate folder. you can save the path in database table that I think it is good.
Here is code for file upload
Drag “Fileupload” control to .aspx page (Use this code is for save .PDF to folder)
protected void fileUpload()
{
if (fileUp.HasFile)
{
fileUp.SaveAs(Server.MapPath("~/PoPDF/" + this.txtCusPo.Text +".PDF"));
string imgPrintPo = this.txtCusPo.Text + ".PDF";
}
}
Here is code for file download
You can put this code in button event but here I have used GridView row command event.
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
if (e.CommandName == "SelectDownload")
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/PoPDF/") + e.CommandArgument);
//Response.Flush();
Response.End();
}
}

reading Html file through OLEDB fails

i am trying to read html file through OLEDB reader using following code
DataTable dTable;
string strDataSource = "";
string strDBFile = "";
long intPos = 0;
strDataSource = mstrFilePath;
dTable = new DataTable();
mCon = new System.Data.OleDb.OleDbConnection();
mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=\"HTML Import;HDR=NO;IMEX=1\";");
if (mCon.State == ConnectionState.Closed)
{
mCon.Open(); // gettting failed here
}
dTable = mCon.GetSchema("Tables");
bSelectionChanged = true;
lstTables.Items.Clear();
foreach (DataRow DRow in dTable.Rows)
{
if (DRow["TABLE_TYPE"].ToString() == "TABLE" || DRow["TABLE_TYPE"].ToString() == "VIEW")
{
intPos = DRow["TABLE_NAME"].ToString().LastIndexOf("FilterDatabase");
lstTables.Items.Add(DRow["TABLE_NAME"]);
}
}
if (lstTables.Items.Count == 1)
{
lstTables.Visible = false;
grdSampleDataControl.Dock = DockStyle.Fill;
}
else
{
lstTables.Visible = true;
grdSampleDataControl.Dock = DockStyle.None;
}
bSelectionChanged = true;
dTable.Dispose();
mCon.Close();
openFileDialog1.Dispose();
It is getting failed here wiht exception\
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
But file is not opened anywhere ??
Edit
On debug, When it throws exception at mCon.Open(), If i press F10 compiler moves to next statement and run the programm succesfully. why it is so ??
This is happening because your Acccess Database file is open.
You can not keep file open, and do changes on that file dynamically.
While the program using that file is running, it tries to open that file.
But, if file is already open exclusively by user, then it fails.
Close the file, and then try to open the connection.
For other details on it, follow this DISCUSSION.

Categories

Resources