Download file method in MVC4 - asp.net

When i tried the below code, i have received "operator does not exist: integer =# integer" and ArgumentException.
Can anyone help me to resolve this issue pls?
public FileContentResult GetFile(int fileid)
{
NpgsqlDataReader rdr;
byte[] fileContent = null;
string mimeType=" ";
string fileName=" ";
NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["portalconnectionstring"].ConnectionString);
using (portalconnectionstring ps = new portalconnectionstring())
{
var query = "select filename,content_type,filedata from tblfiles where fileid='"+fileid+"'";
var cmd = new NpgsqlCommand(query, conn);
cmd.Parameters.AddWithValue("#fileid", fileid);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
fileContent=(byte[]) rdr["filedata"];
mimeType = rdr["content_type"].ToString();
fileName = rdr["filename"].ToString()
}
}
conn.Close();
return File(fileContent, mimeType, fileName);
}

Related

asp.net mvc using string id on details view

Please help me to find error on my code
public ActionResult Details(string id)
{
String connectionString = ConfigurationManager.ConnectionStrings["SAPB1"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = " + id;
SqlCommand cmd = new SqlCommand(sql, conn);
BPModel BP = new BPModel();
using (conn)
{
conn.Open();
if (string.IsNullOrEmpty(id))
{
}
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
BP.CCODE = rdr["CCODE"].ToString();
BP.Name = rdr["Name"].ToString();
}
}
return View(BP);
}
You need to wrap your id values inside single quote ('). Try like below.
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = '" + id + "'";

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

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources