issue with FileUpload Control in ASP.NET & Stored Procedure - asp.net

Friends I need your help to fix an issue.
DETAIL
I have a Registration form based on update panel (works in slides) where one slide asks the user to upload his/her photo (optional).
ISSUE
Everything works fine, fine name is saved in Database, user folder creates in server side But the file is not uploaded ... no error.
CODES
#primePhoto -- FileUpload1
protected void RegisterClick6(object sender, EventArgs e)
{
string pathToCreate = "img/users/" + userName.Text;
if (Directory.Exists(Server.MapPath(pathToCreate)))
{
}
else
{
Directory.CreateDirectory(Server.MapPath(pathToCreate));
}
String imageFolder = pathToCreate;
String savePath;
String saveFile;
if (FileUpload1.HasFile)
{
savePath = Path.Combine(Request.PhysicalApplicationPath, imageFolder);
saveFile = Path.Combine(savePath, FileUpload1.FileName);
FileUpload1.SaveAs(saveFile);
}
SqlConnection con = new SqlConnection(str1);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "RegisterUser";
cmd.Parameters.AddWithValue("#userName", userName.Text);
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#postDate", currentDate.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
cmd.Parameters.AddWithValue("#FirstName", FirstName.Text);
cmd.Parameters.AddWithValue("#LastName", LastName.Text);
cmd.Parameters.AddWithValue("#primePhoto", FileUpload1.FileName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
multiview1.SetActiveView(view7);
}

Add trigger to update panel as like:
<Triggers>
<asp:PostBackTrigger ControlID="RegisterClick6" />
</Triggers>

Related

command failing in login code in C# on ASP.NET

I am making a website using ASP.NET framework.
My code for login page is as below, it is very simple since I'm trying to see step by step where it is going wrong. The C# code is:
protected void userLogin(object sender, EventArgs e)
{
string encoded_pass = encrypt_pass(Password.Text);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString);
connection.Open();
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password"))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
try
{
cmd.ExecuteNonQuery();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//da.Fill(dt);
////Session["User"] = dt.Rows[0]["user_email"];
//Session["User_name"] = dt.Rows[0]["user_f_name"];
//loginlabel.Text = "Welcome, " + Session["User_name"];
}
catch
{
loginlabel.Text = "login error";
}
}
connection.Close();
}
Now every time I enter an email and password it always gives "login errorr".. Why the command is not executed?
Looks like you have declared the connection but haven't assigned it to the SqlCommand
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password",connection))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
Note i added the connection variable in the cmd declaration.
In future you may also like catching your errors in development:
catch (Exception ex)
{
loginlabel.Text = "login error: "+ ex.Message;
}
This will help you know what is going wrong.

how to add confirmation in if statement

In my gridview I am inserting datas. If items repeated then it will show error message that "item repeated".But now I need to show "item repeated" message and another message that "you need to insert this data". If user press yes then that data need to be inserted.My current code only displays item repeated and cannot permit that data to enter. Here is my code
protected void AddNewCustomer(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string SlNo = (control.FindControl("txtSlNo") as TextBox).Text;
string Code = (control.FindControl("txtcode") as TextBox).Text;
string details = (control.FindControl("txtdetails") as TextBox).Text;
string Qty = (control.FindControl("txtqty") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=xxxxx;Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxxx"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from Qtattemp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
}
else
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Qtattemp] VALUES(#Code,#details,#Qty,#SlNo)";
cmd.Parameters.AddWithValue("#SlNo", SlNo);
cmd.Parameters.AddWithValue("#Code", Code);
cmd.Parameters.AddWithValue("#details", details);
cmd.Parameters.AddWithValue("#Qty", Qty);
con.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
BindData();
con.Close();
}
}
}
}
You need to handle it from code behind see the following link
http://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx

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

Move pdf file from SQL database to local ASP.net

I am trying to move the saved pdf file in my database to my local drive. I cannot find a way to do it. When I click on button1 , the dialog save or open shows up. I want to save the file directly on my local drive. Any help ?
please note that reader["FileData"] contains my file.
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text.TrimEnd();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From FileInformation where Id=3";// +id + " ";
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Response.Clear();
//Response.Buffer = true;
Response.ContentType = reader["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + reader["FileName"] + "\"");
Response.BinaryWrite((byte[])reader["FileData"]);
Response.Flush();
Response.End();
con.Close();
}
Any help on this ?

how can i change the text on button at run time after click on hyperlink

i have two text-boxes a button and a gridview.
Q.1 When user enter details in the text-boxes and press submit button i want to update grid-view accordingly
Q.2 When user hits "Edit" link which is present in the gridview, i would like to change the text of submit button to Update button.
how can i do that thanks in advance
what i have tried yet:
aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
string ID = Request.QueryString["ID"];
cmd = new SqlCommand("Select * from UserDetails where ID='" + ID + "'", con);
con.Open();
ad = new SqlDataAdapter(cmd);
dt.Clear();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
tbid.Text = ID;
TextBox1.Text = dt.Rows[0][1].ToString();
TextBox2.Text = dt.Rows[0][2].ToString();
}
con.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
string Name = TextBox1.Text;
string Place = TextBox2.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into UserDetails(Name,Place) values('" + Name + "','" + Place + "')";
cmd.Parameters.AddWithValue("#Name", TextBox1.Text);
cmd.Parameters.AddWithValue("#Place", TextBox2.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Record Successfully inserted";
}
con.Close();
btnSubmit.Text = "Update";
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
private void BindGrid()
{
con.Open();
ad = new SqlDataAdapter("Select * from UserDetails", con);
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Call a Refresh() doesn't help? I'm not sure about ASP.NET, but you have to do it in Forms.
After the user submits new data you can try to call your bindgrid method again, this way it will rebind after the new data is saved. For the edit piece, GridView has an edit template, you can try using that:
http://msdn.microsoft.com/en-us/library/ms972948.aspx

Resources