ASP.NET Web Page Not Available - asp.net

It's pretty difficult to show code for ASP.NET here, so I will try my best to describe my problem.
I have a FileUploadControl and a Button that calls a function when it's clicked. It seems that the Button function works when there is nothing chosen for my FileUploadControl. However, when there is something chosen in the FileUploadControl (I have selected a file to upload), there is a problem when I click the button. It completely does not matter what the function does (it could just be writing to a label, even when it has nothing to do with the FileUploadControl). The error I get is:
This webpage is not available.
The webpage at http://localhost:2134/UploadMedia/Default.aspx might be temporarily down or it may have moved permanently to a new web address.
I have searched on Google, and people seem to have had problems with this, but different causes from me. They have said that their ASP.NET Development Server port is actually different from their port in the address bar. This is not the case for me.
Also, another problem people have had is with Use Dynamic Ports. I have tried both true and false. I have also tried different ports, and I have always gotten the same error.
This is really driving me crazy because it doesn't matter what the code in the buttonFunction is, it doesn't work as long as there is something in the FileUploadControl. If there is nothing, it seems to work fine.
Here is the code for the ASP.NET Controls:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" OnClick="uploadClicked" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
And this is the code for the button function:
protected void uploadClicked(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//Check if the entered username already exists in the database.
String sqlDupStmt = "Select songPath from Songs where songPath ='" + Server.MapPath("~/Uploads/") + filename + "'";
SqlConnection sqlDupConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True;");
SqlCommand sqlDupCmd = new SqlCommand(sqlDupStmt, sqlDupConn);
sqlDupCmd.Connection.Open();
SqlDataReader sqlDupReader = sqlDupCmd.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlDupReader.Read())
{
StatusLabel.Text = "Upload status: The file already exists.";
sqlDupReader.Close();
}
else
{
sqlDupReader.Close();
//See "How To Use DPAPI (Machine Store) from ASP.NET" for information about securely storing connection strings.
String sqlStmt = "Insert into Songs values (#songpath);";
SqlConnection sqlConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True; uid=sa; pwd=password;");
SqlCommand cmd = new SqlCommand(sqlStmt, sqlConn);
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
sqlParam = cmd.Parameters.Add("#userName", SqlDbType.VarChar, 150);
sqlParam.Value = Server.MapPath("~/Uploads/") + filename;
//Attempt to add the song to the database.
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
songList.Items.Add(filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
finally
{
sqlConn.Close();
}
}
}
}
But this buttonfunction provides the same results:
protected void uploadClicked(object sender, EventArgs e)
{
StatusLabel.Text = "FooBar";
}
Has anyone had this problem before, or might know what the cause is?
Thanks!

My friend helped me figure it out. It was because ASP.NET only allowed uploads of 4MB sizes. I had to go into the web.config or the machine.config file and change the value of MaxRequestLength to be larger than 4096. This solved it.

Related

Display the image using Eval function in asp.net

