How to save Video file in DB? - asp.net

I have a task to insert Video in DB and display it by Html5 video control. I did my code well and the video saved well in DB but when I tried to play the video it doesn't and when I checked my code I found that the video saved in DB with this path ~/res/Files/. When I
removed the ~/ as the path will be res/Files/ it worked well. How can I solve this issue?
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
btier.AddObject("~/res/Files/" + FUFile.FileName);
FUFile.SaveAs(Server.MapPath("~/res/Files/" + FUFile.FileName));
}

The reason being, you are passing the path as a string parameter to your method AddObject and to MapPath. Hence the path will remain "~/res/..." instead of resolving to the application root.
You have to first resolve the root and then save that path. One safe option is to use VirtualPathUtility. Something like this:
tempVar = VirtualPathUtility.ToAbsolute("~/res/Files/" + FUFile.FileName);
btier.AddObject(tempVar);
FUFile.SaveAs(Server.MapPath(tempVar));
Where tempVar is a string variable.

protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
cmd.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
cmd.Parameters.AddWithValue("#ContentType", "video/mp4");
cmd.Parameters.AddWithValue("#Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Complete step by step tutorial:
http://www.aspsnippets.com/Articles/Upload-Save-Retrieve-and-Play-MP4-Video-files-with-live-streaming-from-Database-in-ASPNet-using-C-and-VBNet.aspx

Related

MS Access database able to be accessed in debug mode but not accessible when published

I've written some basic code in ASP.NET that accesses a Microsoft Access database, which works when I run in debug mode on IIS Express, but when I published the application and tried to run on the actual website, I get the error.
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2430497
NIM_Tool.Default.Page_Load(Object sender, EventArgs e) +2321
System.Web.UI.Control.OnLoad(EventArgs e) +106
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3785
From modifying some of my code, I'm pretty confident that the database is unable to be found, but I can't figure out why it's able to be accessed in debug/release mode but not from the published mode. After clicking publish, all files went to the bin/Release/Publish/ folder from the root directory, which I then copied all the children of the Publish folder to the correct server path. The children files/folder also contained the correct MS Access database.
code from the DataLayer.cs file
public class DataLayer {
static OleDbConnection conn;
static OleDbCommand cmd;
static String connString;
static OleDbDataAdapter adp;
private static void CreateCommand()
{
// have also tried hardcoding this to the production server path but this failed too
connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath("MyDatabase.mdb") + ";Persist Security Info=False;"
conn = new OleDbConnection(connString);
cmd = new OleDbCommand();
cmd.Connection = conn;
adp = new OleDbDataAdapter();
}
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
}
return dt;
}
}
And The Default.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtDeposit = DataLayer.GetDefaultDeposit();
string fixedCost = (string)dtDeposit.Rows[0]["FixedCost"];
}
}
The MyDatabase.mdb file is located in the same directory as the DataLayer.cs file. I've tried hardcoding the database path as well to where it should be accessed on the server, but got the same error message as well.
A little advice: you are being your own enemy when you catch an error and don't do anything with it. It is called "swallowing an error" and it hides root-causes.
Instead, I would recommend doing a re-throw. Put your (original) Exception as the .InnerException. You might want to have your connString in the .Description for the (outer) Exception. (Just in case MapPath didn't do what you thought it should, etc.)
Like this:
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
throw new Exception("ConnString=" + connString, ex);
}
return dt;
}

Using many sql connection in one code?

I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
you can use like this.
You're using the same connection string for each connection? Why do you need three connections? Why not just open and close the same one?
As long as the connection string is the same, you only need one connection.
In general you should prefer to create and open a connection object as close to where you make use of it as possible, and dispose of it as soon as possible afterwards (preferably by making use of a using statement). Connection pooling will take care of ensuring you only actually create a limited number of real connections to the server, despite the large number of SqlConnection objects your code may seem to create.
Within a single method, however, it is reasonable to use a single connection object:
public partial class Home : System.Web.UI.Page
{
string connString = ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection co = new SqlConnection(connString))
{
co.Open();
using(SqlCommand cm = co.CreateCommand())
{
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
using(SqlCommand cmv = co.CreateCommand())
{
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
using(SqlCommand cmf = co.CreateCommand())
{
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
}
}
}
(You don't need to explicitly close the connection object, the Dispose (within the using is equivalent)
No use declaring/creating multiple connections when you would be using only one at a time. You can do with just one.
Declare variable as close as possible to its first use, and with minimum scope manageable.
Make things modular and reusable as far as possible.
No need to explicitly close the connection, since the IDisposable interface implementation (and using block) does it anyways. But there is no harm in explicitly closing it.
protected void Button1_Click(object sender, EventArgs e)
{
ExecuteNonQuery("select...", null); // why??
ExecuteNonQuery("insert...", null);
ExecuteNonQuery("delete from...", null);
}
protected void ExecuteNonQuery(string query, SqlParameter[] parameters)
{
using (SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString))
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = query;
if (parameters != null) cm.Parameters.AddRange(parameters);
cm.ExecuteNonQuery();
}
}
You can also try this.
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}

update query is not working in ASP.NET web application

