Excel File Upload Working Locally But Not On Azure - asp.net

Using ASP.net MVC on Azure. As subject states, it's working fine locally but not on Azure. The form renders properly. Upon submitting the form, I get my page header and a message stating "An error occurred while processing your request." I've checked the database and all the fields were carried over properly. I'm not sure what else to use to troubleshoot.
namespace WebApplication12.Controllers
{
[Authorize]
public class DashboardController : Controller
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
OleDbConnection Econ;
// GET: Dashboard
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string filename = Guid.NewGuid() + Path.GetDirectoryName(file.FileName);
string filepath = "/excel/" + filename;
file.SaveAs(Path.Combine(Server.MapPath("/excel/"), filename));
InsertExcelData(filepath, filename);
ViewBag.Message = "File successfully uploaded.";
return View();
}
private void ExcelConn(string filepath)
{
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", filepath);
Econ = new OleDbConnection(constr);
}
private void InsertExcelData(string filepath, string filename)
{
string fullpath = Server.MapPath("/excel/") + filename;
ExcelConn(fullpath);
string query = string.Format("Select * from [{0}]", "Sheet1$");
OleDbCommand Ecom = new OleDbCommand(query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable dt = ds.Tables[0];
dt.Columns.Add(new DataColumn("Email", typeof(System.String)));
dt.Columns.Add(new DataColumn("TimeStamp", typeof(System.DateTime)));
foreach (DataRow dr in dt.Rows)
{
dr["Email"] = User.Identity.GetUserId();
dr["TimeStamp"] = DateTime.Now.ToString();
}
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "Upload";
objbulk.ColumnMappings.Add("Email", "Email");
objbulk.ColumnMappings.Add("TimeStamp", "TimeStamp");
objbulk.ColumnMappings.Add("EmployeeId", "EmployeeId");
objbulk.ColumnMappings.Add("Name", "Name");
objbulk.ColumnMappings.Add("Title", "Title");
objbulk.ColumnMappings.Add("Department", "Department");
objbulk.ColumnMappings.Add("Race", "Race");
objbulk.ColumnMappings.Add("Gender", "Gender");
objbulk.ColumnMappings.Add("AnnualizedBase", "AnnualizedBase");
objbulk.ColumnMappings.Add("AnnualizedTCC", "AnnualizedTCC");
con.Open();
objbulk.WriteToServer(dt);
con.Close();
}
}
}
Thanks!

In a cloud environment you typically don't write to the web server file system. Rather, you save the upload off to blob storage and keep a record of the path where you saved it along with the persisted data record.
Here is an article where the author uses the Storage APIs to send an uploaded image off to a blob. But this is a rather standard challenge to solve with blob storage, so the Microsoft documentation will likely provide enough information for you to make progress. Here is an official Microsoft sample MVC controller that combines MVC and blob storage.

Related

Sqllite SQLiteDataReader returns enpty reader while SQLiteDataAdapter returns the right result

