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.
Related
I am writing a Windows Forms application that needs to query 2 fields from a MAS-90 database. For this we use the MAS 90 32-bit ODBC Driver by ProvideX called SOTAMAS90. Here is the code I use to retrieve a DataTable from the MAS-90 database.
public static DataTable getDatatable(string qry)
{
DataTable dt = new DataTable();
using (OdbcConnection conn = new OdbcConnection(GetSQLConnection()))
{
try
{
OdbcCommand cmd = new OdbcCommand(qry, conn);
cmd.CommandType = CommandType.Text;
conn.Open();
OdbcDataAdapter adpt = new OdbcDataAdapter(cmd);
adpt.Fill(dt);
cmd.Dispose();
conn.Close();
conn.Dispose();
}
catch (OdbcException e) { conn.Close(); }
catch (AccessViolationException ae) { conn.Close(); }
catch (UnauthorizedAccessException ue) { conn.Close(); }
}
return dt;
}
On line adpt.Fill(dt) I get the following exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This was working just fine yesterday. Today Visual Studio is telling me that this is an Unhandled AccessViolationException even though you can clearly see the try/catches. I had to add <legacyCorruptedStateExceptionsPolicy enabled="true"/> to my config file just for the exception to be caught in the try/catch.
The other strange thing is I am able to connect to the database and run the same exact query (which is just selecting 2 fields from a table) using the ODBC Query Tool by Jaime De Los Hoyos M. (Available here)
Any help at resolving this issue is greatly appreciated. Please let me know if you need additional information.
I also wanted to add that I have tried:
Targeting x86 in my app as the Driver is 32-bit
Giving permissions to the directory where the database is stored
Restarting PC
Changing query to add parameters with cmd.Parameters.AddWithValue("#PARAM", "Value")
I was able to resolve my issue. The database was stored on a server to which my PC had a mapped drive to. For whatever reason, the mapping broke for the MAS 90 32-bit ODBC Driver. This was strange because I was still able to access the network drive's files via File Explorer and I was also able to query the table via the ODBC query tool I mentioned (which uses the same ODBC driver). I discovered this when I wanted to change the Database Directory field (seen below) and it kept telling me the path was invalid or inaccessible (even though it was accessing it for the ODBC query tool).
Anyway, I remapped the network drive, then deleted and recreated the SOTAMAS90 DSN and it worked again.
I have an asp.net C# application (.net 4.0) connected to SQL Server 2012 using ADO.Net and am encountering an error which says:
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
I very well know what a DataReader is but, my problem is getting this error in below conditions:
I have not at all used any DataReader in my application, I have only
used DataAdapters everywhere. The code works fine while running in
local environment and there is no errors.
Application works fine even after deployment in IIS7 when used by a
single user.
The error only occurs when multiple users starts using the website hosted in IIS7.
Kindly help, I am also doubting for any problems with my hosting in IIS7
After a lot of trial and error, finally I found out that it's a problem with SqlConnections. What I used to do was open a connection at the instantiation of my DAL layer object. So, whenever two methods from the same DAL object called together, it used to throw the error.
I solved it by opening and closing a connection in every call to the database. Now it all works fine. This also allows max number of users to use the application at a time. Below is my code sample from DAL:-
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlCommand = new SqlCommand
{
Connection = sqlcon,
CommandType = CommandType.StoredProcedure,
CommandText = "MyStoredProc"
};
sqlCommand.Parameters.AddWithValue("#Parameter1", Parameter1);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
adapter.Fill(dt);
}
}
return dt;
}
catch (Exception exp)
{
LogHelper.LogError(string.Concat("Exception Details: ", ExceptionFormatter.WriteExceptionDetail(exp)));
throw exp;
}
finally
{
dt.Dispose();
}
Please post a better way of doing it if you know any, thank you.
I have a C# winform app named xyz.exe. It operates using xyz.config file. The config file is a plain text file and in it I put my settings I need to run my app , such as how many times it has to iterate, what files to read, what are the default values etc etc. It works just fine. All is working OK. Today I started to work on some enhancement request, I need to make a connection to a sql server database and retrieve some information. Very straight forward.
If I run debug (F5) all is working OK. But if I run it from command prompt by typing xyz.exe it throws exception "The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception." and it points to the connection section. if I rename xyz.config to something else , the exception went away. if I create a blank App.config (this will generate xyz.exe.config), the exception went away.
What is going on? Can anybody explain this to me and what are the possible solutions, options, best solution? is is possible to make the app to not looking for xyz.config and xyz.exe.config w/o throwing exception. It was ok before I introduce connection to db.
SqlConnection connection = new SqlConnection(
"user id=xx;" +
"password=xx;" +
"server=xx;" +
"database=xx; " +
"connection timeout=xx");
try
{
connection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from xx",
connection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["xx"].ToString());
Console.WriteLine(myReader["xx"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
connection.Close();
Config files should be named <exename>.exe.config, e.g. if your exe name is xyz.exe, its config file name should be xyz.exe.config.
If you want to use non-standard names, you have to read config files manually.
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.
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.