Image not display in webpage - c#

I am using VS 2010 for developing a web application. I am storing the uploaded images in physical path of the Server and also created virtual path in IIS 7.5 (the screenshot below).In Authorization,one Warning is displayed.For using the belo code I try to retrieve the image from the server but the image is not display.Where the problem, in virtual path or in the path mention in code ?
private void CallImage()
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
SqlCon.Open();
string query = "SELECT Cmp_DocPath FROM Company_Info WHERE
Vendor_ID= '" + ddlVendorID.SelectedValue + "'";
SqlCommand SqlCmd = new SqlCommand(query, SqlCon);
SqlDataAdapter da = new SqlDataAdapter(SqlCmd);
DataTable dt = new DataTable();
da.Fill(dt);
string ImageName = Convert.ToString(dt.Rows[0][0].ToString());
Image1.ImageUrl = this.ResolveUrl("D:/Upload/Commerical Certificates/"+ImageName);
// Image1.ImageUrl = this.ResolveUrl("D:\\Upload\\Commerical Certificates\\"+ImageName);
// Image1.ImageUrl = this.ResolveUrl("~\\Upload\\Commerical Certificates\\"+ImageName);
SqlCon.Close();
}

You can't reference a physical location to an image and expect it to work on a Web site. Store the paths to the images as virtual paths from the root of the site. For instance:
If your site root is at:
d:\inetpub\mysite\
And your images are at:
d:\inetpub\mysite\uploads\images\
Then your virtual paths int he database need to be:
~\uploads\images\image1.jpg
~\uploads\images\image2.jpg
Then you can set that as the ImageUrl property and no, you don't need to resolve it (the Image control does that automatically).
My guess is that the reason you're having this problem is because you are trying to reference images that are not within the Web site, which even if you get to work in your dev environment by giving access to NETWORK SERVICE, IIS_IUSRS, the second you move this application into a production environment, you are going to have problems. Not to mention that is a very poor way to do things in terms of security and modularity.

The username that you used might not have read/write permissions on server. Go to the user settings of the corresponding user and enable read and write permission. Also check whether you are giving the correct path of the image. Hope it helps.

Related

Why session timeouts after OledbConnection open

i am calling the OledbConnection to Microsoft Access Database. there is no issue calling the method and also retrieves necessary data.
i dont know after that method the session timeouts automatically. and goes to login page. why?
i have lost entire day debugging and finding the issue.
string strQuery = "select count(LOC1) as LOC1 from shrmwise";
DataTable dt = new DataTable();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand(strQuery, connection))
{
try
{
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
}
catch (Exception ex)
{
throw ex;
//Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
return dt;
}
}
Edited
Does not timeout if the above method call is commented.
it does not timeout on localhost, but on live server.
my connectionString as follows
string connectionString =
#"Provider=Microsoft.Jet.OLEDB.4.0;" +
#"Data Source=E:\Data\MyDatabase.mdb;" +
#"User Id=;Password=;";
Usually in a IIS/ASP.NET environment the application runs with MEDIUM TRUST settings and not with FULL TRUST. This means that your code cannot access any part of the file system that resides outside the root of your site.
To resolve the problem in which applications need a place where they can read and write without worrying about too much security restrictions a convention has been adopted.
The convention is to have a subfolder of the site root called APP_DATA where the user (IUSR) under which the ASP.NET service runs your application has Read/Write permissions. Here you can place your database or other read/write files. Create subfolder to store different type of documents and so on.
So your problem can be solved just following the convention and moving the database in that folder. Or, after verifying the security consequences of such move, force your site to run in FULL TRUST.
Of course if you have to manually create the APP_DATA folder be sure to also set the correct permissions for the IIS user.

C# mdf local database

I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?

Can i make sql Database part of c# Project