using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=GAGAN-PC\SQLEXPRESS;Initial Catalog=update_test;Integrated Security=True");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void delete_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("delete from update_delete where id like'"+TextBox1.Text+"'",con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully deleted.");
}
protected void update_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update update_delete set password ='"+TextBox3.Text+"' where id like'"+TextBox2+"'", con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully Updated.");
}
}
I am trying to implement update query but there is a little problem in it. I have used SQL Server as database and update_delete is a table in which there are 3 columns id,sname,password and I am trying to update password with respect to id.
Problem is when I click on update button control reaches cmd.ExecuteNonQuery(); no error is displayed. but updating is not taking place. what should I do. Please Please Please help me. Thanks in advance. :) :)
I'm just guessing here - if Id is a numeric datatype, then you cannot use LIKE with it.
Also: please use using()... blocks to ensure proper disposal and use parametrized queries to avoid SQL Injection attacks.
Write your UPDATE command like this:
protected void update_button_Click(object sender, EventArgs e)
{
// get the values to use
string idValue = Convert.ToInt32(TextBox3.Text.Trim());
string password = TextBox2.Text.Trim();
// define the query text with *parameters* !
string updateQuery = "update update_delete set password = #password where id = #ID";
// put things like SqlConnection and SqlCommand into "using()...." blocks
using (SqlCommand updCmd = new SqlCommand(updateQuery, con))
{
// define parameters and their values
updCmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = password;
updCmd.Parameters.Add("#ID", SqlDbType.Int).Value = idValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Data successfully Updated.");
}
}
I suppose you get an Exception. I would kindly suggest to catch your exception and tell us the message... You can catch the exception using the debugger or a try-catch clause.
If you don't get an exception and "Control reached" message is displayed, you would have to use the formed SQL string to use it directly in SQL Server and see if there is a mistake in the SQL statement. I suppose that you somehow form an invalid SQL statement (eg using a non-existing ID).
Hope I helped!

Database does not exist

Here is my code to back up a database.
These are my databases:
I got this as Error:
Database 'BakupDB' does not exist. Make sure that the name is entered
correctly. BACKUP DATABASE is terminating abnormally.
And the code for my web page:
public partial class Default2 : System.Web.UI.Page
{
string dbname = "BakupDB";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
//Mentioned Connection string make sure that user id and password sufficient previlages
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
//Enter destination directory where backup file stored
string destdir = "D:\\backupdb";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database "+dbname+" to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Response.Write("Backup database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
}
}
What do I wrong?
It looks like you're trying to use a User Instance. As an aside (not 100% related to your question) I believe that this feature is deprecated in SQL Server Express 2012 (and have been on a deprecation path since SQL Server 2008).
Sorry for the aside. With regards to your question perhaps the following will help you:
Stack Overflow question
Accomplishing the task using SMO
I would say the Stack Overflow question is closer to the use case you're trying to achieve with executing the SQL command, but have referenced the SMO way in case you were interested or wanted to try a different approach. Based on the SO question it appears that your connection string:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
Is missing a Database= section so perhaps it should read like:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True;Database=BakupDB";
This code worked for me:
private void button5_Click(object sender, EventArgs e)
{
try
{
string dlink= #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\jsdb.mdf; Database=jsdb; User Instance=True; Integrated Security=True;Asynchronous Processing= True";
SqlConnection dcc = new SqlConnection(dlink);
dcc.Open();
string database = "jsdb";
string blc = textBox1.Text; //(Its the location to save the file)
string nm = "dbBackup";
string dt =DateTime.Today.ToShortDateString();
string sl = "BACKUP DATABASE "+database+" TO DISK = '"+blc+"\\"+nm+"-"+dt+".bak'" ;
SqlCommand cql = new SqlCommand(sl,dcc);
cql.ExecuteNonQuery();
MessageBox.Show("Database backup completed successfully..");
dcc.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}

Execute Query from another function

I want to execute a query on a button click event.
But that query is written in another function.
Here is my code, and it's not working. What is my problem?
namespace MCE_Member_Registration
{
public partial class registration_form_view : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
createform();
}
protected void createform() {
NameValueCollection nvc = Request.Form;
surname.Text = nvc["txt_surname"];
cmd.CommandText = "Insert into mce_applicants_information values(N'" + nvc["txt_surname"] + "')";
}
protected void confirm_Click(object sender, EventArgs e)
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
I'm not sure if this solves your problem. But if you really need another method to create your command, let it return it.
protected SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand("Insert into blahblah values(blahblah)", connection);
return cmd;
}
protected void Button1_Click() {
connection.Open();
GetCommand().ExecuteNonQuery();
connection.Close();
}
Note that this is not best-practise due to several reasons. The connection should be closed even if an exception occured so use using statement instead. But that would be a problem in this approach since the connection is a field.
So i would prefer the all-in-one method approach which also uses parameters tro prevent sql-injection attacks:
protected void Button1_Click()
{
ExecuteBlahBlahCommand("blahblah");
}
private void ExecuteBlahBlahCommand(string blaColumnVal)
{
const string sql = "Insert into blahblah values(#blaColumn)";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#blaColumn", blaColumnVal);
con.Open();
cmd.ExecuteNonQuery();
}
}
I suggest you to use CommandText property and not contructor, because instance of cmd is created before this code, so you adjust your property
protected void CreateQuery() {
cmd.CommandText = "Insert into blahblah values(blahblah)";
}
protected void Button1_Click() {
connection.Open();
CreateQuery();
cmd.ExecuteNonQuery();
connection.Close();
}
Answering the question itself - Any variable you declare inside a function cannot be seen outside that function. You need to declare the SqlCommand in the correct scope...
For instance:
SqlCommand cmd;
protected void CreateQuery()
{
cmd = new SqlCommand("Insert into blahblah values(blahblah),connection)";
}
protected void Button1_Click()
{
CreateQuery();
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
This will declare the variable in the class level, and be accessible to all other methods in that class.
I'll just mention that #Tim Schmelter's answer is a good solution that might better suit your needs.

Resources