So, when I connected, or attempt, it runs this code in Database.cs.
Also, I'm using SmartIRC4Net for IRC handling
Now I know this is the error because Init() in Database.cs doesn't even run! If it is, it doesn't create the "trubot.sqlite" file with the tables.
I have no idea why it's doing it, but it is.
Here's the Database.cs code:
public void Init(){
try {
if (File.Exists("trubot.sqlite")) {
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
} else {
SQLiteConnection.CreateFile("trubot.sqlite");
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
}
} catch (Exception s) {
Console.WriteLine("[ERROR] Error in code. " + s.Message);
}
}
public void addUser(String user) {
// add new user
try {
if (!usrExist(user)) {
String db = "INSERT INTO '"+chan+"' (user) VALUES ('"+user+"');";
using (query = new SQLiteCommand(db,dbf)) {
query.ExecuteNonQuery();
}
}
} catch (Exception err) {
Console.WriteLine("addUser is causing an error: " + err.Message);
}
}
and here's the other reason it crashes (which is in Program.cs)
public static void OnJoined(object sender, JoinEventArgs e) {
try {
var conf = new Config();
var db = new Database();
Console.WriteLine("[SELF] ["+conf.Channel+"] > *** "+e.Data.Nick+" has joined the channel!");
if (!db.usrExist(e.Data.Nick)) {
try {
db.addUser(e.Data.Nick);
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
Side note: I'd use MySQL but I need this application to be as portable as possible and run on as many operating systems as possible. I'd rather use SQLite than MSSQL or MySQL.
I fixed it. The problem was when I assigned the channel to the SQL as a Table Name, I needed to remove the "#" from it. So here's the resulting code:
public Database() {
var conf = new Config();
chan = conf.Channel.Replace("#","");
Init();
}
Related
I'm using Mangement class to create a process, but That starts a UI console - I want to console to run in background.
public uint LaunchProcess(string sIPAddress, string sPort)
{
uint iPid = 0;
try
{
logger.AddLog("LaunchProcess : " + sIPAddress + " " + sPort);
object[] PlugInRunnerInfo = { StaticUtils.GetLocation(AgilentPluginCommonConstants.PlugInRunnerPath) + "\\" + "PlugInRunner.exe" + " " + sIPAddress + " " + sPort, null, null, 0 };
//ManagementClass is a part of Windows Management Intrumentation,namespaces. One of its use is to provides access to manage applications.
//Here this class is used to launch PlugInRunner as detached process.By setting the ManagementClass object's property 'CreateFlags' to value 0x00000008
//we can start the PlugInRunner as detached one.
using (var mgmtObject = new ManagementClass("Win32_Process"))
{
var processStartupInfo = new ManagementClass("Win32_ProcessStartup",null);
processStartupInfo.Properties["CreateFlags"].Value = 0x00000008;//DETACHED_PROCESS.
var result = mgmtObject.InvokeMethod("Create", PlugInRunnerInfo);
if (result != null)
{
logger.AddLog("Process id " + Convert.ToUInt32(PlugInRunnerInfo[3]));
iPid = Convert.ToUInt32(PlugInRunnerInfo[3]);
}
}
}
catch (Exception ex)
{
logger.AddLog("Exception " + ex.Message);
}
return iPid;
}
The above code what I have got. Please help me.
I am fairly new at trying to get data from CRM using C#, I am trying to get the display names of all of my attribute on CRM, When I try, I am getting a result of Microsoft.Xrm.Sdk.Label and it doesn't seem to straight forward to get the value of that label, could someone point me in the right direction?
using System;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace CRM_MetaData_Download
{
class Program
{
static void Main(string[] args)
{
try {
var connectionString = #"AuthType = Office365; Url = https://CRMINFORMATION";
CrmServiceClient conn = new CrmServiceClient(connectionString);
IOrganizationService service;
service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = "account"
};
RetrieveEntityResponse retrieveAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
EntityMetadata AccountEntity = retrieveAccountEntityResponse.EntityMetadata;
Console.WriteLine("Account entity attributes:");
foreach (object attribute in AccountEntity.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
Console.WriteLine(a.LogicalName + " " +
a.Description + " " +
a.DisplayName + " " +
a.EntityLogicalName + " " +
a.SchemaName + " " +
a.AttributeType + " "
);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
Since Dynamics CRM supports multi-lingual capabilities, the display name label will be stored for each language. You can get it like below:
a.DisplayName.UserLocalizedLabel.Label
this is my first question in here.
So I have this app that connects to a remote database using Npgsql library.
I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.
Sorry about my english
public static NpgsqlConnection ConnectRemote()
{
try
{
remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
"Port = " + remoteData.port + "; " +
"User Id = " + remoteData.user + "; " +
"Password = " + remoteData.password + "; " +
"Database = " + remoteData.dataBase + "; ");
remoteConnection.Open();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
public static bool CheckRemote()
{
if (remoteConnection != null)
{
if (remoteConnection.FullState.Equals(ConnectionState.Open))
return true;
return false;
}
return false;
}
public bool AddNewProduct(Product product)
{
try
{
DBManager.ConnectLocal();
DBManager.ConnectRemote();
object[] parameters;
if (DBManager.CheckRemote())
{
if (!DBManager.isSyncronized)
{
DBManager.Syncronize();
}
parameters = new object[8];
parameters[0] = 1;
parameters[1] = product.id;
parameters[2] = product.description;
parameters[3] = (decimal)product.salePrice;
parameters[4] = (decimal)product.cost;
parameters[5] = product.minStock;
parameters[6] = product.providerName;
parameters[7] = product.category;
DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
}
else
{
string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
+ (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
parameters = new object[1];
parameters[0] = sql;
DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);
DBManager.isSyncronized = false;
}
parameters = new object[6];
parameters[0] = product.description;
parameters[1] = (decimal)product.salePrice;
parameters[2] = (decimal)product.cost;
parameters[3] = product.minStock;
parameters[4] = product.providerName;
parameters[5] = product.category;
DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
DBManager.DisconnectLocal();
DBManager.DisconnectRemote();
return true;
}
catch (Npgsql.NpgsqlException ex)
{
return false;
}
}
A few things -- one unrelated, and two related. I am hopeful that some combination of these will help.
First, the unrelated comment. The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings. I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query. Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.
If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database. If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused. Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.
If this doesn't work, try a trivial query. The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.
All three suggestions are reflected here:
public static NpgsqlConnection ConnectRemote()
{
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.ApplicationName = "Connection Tester";
sb.Host = remoteData.server;
sb.Port = remoteData.port;
sb.Username = remoteData.user;
sb.Password = remoteData.password;
sb.Database = remoteData.database;
sb.Pooling = false;
remoteConnection = new NpgsqlConnection(sb.ToString());
try
{
remoteConnection.Open();
NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
test.ExecuteScalar();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
So i am making an application which can open connections to remote devices and execute different commands. So yesterday before i left work i was debugging when i got an error. But as my application ignored it and proceeded and having not enough time to fix it immedietly i decided to do it today. When i wanted to make connection with my program again it said it couldn't authenticate (note* the parameters did not change).
So i did some checks to determine the problem, after logging in on the server and running netstat i found out that there was an active connection to port 22, which originated from my application.
Somehow the connection did not show up in my SSH manager until i rebooted it TWICE.
So to prevent things like this in a production environment, how do i prevent things like this.
my Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
my executeCommand class:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand )
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
and my class where i make conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
Note* i have not included my XMLParser class because it is not relevant to the question, nor does it have any connections regarding SSH in general.
EDIT
i found out i had compiled the application and it was running in the commandline. Turns out there is no error with the code
I have a static dictionary that i create globally. I declare it like this =>
static Dictionary<int, Artikels> dicArtikels = new Dictionary<int, Artikels>();
Artikels is a class i have created to store the products.
for (int rijenTeller = 0; rijenTeller < aantalRijen; rijenTeller++)
{
Artikels artikel = new Artikels();
if (dicArtikels.ContainsKey(rijenTeller))
{
artikel = dicArtikels[rijenTeller];
}
else
{
dicArtikels.Add(rijenTeller, artikel);
}
artikel.naam = txtNameInstance.Text;
artikel.prijs = txtPriceInstance.Text;
dicArtikels[rijenTeller] = artikel;
artikel = null;
}
Well when i print the output with a button like below it's always showing the value of the last instance. That't not what i want. I want the value of the seperate instances but they are always getting the same value. =>
protected void Button3_Click(object sender, EventArgs e)
{
try
{
Artikels artikel = new Artikels();
artikel = dicArtikels[0];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[3];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[1];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[2];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
}
catch (Exception ex)
{
Response.Write("Foutbericht Artikelchangedssssssss: " + ex.Message);
}
}