I have made a sample c# application (First project ive done) Its quite a simple application which uses a database to store data and edit data.
The problem i am having is the program works perfectly fine on my computer but if i publish the application and put it on another computer it cannot use the database as it is not part of the project.
I used connection string
private SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Ryan\\Documents\\Visual Studio 2015\\Projects\\youtubeLoginTut\\youtubeLoginTut\\data.mdf\"; Integrated Security = True; Connect Timeout = 30");
Which is obviously the path to the database on my computer and will not be the same on the next computer. Is there anyway i could include the database in the package so its referenced from where ever the application sits.
Ive tried shortening the path to for example ..\data.mdf but to no avail and i cant find anything on google so im all out of ideas.
Go easy im very new to c#
Cheers
Ryan
There is a way to get the location of your project in every computer : (inside the bin/debug/)
string path = AppDomain.CurrentDomain.BaseDirectory //example : C:/Users/Ryan/Documents/Visual Studio 2015/Projects/Youtubetut/bin/debug
you just need add the location of the database inside of the project's folder to this path. path will replace your "C:\Users\Ryan\Documents\Visual Studio 2015\Projects\youtubeLoginTut" and make sure to move your database inside the debug folder.
Afeter publiching your database with your project you get the Installtion Path From Deployment byuse :
string sourcePath =System.Reflection.Assembly.GetExecutingAssembly().Location
sourcePath =sourcePath +"\data.mdf";
If it's a simple application you can try to use embeded DB like SQLite. I use it in my application and it works fine.
If you want to use SQLite, let's go step by step.
download the dynamic library System.Data.SQLite.dll for your version of the .NET Framework
link System.Data.SQLite.dll to your project
write a code something like this
Create a table
SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=True;", "./db/mydatabase.sdb"));
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = #"CREATE TABLE Books (BookId int, BookName varchar(255), PRIMARY KEY (BookId));";
cmd.ExecuteNonQuery();
con.Close();
Read the data
using(SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=False;", "./db/mydatabase.sdb")) {
con.Open();
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT BookName FROM Books WHERE BookId=1 LIMIT 1;";
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows && reader.Read()) {
oResult = Convert.ToString(reader["BookName"]);
}
reader.Close();
}
}
con.Close();
}

C# Winform Application

I am creating a winform application which connects to a ms-access database. The problem is with my connection string as i can access the database locally but if i run from my usb stick or from any other pc it would give me error. How can i modify my connection string so that i can run my application on other pc without any trouble.
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Aakash\Documents\Visual Studio 2013\Projects\Industrial Foundry\record.accdb";
using (OleDbConnection con = new OleDbConnection(strConnect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("select * from Industry ", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Perhaps this would be a good start:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Since your title indicates you have a WinForms application, you may also want to consider adding a "Browse" button to locate the database and then using a connection string builder to build your connection.
I hope this can help you.
Create a winform where you can input parameters like "server", "password", etc., etc
After that, update your connection string with the parameters:
Friend Principal As New SqlClient.SqlConnection("data source=" & My.Settings.Server & ";INITIAL CATALOG=" & My.Settings.DB & ";UID=" & My.Settings.User & ";PWD=" & My.Settings.Password & ";workstation id=" & My.Settings.PC & ";packet size=4096")
Your connection string points directly to a path on your C: drive.
There are a number of ways that you could fix it; you could just prompt the user for the file location, and/or store it in a user configurable settings file.
I think simple way for you would be use App.Config file (Application Configuration File), you can add your database key in config file, when app launch you can check if key value is null than you should force user to choose database path, and you can set that database path to your config file. You can read your key value something using..
Code for Read Key
System.Configuration.ConfigurationSettings.AppSettings["DBKey"];
Code for Write Key
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("DBKey", "DBPath");
config.Save(ConfigurationSaveMode.Modified)
Thanks
Suresh

asp.net database connection with Access

I want to make a login page with an Access database for a school project with asp.net. I dont have really experience with C# so im doing different tutorials.
protected void Login1_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb";
string query = "Select Count(*) From users Where username = ? And userpassword = ?";
int result = 0;
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", UserName.Text);
cmd.Parameters.AddWithValue("", Password.Text);
conn.Open();
Session["User"] = UserName.Text;
result = (int)cmd.ExecuteScalar();
}
}
if (result > 0)
{
Response.Redirect("index.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
}
}
In Access I have the table 'users' with the 'username' and 'userpassword' rows.
The problem you are encountering is almost certainly to do with the data source segment of your connection string:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb"
The Access mdb file should be on a local path. This can be anywhere on your local file system that the account your web application is running as has permission to access, but, usefully, ASP.Net actually has a better place to put these files, the App_Data folder.
If you place your mdb file in this folder, your connection string would then become:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|ek2012.mdb"
The contents of the App_Data folder will not be served to clients so this is a secure place to put your data. It's also a good idea to use it as it keeps the data with the project; often, people will put data related files in a file system folder outside of the web root, which means you then have to remember this dependency when moving the site to another computer.
A common issue you might have with accessing files in App_Data is usually related to permissioning; the user you are running the code as will need read and write permissions in this directory in order to modify the mdb file. This is covered in the section "Configuring Permissions for an Access Database" in this MSDN Article.

Categories