C# ApplicationContext usage
Posted
by
rd42
on Stack Overflow
See other posts from Stack Overflow
or by rd42
Published on 2011-01-04T22:34:24Z
Indexed on
2011/01/04
22:53 UTC
Read the original article
Hit count: 197
Apologies if my terminology is off, I'm new to C#. I'm trying to use an ApplicationContext file to store mysql conn values, like dbname, username, password. The class with mysql conn string is "using" the namespace for the ApplicationContext, but when I print out the connection string, the values are making it.
A friend said, "I'm not initializing it" but couldn't stay to expand on what "it" was.
and the "Console.WriteLine("1");" in ApplicationContext.cs never shows up. Do I need to create an ApplicationContext object and the call Initialize() on that object?
Thanks for any help.
ApplicationContext.cs:
namespace NewApplication.Context
{
class ApplicationContext
{
public static string serverName;
public static string username;
public static string password;
public static void Initialize()
{
//need to read through config here
try
{
Console.WriteLine("1");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(".\\Settings.xml");
XmlNodeList serverNodeList = xDoc.GetElementsByTagName("DatabaseServer");
XmlNodeList usernameNodeList = xDoc.GetElementsByTagName("UserName");
XmlNodeList passwordNodeList = xDoc.GetElementsByTagName("Password");
}
catch (Exception ex)
{
// MessageBox.Show(ex.ToString());
//TODO: Future write to log file
username = "user";
password = "password";
serverName = "localhost";
}
}
}
}
MySQLManager.cs: note: dbname is the same as the username as you'll see in the code, I copied this from a friend who does that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using NewApplication.Context;
namespace NewApplication.DAO
{
class MySQLManager
{
private static MySqlConnection conn;
public static MySqlConnection getConnection()
{
if (conn == null || conn.State == System.Data.ConnectionState.Closed)
{
string connStr = "server=" + ApplicationContext.serverName +
";user=" + ApplicationContext.username + ";database=" + ApplicationContext.username + ";port=3306;password=" +
ApplicationContext.password + ";";
conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL... ");
Console.WriteLine("Connection string: " + connStr + "\n");
conn.Open();
// Perform databse operations
// conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
return conn;
}
}
}
and, thanks for still reading, this is the code that uses the two previous files:
class LogDAO
{
MySqlConnection conn;
public LogDAO()
{
conn = MySQLManager.getConnection();
}
Thank you, rd42
© Stack Overflow or respective owner