In my C# apps "MyApps.Exe", i use Provider Microsoft.ace.oledb.12.0 to access my accdb file..
I set data source with
Data Source="+Application.StartupPath+"\\databaseFile.accdb
So my apps will read the databaseFile.accdb in the same folder with Exe file. The folder name is CurrentFolder.
I have compile my apps and install it in : "C:\Program Files(x86)\CurrentFolder"
Peculiarities occur, when file "databaseFile.accdb" has been deleted from folder "CurrentFolder".
When I run "MyApps.exe", then login entry username and password, and then Entry ,read data. The Apps is still running.
This should not happen because "databaseFile.accdb" has been deleted.
Why it can happen? I am confused for this happen.
Anyone can explain this ? why my Apss still can access/read database.accdb
eventough the database was deleted.
Thanks in advance.
--Addition Information --
Before, i share folder "C:\Program Files(x86)\CurrentFolder" to network. and add Permissions to Everyone Full Control.
I hope this information can help our problem analysis.
Here source code my connection.cs
public Connection()
{
try
{
alamat = "Provider=Microsoft.ace.Oledb.12.0; Data Source="+Application.StartupPath+"\\databaseFile.accdb";
koneksi = new OleDbConnection(alamat);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static Connection GetInstance(){
if(Connection.connection == null){
Connection.connection = new Connection();
}
return Connection.connection;
}
//this is for check wether the file databaseFile.accdb is exist in that folder
public int cekDb(string locasi)
{
int a=0;
if (File.Exists(locasi))
{
a = 1;
}
return a;
}
public int CekLogin(string user,string pass)
{
koneksi.Close();
koneksi.Open();
perintah = new OleDbCommand("select * from [user] where username = '" + user + "' and password = '" + pass + "';", koneksi);
myReader = perintah.ExecuteReader();
int count = 0;
while (myReader.Read())
{
leveluser = myReader["type"].ToString();
count++;
}
koneksi.Close();
return count;
}
In my login.cs
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Please Fill your Username or Password");
textBox1.Focus();
}
else
{
if(connection.cekDb(Application.StartupPath+"\\databaseFile.accdb")==1){
int cek = connection.CekLogin(textBox1.Text.Trim().Replace("'", "''"), textBox2.Text.Trim().Replace("'", "''"));
if (cek != 0)
{
DashBoard entry = new DashBoard();
entry.Show();
UseWaitCursor = false;
}
else if (cek == 0)
{
// konek.Disconnect();
MessageBox.Show("Please Check your username and password !!");
}
else
{
MessageBox.Show(cek.ToString());
}
}
else
{
MessageBox.Show("File DatabaseFile.accdb Not Found !!");
}
}
}
Related
I want to create a Windows Folder the name of the folder will get it from a TextBox.Text that the user will fill in, but inside this folder it should also create automatically an app.config
This is what I got so far:
private void CreateNewCustomer()
{
Directory.CreateDirectory(#"C:\Users\khaab\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\" + CustomerTextBox.Text);
StreamWriter File = new StreamWriter(#"C:\Users\k.abdulrazak\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\app.config");
File.Close();
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
How can I do that?
You should have a variable that holds the root path whether to create the new folder and the app.config file, e.g., string root = Environment.CurrentDirectory. Then the CreateNewCustomer method would look like:
public void CreateNewCustomer()
{
var di = Directory.CreateDirectory(Path.Combine(root, CustomerTextBox.Text));
if (di.Exists)
{
var fs = File.Create(Path.Combine(di.FullName, "app.config"));
fs.Close();
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
}
How about this:
public void SubmitButton_Click(object sender, EventArgs args)
{
var name = CustomerTextBox.Text
if (String.IsNullOrWhiteSpace(name))
{
MessageBox.Show("Enter a customer name!");
return;
}
var result = CreateNewCustomer(name);
if (result)
{
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("Something went wrong.", "Customer add failed", MessageBoxButtons.OK);
}
}
private bool CreateNewCustomer(string customerName)
{
var result = true;
try
{
var basepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Customers");
var custPath = System.IO.Path.Combine(basepath, customerName);
var appconfigpath = System.IO.Path.Combine(custPath, "app.config");
if (!System.IO.Directory.Exists(custPath))
{
System.IO.Directory.CreateDirectory(custPath);
}
System.IO.File.Create(appconfigpath);
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError("Error creating customer folder: {0}", ex);
result = false;
}
return result;
}
I'm deploying a ClickOnce Application and want to restart the application after it was updated. Therefore I wrote following code:
private async void updateCheck()
{
using (var releaser = await _asyncLock.LockAsync())
{
UpdateCheckInfo info = null;
bool updateAvailable = false;
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
ad.UpdateCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Ad_UpdateCompleted);
try
{
updateAvailable = ad.CheckForUpdate(false);
info = ad.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
return;
}
catch (InvalidDeploymentException ide)
{
MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
return;
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
return;
}
if (/*info.UpdateAvailable*/ updateAvailable)
{
Boolean doUpdate = true;
if (!info.IsUpdateRequired)
{
MessageBoxResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButton.OKCancel);
if (!(MessageBoxResult.OK == dr))
{
doUpdate = false;
}
}
else
{
// Display a message that the app MUST reboot. Display the minimum required version.
MessageBox.Show("This application has detected a mandatory update from your current " +
"version to version " + info.MinimumRequiredVersion.ToString() +
". The application will now install the update and restart.",
"Update Available", MessageBoxButton.OK,
MessageBoxImage.Information);
}
if (doUpdate)
{
try
{
//ad.Update();
ad.UpdateAsync();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
return;
}
}
}
}
}
}
private void Ad_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("The application has been upgraded, and will now restart.");
String ApplicationEntryPoint = ApplicationDeployment.CurrentDeployment.UpdatedApplicationFullName;
Process.Start(ApplicationEntryPoint);
Application.Current.Shutdown();
}
}
Unfortunate in UpdatedApplicationFullName a URL to the Website where the deployment packages are stored. So Process.Start(ApplicationEntryPoint) opens a Browser Window and tries to download the package once again.
The behaviour I want is that the Process.Start(...) opens the new updated application.
Has anyone an idea what I'm doing wrong?
Thanks.
I have a c# program which does the following on form load:
Creates an OleDbConnection to a database in the same folder as the program
Gets the computer name
Gets the username
Fills in some textbox fields on the form with data obtained from the database
When I open the form using Windows explorer, shortcut, or debugging in visual studio express 2013, it does all of this without any issues. When trying to open it with a command prompt or with a hyperlink, the database connection is not established, but no error messages appear. The textbox fields are filled with "not found" as a result of my try-catch statements around the oledb commands. The same try-catch statement should print ex.message to a text file, but that does not happen either. As stated before, this all runs flawlessly when running from debug mode in vs or running the program by opening it in Windows explorer, so I'm not sure how to debug this.
2 questions - Is there a known problem with opening c# forms which try to establish OleDb connections with access databases on form load when launching the program from command prompt or a shortcut? If so, are there any workarounds? Given that it runs fine in debug mode in vs, and my catch statements seem to be terminating prematurely without error messages, is there any other way to debug and find out exactly where the problem occurs?
I left off some of the irrelevant lines of code to make this shorter.
private void Form1_Load(object sender, EventArgs e)
{
userData = onLoad.loadDb(out userNotFound);
ComputerName = onLoad.getComputer();
// Session Notification
WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);
// Initialize Hooks
initialize_Hooks();
if (userData.Count < 4)
{
for(int i = 0; i<4; i++) { userData.Add("Not Found"); }
}
// globals:
FullID = userData[0];
ID = userData[2];
firstName = userData[1];
lastName = userData[0];
nanid = userData[3];
fullName = firstName + " " + lastName;
// Fill in Form
label1.Text = fullName;
label2.Text = ID;
label3.Text = nanid;
}
public class onLoad
{
public static string getUser() // returns Environment.UserName
public static string getComputer() // returns System.Environment.MachineName;
public static List<string> loadDb(out bool userNotFound)
{
List<string> rList = new List<string>();
string strAccessConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=db.mdb";
string strAccessSelect = "SELECT (//select statement which works fine when I open the program in explorer or vs debug)
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch(Exception ex)
{
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
error_handler.error_logger(ex.Message);
userNotFound = true;
return rList;
}
try
{
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myAccessConn.Open();
myDataAdapter.Fill(myDataSet,"table1");
}
catch (Exception ex)
{
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
finally
{
myAccessConn.Close();
}
try
{
DataRowCollection dra = myDataSet.Tables[0].Rows;
foreach (DataRow dr in dra)
{
code that conditions the data, works fine when running the program
}
}
catch(Exception ex)
{
string returnString = ex.Message;
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
return rList;
}
}
class error_handler
{
public static string filename = "error.txt";
public static void error_logger(string error_message)
{
error_message = onLoad.getUser() + "\t" + DateTime.Now.ToString("MM/dd/yy hh:mm:ss") + "\t" + onLoad.getComputer() + "\t" + "Error: " + error_message;
if (!File.Exists(filename))
//writes error_message to a new text file or appends if it already exists. works fine when running from windows explorer or vs debug
}
}
I bet that shortcut passes in the working directory as a parameter. The documentation for File.Exists() states that when using a relative path the relative path information is interpreted as relative to the current working directory.
You can use the Directory.GetCurrentDirectory() function to determine if the path is set correctly.
If you are using files that you know are going to be in a path relative to the application I would use Application's path or at least set Environment.CurrentDirectory = Application's path.
Also take a look at the Environment.GetCommandLineArgs()[0]. That is probally being set by the shortcut.
Got an issue here. I have a program that when it starts a loginForm dialog pops up. Now on this loginForm I've added a rememberMe (onthoudMij) button. So if the user selects this box log's in, closes the program and then opens it again, his user credentials will already be filled in.
Here's my code for my loginButton.
private void loginButton_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C:\\" + inlogNaamTextbox.Text + "\\Login.txt");
gebruikersnaam = sr.ReadLine();
passwoord = sr.ReadLine();
sr.Close();
if (gebruikersnaam == inlogNaamTextbox.Text && passwoord == inlogPasswoordTextbox.Text)
{
classUsername.name = inlogNaamTextbox.Text;
MessageBox.Show("Je bent nu ingelogd!", "Succes!");
this.Dispose();
}
else
{
MessageBox.Show("Gebruikersnaam of wachtwoord fout!", "Fout!");
}
}
catch (System.IO.DirectoryNotFoundException ex)
{
MessageBox.Show("De gebruiker bestaat niet!", "Fout!");
}
}
NOW MY PROBLEM IS:
I have searched the web for options on remember me implementation, but they always use SQL databases etc. I just have a login that stores the username & password in a txt file as you can see in the code.
Question is..
So no my question is; How can I implement this remember me checkbox? I already know I should use System.Net , but what else for this to work without sql databases or anything like that?
If your problem is the saving part, you could use something like 3DES encryption to have a somewhat save solution to save the username and password.
You could use your current code and add something like in this SO article to encrypt and decrypt the password: How to implement Triple DES in C# (complete example)
If the problem is just how to do read/save this?
I would create a text, something like this:
private void CallOnFormLoad()
{
string[] allLines = File.ReadAllLines(#"C:\passwordfile.txt");
if (allLines.Length > 1)
{
// at least one 2 lines:
inlogNaamTextbox.Text = allLines[0];
inlogPasswoordTextbox.Text = allLines[1];
}
}
private void loginButton_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C:\\" + inlogNaamTextbox.Text + "\\Login.txt");
gebruikersnaam = sr.ReadLine();
passwoord = sr.ReadLine();
sr.Close();
if (gebruikersnaam == inlogNaamTextbox.Text && passwoord == inlogPasswoordTextbox.Text)
{
classUsername.name = inlogNaamTextbox.Text;
MessageBox.Show("Je bent nu ingelogd!", "Succes!");
File.WriteAllLines(#"C:\passwordfile.txt", string.Format("{0}\n{1}", inlogNaamTextbox.Text, inlogPasswoordTextbox.Text))
// Don't call Dispose!
// this.Dispose();
}
else
{
MessageBox.Show("Gebruikersnaam of wachtwoord fout!", "Fout!");
}
}
catch (System.IO.DirectoryNotFoundException ex)
{
MessageBox.Show("De gebruiker bestaat niet!", "Fout!");
}
}
I have got 3-tier where carry out my code in business layer I run code for update
public override bool LoadProperties2List(string TypeOfOperation)
{
SortedList Sl = new SortedList();
Sl.Add("#CommandType", TypeOfOperation);
Sl.Add("#UserName",UserName);
Sl.Add("#SecondarySchool",SecondarySchool);
Sl.Add("#University",University);
Sl.Add("#Qualification",Qualification);
Sl.Add("#JobTitle",JobTitle);
Sl.Add("#Company",Company);
Sl.Add("#PhotoUrl", PhotoUrl);
ProcedureName = "MangeUserInfo";
if (db.RunProcedure(ProcedureName, Sl) == 1)
return true;
else
return false;
}
public bool updateUser(string User, string SecondaryS, string Unvi, string Qua, string jobtitle, string company)
{
this.UserName = User;
this.SecondarySchool = SecondaryS;
this.University = Unvi;
this.Qualification = Qua;
this.JobTitle = jobtitle;
this.Company = company;
if (Update())
return true;
else
return false;
}
and in data access layer
public void ConnectDB(CommandType CT,string ProNameSQl)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=Conversation;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CT;
cmd.CommandText = ProNameSQl;
cn.Open();
}
public int RunProcedure(string ProcedureName, SortedList Paraval)
{
ConnectDB(CommandType.StoredProcedure, ProcedureName);
for (int x = 0; x < Paraval.Count; x++)
{
try
{
cmd.Parameters.AddWithValue(Paraval.GetKey(x).ToString(), Paraval.GetByIndex(x));
}
catch
{
;
}
}
return ExceNoneQuery();
}
and then in another layer I use this method to call procedure process kind and run
public bool Update()
{
return LoadProperties2List("u");
}
at last layer presentation layer
I do that
protected void btnsave_Click(object sender, EventArgs e)
{
//upadate info
bool Result = false;
UsersInfo Upd = new UsersInfo();
try
{
Result = Upd.updateUser(username, TxtSecondarySchool.Text, TxtUniversity.Text, TxtQualification.Text, TxtJobTitle.Text, TxtCompany.Text);
if (Result==true)
lblMessage.Text = "Record Updated Successfully.";
else
lblMessage.Text = "Record couldn't updated";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
} finally
{
Upd = null;
}
}
When I run the code only the result is
lblMessage.Text = "Record couldn't updated";
What is the error which makes it not to work correctly?
I also find something strange that the textboxes doesn't take the new values it pass the same value despite change why? I need help
The error is that the textbox loads in a routine in the Page's Startup event, with the routine placed outside the If IsNotPostback loop. So, the default value just reloads every time the page is refreshed, and thus appears to be 'unchangeable'.