I would like to display the image which i have stored as byte in Sql Table.
ItemTemplate code
ImageUrl=<%# Eval("Image")%>
Image is the byte from sql server. In my application couldn't able to show the picture from server.
SQL Schema : [Image] [image] NULL
Please suggest, how to display the image.
As if you have tried, you might have got some useful links. However here you go.
STEPS:-
1.To retreive Images from database, first you change your datatype from Image to nvarchar(550)
2.You need to write code fetching images on the basis of ID
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ImageID"] != null)
{
string strQuery = "select ImageName, ImagePath, ImageData from youtableName where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
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]["ImageName"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
GetData will be your datatable value which will be coming from the database.
To Display the image on the aspx page I have used ASP.Net Image Control refer below.
<asp:image id="Image1" runat="server" imageurl="ImageCSharp.aspx?ImageID=1" />
<asp:image id="Image2" runat="server" imageurl="ImageCSharp.aspx?ImageID=2" />
<asp:image id="Image3" runat="server" imageurl="ImageCSharp.aspx?ImageID=3" />
Here is your complete reference:-
Display Images from the database using asp.net

How to prevent a user from resubmitting a form?

I am developping a Single Page Application.
At the end of the application, the user gets to submit his contact information (name, phone number, etc). This sends an Email and modifies the page to a "Thanks for submitting [...]" page.
The problem is, the client can press the Back button and REsend the Email.
Is there a way to prevent this sort of.. spam?
Code
Sub BT_Send(sender As Object, e As EventArgs) Handles BT_Send.Click
Try
'Creating the Email Message
Dim mailMessage As New MailMessage()
mailMessage.To.Add("SomeOne#a.com")
mailMessage.From = New MailAddress("Robot#a.com", "Robot")
mailMessage.Subject = "Test"
mailMessage.IsBodyHtml = True
mailMessage.Body = LBL_Emailbody.Text & _
"<br><br><br><div style=""font-size: 0.7em;"">Robot speaking, I will not answer if you send me a message.</div>"
Dim smtpClient As New SmtpClient("Something.com")
smtpClient.Send(mailMessage)
PNL_Before.Visible = False
PNL_After.Visible = True
Catch ex As Exception
LBL_errorEmail.Visible = True
'Should never happen...
End Try
End sub
Here is a very simple example, where I use a static variable on page and avoid database.
the asp.net page is
<asp:Literal runat="server" ID="txtInfos"></asp:Literal><br />
<asp:TextBox runat="server" ID="txtEmail"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />/>
and the code behind.
static Dictionary<string, DateTime> cLastSubmits = new Dictionary<string, DateTime>();
private static readonly object syncLock = new object();
protected void Button1_Click(object sender, EventArgs e)
{
DateTime cWhenLast;
lock (syncLock)
{
var cNowIs = DateTime.UtcNow;
if (cLastSubmits.TryGetValue(txtEmail.Text, out cWhenLast))
{
if (cWhenLast > cNowIs )
{
txtInfos.Text = "Please contact us again after 10 seconds";
return;
}
else
{
// ok I let him submit the form, but note the last date time.
cLastSubmits.Remove(txtEmail.Text);
}
}
foreach(var DelMe in cLastSubmits.Where(x => cNowIs > x.Value).ToList())
cLastSubmits.Remove(DelMe.Key);
// if reach here, note the last datetime of submit
cLastSubmits.Add(txtEmail.Text, cNowIs.AddSeconds(10));
}
// and submit the form.
txtInfos.Text = "thank you for submit the form";
}
Some notes.
If you have many pools (web garden), then this may left user to
submit at the same time up to the pool you have.
Of course if a user submit fake data this can not protect you, and thats why we can use:
The honey pot trick.
captcha
Other control thats understands the bots
Code that understand the re-submit.

Update database in asp.net not working

i have in asp.net a few textboxes and i wish to update my database with the values that they encapsulate .
The problem is that it doesn't work and although it doesn't work, the syntax seems correct and there are no errors present . Here is my linkbutton :
<asp:linkbutton id="clickOnSave" runat="server"
onclick="Save_Click" Text="Save Profile" />
and my update function
protected void Save_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "DataSource=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\alex\\Documents\\seeubook_db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
String commandString = "UPDATE users SET last_name='" + Text4.Text.Trim() + "' , first_name='" + Textbox1.Text.Trim() + "' , about_me='" + Textbox5.Text.Trim() + "' , where_i_live='" + Textbox2.Text.Trim() + "' , where_i_was_born='" + Textbox3.Text.Trim() + "' , work_place='" + Textbox4.Text.Trim() + "' WHERE email='" + Session["user"] + "'";
SqlCommand sqlCmd = new SqlCommand(commandString, con);
sqlCmd.ExecuteNonQuery();
con.Close();
}
I'm always a bit weary about the User Instance=true in a connection string..... at times, it tends to create a new MDF file "on the fly" and when you update that MDF, then your changes might be just "gone" one your app has completed running.... See MSDN docs on User Instances.
I would suggest that you:
attach your MDF file to SQL Server Express on your machine, using SQL Server Express Management Studio
then use a server-based approach to your SQL Server Express database rather than attaching a file...
In that case, your database connection string would then look something like:
server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;
And while you're at it, I would also recommend to:
wrap your SqlConnection and SqlCommand into using blocks to ensure proper disposal
open your connection as late as possible
use a parametrized query instead of concatenating together your SQL command - doing so is a wide open door for SQL injection attacks!
So your code would look something like this:
string connStr = "server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;";
string cmdStmt = "UPDATE dbo.Users SET last_name = #lastName, " +
"first_name = #firstName, about_me = #aboutMe, where_i_live = #whereILive, " +
"where_i_was_born = #whereIWasBorn, work_place = #workPlace " +
"WHERE email = #userEMail";
using(SqlConnection sqlCon = new SqlConnection(connStr))
using(SqlCommand sqlCmd = new SqlCommand(cmdStmt, sqlCon))
{
// define parameters
sqlCmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50);
sqlCmd.Parameters["#lastName"].Value = Text4.Text.Trim();
// and so on for all the parameters
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
Debug! Look your LinkButton Click Event really go into Save_Click function. And then check 'sqlCmd.ExecuteNonQuery();' return result.
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}

Use of SqlCommandBuilder in ASP.NET

I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?
Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.
Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.

ASP.NET store Image in SQL and retrieve for Asp:Image

I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :
// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImageID", conn))
{
command.Parameters.Add("#ImageID", SqlDbType.Int).Value = imageId;
conn.Open();
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:
<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />
That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.
If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.
After a few hundred gigabytes of images, I believe you'll find yourself thinking that the operating systems' file system and static file http servers is better suited than the database, which is busy which a lot of other details, for storing images. It also allows you to use thousands of existing free tools to work with, move, host, etc the images.
Instead of storing images in the database, store the path and/or filename for the image. Images will fill up the database and make it slow.
protected void Page_Load(object sender, EventArgs e) {
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e) {
string strImageName = txtImageName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "File Uploaded";
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
con.Close();
}
}
Try these links it might help you..
you can also try by storing the image files on the server and store the paths on the Sql table..
by these links
http://pratikataspdotnet.blogspot.in/2014/11/retrieve-images-from-path-stored-in.html

Resources