Converting a json string to a public ulong - c#

I need to use a string from a json file as an ulong, and then use that varialble in a different class. I tried parsing it to be a uint, but the public ulong is then said to be unused, even though it seems as if it's being used to me. This might be super obvious but I'm new to c#.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinecraftClient
{
class Utilities
{
private static Dictionary<string, string> whitelisted;
static Utilities()
{
string json = File.ReadAllText("whitelists/walls.json");
var data = JsonConvert.DeserializeObject<dynamic>(json);
whitelisted = data.ToObject<Dictionary<string, string>>();
}
public static ulong GetWhitelisted(string key)
{
if (whitelisted.ContainsKey(MinecraftClient.ChatBots.WeeWoo.username))
{
ulong whitelistedid;
bool parsed = UInt64.TryParse(key, out whitelistedid);
}
return 0;
}
public static ulong whitelistedid;
}
}

Inside your if block you are declaring a new variable named whitelistedid (and you're creating a variable named parsed), but they are never used and the method always returns 0.
Instead you probably want to do something like:
public static ulong GetWhitelisted(string key)
{
if (whitelisted.ContainsKey(MinecraftClient.ChatBots.WeeWoo.username))
{
ulong userWhiteListId;
if (UInt64.TryParse(key, out userWhiteListId))
{
// If parsing succeeded, return the value
return userWhiteListId;
}
// Optionally, return some other value if the user was found but parsing failed
// return -1;
}
// Either the user wasn't found or the parsing failed
return 0;
}

It looks to me that rather than having a public static variable you actually just want to return the ulong from your static method. Probably something more like...
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinecraftClient
{
class Utilities
{
private static Dictionary<string, string> whitelisted;
static Utilities()
{
string json = File.ReadAllText("whitelists/walls.json");
var data = JsonConvert.DeserializeObject<dynamic>(json);
whitelisted = data.ToObject<Dictionary<string, string>>();
}
public static ulong GetWhitelisted(string key)
{
if (whitelisted.ContainsKey(MinecraftClient.ChatBots.WeeWoo.username))
{
ulong parsedId;
if (UInt64.TryParse(key, out parsedId))
return parsedId;
}
return 0;
}
}
}
Then to get your whitelist you would do...
var whileListId = Utilities.GetWhiteListed("someKey");

Related

Cannot figure out 'The name does not exist in the current context; Error

I want to assign my program a Guid and use it to pull config data from the SQL server. However, I keep getting the error:
The name 'ApplicationID' does not exist in the current context
I've always struggled with variable declaration. I can usually figure it out, but I'm stuck on this one....
Program.cs creates the ApplicationID, then I call LoadConfig to grab and set the rest of the variables based on that ApplicationID. However when I go to use the ApplicationID in LoadConfig it gives me that error.
I confirmed that if I replaced the ApplicationID with the Guid string it pulls everything as expected.
I also tried adding using ABBAS.ProgC to Config, but that didn't help either.
using System;
using System.Collections.Generic;
using ABBAS.sFTP;
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Reflection;
namespace ABBAS.ProgC {
class Program {
static private Guid processid;
static private SftpClient sftpc;
static private sFTPFiles sFTPFiles;
static public Guid ApplicationID = new Guid("d71b536f-1428-4797-95e6-3948e736fcca");
static async Task Main() {
ManualResetEvent exitEvent = new(false);
TaskCompletionSource tcs = new();
Console.WriteLine($"Program Starting at {DateTime.Now}");
Console.WriteLine($"Process id: {Environment.ProcessId}");
programversion = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion;
Console.WriteLine($"Version: {programversion}");
Config.LoadConfig();
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thinktecture.IdentityModel.Client;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using ABBASLibrary.Configuration;
using System.Text.Json;
using System.Data;
namespace ABBAS {
static public partial class Config {
// Environmental Variables
static public int ConfigurationID;
//Global Variables
static public string sFTPServer;
static public string sFTPServerUID;
static public string sFTPServerPWD;
static public int sFTPServerPort;
static public int sFTPRetryMax;
static public int sFTPConnectDelayMin;
static public int sFTPConnectDelayMax;
static public void LoadConfig() {
using (SqlConnection _sqlconn = new SqlConnection())
{
_sqlconn.ConnectionString = sqlconnstring;
_sqlconn.Open();
SqlDataAdapter da;
DataSet ds = new DataSet();
string varName;
string varValue;
int newNum;
bool isParsable;
try
{
String query = "SELECT * FROM [ConfigurationDetails] WHERE [ApplicationID] = " + ApplicationID;
da = new SqlDataAdapter(query, _sqlconn);
da.Fill(ds);
for (int cnt = 0; cnt < ds.Tables[0].Rows.Count; cnt++)
{
varName = "";
varValue = "";
varName = ds.Tables[0].Rows[cnt][4].ToString(); // VariableName
varValue = ds.Tables[0].Rows[cnt][5].ToString(); // VariableValue
if (varName.ToString() == "sFTPServer")
sFTPServer = varValue;
if (varName.ToString() == "sFTPServerUID")
sFTPServerUID = varValue;
if (varName.ToString() == "sFTPServerPWD")
sFTPServerPWD = varValue;
if (varName.ToString() == "P21CompanyID")
P21CompanyID = varValue;
if (varName.ToString() == "sFTPServerPort")
{
isParsable = Int32.TryParse(varValue, out newNum);
if (isParsable)
sFTPServerPort = newNum;
}
if (varName.ToString() == "sFTPRetryMax")
{
isParsable = Int32.TryParse(varValue, out newNum);
if (isParsable)
sFTPRetryMax = newNum;
}
if (varName.ToString() == "sFTPConnectDelayMin")
{
isParsable = Int32.TryParse(varValue, out newNum);
if (isParsable)
sFTPConnectDelayMin = newNum;
}
if (varName.ToString() == "sFTPConnectDelayMax")
{
isParsable = Int32.TryParse(varValue, out newNum);
if (isParsable)
sFTPConnectDelayMax = newNum;
}
}
}
catch (Exception ex)
{
_sqlconn.Close();
}
finally
{
if (_sqlconn != null)
_sqlconn.Dispose();
if (ds != null)
ds.Dispose();
}
}
}
}
}
The original idea (not mine!) was to create the variable in Config, and they set it in Program.cs, but since we are calling LoadConfig and need the variable set to get the rest of our variables that clearly won't work.
Because it doesn't exist in that context. It's declared as a static member of the Program class:
class Program {
//...
static public Guid ApplicationID = new Guid("d71b536f-1428-4797-95e6-3948e736fcca");
To access it you'd need to reference it statically from that class:
String query = "SELECT * FROM [ConfigurationDetails] WHERE [ApplicationID] = " + Program.ApplicationID;
Note that there are a few anti-patterns in your code. Including, but not limited to:
Making everything static is going to drastically increase complexity and the potential for bugs. (You've already encountered a problem with it here in this question.) This is generally the approach when developers want "global variables" for everything. It sounds nice at first, because that way you always have access to everything and can use what you want when you want. But it quickly becomes problematic because you always have access to everything and can't effectively isolate any of the code into meaningful components.
Silently ignoring exceptions is going to make it very difficult to identify, diagnose, and correct problems. At the very least there should be some logging or output of exception information.

Formating a string (mask?)

I found that with long.Parse, ToString can take argument and I can format it to desired string, for example.
Input:
Console.WriteLine(long.Parse("123").ToString("#-#-#"));
Output:
1-2-3
I wanted to do something similar with string, lets say I wanna parse string to format ####-###-####. Is there any way to do it without regex with one liner like example above?
EDIT
Ok, so I may be misunderstood, I didn't want to parse numbers, but string instead. I can do in python like:
'{}-{}-{}'.format(*'abc') and I will receive a-b-c. In C# it seems to work only with numbers.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.WriteLine("helloWorld".ToPhoneNumber("###-###-####"));
}
}
public static class AdvancedFormatString
{
public static string ToPhoneNumber(this string strArg, string outputformat)
{
if (outputformat == null)
return strArg;
var sb = new StringBuilder();
var i = 0;
foreach (var c in outputformat)
{
if (c == '#')
{
if (i < strArg.Length)
{
sb.Append(strArg[i]);
}
i++;
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}

Unable to use ICollection.ToList()

I am trying to call ToList() here:
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace CSVStuff
{
public static class CSVContentGenerator
{
public static string GetContent(IOrderedDictionary headingsPropertiesMapping)
{
var propertyNames = headingsPropertiesMapping.Keys.ToList(); //ICollection does not contain a definition for ToList()
//var propertyNames = new List<object>(headingsPropertiesMapping.Keys); //Cannot convert from ICollection to int
return "";
}
}
}
Why are these not working?
Try this:
var propertyNames = headingsPropertiesMapping.Keys.Cast<T>().ToList();
and type T is the type of dictionary keys.

Finding a word on a dictionary in a string C# and the value of that word

Right now I have this code which checks if a string has a any word in a dictionary:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PlayerIOClient;
public static Connection conn;
public static Client client;
public static Dictionary<int, string> users = new Dictionary<int, string>();
public static Dictionary<string, string> corList = new Dictionary<string, string>();
public bool isConnected;
static void OnMessage(object sender, PlayerIOClient.Message m)
{
if (m.Type == "init")
{
conn.Send("access", wldcode);
conn.Send("init2");
corList.Add("hes", "he's"); //Example of one item on the list.
conn.Send("say", "Grammar fixer bot connected. Repare to be corrected.");
}
if (m.Type == "add")
{
users.Add(m.GetInt(0), m.GetString(1));
}
if (m.Type == "left")
{
users.Remove(m.GetInt(0));
}
if (m.Type == "say")
{
if (users.ContainsKey(m.GetInt(0)))
{
string username = users[m.GetInt(0)];
if (corList.Keys.Any(m.GetString(1).Contains)) //Problem is here.
{ //m.GetString(1) Are usually long strings, such as sentences.
conn.Send("say", "Grammar Fixer: " + corList[]);
}
}
}
}
However, I am not able to get the specific key that was detected in the word or the value of this key. This dictionary is also going to hold a lot of definitions, so just having the if then for one specific word will not work.
var key = m.GetString(1);
string correction = null;
if (corList.TryGetValue(key, out correction))
{
conn.Send("say", string.format("Grammar Fixer: {0}, not {1}!", correction, key));
}
Hard to say without seeing what corList is or what m.GetString(1).Contains is. So I have to do a lot of guessing about what you want to do, but you can try this:
var key = m.GetString(1);
if (corList.Keys.Any(key))
{
conn.Send("say", string.format("Grammar Fixer: {0}, not {1}!", corList[key], key));
}

Pass data to nunit testcase

How pass data from the testrunner to the unittest?
For example an output path or interface configuration of the host machine?.
You may have already gone done a different path at tis point but I though I would share this. In post 2.5 versions of NUnit the ability to drive test cases in a via an external source was implemented. I did a demo of a simple example using a CSV file.
The CSV was something that contained my two test inputs and the expected result. So 1,1,2 for the first and so on.
CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace NunitDemo
{
public class AddTwoNumbers
{
private int _first;
private int _second;
public int AddTheNumbers(int first, int second)
{
_first = first;
_second = second;
return first + second;
}
}
[TestFixture]
public class AddTwoNumbersTest
{
[Test, TestCaseSource("GetMyTestData")]
public void AddTheNumbers_TestShell(int first, int second, int expectedOutput)
{
AddTwoNumbers addTwo = new AddTwoNumbers();
int actualValue = addTwo.AddTheNumbers(first, second);
Assert.AreEqual(expectedOutput, actualValue,
string.Format("AddTheNumbers_TestShell failed first: {0}, second {1}", first,second));
}
private IEnumerable<int[]> GetMyTestData()
{
using (var csv = new StreamReader("test-data.csv"))
{
string line;
while ((line = csv.ReadLine()) != null)
{
string[] values = line.Split(',');
int first = int.Parse(values[0]);
int second = int.Parse(values[1]);
int expectedOutput = int.Parse(values[2]);
yield return new[] { first, second, expectedOutput };
}
}
}
}
}
Then when you run it with the NUnit UI it looks like (I included a failure for example purposes:

Categories