I have trouble with Sqllite SQLiteDataReader. Using the same connection string and the same sql statement SQLiteDataReader returns empty reader while SQLiteDataAdapter returns suspected record.
I this case I try to get the record with the highest value in the Id field.
The database contains several records with unique values in the Id field, but the reader return is empty when using SQLiteDataReader. When I use the same connection string and sql statement with SQLiteDataAdapter suspected results appears. I supply a part of the static class I use for communication with the database. The method SenasteBokning using SQLiteDataReader isn’t working. The method SenasteBokning2 using SQLiteDataAdapter works perfect.
What’s wrong with the method SenasteBokning?
I use:
Windows 10
Visual Studio 2017
.net framework 4.5.2 (Was default at creation of Windows Forms application)
Nuget package System.Data.SQLite.Core 1.0.108
static class Databas
{
private static string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string dbPath = #"\BokningarConvention.db";
private static string connectionString = "Data Source= " + appPath + dbPath;
private static SQLiteConnection con;
private static SQLiteCommand cmd;
private static SQLiteDataReader reader;
private static SQLiteDataAdapter adapter;
private static SQLiteCommandBuilder commandBuilder;
private static DataTable table;
private static string senaste = "SELECT Nummer, NrSammaDag, Datum FROM Bekraftelser WHERE Id = (SELECT MAX (Id) FROM Bekraftelser)";
// This don't work
public static Bokning SenasteBokning()
{
Bokning bokning = new Bokning();
using (SQLiteConnection con2 = new SQLiteConnection(connectionString))
{
con2.Open();
SQLiteCommand cmd2 = new SQLiteCommand(senaste, con2);
SQLiteDataReader reader2 = cmd2.ExecuteReader();
// Here the reader is empty
while (reader2.Read())
{
// Error at first read
// should handle results the same way as in SenasteBokning2
// removed during testing
}
}
return bokning;
}
//This works perfekt
public static Bokning SenasteBokning2()
{
Bokning bokning = new Bokning();
using (SQLiteConnection db = new SQLiteConnection(connectionString))
{
adapter = new SQLiteDataAdapter(senaste, connectionString);
commandBuilder = new SQLiteCommandBuilder(adapter);
table = new DataTable();
db.Open();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
int nummer;
int samma;
DateTime datum;
nummer = (int)((long)row["Nummer"]);
datum = Verktyg.FromDateInteger((int)((long)row["Datum"]));
if (!row.IsNull("NrSammaDag"))
{
samma = (int)((long)row["NrSammaDag"]);
bokning = new Bokning(nummer, samma, datum);
}
else
{
bokning = new Bokning(nummer, datum);
}
}
}
return bokning;
}
}

Retrieving the image from database and displaying in web page in Asp.Net

I am trying to store the profile picture which the user uploads in a database and retrieve from the database and display in web page.I have successfully saved the image in database but I don't know how to retrieve it.I have tried to display but when I click the retrieve button nothing happens.
This is the code in Handler page and instead of retrieving the image based on Id I am trying to do it by passing the name of the user which will be on the welcome page.
public void ProcessRequest(HttpContext context)
{
//passing name here
if (context.Request.QueryString["name"] != null)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
//passing name
SqlParameter p1 = new SqlParameter("#userName", context.Request.QueryString["name"]);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["image"]);
dr.Close();
con.Close();
}
}
else
{
context.Response.Write("No Image Found");
}
}
public bool IsReusable
{
get
{
return false;
}
}
I have created a stored procedure which accepts username and gives image.Stored procedure name is "RetrieveImage"
This is the button click event.On clicking the button "RetrieveImage" it calls handler and passes value as "name"which then calls stored procedure and displays image
protected void RetrieveImage_Click(object sender, EventArgs e)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("#userName", WelcomeUsername.Text);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
ImageDisp.ImageUrl = "~/ImagePage.ashx?name=" + WelcomeUsername.Text;
con.Close();
}
}
When I run the page I am not getting any error but when I click the button nothing happens.I am new to .Net .Please help.!! Thanks in advance

Reading the Excel sheeet from Asp.net?

Getting error while reading the excel sheet from the local drive. I am using asp.net to read the excel sheet. My error:
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.
protected void btnup_Click(object sender, EventArgs e)
{
string Extension = Path.GetExtension("Book1.xlsx");
string FolderPath = #"D:/Book1.xlsx";
Import_To_Grid(FolderPath, Extension);
}
private void Import_To_Grid(string FilePath, string Extension )
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"] .ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"] .ConnectionString;
break;
}
using (OleDbConnection conn = new OleDbConnection(conStr))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string firstSheetName = sheetsName.Rows[0][2].ToString();
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
OleDbDataAdapter ada = new OleDbDataAdapter(sql, conStr);
DataSet set = new DataSet();
ada.Fill(set);
}
}
I am getting error at conn.Open().
This error may happen because you are opening that excel file by using MS Office or another process is opening your excel file.
i got the solution for my question. Actually i did some thing wrong in connection string in connection string at source i not given the path, that is the reason it is throwing error.

trouble using httphandler to retrieve image url

