Why is my static dictionary not initialising? [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am using a big dictionary I want to only be created once to store some information along with a static function to extract info from it like so:
public static class AceMimeInfo
{
static Dictionary<string, Info> mimedictionary = new Dictionary<string, Info>
{
{".abap", new Info("abap", "ABAP")},
{".asciidoc", new Info("asciidoc", "AsciiDoc")},
{".c9search_results", new Info("c9search", "C9Search")},
{".coffee", new Info("coffee", "CoffeeScript")},
{".cf", new Info("coffee", "CoffeeScript")},
{".xul", new Info("xml", "XML")},
{".xbl", new Info("xml", "XML")},
{".xq", new Info("xquery", "XQuery")},
{".yaml", new Info("yaml", "YAML")}
};
public class Info
{
public string Mode;
public string Name;
public Info(string mode, string name)
{
Mode = mode;
Name = name;
}
}
public static string GetMode(string fileext)
{
string fe;
fe = fileext.ToLower();
if(!fe.StartsWith("."))
fe = "." + fe;
if (mimedictionary.ContainsKey(fe))
return mimedictionary[fe].Mode;
return "";
}
}
However when I step through GetMode with the debugger, the dictionary mimedictionary is always null.
What do I need to do to make sure this isn't the case?
Any suggestions as to a better way of doing this would also be appreciated.
I am calling GetMode this like so:
string mode = AceMimeInfo.GetMode("filename.cpp");
Thanks in advance
Update:
I tried the above code and it does indeed work. The dictionary above is a shorter version of what I am actually using (because it's quite long).
Here is the actual class I am using - and it doesn't work. When I shorten the dictionary, it does work.
public static class AceMimeInfo
{
static Dictionary<string, Info> mimedictionary = new Dictionary<string, Info>
{
{".abap", new Info("abap", "ABAP")},
{".asciidoc", new Info("asciidoc", "AsciiDoc")},
{".c9search_results", new Info("c9search", "C9Search")},
{".coffee", new Info("coffee", "CoffeeScript")},
{".cf", new Info("coffee", "CoffeeScript")},
{".cfm", new Info("coldfusion", "ColdFusion")},
{".cs", new Info("csharp", "C#")},
{".css", new Info("css", "CSS")},
{".dart", new Info("dart", "Dart")},
{".diff", new Info("diff", "Diff")},
{".patch", new Info("diff", "Diff")},
{".dot", new Info("dot", "Dot")},
{".glsl", new Info("glsl", "Glsl")},
{".frag", new Info("glsl", "Glsl")},
{".vert", new Info("glsl", "Glsl")},
{".go", new Info("golang", "Go")},
{".groovy", new Info("groovy", "Groovy")},
{".hx", new Info("haxe", "Haxe")},
{".haml", new Info("haml", "HAML")},
{".htm", new Info("html", "HTML")},
{".html", new Info("html", "HTML")},
{".xhtml", new Info("html", "HTML")},
{".c", new Info("c_cpp", "C/C++")},
{".cc", new Info("c_cpp", "C/C++")},
{".cpp", new Info("c_cpp", "C/C++")},
{".cxx", new Info("c_cpp", "C/C++")},
{".h", new Info("c_cpp", "C/C++")},
{".hh", new Info("c_cpp", "C/C++")},
{".hpp", new Info("c_cpp", "C/C++")},
{".clj", new Info("clojure", "Clojure")},
{".jade", new Info("jade", "Jade")},
{".java", new Info("java", "Java")},
{".jsp", new Info("jsp", "JSP")},
{".js", new Info("javascript", "JavaScript")},
{".json", new Info("json", "JSON")},
{".jsx", new Info("jsx", "JSX")},
{".latex", new Info("latex", "LaTeX")},
{".tex", new Info("latex", "LaTeX")},
{".ltx", new Info("latex", "LaTeX")},
{".bib", new Info("latex", "LaTeX")},
{".less", new Info("less", "LESS")},
{".lisp", new Info("lisp", "Lisp")},
{".scm", new Info("lisp", "Lisp")},
{".rkt", new Info("lisp", "Lisp")},
{".liquid", new Info("liquid", "Liquid")},
{".lua", new Info("lua", "Lua")},
{".lp", new Info("luapage", "LuaPage")},
{".lucene", new Info("lucene", "Lucene")},
{".make", new Info("makefile", "Makefile")},
{".md", new Info("markdown", "Markdown")},
{".markdown", new Info("markdown", "Markdown")},
{".m", new Info("objectivec", "Objective-C")},
{".ml", new Info("ocaml", "OCaml")},
{".mli", new Info("ocaml", "OCaml")},
{".pl", new Info("perl", "Perl")},
{".pm", new Info("perl", "Perl")},
{".pgsql", new Info("pgsql", "pgSQL")},
{".php", new Info("php", "PHP")},
{".phtml", new Info("php", "PHP")},
{".ps1", new Info("powershell", "Powershell")},
{".py", new Info("python", "Python")},
{".r", new Info("r", "R")},
{".Rd", new Info("rdoc", "RDoc")},
{".Rhtml", new Info("rhtml", "RHTML")},
{".ru", new Info("ruby", "Ruby")},
{".gemspec", new Info("ruby", "Ruby")},
{".rake", new Info("ruby", "Ruby")},
{".rb", new Info("ruby", "Ruby")},
{".scad", new Info("scad", "OpenSCAD")},
{".scala", new Info("scala", "Scala")},
{".scss", new Info("scss", "SCSS")},
{".sass", new Info("scss", "SCSS")},
{".sh", new Info("sh", "SH")},
{".bash", new Info("sh", "SH")},
{".bat", new Info("sh", "SH")},
{".sql", new Info("sql", "SQL")},
{".styl", new Info("stylus", "Stylus")},
{".stylus", new Info("stylus", "Stylus")},
{".svg", new Info("svg", "SVG")},
{".tcl", new Info("tcl", "Tcl")},
{".tex", new Info("tex", "Tex")},
{".txt", new Info("text", "Text")},
{".textile", new Info("textile", "Textile")},
{".typescript", new Info("typescript", "Typescript")},
{".ts", new Info("typescript", "Typescript")},
{".str", new Info("typescript", "Typescript")},
{".xml", new Info("xml", "XML")},
{".rdf", new Info("xml", "XML")},
{".rss", new Info("xml", "XML")},
{".wsdl", new Info("xml", "XML")},
{".xslt", new Info("xml", "XML")},
{".atom", new Info("xml", "XML")},
{".mathml", new Info("xml", "XML")},
{".mml", new Info("xml", "XML")},
{".xul", new Info("xml", "XML")},
{".xbl", new Info("xml", "XML")},
{".xq", new Info("xquery", "XQuery")},
{".yaml", new Info("yaml", "YAML")}
};
public class Info
{
public string Mode;
public string Name;
public Info(string mode, string name)
{
Mode = mode;
Name = name;
}
}
public static string GetMode(string fileext)
{
string fe;
fe = fileext.ToLower();
if(!fe.StartsWith("."))
fe = "." + fe;
if (mimedictionary.ContainsKey(fe))
return "ace/mode/" + mimedictionary[fe].Mode;
return "";
}
}
Debugger output:
{"The type initializer for 'TestApp.AceMimeInfo' threw an exception."}
Update II: Where's the repeated key?

You are adding a key to your dictionary more than once, which is causing the static initializer to throw an exception. You can determine this by examining the InnerException property of the exception that is thrown.

This is most likely just a debugger artifact. The runtime may delay initialization of static fields until they're actually needed. Just viewing the field in the debugger doesn't trigger that initialization, so the debugger can observe uninitialized fields which the program itself doesn't observe.
If your class has a static constructor, it's even forced to delay all static initialization until you either instantiate the class, access a static field, or call a static method.
I'm pretty sure that your code won't see mimedictionary == null. You can add a Debug.Assert(mimedictionary!=null) and you'll see that it doesn't get triggered.
Another possibility that can cause trouble is building some circular calls in your initializer. But your code as posted doesn't have this property.

I cannot reproduce the problem. The dictionary is filled and contains 9 entries in my tests. The problem is your argument "filename.cpp" that is not a key in the dictionary. And ".cpp" is not contained either. It works if you call with ".cf" for instance.
Use this code if you want to apply it to filenames as well:
public static string GetMode(string fileOrExt)
{
string ext = System.IO.Path.GetExtension(fileOrExt);
if (ext == String.Empty) {
ext = fileOrExt;
if (!ext.StartsWith(".")) {
ext = "." + ext;
}
}
Info info;
if (mimedictionary.TryGetValue(ext, out info)) {
return info.Mode;
}
return "-";
}

I would suggest you create a static constructor and initialize all your static types there like in the following example:
public class AcmeMimeInfo
{
private static List<string> list;
static AcmeMimeInfo()
{
list = new List<string>();
}
}

Related

How to Use FontFamily in a concise manner

I'm new to C# programming and I have a function involving FontFamily. The code seems to work fine but I wanted it written in a more concise manner.
I searched online but seems unable to get the right solution. The following code is what I currently have.
public FontFamily[] FontFamilyExt()
{
FontFamily[] f =
{new FontFamily(_fnt[0]),
new FontFamily(_fnt[1]),
new FontFamily(_fnt[2]),
new FontFamily(_fnt[3]),
new FontFamily(_fnt[4]),
new FontFamily(_fnt[5]),
new FontFamily(_fnt[6]),
new FontFamily(_fnt[7]),
new FontFamily(_fnt[8]),
new FontFamily(_fnt[9]),
new FontFamily(_fnt[10]),
new FontFamily(_fnt[11]),
new FontFamily(_fnt[12]),
new FontFamily(_fnt[13]),
new FontFamily(_fnt[14]),
new FontFamily(_fnt[15]),
new FontFamily(_fnt[16]),
new FontFamily(_fnt[17]),
new FontFamily(_fnt[18]),
new FontFamily(_fnt[19]),
new FontFamily(_fnt[20]),
new FontFamily(_fnt[21]),
new FontFamily(_fnt[22]),
new FontFamily(_fnt[23]),
new FontFamily(_fnt[24]),
new FontFamily(_fnt[25]),
new FontFamily(_fnt[26]),
new FontFamily(_fnt[27]),
new FontFamily(_fnt[28]),
new FontFamily(_fnt[29]),
new FontFamily(_fnt[30]),
new FontFamily(_fnt[31])
};
return f;
}
I am looking for something that works similarly but uses less codes. Thank you in advance.
You could use a loop as recommended. You could also use Enumerable.Range, which basically creates a loop under the covers, but will put the code into one line. Something like:
using System.Linq;
public FontFamily[] FontFamilyExt()
{
return Enumerable.Range(0, 32).Select(x => new FontFamily(_fnt[x])).ToArray();
}
You can try this:
public FontFamily[] FontFamilyExt()
{
FontFamily[] f = new FontFamily[32];
for ( int index = 0; index <= 31; index++ )
f[index] = new FontFamily(_fnt[index]);
return f;
}

c# CodeDOM - Initialize array

I'm trying to create a simple dll runtime, using CodeDOM.
I have quite understand what I need to finish this simple test application.
I need to create with CodeDOM object this statement:
List<string> test = new List<string>() {"A", "B", ... }
I'm just having this statement for declaration of a List of n values, but find nowhere the instructions for reach what I need.
This is my actual code:
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeNamespace samples = new CodeNamespace("ClassLibrary1");
compileUnit.Namespaces.Add(TestNamespace);
samples.Imports.Add(new CodeNamespaceImport("System"));
samples.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
samples.Imports.Add(new CodeNamespaceImport("System.Text"));
CodeTypeDeclaration _class = new CodeTypeDeclaration("TestClass");
CodeMemberField _field = new CodeMemberField();
_field.Attributes = MemberAttributes.Private;
_field.Name = "_testMember";
_field.Type = new CodeTypeReference(typeof(List<string>));
//This is where I cannot understand how to insert the values
_field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(List<string>)), new CodePrimitiveExpression(64));
class1.Members.Add(_field);
How to initialize a list (or an array) with some default values?
Thank you in advance.
As suggested, the answer lies in CodeArrayCreateExpression.
Here is the completed (working) code snippet:
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeNamespace samples = new CodeNamespace("ClassLibrary1");
compileUnit.Namespaces.Add(samples);
samples.Imports.Add(new CodeNamespaceImport("System"));
samples.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
samples.Imports.Add(new CodeNamespaceImport("System.Text"));
CodeTypeDeclaration _class = new CodeTypeDeclaration("TestClass");
CodeMemberField _field = new CodeMemberField();
_field.Attributes = MemberAttributes.Private;
_field.Name = "_testMember";
_field.Type = new CodeTypeReference(typeof(List<string>));
var initialiseExpression = new CodeArrayCreateExpression(
new CodeTypeReference(typeof(string)),
new CodePrimitiveExpression("A"),
new CodePrimitiveExpression("B"),
new CodePrimitiveExpression("C"));
_field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(List<string>)), initialiseExpression);
_class.Members.Add(_field);
The important part is the new initialiseExpression variable that defines the array.

