C# ApplicationContext usage - c#

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

Ignoring that there's already a very rich set of Configuration Classes in .NET including ones for Connections that support encryption, you do need to as some point call Application.Initialize() in order for it fields to be populated.
I should mention that this looks like an implementation of a singleton. You might want to read Jon Skeet's article on singletons because there are probably things you want to watch out for. For example what would happen if two threads called ApplicationContext.Initialize()? Are multiple calls to ApplicationContext.Initialize() even sensible?
Also public fields are probably a bad idea especially when you have automatic implemented properties available to you.

Related

Is there a Method to read the Content of a Website?

I wanted to write a Program that reads an online Calendar, compares it with Names in a Database and uses this Data in some way. But if I use the WebClient, it reads the Source Code of the Website, not the Content. This is my Code:
using System;
using System.Diagnostics;
using System.Net;
using MySql.Data.MySqlClient;
namespace CalendarCrawler
{
class Program
{
static void KillTask(string Task)
{
Process[] Process = new Process[] { };
Process = Process.GetProcessesByName(Task);
foreach (Process Instance in Process)
{
Instance.Kill();
}
}
static String ReadContent(String Website)
{
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead(Website);
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
String text = reader.ReadToEnd();
return text;
}
}
static void Main(string[] args)
{
Console.WriteLine("Getting Connection ...");
var datasource = "localhost";//your server
var database = "database"; //your database name
var username = "username"; //username of server to connect
var password = "password"; //password
//your connection string
string connStr = $"Server={datasource};Database={database};Uid={username};Pwd={password}";
//create instanace of database connection
using (var conn = new MySqlConnection(connStr))
{
try
{
Console.WriteLine("Openning Connection ...");
//open connection
conn.Open();
Console.WriteLine("Connection successful!");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
String Websitetext = ReadContent("http://www.esel.at/termine");
var stm = $"INSERT INTO content(Content) VALUES (#1);";
var cmd = new MySqlCommand(stm, conn);
cmd.Parameters.AddWithValue("#1", Websitetext);
cmd.ExecuteNonQuery();
Console.WriteLine(Websitetext);
KillTask("CalendarCrawler");
}
}
}
}
The Killtask Method is only to Clear it from the Background Processes, so there are no Problems with building a new Version.
I hope someone can help me.
There are effectively 2 different users of the web. People and computers. People like shiney things like buttons and tables (UI), computers prefer things like XML or JSON (API).
Your calendar web site has a UI, this is what you are currently seeing (both in a browser and when you 'download the code'). It probably has an API too and that is what you should be using in your program.
I've just had a quick look at esel.at and it doesn't appear to have a (public) API (but maybe that is because Google can't translate the page properly).

Firebird FBConnection losing connectionString

The use of FBConnection is giving me some trouble.
In examples of the Firebird Ole-Db I find only examples using a static main method, but I'm not sure how to implement the use of an FbConnection in instance methods.
Right now I'm initializing and using the connection as shown in the code example below.
Every now and then I get the error "connectionstring is not initialized". The connection object is not null, but the connectionstring seems to be null.
What causes this behaviour? Should I reinitialize the FbConnect object every time I access the method (making it a local variable), or is this performance-wise a very bad idea?
public class MyUserStore<TUser> : IUserPasswordStore<TUser, int>, IUserStore<TUser, int>, IDisposable where TUser : ApplicationUser, new()
{
private FbConnection Connection = new FbConnection("User=-----;" +
"Password=-------;" +
"Database=C:\\------\\Testing.GDB;" +
"DataSource=localhost;" +
"Dialect=3;Charset=NONE;");
public Task<TUser> FindByIdAsync(int userId)
{
if (userId == 0)
{
throw new ArgumentNullException("userId");
}
TUser User = null;
if (Connection != null)
{
FbTransaction transaction = null;
FbDataReader Reader = null;
using (Connection)
{
try
{
Connection.Open();
FbCommand Command = new FbCommand(GetByIdQuery, Connection);
Command.Parameters.AddWithValue("id", userId);
Reader = Command.ExecuteReader();
catch (Exception e)
{
if (transaction != null)
{
transaction.Rollback();
}
System.Diagnostics.Debug.WriteLine(e.StackTrace);
return Task.FromResult<TUser>(null);
}
finally
{
if (Reader != null)
{
Reader.Close();
}
Connection.Close();
}
}
}
}
Mark Rotteveel is right in his comment.
Apparently, the using clause means the resource is being disposed of right at the end of the block. This means I would need to create a new connection every time I use the "using" block.

Why would this query generate a file sharing violation?

The following code gives me the error (I get it from the MessageBox.Show() in the catch block)
"Exception in PopulateBla() : There is a file sharing violation. A
different process might be using the file [,,,,,,]
CODE
using (SqlCeCommand cmd = new SqlCeCommand(SQL_GET_VENDOR_ITEMS, new SqlCeConnection(SQLCE_CONN_STR)))
{
cmd.Parameters.Add("#VendorID", SqlDbType.NVarChar, 10).Value = vendorId;
cmd.Parameters.Add("#VendorItemID", SqlDbType.NVarChar, 19).Value = vendorItemId;
try
{
cmd.Connection.Open();
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (SQLCEReader.Read())
{
itemID = SQLCEReader.GetString(ITEMID_INDEX);
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
}
catch (SqlCeException err)
{
MessageBox.Show(string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message));//TODO: Remove
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
}
SQL_GET_VENDOR_ITEMS is my query string.
What file sharing problem could be happening here?
UPDATE
This is the kind of code that makes that sort of refactoring recommended by ctacke below difficult:
public void setINVQueryItemGroup( string ID )
{
try
{
dynSQL += " INNER JOIN td_item_group ON t_inv.id = td_item_group.id AND t_inv.pack_size = td_item_group.pack_size WHERE td_item_group.item_group_id = '" + ID + "'";
}
catch( Exception ex )
{
CCR.ExceptionHandler( ex, "InvFile.setINVQueryDept" );
}
}
A SQL statement is being appended to by means of a separate method, altering a global var (dynSQL) while possibly allowing for SQL Injection (depending on where/how ID is assigned). If that's not enough, any exception thrown could mislead the weary bughunter due to indicating it occurred in a different method (doubtless the victim of a careless copy-and-paste operation).
This is "Coding Horror"-worthy. How many best practices can you ignore in a scant few lines of code?
Here's another example:
string dynSQL = "SELECT * FROM purgatory WHERE vendor_item = '" + VendorItem + "' ";
if (vendor_id != "")
{
dynSQL += "AND vendor_id = '" + vendor_id + "' ";
}
It could be done by replacing the args with "?"s, but the code to then determine which/how many params to assign would be 42X uglier than Joe Garagiola's mean cleats.
I really like Chris' idea of using a single connection to your database. You could declare that global to your class like so:
public ClayShannonDatabaseClass
{
private SqlCeConnection m_openConnection;
public ClayShannonDatabaseClass()
{
m_openConnection = new SqlCeConnection();
m_openConnection.Open();
}
public void Dispose()
{
m_openConnection.Close();
m_openConnection.Dispose();
m_openConnection = null;
}
}
I'm guessing your code is crashing whenever you attempt to actually open the database.
To verify this, you could stick an integer value in the code to help you debug.
Example:
int debugStep = 0;
try
{
//cmd.Connection.Open(); (don't call this if you use m_openConnection)
debugStep = 1;
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
debugStep = 2;
if (SQLCEReader.Read())
{
debugStep = 3;
itemID = SQLCEReader.GetString(ITEMID_INDEX);
debugStep = 4;
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
debugStep = 5;
recordFound = true;
}
}
}
catch (SqlCeException err)
{
string msg = string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message);
string ttl = string.Format("Debug Step: {0}", debugStep);
MessageBox.Show(msg, ttl); //TODO: Remove
}
// finally (don't call this if you use m_openConnection)
// {
// if (cmd.Connection.State == ConnectionState.Open)
// {
// cmd.Connection.Close();
// }
// }
I'm guessing your error is at Step 1.
Provided the file isn't marked read-only (you checked that, right?), then you have another process with a non-sharing lock on the file.
The isql.exe database browser that comes with SQL CE is a common culprit if it's running in the background.
Depending on your version of SQLCE, it's quite possible that another process has an open connection (can't recall what version started allowing multiple process connections), so if you have any other app in the background that has it open, that may be a problem too.
You're also using a boatload of connections to that database, and they don't always get cleaned up and released immediately up Dispose. I'd highly recommend building a simple connection manager class that keeps a single (or more like two) connections to the database and just reuses them for all operations.

Why an error message 'InvalidOperationException' has been occured

My code as follows:
namespace EntityDAO
{
public static class StudentDAO
{
public static Boolean AddStudent(StudentDTO oDto)
{
string str =System.Configuration.ConfigurationManager.AppSettings["myconn"];
SqlConnection oconnection = new SqlConnection(str);
oconnection.Open();
try
{
string addstring = "insert into STUDENT(ID,NAME)values('"
+ oDto.ID + "','"
+ oDto.NAME + "')";
SqlCommand ocommand = new SqlCommand(addstring,oconnection);
ocommand.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
oconnection.Close();
}
but when I run this program ,an error message has been occured and the error message for oconnection.Open(); and the message is 'InvalidOperationException'(Instance failure).I have tried many times to solve this problem but i did't overcome this problem.so please,anyone help me.
The following is not proposed as a complete solution to your problem, but should help you figure it out:
namespace EntityDAO
{
public static class StudentDAO
{
public static Boolean AddStudent(StudentDTO oDto)
{
var str = ConfigurationManager.AppSettings["myconn"];
using (var oconnection = new SqlConnection(str))
{
oconnection.Open();
try
{
var addstring = string.Format(
"insert into STUDENT(ID,NAME)values('{0}','{1}')", oDto.ID, oDto.NAME);
using (var ocommand = new SqlCommand(addstring, oconnection))
{
ocommand.ExecuteNonQuery();
}
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
}
}
}
}
Don't ever hide exceptions from yourself. Even if the caller of this code wants true or false, make sure you log the details of the exception.
Also, what AYK said about SQL Injection. I'm entering this as CW, so if someone has more time than I do, they should feel free to edit to use parameters.

Crystal Report Connection string from properties.settings winform c#

Is it possible to set the connection string of crystal report from the properties.settings of a winform in c# like the following?
this is just my assumptions
rpt.connectionString = Properties.Settings.Default.ConnectionString
This is my code for managing logins/connectionstrings (dbLogin is just a simple class for storing information, you can replace that with string values).
//Somewhere in my code:
foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdCurrent.Database.Tables)
SetTableLogin(tbCurrent);
//My set login method
private void SetTableLogin(CrystalDecisions.CrystalReports.Engine.Table table)
{
CrystalDecisions.Shared.TableLogOnInfo tliCurrent = table.LogOnInfo;
tliCurrent.ConnectionInfo.UserID = dbLogin.Username;
tliCurrent.ConnectionInfo.Password = dbLogin.Password;
if(dbLogin.Database != null)
tliCurrent.ConnectionInfo.DatabaseName = dbLogin.Database; //Database is not needed for Oracle & MS Access
if(dbLogin.Server != null)
tliCurrent.ConnectionInfo.ServerName = dbLogin.Server;
table.ApplyLogOnInfo(tliCurrent);
}
In case you already have a successfull connectiont to SQL Server, you may use the following static method to set your report connection based on your SqlConnection:
using System.Text;
using CrystalDecisions.Shared;
using System.Data.SqlClient;
namespace StackOverflow
{
public class MyCrystalReports
{
// This method will allow you may easily set report datasource based on your current SqlServerConnetion
public static void SetSqlConnection(CrystalDecisions.CrystalReports.Engine.ReportClass MyReport, SqlConnection MySqlConnection)
{
// You may even test SqlConnection before using it.
SqlConnectionStringBuilder SqlConnectionStringBuilder = new SqlConnectionStringBuilder(MySqlConnection.ConnectionString);
string ServerName = SqlConnectionStringBuilder.DataSource;
string DatabaseName = SqlConnectionStringBuilder.InitialCatalog;
Boolean IntegratedSecurity = SqlConnectionStringBuilder.IntegratedSecurity;
string UserID = SqlConnectionStringBuilder.UserID;
string Password = SqlConnectionStringBuilder.Password;
// Of course, you may add extra settings here :D
// On Crystal Reports, connection must be set individually for each table defined on the report document
foreach (CrystalDecisions.CrystalReports.Engine.Table Table in MyReport.Database.Tables)
{
CrystalDecisions.Shared.TableLogOnInfo TableLogOnInfo = Table.LogOnInfo;
TableLogOnInfo.ConnectionInfo.ServerName = ServerName;
TableLogOnInfo.ConnectionInfo.DatabaseName = DatabaseName;
TableLogOnInfo.ConnectionInfo.IntegratedSecurity = IntegratedSecurity;
if (IntegratedSecurity != true)
{
TableLogOnInfo.ConnectionInfo.UserID = UserID;
TableLogOnInfo.ConnectionInfo.Password = Password;
}
Table.ApplyLogOnInfo(TableLogOnInfo);
}
}
}
}

Categories