I am trying to write a httphandler to retrieve image url and later display it on a image control i am using this code but its not working
OleDbConnection mDB = new OleDbConnection(
ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
mDB.Open();
OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
context.Response.BinaryWrite((byte[])rdr[0]);
mDB.Close();
context.Response.End(); */
sorry that i caused a confusion earlier in the SELECT statement the pProductId does not contain the URL of the image instead pProductImage is the field that contain the URL. i am using the Id to identify which image to display accordingly.
this is my expected output:
<img src="ImgHandler.ashx?pProductId=2" alt="" />
i cant place image this is the link to my error msg:http://imgur.com/Cix67
This is a two steps answer.
In the page, you can do something like this:
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
using (OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.Write("<img src=\"ImgHandler.ashx?pProductId=");
context.Response.Write((int)rdr[0]); // I suppose pProductId is an int, adapt accordingly
context.Response.Write("\" />");
}
}
}
and in the HTTP handler implicitly triggered, something like this:
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
// select the file data (I put pData here as a placeholder, and assume it will be a byte[])
using (OleDbCommand cmd = new OleDbCommand("select pData from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.ContentType = "image/png";// put the content type here
context.Response.BinaryWrite((byte[])rdr[0]);
}
}
}
}
}
Note the using pattern which ensures proper resources cleanup once used. Also, ideally you could cache the data on the client using proper cache HTTP headers (like if-modified-since) but this is another story ...

Asp.Net: Returning a DataSet from a Class

I've decided to start another thread based on the responses I got in this thread:
Asp.Net: Returning a Reader from a Class
I was returning a reader, but members have suggested I'd be better off returning a Dataset instead and also try to seperate the data access tier from the presentation tier.
This is what I have so far:
//my class methods
public DataSet GetSuppliers()
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", HttpContext.Current.Request.QueryString["p"]);
return FillDataSet(cmd, "SuppliersList");
}
//my FillDataSet method
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
// on my ascx page I call the method like so:
protected void Page_Load(object sender, EventArgs e)
{
//instantiate our class
MyClass DB = new MyClass();
// grab the table of data
DataTable dt = DB.GetSuppliers().Tables["SuppliersList"];
//loop through the results
foreach (DataRow row in dt.Rows)
{
this.supplierslist.InnerHtml += Server.HtmlEncode(row["Address"].ToString()) + "<br/>";
this.supplierslist.InnerHtml += "<b>Tel: </b>" + Server.HtmlEncode(row["Telephone"].ToString()) + "<p/>";
}
}
}
Would anyone like to suggest improvements?
Is my loop 'data tier' or 'presentation tier', should the loop be inside the class and I just return a formatted string instaed of a dataset?
Thanks for all the great advice
I also would use a Typed DataSet or create your own class that holds the properties so you are not dealing with strings like row["Address"] you would say object.Address and get compile time checking.
DataSets have a lot of built in functionality that is nice but also caries with it a lot of overhead that might not be needed in something simple. Creating a simple class with properties and passing that out of your data access layer is probably the simplest way to implement what you want.
Something like this on the DAL (Data Access Layer) side:
//Also pass in the blogID dont have the DAL get the value from the UI layer..
//make the UI layer pass it in.
public IList<Supplier> GetSuppliers(string connectionString, int blogID)
{
IList<Supplier> suppliers = new List<Supplier>();
//wrap with the using statements
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", blogID);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
suppliers.Add(new Supplier
{
Address = reader.GetString(0),
Telephone = reader.GetString(1)
});
}
}
}
return suppliers;
}
}
public class Supplier
{
//I would have Address an object....but you have as string
//public Address Address { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}
//Example if you went with Address class...
public class Address
{
//Whatever you want in the address
public string StreetName { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public string City { get; set; }
}
One thing you should get in the habit of doing is calling Dispose() on your SqlConnection. The best pattern to do this is to use the using statement, which will automatically dispose of it for you. It looks like this:
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
}
What you have in the foreach loop in Page_Load, is presentation logic (layout), and IMO this should not be in the code-behind of your page, but in the markup.
I'd suggest that instead of using a foreach loop to construct the HTML output, you should use a databound control (such as a asp:Repeater, DataList or GridView). Then you can bind the repeater to your dataset or datatable and have all the markup where it belongs (in the ASCX file). See this page for an example.
As a general note: you can find lots of tutorials on www.asp.net, e.g. about data access: http://www.asp.net/%28S%28pdfrohu0ajmwt445fanvj2r3%29%29/learn/data-access/

Resources