Nesting XML Tags using Linq with Data From DB

I am trying to build an XML document using Linq, XElement and data from Database,
It's working kinda, but in my XML, I want to close the tag and start a new tag and get the results from the query to populate into for the Tag, it is complaining that my variable r in the tag is unresolved, how can I make this work, or is there a better way of building the XML. All the child elements should be under the parent , having two children and , which has their own set of children.
Here is the code below
public void GenerateXML(int id, string site, string state, string country, string bFn, string bLn, string sFn, string sLn)
{
var results = (from o in _db.Orders
where o.OrderId == id
select o).ToList();
var xmlDoc = new XElement("Order",
from r in results
select
new XElement("OrderHeader",
new XElement("SiteId", site),
new XElement("OrderId", r.OrderId),
new XElement("Time", r.OrderDate.Value),
new XElement("Subtotal", r.SubTotal),
new XElement("Shipping", ""),
new XElement("SalesTax", r.SalesTax),
new XElement("Total", r.Total),
new XElement("PaymentAmount", ""),
new XElement("PaymentMethod", ""),
new XElement("ArchiTypeAcctNum", "20001"),
new XElement("TaxExempt", r.TaxExempt),
new XElement("SpecialInstructions", r.SpecialInstructions),
new XElement("BillTo",
new XElement("BillEmail", r.BillToEmail),
new XElement("FirstName", bFn),
new XElement("LastName", bLn),
new XElement("CompanyName", r.BillCompany),
new XElement("Address1", r.BillToAddress),
new XElement("City", r.BillToCity),
new XElement("State", state),
new XElement("Country", country),
new XElement("Zip", r.BillToZip),
new XElement("Phone", r.BillToPhoneNumber)),
new XElement("ShipTo",
new XElement("FirstName", sFn),
new XElement("LastName", sLn),
new XElement("CompanyName", r.ShipCompany),
new XElement("Address1", r.ShipToAddress),
new XElement("City", r.ShipToCity),
new XElement("State", state),
new XElement("Country", country),
new XElement("Zip", r.ShipToZip),
new XElement("Phone", r.ShipToPhoneNumber))),
new XElement("Items",
from i in r.Items
select new XElement("Item",
new XElement("SKU", i.SkuNumber),
new XElement("PROD_Name", i.ProductName),
new XElement("Description", i.Description),
new XElement("Attributes", i.Attributes),
new XElement("Quantity", i.Quantity),
new XElement("UnitPrice", i.UnitPrice),
new XElement("InkColor", i.InkColor)))
);
xmlDoc.Save(Server.MapPath(#"~/Xml/Orders.xml"));
RedirectToAction("Save");
}
I wrote an extension for same purpose. I think much easier . you can just use as orders.EntityToXml();
public static class XmlExtensions
{
public static bool EntityToXml<T>(this T entity, string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
var dir = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(dir))
{
throw new ArgumentNullException(nameof(filePath));
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var serializer= new System.Xml.Serialization.XmlSerializer(typeof(T));
using (var stream = new StreamWriter(filePath))
{
serializer.Serialize(stream , entity);
return true;
}
}
}

Getting Country Calling Code in .NET Framework

In my program I need to get currency symbol and country calling code for specific countries.
I can get currency symbol from RegionInfo class
new RegionInfo(abbreviation).CurrencySymbol
But I cannot find a way to get country calling code from .NET Framework.
Years too late for the original poster, but if someone stumbles across this & wants a bit of code to save creating themselves a list of dial codes from Wikipedia, an open source project (of mine) has this C# file:
https://github.com/mcshaz/SimPlanner/blob/master/SP.DTOs/ProcessBreezeRequests/ISO3166.cs
public List<CountryTelCode> TelCodes { get; set; }
//*****************************************************************
public class CountryTelCode
//*****************************************************************
{
public string Pfx { get; set; }
public string Iso { get; set; }
public int Priority { get; set; }
public CountryTelCode(string pfx, string iso, int priority = 0)
{
Pfx = pfx;
Iso = iso;
Priority = priority;
}
}
//-----------------------------------------------------------------
public void InitTelCodes()
//-----------------------------------------------------------------
{
TelCodes = new List<CountryTelCode>
{
new CountryTelCode("+93", "AF"),
new CountryTelCode("+355", "AL"),
new CountryTelCode("+213", "DZ"),
new CountryTelCode("+1-684", "AS"),
new CountryTelCode("+376", "AD"),
new CountryTelCode("+244", "AO"),
new CountryTelCode("+1-264", "AI"),
new CountryTelCode("+672", "AQ"),
new CountryTelCode("+1-268", "AG"),
new CountryTelCode("+54", "AR"),
new CountryTelCode("+374", "AM"),
new CountryTelCode("+297", "AW"),
new CountryTelCode("+61", "AU"),
new CountryTelCode("+43", "AT"),
new CountryTelCode("+994", "AZ"),
new CountryTelCode("+1-242", "BS"),
new CountryTelCode("+973", "BH"),
new CountryTelCode("+880", "BD"),
new CountryTelCode("+1-246", "BB"),
new CountryTelCode("+375", "BY"),
new CountryTelCode("+32", "BE"),
new CountryTelCode("+501", "BZ"),
new CountryTelCode("+229", "BJ"),
new CountryTelCode("+1-441", "BM"),
new CountryTelCode("+975", "BT"),
new CountryTelCode("+591", "BO"),
new CountryTelCode("+387", "BA"),
new CountryTelCode("+267", "BW"),
new CountryTelCode("+55", "BR"),
new CountryTelCode("+246", "IO"),
new CountryTelCode("+1-284", "VG"),
new CountryTelCode("+673", "BN"),
new CountryTelCode("+359", "BG"),
new CountryTelCode("+226", "BF"),
new CountryTelCode("+257", "BI"),
new CountryTelCode("+855", "KH"),
new CountryTelCode("+237", "CM"),
new CountryTelCode("+1", "CA"),
new CountryTelCode("+238", "CV"),
new CountryTelCode("+1-345", "KY"),
new CountryTelCode("+236", "CF"),
new CountryTelCode("+235", "TD"),
new CountryTelCode("+56", "CL"),
new CountryTelCode("+86", "CN"),
new CountryTelCode("+61", "CX"),
new CountryTelCode("+61", "CC"),
new CountryTelCode("+57", "CO"),
new CountryTelCode("+269", "KM"),
new CountryTelCode("+682", "CK"),
new CountryTelCode("+506", "CR"),
new CountryTelCode("+385", "HR"),
new CountryTelCode("+53", "CU"),
new CountryTelCode("+599", "CW"),
new CountryTelCode("+357", "CY"),
new CountryTelCode("+420", "CZ"),
new CountryTelCode("+243", "CD"),
new CountryTelCode("+45", "DK"),
new CountryTelCode("+253", "DJ"),
new CountryTelCode("+1-767", "DM"),
new CountryTelCode("+1-809", "DO"),
new CountryTelCode("+1-829", "DO"),
new CountryTelCode("+1-849", "DO"),
new CountryTelCode("+670", "TL"),
new CountryTelCode("+593", "EC"),
new CountryTelCode("+20", "EG"),
new CountryTelCode("+503", "SV"),
new CountryTelCode("+240", "GQ"),
new CountryTelCode("+291", "ER"),
new CountryTelCode("+372", "EE"),
new CountryTelCode("+251", "ET"),
new CountryTelCode("+500", "FK"),
new CountryTelCode("+298", "FO"),
new CountryTelCode("+679", "FJ"),
new CountryTelCode("+358", "FI"),
new CountryTelCode("+33", "FR"),
new CountryTelCode("+689", "PF"),
new CountryTelCode("+241", "GA"),
new CountryTelCode("+220", "GM"),
new CountryTelCode("+995", "GE"),
new CountryTelCode("+49", "DE"),
new CountryTelCode("+233", "GH"),
new CountryTelCode("+350", "GI"),
new CountryTelCode("+30", "GR"),
new CountryTelCode("+299", "GL"),
new CountryTelCode("+1-473", "GD"),
new CountryTelCode("+1-671", "GU"),
new CountryTelCode("+502", "GT"),
new CountryTelCode("+44-1481", "GG"),
new CountryTelCode("+224", "GN"),
new CountryTelCode("+245", "GW"),
new CountryTelCode("+592", "GY"),
new CountryTelCode("+509", "HT"),
new CountryTelCode("+504", "HN"),
new CountryTelCode("+852", "HK"),
new CountryTelCode("+36", "HU"),
new CountryTelCode("+354", "IS"),
new CountryTelCode("+91", "IN"),
new CountryTelCode("+62", "ID"),
new CountryTelCode("+98", "IR"),
new CountryTelCode("+964", "IQ"),
new CountryTelCode("+353", "IE"),
new CountryTelCode("+44-1624", "IM"),
new CountryTelCode("+972", "IL"),
new CountryTelCode("+39", "IT"),
new CountryTelCode("+225", "CI"),
new CountryTelCode("+1-876", "JM"),
new CountryTelCode("+81", "JP"),
new CountryTelCode("+44-1534", "JE"),
new CountryTelCode("+962", "JO"),
new CountryTelCode("+7", "KZ"),
new CountryTelCode("+254", "KE"),
new CountryTelCode("+686", "KI"),
new CountryTelCode("+383", "XK"),
new CountryTelCode("+965", "KW"),
new CountryTelCode("+996", "KG"),
new CountryTelCode("+856", "LA"),
new CountryTelCode("+371", "LV"),
new CountryTelCode("+961", "LB"),
new CountryTelCode("+266", "LS"),
new CountryTelCode("+231", "LR"),
new CountryTelCode("+218", "LY"),
new CountryTelCode("+423", "LI"),
new CountryTelCode("+370", "LT"),
new CountryTelCode("+352", "LU"),
new CountryTelCode("+853", "MO"),
new CountryTelCode("+389", "MK"),
new CountryTelCode("+261", "MG"),
new CountryTelCode("+265", "MW"),
new CountryTelCode("+60", "MY"),
new CountryTelCode("+960", "MV"),
new CountryTelCode("+223", "ML"),
new CountryTelCode("+356", "MT"),
new CountryTelCode("+692", "MH"),
new CountryTelCode("+222", "MR"),
new CountryTelCode("+230", "MU"),
new CountryTelCode("+262", "YT"),
new CountryTelCode("+52", "MX"),
new CountryTelCode("+691", "FM"),
new CountryTelCode("+373", "MD"),
new CountryTelCode("+377", "MC"),
new CountryTelCode("+976", "MN"),
new CountryTelCode("+382", "ME"),
new CountryTelCode("+1-664", "MS"),
new CountryTelCode("+212", "MA"),
new CountryTelCode("+258", "MZ"),
new CountryTelCode("+95", "MM"),
new CountryTelCode("+264", "NA"),
new CountryTelCode("+674", "NR"),
new CountryTelCode("+977", "NP"),
new CountryTelCode("+31", "NL"),
new CountryTelCode("+599", "AN"),
new CountryTelCode("+687", "NC"),
new CountryTelCode("+64", "NZ"),
new CountryTelCode("+505", "NI"),
new CountryTelCode("+227", "NE"),
new CountryTelCode("+234", "NG"),
new CountryTelCode("+683", "NU"),
new CountryTelCode("+850", "KP"),
new CountryTelCode("+1-670", "MP"),
new CountryTelCode("+47", "NO"),
new CountryTelCode("+968", "OM"),
new CountryTelCode("+92", "PK"),
new CountryTelCode("+680", "PW"),
new CountryTelCode("+970", "PS"),
new CountryTelCode("+507", "PA"),
new CountryTelCode("+675", "PG"),
new CountryTelCode("+595", "PY"),
new CountryTelCode("+51", "PE"),
new CountryTelCode("+63", "PH"),
new CountryTelCode("+64", "PN"),
new CountryTelCode("+48", "PL"),
new CountryTelCode("+351", "PT"),
new CountryTelCode("+1-787", "PR"),
new CountryTelCode("+1-939", "PR"),
new CountryTelCode("+974", "QA"),
new CountryTelCode("+242", "CG"),
new CountryTelCode("+262", "RE"),
new CountryTelCode("+40", "RO"),
new CountryTelCode("+7", "RU"),
new CountryTelCode("+250", "RW"),
new CountryTelCode("+590", "BL"),
new CountryTelCode("+290", "SH"),
new CountryTelCode("+1-869", "KN"),
new CountryTelCode("+1-758", "LC"),
new CountryTelCode("+590", "MF"),
new CountryTelCode("+508", "PM"),
new CountryTelCode("+1-784", "VC"),
new CountryTelCode("+685", "WS"),
new CountryTelCode("+378", "SM"),
new CountryTelCode("+239", "ST"),
new CountryTelCode("+966", "SA"),
new CountryTelCode("+221", "SN"),
new CountryTelCode("+381", "RS"),
new CountryTelCode("+248", "SC"),
new CountryTelCode("+232", "SL"),
new CountryTelCode("+65", "SG"),
new CountryTelCode("+1-721", "SX"),
new CountryTelCode("+421", "SK"),
new CountryTelCode("+386", "SI"),
new CountryTelCode("+677", "SB"),
new CountryTelCode("+252", "SO"),
new CountryTelCode("+27", "ZA"),
new CountryTelCode("+82", "KR"),
new CountryTelCode("+211", "SS"),
new CountryTelCode("+34", "ES"),
new CountryTelCode("+94", "LK"),
new CountryTelCode("+249", "SD"),
new CountryTelCode("+597", "SR"),
new CountryTelCode("+47", "SJ"),
new CountryTelCode("+268", "SZ"),
new CountryTelCode("+46", "SE"),
new CountryTelCode("+41", "CH"),
new CountryTelCode("+963", "SY"),
new CountryTelCode("+886", "TW"),
new CountryTelCode("+992", "TJ"),
new CountryTelCode("+255", "TZ"),
new CountryTelCode("+66", "TH"),
new CountryTelCode("+228", "TG"),
new CountryTelCode("+690", "TK"),
new CountryTelCode("+676", "TO"),
new CountryTelCode("+1-868", "TT"),
new CountryTelCode("+216", "TN"),
new CountryTelCode("+90", "TR"),
new CountryTelCode("+993", "TM"),
new CountryTelCode("+1-649", "TC"),
new CountryTelCode("+688", "TV"),
new CountryTelCode("+1-340", "VI"),
new CountryTelCode("+256", "UG"),
new CountryTelCode("+380", "UA"),
new CountryTelCode("+971", "AE"),
new CountryTelCode("+44", "GB"),
new CountryTelCode("+1", "US"),
new CountryTelCode("+598", "UY"),
new CountryTelCode("+998", "UZ"),
new CountryTelCode("+678", "VU"),
new CountryTelCode("+379", "VA"),
new CountryTelCode("+58", "VE"),
new CountryTelCode("+84", "VN"),
new CountryTelCode("+681", "WF"),
new CountryTelCode("+212", "EH"),
new CountryTelCode("+967", "YE"),
new CountryTelCode("+260", "ZM"),
new CountryTelCode("+263", "ZW"),
};
}
If you're talking about phone calling codes you have to build a look-up table.
I would recommend looking this list of calling codes: Wikipedia
There's also quite a handy ReST API for this. I'd suggest copying the data locally into a json file or whatever rather than relying on a third-party service.
GET https://restcountries.eu/rest/v2/all

Errors while attempting to generate code using Codedom

My goal: To create a windows form application (executable) through the use of CodeDom. By this I mean I would like a form (with some code behind the form) and turn it into an executable file (as if I had gone into Visual Studio and clicked "Build" > "Build File"). Admittingly, I found this example online and I have since lightly modified it. I am getting errors while trying to generate this code - errors that I have never seen before. Furthermore, I could not find these errors on Google (odd right?)...
Here is the error I am getting:
Element type System.CodeDom.CodeExpression is not supported.
Parameter name: e
I am getting this error on the following line:
CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());
Here is my full code:
{
CodeDomProvider CodeProvider = CodeDomProvider.CreateProvider("CSharp");
// Create the Unit
CodeCompileUnit Unit = new CodeCompileUnit();
// Define a namespace and add Imports statements
CodeNamespace Namespaces = new CodeNamespace("Test.CreateForm");
Namespaces.Imports.Add(new CodeNamespaceImport("System"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Drawing"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Xml"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Data"));
Unit.Namespaces.Add(Namespaces);
// Declare the type including base type
CodeTypeDeclaration MyType = new CodeTypeDeclaration("Form1");
MyType.IsClass = true;
MyType.TypeAttributes = System.Reflection.TypeAttributes.Public;
MyType.BaseTypes.Add("System.Windows.Forms.Form");
Namespaces.Types.Add(MyType);
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),"InitializeComponent", new CodeExpression() {}));
Constructor.Attributes = MemberAttributes.Public ;
MyType.Members.Add(Constructor);
// Declare component container
MyType.Members.Add(new CodeMemberField("System.ComponentModel.IContainer", "components"));
// Implement the Dispose method
CodeMemberMethod DisposeMethod = new CodeMemberMethod();
DisposeMethod.Name = "Dispose";
DisposeMethod.Attributes = MemberAttributes.Family;
DisposeMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
typeof(Boolean), "disposing"));
CodeConditionStatement Statement = new CodeConditionStatement();
Statement.Condition = new CodeArgumentReferenceExpression("disposing");
CodeConditionStatement TrueStatement = new CodeConditionStatement();
TrueStatement.Condition =
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("components"),
CodeBinaryOperatorType.IdentityInequality,
new CodePrimitiveExpression(null));
TrueStatement.TrueStatements.Add(
new CodeMethodInvokeExpression(
new CodeFieldReferenceExpression(null,
"components"), "Dispose", new CodeExpression() {}));
Statement.TrueStatements.Add(TrueStatement);
DisposeMethod.Statements.Add(Statement);
DisposeMethod.Statements.Add(new CodeMethodInvokeExpression( new CodeBaseReferenceExpression(), "Dispose", new CodeArgumentReferenceExpression[]
{new CodeArgumentReferenceExpression("disposing")}));
MyType.Members.Add(DisposeMethod);
// InitializeComponent
CodeMemberMethod InitializeMethod = new CodeMemberMethod();
InitializeMethod.Name = "InitializeComponent";
InitializeMethod.Attributes = MemberAttributes.Private;
InitializeMethod.CustomAttributes.Add(
new CodeAttributeDeclaration(
"System.Diagnostics.DebuggerStepThrough"));
InitializeMethod.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "components"),
new CodeObjectCreateExpression(
new CodeTypeReference(
typeof(System.ComponentModel.Container)),
new CodeExpression() { })));
MyType.Members.Add(InitializeMethod);
// Main entry point
CodeEntryPointMethod MainMethod = new CodeEntryPointMethod();
MainMethod.Name = "Main";
MyType.Members.Add(MainMethod);
//Add mouse move event
CodeMemberEvent eventstate = new CodeMemberEvent();
eventstate.Name = "MouseMove";
eventstate.Attributes = MemberAttributes.Final | MemberAttributes.Public;
eventstate.Type = new CodeTypeReference("System.Windows.Forms.MouseEventHandler");
MyType.Members.Add(eventstate);
string OutputName = "Some.cs";
try
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BlankLinesBetweenMembers = true;
options.ElseOnClosing = false;
options.BracingStyle = "C";
// This is what we'll write the generated code to
IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(OutputName, false), " ");
try
{
CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());
writer.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
writer.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// Create the compiler options
// Include referenced assemblies
CompilerParameters Options = new CompilerParameters();
Options.GenerateExecutable = true;
Options.OutputAssembly = "TestForm1.exe";
Options.CompilerOptions = "/target:winexe";
Options.MainClass = "Test.CreateForm.Form1";
string[] referenceAssemblies = { "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.XML.dll" };
Options.ReferencedAssemblies.AddRange(referenceAssemblies);
//Build and look for compiler errors
CompilerResults Result = CodeProvider.CompileAssemblyFromFile(Options, "Some.cs");
if (Result.Errors.Count > 0)
{
foreach(CompilerError ce in Result.Errors)
{
Console.WriteLine(ce.ErrorText);
}
}
else
{
Console.WriteLine("compiled successfully");
}
Console.WriteLine("press enter to continue");
Console.ReadLine();
}
You have many instances where you create an empty CodeExpression, such as in the constructor code:
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression() { }));
If you don't want to pass any parameters to the method (which is the case in the code above), simply don't pass anything (CodeMethodInvokeExpression constructor takes a params[] array, so if you don't pass anything, it means that it receives an empty array):
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"InitializeComponent"));
in case above code is not spitting the required code make sure you are closed the IndentedTextWriter e.g. writer.Close() enjoy..
CodeMemberMethod DisposeMethod = new CodeMemberMethod();
DisposeMethod.Name = "Dispose";
DisposeMethod.ReturnType = new CodeTypeReference(typeof(void));
DisposeMethod.Attributes = MemberAttributes.Override | MemberAttributes.Private;
DisposeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "disposing"));
myDesignerClass.Members.Add(DisposeMethod);
CodeConditionStatement cstif2 = new CodeConditionStatement();
CodeExpression dis = new CodeVariableReferenceExpression("disposing");
CodeExpression comp = new CodeVariableReferenceExpression("components");
cstif2.Condition = new CodeBinaryOperatorExpression(dis, CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(dis, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)));
CodeExpression dispos = new CodeMethodInvokeExpression(comp, "Dispose", new CodeExpression[] { });
cstif2.TrueStatements.Add(dispos);
DisposeMethod.Statements.Add(cstif2);
CodeExpression bdispos = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Dispose", new CodeExpression[] { });
DisposeMethod.Statements.Add(bdispos);
Replace () after CodeExpression with [] and error will vanish.

Categories