URL error for some files,The requested document was not found on this server - asp.net

Hi every one i have a funny problem. i want to read an URL from a database ,but it give me this error for some videos! not all of them!(the error is The requested document was not found on this server. )In local network it work fine and all the movies are playing!, but when i upload the site in internet, the error occurs.
any idea?
and here is the fine URL:
http://babakpirmoradi.ir/User/videos/Ostadpirmoradi2.flv
here is the url that gives error:
http://babakpirmoradi.ir/User/videos/418619301525735_21489.mp4
here is my code:
(GetUrl() pass the URL dynamically)
<div style="width: 650px">
<video id="example_video_1" align="center" class="video-js" controls="controls"
height="442" preload="auto" width="590">
<source src=<%=GetURL()%> type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'/>
</video></div>
here is my url cod:
public string GetURL()
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(connStr);
SqlCommand sqlcmd = new SqlCommand();
sqlconn.Open();
sqlcmd = new SqlCommand("SELECT Video FROM AddVideo where ID=#ID", sqlconn);
sqlcmd.Parameters.AddWithValue("#ID", Request.QueryString["ID"]);
string URL = ((string)sqlcmd.ExecuteScalar()).ToString();
return URL;
}

This is happening because the video actually does not exists or we have no rights to access it:

Related

'SqlConnection' is not declared error for aspx net

I am fairly new to this Aspx.Net. I am trying to connect to a remote SQL Server and below is the connection string I am trying on IIS server.
SQL Server version is 2012
MySqlConnection connection = new MySqlConnection("Database=DB;Server=server.name;Uid=user.name;Pwd=pass");
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "select * from dbo.TableName";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
Below is the error:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30451: Name 'SqlConnection' is not declared.
Appreciate any help, please keep in mind this is my first tries out on aspx. Yes, I tried searching online but can't seem to find a resolution.
Well, if you want to use SQL Server in C#, try follow below technique:
SqlConnection sqlConn = new SqlConnection("Server=server.name;Database=DB;User Id=userid;Password=yourpass;");
SqlCommand cmd = new SqlCommand("select * from dbo.TableName", sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
sqlConn.Close();

ASP.NET Login control not redirecting

My login control isn't working as intended anymore. It pulls the username and password from a database and then redirects the user to Home.aspx. Redirecting sadly doesn't happen. It does add this to the end of the url, but nothing happens
ReturnUrl=%2fHome.aspx
This is the shortend ASP code
<asp:Login ID="Login1" runat="server" OnAuthenticate= "ValidateUser"
DestinationPageUrl="~/Home.aspx"> </asp:Login>
Plus .cs code
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_CONNE"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Wachtwoord", Login1.Password);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Session["Uname"] = Login1.UserName;
if (dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx");
}
I have been working on functionality in which not logged in users cant acces certain pages, but I'm not sure if that's the thing that's screwing it up..
After fiddling a little I noticed deny users seems to have an effect on it, but don't know any other way to be redirecting non-login attempts.
Any help would be greatly appreciated!
Looking at your code, in sql command your query have password parameter defined as #Password while adding it to the cmd parameters collection you have #Wachtwoord instead of the #Password.
Here is the updated code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Password", Login1.Password);
Also, instead of always redirecting to Home.aspx you can get the return url using FormsAuthentication.GetRedirectUrl. So if you try to access some page Protected.aspx without logging in the user will be redirected to Login.aspx?ReturnUrl=protected.aspx and after login user will be redirected to Protected.aspx page.
if (dt.Rows.Count > 0)
{
Response.Redirect(FormsAuthentication.GetRedirectUrl( Login1.UserName, false));
}

Add values from DB (Select Query) in a text. Asp.net

On my Homepage i made i Visual Studio i want to have some welcome text on my firstpage.
The Thing is that i want in the middle of the text present some values that i grab from my db with a select query.
Lets say for example:
Welcome to my Homepage!
Currently there are (Select Count(UserID) FROM users where Status = 'active') Users active on my page and (Select Count(UserID) FROM users where Status = 'inactive') that are inactive.
Im really new to this but somehow i Need to run the my questions on Page_load and then be able to take that value and present it in a Label or something?
Thanks for your help
Using ADO.NET:
1: Create a connection object, set it's connection string property
2: Create a command object and set its text property to
Select Count(UserID) FROM users where Status = 'active'
3: Use ExecuteScalar method of the command object to find the result you want and set the label text property equal to that result.
Procedure
create procedure select
#activity
as
Begin
Select Count(UserID) FROM users where Status = #activity
end
C# Page Load
string activity1="active";
string activity2="Inactive";
sqlconnection con=new sqlconnection("give your connection string");
sqlcommand cmd=new sqlcommand();
cmd=new sqlcommand("select",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#activity",activity1);
String result1=cmd.ExecuteNonQuery();
sqlcommand cmd1=new sqlcommand();
cmd1=new sqlcommand("select",con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#activity",activity2);
String result2=cmd.ExecuteNonQuery();
Label1.Text=result1;
Label2.Text=result2;
.aspx page
Welcome to my HomePage
Currently there are <asp:label id="Label1" runat="server"></asp:Label> Users active on my page and <asp:label id="Label2" runat="server"></asp:Label> that are inactive.
If you find this as useful and it solved your issue mark it as answer and give upvote.
Try this
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(#"MY CONNECTION");
SqlCommand com = new SqlCommand("Select Count(UserID) FROM users where Status = 'active'", con);
SqlDataReader dr;
con.Open();
while (dr.Read())
{
Debug.WriteLine(dr[0].ToString());
}
con.Close();
}

Retrieving images from SQL Server 2008 and displying it in a image controller of asp.net

I have a table images in SQL Server 2008 and it contains two columns imageid and image. I am able to insert images into the image column using the FileUpload controller and image which I have converted to binary form for storing. Now I want to display the images in an image box corresponding with the image id. I am using a textbox for having the user type in the id and a button to execute the command for displaying.
public void ShowImage()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["anu"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ID,Image from Images where ID=" + txtid.Text;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader dreader = cmd.ExecuteReader();
dreader.Read();
Context.Response.BinaryWrite((byte[])dreader["image"]);
dreader.Close();
con.Close();
}
This code is working fine but it loads the image in a separate page but I need to display it in a particular image box. My front end is ASP.NET. If any one knows the answer, please help me.
Instead of Response.Write Store the byte array in a session
Session["image"]=(byte[])dreader["image"];
Use this as the the source of your image
byte[] imgSrc=(byte[])Session["image"]
string imgSrcStr= Convert.ToBase64String(imgSrc);
string imageSrc = string.Format("data:image/gif;base64,{0}", imgSrcStr);
In the view:
<img src='"<%=imageSrc%>"' />
Or simply do all this in your function itself instead of Response
First you should really use a parameter in your query (or a stored procedure)
And you can just create an Image from the binary data and save that to the outputstream with the correct imageformat.
var ms = new MemoryStream((byte[])dreader["image"]);
var image = Image.FromStream(ms);
Context.Response.ContentType = "image/jpeg"; //or your actual imageformat
image.Save(Context.Response.OutputStream, format);

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