How do display the word document in asp.net page retrieved from SQL Server database - asp.net

How do display a Word document on an asp.net page retrieved from a SQL Server database table?
I have uploaded the word document into database, please see the code,
Now I want to display the word document details in gridview, when I click the word document name in the gridview then the word document should display in webpage. Please help me how to do this.
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("user id=sa;password=123;database=Shashank;data source=Shashank");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

To my knowledge you have to convert the word document to .html to display it in a web page itself. You can check out this article that shows you how to do it. http://www.c-sharpcorner.com/UploadFile/munnamax/WordToHtml03252007065157AM/WordToHtml.aspx
I guess what I would do is convert the ms doc file to HTML at upload and then store that along with the .doc or .docx. The HTML you would select and display it in an iframe and the actual .doc file you could use if the user wanted to download it.

Related

how to display a .docx file in ckeditor?

I am making a website in ASP.NET using C#. I have stored .docx file in database in binary form. I have successfully retrieved it but now my task is that I have to open .docx file from database in ckeditor. And if I make any changes then the file in the database should be updated.
Code for saving .docx file in DB...
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
Retrieving from DB...
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
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();
}
protected void btnshow_Click(object sender, EventArgs e)
{
string s1 = proclist.SelectedItem.Value;
string str1 = "";
db.con.Open();
try
{
string str = "select Name, ContentType, Data from tblFiles where Name='" + proclist.SelectedItem.Value + "'";
db.com = new SqlCommand(str, db.con);
SqlDataReader dr = db.com.ExecuteReader();
DataTable dt = GetData(db.com);
if (dt != null)
{
download(dt);
}
}
catch (NullReferenceException ex)
{
ex.ToString();
}
db.con.Close();
}
Javascript method:
function button_convertDocxToHTML_DisplayInCKEditor() {
$.ajax({
type: "POST",
async: false,
url: "Page.aspx/GetHTML",
data: "{'pathFile':'UploadFolder/',
'fileName':'docName',
'extensionFile':'.docx'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultHtml = result.d;
var objEditor = CKEDITOR.instances["yourID_Description"];
objEditor.setData(resultHtml);
},
error: function (result) {
// Unexpected error...
return false;
}
});
}
In the code-behind Page.aspx.cs, we have a web method in the side server. Maybe you will need some using like these:
using System.Reflection;
using System.Runtime.InteropServices;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetHTML(string pathFile, string fileName, string extensionFile)
{
string result = string.Empty;
object path_DocsName = HttpContext.Current.Request.MapPath(pathFile + fileName + extensionFile);
object o = Missing.Value;
object oFalse = false;
object oTrue = true;
Microsoft.Office.Interop.Word._Application app = null;
Microsoft.Office.Interop.Word.Documents docs = null;
Microsoft.Office.Interop.Word.Document doc = null;
StreamReader reader = null;
try
{
app = new Microsoft.Office.Interop.Word.Application
{
Visible = false,
DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
};
docs = app.Documents;
doc = docs.Open(ref path_DocsName, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
doc.Activate();
string newHtmlFile = HttpContext.Current.Request.MapPath("pathHtmlTEMPORAL/" + fileName + ".html");
// Create html file
doc.SaveAs(FileName: newHtmlFile, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
doc.Close(ref o, ref o, ref o);
app.Quit(ref o, ref o, ref o);
using (reader = new StreamReader(newHtmlFile, Encoding.GetEncoding("utf-8")))
{
result += reader.ReadToEnd();
reader.Dispose();
reader.Close();
}
}
catch (Exception ex)
{
result = Resources.WholeSite.Validation_UnexpectedError + ": " + ex.Message;
}
finally
{
if (doc != null) Marshal.FinalReleaseComObject(doc);
if (docs != null) Marshal.FinalReleaseComObject(docs);
if (app != null) Marshal.FinalReleaseComObject(app);
if (reader != null) { reader.Dispose(); reader.Close(); }
}
return result; // this result has all html that you have to display into CKEditor.
}

rdlc Report works in local but not on server

I have a report with some datasets, working perfectly in local, but on the server i get the error :
One or more parameters required to run the report have not been specified.
I don't have any parameters on this report, so i don't understand this error... I have this code in controller :
public ActionResult RunReport(int PremiseId)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Views/Report/PremisePricing.rdlc");
Premise premise = _db.GetPremise(PremiseId);
ICollection<PremisePricing> premisePricings;
if (premise.PremiseMeters.Count() > 0)
{
premisePricings = premiseMeterPricingToPremisePricing(_db.FindAllPremiseMeteredPricing(premise).ToList());
}
else
{
premisePricings = _db.FindAllPremisePricing(PremiseId).ToList();
}
// Add your data source
List<ReportDataSource> listDS = new List<ReportDataSource>();
ICollection<Premise> premises = new List<Premise>();
premises.Add(premise);
ReportDataSource premiseDS = new ReportDataSource("Premise", premises);
listDS.Add(premiseDS);
ReportDataSource premisePricingDS = new ReportDataSource("PremisePricing", premisePricings);
listDS.Add(premisePricingDS);
ICollection<CompanyProvider> companyProviders = new List<CompanyProvider>();
CompanyProvider companyProvider = _db.GetCompanyProvider();
companyProviders.Add(companyProvider);
ReportDataSource companyProviderDS = new ReportDataSource("CompPro", companyProviders);
listDS.Add(companyProviderDS);
ICollection<CompanyProviderContactManager> companyProviderContactManager = new List<CompanyProviderContactManager>();
if (companyProvider.CompanyProviderContactManager != null)
{
companyProviderContactManager.Add(companyProvider.CompanyProviderContactManager);
}
ReportDataSource companyProviderContactManagerDS = new ReportDataSource("CompProContactManager", companyProviderContactManager);
listDS.Add(companyProviderContactManagerDS);
ICollection<Customer> customer = new List<Customer>();
if (_db.GetPremiseProviderByPremiseId(PremiseId) != null)
{
Customer cust = _db.GetPremiseProviderByPremiseId(PremiseId).Customer;
customer.Add(cust);
}
ReportDataSource customerDS = new ReportDataSource("Customer", customer);
listDS.Add(customerDS);
RenderReport(localReport, listDS, companyProvider.logo);
return View();
}
private void RenderReport(LocalReport localReport, List<ReportDataSource> listDS, byte[] logo)
{
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=Pricing." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
Any suggestion?

Open button do not works properly in downloading with a linkbutton

There is a section in my site that users can download files. I want that As users push the download button and hit "Open" button instead of "save" button, the download get open with it's own program. For example a pdf file should not en with ms word. Now my problem is that, as a user open the file an XML extension will be added to the download URL!!
For example it should be:
www.mysite.com/inputfile/12.dox
but instead of that, it goes for
www.mysite.com/inputfile/12.dox.xml
Here is my cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
string contenttype = String.Empty;
string ext = Path.GetExtension(fileName);
Response.ClearContent();
Response.ClearHeaders();
switch (ext)
{
case ".doc":
contenttype = "application/msword";
break;
case ".docx":
contenttype = "application/msword";
break;
case ".xls":
contenttype = "application/msexcel";
break;
case ".xlsx":
contenttype = "application/msexcel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Response.ContentType = contenttype;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}

How to open a file with it's own program with a linkbutton

I have developed a website using Asp.net. In a section of my program users need to download some variable files. (Jpeg,Pdf,doc,docx...) As they push the download button and hit "Open" button instead of "save" button, the file will open with Adobe Acrobat. The problem is that if it is a word file, again it will be open with Adobe Acrobat!
How can i avoid this and each file open with it's own program?
I used this cod in my behind cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}
Like this :
string ext = System.IO.Path.GetExtension(this.File1.PostedFile.FileName);
string contenttype = String.Empty;
OR
string ext = Path.GetExtension(filename);
switch(ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Use
FileInfo fInfo = new FileInfo(fileName);
string fileExtn = fInfo.Extension;

uploading more than of 1mb is not possible

i have used below structure for my table in database. i can not upload files more than of 1mb in the database, please help what is the problem.
fileid(int), FileName(varchar(100)), ContentType (varchar(75)), data varbinary(MAX)
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
if (di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
//Giving Error:Object reference not set to an instance of an object.
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
string s = ((HyperLink)di.Cells[1].Controls[0]).Text;
var tr = from transmittal in _DataContext.tbltransmittalNos
where transmittal.TRANSMITTAL == s
select transmittal.TransID;
int _transid = tr.SingleOrDefault();
// int _transid = Convert.ToInt32(tr.SingleOrDefault());
Label1.Text = _transid.ToString();
Label2.Text = s;
}
}
}
tblFile fn = new tblFile();
fn.DocId = _DocID;
fn.TransId = Convert.ToInt32(Label1.Text);
fn.FileName = filename;
fn.ContentType = contenttype;
fn.Data = bytes;
// BookAuthor bookAuthor = new BookAuthor();
_DataContext.tblFiles.InsertOnSubmit(fn);
_DataContext.SubmitChanges();
//doctranscon.TransmitToConid = Convert.ToInt32(ddlTransmittaltoCon.SelectedValue);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
// Update display
DisplayDocument();
}
}
You are not sharing your specific error but this is likely the cause. Increase the maxRequestLength size in your web.config file. The default is 4096 KB (4 MB).
<configuration>
<system.web>
<httpRuntime maxRequestLength="size in kbytes"
...
/>
Allocating an array size of data will, eventually, fail. Look into streaming semantics.
Check your configured maxRequestLength

Resources