when upload the same file for the multiple times i am getting this error......
"The process cannot access the file 'd:\MarketingSystem\ExcelImport\Sample.xls' because it is being used by another process."
getting error in this line
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
This is my full code.....
protected void btnImport_Click(object sender, EventArgs e)
{
if (RevenueDumpFileUpload.HasFile)
{
string strFilePathOnServer = ConfigurationManager.AppSettings["RevenueDumpFileLocation"];
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName + ";Extended Properties=Excel 8.0;";
string strPostedFileName = RevenueDumpFileUpload.PostedFile.FileName;
if (strPostedFileName != string.Empty && RevenueDumpFileUpload.PostedFile.ContentLength != 0)
{
//Delete Old file before uploading new file.
if (System.IO.File.Exists(strFilePathOnServer))
{
System.IO.File.Delete(strFilePathOnServer);
}
//Save-Upload File to server.
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
RevenueDumpFileUpload.FileContent.Dispose();
}
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
try
{
Exlcon.Open();
}
catch
{
return;
}
finally
{
RevenueDumpFileUpload.PostedFile.InputStream.Flush();
RevenueDumpFileUpload.PostedFile.InputStream.Close();
}
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", Exlcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1, "XLData");
methodtosave();
}
}
In my web config file:
<appSettings>
<add key="RevenueDumpFileLocation" value="~/ExcelImport/"/>
How to resolve this?
Help me..
Thanks in advance
Well, if the OleDbConnection acts anything like the SqlConnection object, you've got this line:
Exlcon.Open();
which is opening the connection, but you don't have a matching line to close the connection. Which means the Jet database provider is going to continue to keep this file open until the connection object is garbage collected. It would be far better to wrap this line:
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
In a using statement, whose body extends over the remainder of the function, so that you're guaranteed that it's closed/disposed.
Next, have you considered what happens if multiple users upload files with the same name simultaneously - this method will be broken. It may be better to use a new file name on the server, related to the user ID or session ID, and wrap a try/finally around the whole method to ensure the file is deleted after use.
The above may be the cause of your current issues, if this is an error coming out of production - if two people attempt an upload at the same time, then both of their requests may go past the "delete if it exists" part of the code, then one request manages to save the file and open a connection, then the other request will fall over when trying to save the same file name.
You forget to pass the File Name and File Extension when you are trying to delete the file.
if (System.IO.File.Exists(Server.MapPath(strFilePathOnServer) + strPostedFileName+
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName)))
{
System.IO.File.Delete(Server.MapPath(strFilePathOnServer) + strPostedFileName +
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName) );
}
Related
I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.
I'm trying to restore a database from a bak file. I found some code on how to do it grammatically but I'm not sure what I'm doing wrong. I'm getting an error:
Error:
Restore failed for Server 'www.freegamedata.com'.
I assume because i'm remotely connected? I'm not sure. The bak file is not on the server machine. I'm trying to build a desktop application that will install my database on the users server using my file. Here is my code:
private void Restore_Database()
{
try
{
Server server = new Server(Properties.Settings.Default.SQL_Server);
string filename = "Test.bak";
string filepath = System.IO.Directory.GetCurrentDirectory() + "\\file\\" + filename;
Restore res = new Restore();
res.Database = Properties.Settings.Default.SQL_Database;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(filepath, DeviceType.File);
res.PercentCompleteNotification = 10;
res.ReplaceDatabase = true;
res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);
res.SqlRestore(server);
}
catch(Exception ex)
{
}
}
I'm not sure if I'm going about this the correct way. I'd like to add my database with my data to the users server as a base database. Am I doing something wrong? My connection string is good so I know its not a connection issue.
I have found a workaround for those whom do not have local access. This is a bit involved so I hope I explain this correctly and it makes sense.
Also note you will need to export your data to an excel spreadsheet before you do the steps listed below.
Exporting Data
Part 1:
Backup Your DATA!
This is a pretty simple process. Open SQL Management Studio and right click on your database. Choose export data and export it as an excel spreadsheet 2007. I'm not going to give detailed steps on this part because its pretty basic and you can google it. Sorry for the inconvenience.
Part 2:
Delete your database for testing purposes but make sure you have a working backup before you delete your database.
Importing Data
Part 1:
You need to create a script that will build your database for you automatically. You can do this by logging into SQL management Studio and right click on the database and choose:
Task -> Generate scripts
you should only need the default information. However, if your like me, I excluded the users in the list. This will generate a large SQL script.
Part 2:
Next you will want to store this file in your solution/project. Make sure you right click it and choose always copy or or copy if newer. I think that's the options. Basically it just copies your file when you debug or build it. This is critical because you will need to access this file to execute the script. Next you need to make a SQL function similar to mine to execute the script:
public bool SQLScript_ExecuteSQLScript(string ScriptLocation)
{
try
{
//5 min timeout
SqlConnection SQLConn = new SqlConnection(cn + "; Connection Timeout = 300;");
string script = File.ReadAllText(ScriptLocation);
Server server = new Server(new ServerConnection(SQLConn));
server.ConnectionContext.ExecuteNonQuery(script);
return true;
}
catch (Exception ex)
{
return false;
}
}
In my code sample please note I changed my timeout to 5 minutes. In the event you have a large script you may need to adjust the timeout to make sure your script fully executes.
Congrats you have rebuilt your database.
Part 3:
Load SQL Management Studio and make sure your database has been rebuilt successfully. You should see all your tables and Stored Procs but no data. If this is true, great you can continue. If not please go back and review your script. If you have SQL comments in your script, you may need to remove them. I had to in order for my script to execute without errors.
Part 4:
Now you need to import your data from your excel spreadsheet you created earlier. If your like me, you had multipal sheets. If you have multipal sheets then you will want to make a list to loop through each item in your list to import the sheets. If not then you can ignore my code on the list. I also put mine in a background worker but you don't need to depending on the size of your data. Also note I created a separate class containing my list but you dont have to do that if you don't want too. My sheet names are Table_1, Table_2 and Table_3 your will be differently most likely.
Sample Sheet List:
public List<string> GetTestTableList()
{
try
{
List<string> testlist = new List<string>();
testlist.Add("Table_1");
testlist.Add("Table_2");
testlist.Add("Table_3");
return testlist;
}
catch (Exception ex)
{
return null;
}
}
Part 5:
Next we will import the data from excel into SQL. This is a function I made but you can modify this to meet your needs.
Function:
private bool Import_Data_Into_SQL(string filepath, string SheetName, string Database, string Schema)
{
try
{
// sql table should match your sheet name in excel
string sqltable = SheetName;
// select all data from sheet by name
string exceldataquery = "select * from [" + SheetName + "$]";
//create our connection strings - Excel 2007 - This may differ based on Excel spreadsheet used
string excelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + filepath + " '; Extended Properties=Excel 8.0;";
string sqlconnectionstring = Properties.Settings.Default.SQL_Connection;
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(exceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlconnectionstring);
bulkcopy.DestinationTableName = Database + "." + Schema +"." + sqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
I hope this helps. This was my workaround solution. Originally I wanted/tried to import my data using the .bak file but as pointed out above you can only do that if the sql server is local. So I hope this work around helps those who where faced with a similar issue as me. I'm not marking this as the answer because the above post answers the question but I'm posting this in case someone else needs this workaround. Thanks
Restore file must be on server. For installation use SQL script. This can be generated by SQL Server Management Studio (including data).
Right click on database. Choose "Tasks" - "Generate scripts". On second page of wizard choose "Advanced" and find "Types of data to script". Select "Schema and data" and save script to file.
Then use this code to run script on database
string scriptText = File.ReadAllText(scriptFile, Encoding.Default);
ExecuteBatch executeBatch = new ExecuteBatch();
StringCollection commandTexts = executeBatch.GetStatements(scriptText);
using (SqlConnection sqlConnection = new SqlConnection(conn))
{
sqlConnection.InfoMessage += SqlConnection_InfoMessage;
sqlConnection.Open();
for (int i = 0; i < commandTexts.Count; i++)
{
try
{
log.InfoFormat("Executing statement {0}", i + 1);
string commandText = commandTexts[i];
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
log.Debug(commandText);
sqlCommand.CommandText = commandText;
sqlCommand.CommandTimeout = 300;
int r = sqlCommand.ExecuteNonQuery();
log.DebugFormat("{0} rows affected", r);
}
}
catch (Exception ex)
{
log.Warn("Executing command failed", ex);
try
{
sqlConnection.Open();
}
catch (Exception ex2)
{
log.Error("Cannot reopen connection", ex2);
}
}
}
sqlConnection.Close();
}
This is my coding for the upload to eport to excel...it is working fine when i run
through local in case while running through IIS it is not working.....
This is my code....
protected void btnImport_Click(object sender, EventArgs e)
{
if (RevenueDumpFileUpload.HasFile)
{
string strFilePathOnServer = ConfigurationManager.AppSettings["RevenueDumpFileLocation"];
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName + ";Extended Properties=Excel 8.0;";
// RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
try
{
Exlcon.Open();
}
catch
{
return;
}
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", Exlcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1, "XLData");
methodtosave();
}
}
How to solve this?
In fact Fileupload will work and should save the file, but there is problem in the connection string when you try to read the uploaded file. It should be the same file path as you are using to save the file.
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=" + strFilePathOnServer + RevenueDumpFileUpload.PostedFile.FileName + ";
Extended Properties=Excel 8.0;";
What type of application is this. Is it a Web Forms app? If so:
What do you mean by local and through IIS? Do you mean on the Server IIS?
If you're running the code on the server and it's not working then you are trying to force the server to do something it's not allowed to do.
For security reasons you shouldn't be accessing Excel on the server from an outside source. What you can do, if this is a Web Forms app, is use java script and an active x control to access the client's excel and write client side java script to save the file to the correct directory. There are plenty of examples online, use Google, to do this. I recently had to do this for 2 Web Applications at work.
If not then this might not be your problem.
I'm trying to write a function to read csv contents into a datatable.
I'm getting an exception about the file path and wondering what it is that I'm doing wrong.
All I did was create the console app and create a folder in the project called 'Data'.
public DataTable ReadCSV(string filename)
{
DataTable dt = new DataTable();
string sql = "SELECT * FROM " + filename;
string path = "Data\\";
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";" + "Extended Properties='text;FMT=Delimited(;);HDR=YES'";
OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connstring);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
try
{
conn.Open();
da.Fill(dt);
}
catch (Exception ex)
{
Console.WriteLine(filename + "not found");
}
finally
{
conn.Close();
}
return dt;
}
}
My connection string in the Text visualizer when I run in debug mode:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\Positions.csv;Extended Properties='text;FMT=Delimited(;);HDR=YES'
I'm getting an exception
base {System.Data.Common.DbException} = {"'Data\Positions.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides."}
Can anyone point me in the right direction? I have limited experience doing console apps so it's probably some formatting mistake that I've made. Thanks
and create a folder in the project called 'Data'.
That doesn't work. Your program is running in the bin\Debug subdirectory of your project. It doesn't have a Data subdirectory. You'd have to use ..\..\Data\Positions.csv to find that file.
Well, that would solve your problem right now but it isn't going to be useful once you copy your program to another machine. There won't be a ..\..\Data directory there. Think about ways that your user is going to tell you where the .csv file is located. A GUI with OpenFileDialog is the friendly way but not very compatible with a console app. The standard way for that is to pass command line arguments. Environment.CommandLine. Not very compatible with the typical user. You'll have to weigh these options by yourself.
Hey guys, I'm just doin' practise Program to read,write data to Access DB in C# and i'm having a problem in writing data to Access DB though i'm able to read data i.e fetchin' is working fine but when i insert data my "ExecuteNonQuery" is working fine i mean without ne error but when open the Access DB the data is not there.... here is the code what m tryin' to do...
//// Function For ExecuteNonQuery
public static bool ExecuteNonQuery(string Query)
{
OleDbCommand oledbCommand = new OleDbCommand(Query, connection);
if (connection.State == ConnectionState.Open)
connection.Close();
try
{
connection.Open();
if (oledbCommand.ExecuteNonQuery() > 0)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
finally
{
connection.Close();
}
}
This below code is for Adding Data which gets fired on "Add" Button Press
private void btnAdd_Click(object sender, EventArgs e)
{
simOperator.aim_network_name = txtAimNetNm.Text;
simOperator.network_id = txtOxiNetID.Text;
simOperator.network_name = txtNetName.Text;
simOperator.pack_id = txtPackID.Text;
simOperator.pack_name = txtPackName.Text;
SimOperator.Add(simOperator);
fillText();
}
public void fillText()
{
txtResult.Text = "";
SimOperator[] simOperatorList = SimOperator.GetAllOperators();
foreach (SimOperator sm in simOperatorList)
{
txtResult.Text += Program.operator_id + " " + sm.aim_network_name + " " + sm.network_name + " " + sm.network_id + " " + sm.pack_id + " " + sm.pack_name + "\r\n";
}
}
Here's the "Add" Function
string Query = string.Format("insert into {0}({2}) values({1});", calledObject.Name, PropertyValue,PropertyName);
ExecuteNonQuery(Query);
Actuall SQL query is:
insert into SimOperator(aim_network_name,network_id,network_name,pack_id,pack_name) values('FiveNet','2563','FiveNet-Kurla','1236','5236');
Yeah and My Connection String
static OleDbConnection connection = new OleDbConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
App.config file contains string as
add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AutoMobileRecharge.mdb;User Id=; Password=;Persist Security Info=True"
The thing m not getting is I have put a Text-Area just beside all the inside fields textboxes so that i can see what is getting inserted, so when insert data that text-area shows the data perfectly but when i open the access db, then theres no data in that, when i close my application and again i ran it then that text-area is empty...this sounds wierd to me.. Any one outthere have faced this kind a problem please help me out here..
Are you doing it during debug ? in that case look if there's an mdf file inside debug folder and if it contains the data you've just inserted. Vs copy some file to debug folder when you run the app in that mode. If i remember correctly there's an option to tell vs not to copy files when debugging