Search Results

Search found 414 results on 17 pages for 'enums'.

Page 12/17 | < Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Spawning a thread in python

    - by morpheous
    I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks. Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows. from foobar import alice, bob charles data = getWorkData() # these are enums (which I just found Python doesn't support natively) :( tasks = (alice, bob, charles) for task in tasks # Ok, just found out Python doesn't have a switch - @#$%! # yet another thing I'll need help with then ... switch case alice: #spawn thread here - how ? alice.spawnWorker(data) No prizes for guessing I am still thinking in C++. How can I write this in a Pythonic way using Pythonic 'enums' and 'switch'es, and be able to run a module in a new thread. Obviously, the modules will all have a class that is derived from a ABC (abstract base class) called Plugin. The spawnWorker() method will be declared on the Plugin interface and defined in the classes implemented in the various modules. Maybe, there is a better (i.e. Pythonic) way of doing all this?. I'd be interested in knowing

    Read the article

  • Enum.TryParse with Flags attribute

    - by Sunny
    I have written code to TryParse enum either by value or by its name as shown below. How can I extend this code to include parsing enums with Flags attribute? public static bool TryParse<T>(this T enum_type, object value, out T result) where T : struct { return enum_type.TryParse<T>(value, true, out result); } public static bool TryParse<T>(this T enum_type, object value, bool ignoreCase, out T result) where T : struct { result = default(T); var is_converted = false; var is_valid_value_for_conversion = new Func<T, object, bool, bool>[]{ (e, v, i) => e.GetType().IsEnum, (e, v, i) => value != null, (e, v, i) => Enum.GetNames(e.GetType()).Any(n => String.Compare(n, v.ToString(), i) == 0) || Enum.IsDefined(e.GetType(), v) }; if(is_valid_value_for_conversion.All(rule => rule(enum_type, value, ignoreCase))){ result = (T)Enum.Parse(typeof(T), value.ToString(), ignoreCase); is_converted = true; } return is_converted; } Currently this code works for the following enums: enum SomeEnum{ A, B, C } // can parse either by 'A' or 'a' enum SomeEnum1 : int { A = 1, B = 2, C = 3 } // can parse either by 'A' or 'a' or 1 or "1" Does not work for: [Flags] enum SomeEnum2 { A = 1, B = 2, C = 4 } // can parse either by 'A' or 'a' // cannot parse for A|B Thanks!

    Read the article

  • What do I need to do if I want all typeof(MyEnum)'s to be handled with MyEnumModelBinder?

    - by Byron Sommardahl
    I have an Enum that appears in several of my models. For the most part, the DefaultModelBinder handles binding to my models beautifully. That it, until it gets to my Enum... it always returns the first member in the Enum no matter what is handed it by the POST. My googling leads me to believe I need to have a model binder that knows how to handle Enums. I found an excellent article on a possible custom modelBinder for Enums: http://eliasbland.wordpress.com/2009/08/08/enumeration-model-binder-for-asp-net-mvc/. I've since implemented that modelBinder and registered it in my global.asax: ModelBinders.Binders[typeof (MyEnum)] = new EnumBinder<MyEnum>(MyEnum.MyDefault); For some reason, the EnumBinder< isn't being called when the model I'm binding to has MyEnum. I have a breakpoint in the .BindModel() method and it never break. Also, my model hasn't changed after modelBinding. Have I done everything? What am I missing here?

    Read the article

  • How to get the Actual Link file location in VSS?

    - by Regi
    I use VSS and currently I am adding a link file using following code: int ShareFlags = (int)VSSFlags.VSSFLAG_RECURSNO; //Link in sourcesafe IVSSDatabase ssdb = GetVssDatabase(); Shared.Enums.SqlObjectSubType _sqlSubType = new Shared.Enums.SqlObjectSubType(); VSSItem SourceItem = ssdb.get_VSSItem(pSourceItemPath, false); //if source is a proj, recursively share the whole thing if (SourceItem.Type == (int)VSSItemType.VSSITEM_PROJECT) ShareFlags = (int)VSSFlags.VSSFLAG_RECURSYES; VSSItem DestItem = ssdb..get_VSSItem(pDestItemPath, false); //share the item DestItem.Share(SourceItem, pComment, ShareFlags); if (SourceItem.Type == (int)VSSItemType.VSSITEM_FILE) { bResult = true; } return bResult; This will works fine. My issue is that I need to find the actual link location. For example I have a Project named as Link and it contains 2 files say file1 and file2. I added a Link to my Working project (say CurrentProject). This current project have 2 files say f1 and f2. After sharing the Link project then we get the item in Current project as: $/CurrentProject/File1 $/CurrentProject/File2 $/CurrentProject/F1 $/CurrentProject/F2 Here File1 and File2 are link files. I need to get its parent (Actual) location i.e. $/Link/file1 and $/Link/File2 Is there any way to find Link files location using SourceSafeTypeLib?

    Read the article

  • Question about singleton property

    - by Jack
    I'm reading the java tutorial for enums located here and have a question: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html#Card The part i'm confused about is as follows: "The Card class, above, contains a static factory that returns a deck, but there is no way to get an individual card from its rank and suit. Merely exposing the constructor would destroy the singleton property (that only a single instance of each card is allowed to exist). Here is how to write a static factory that preserves the singleton property, using a nested EnumMap: " Now as I understand, changing the original private "Card" constructor to public would allow us to instantiate an unlimited number of copies of a "Card" object with a given suit+rank. The solution as proposed was to create an EnumMap which would store four Maps (one for each suit), which themselves contained 13 Card objects with the rank as their keys. And so now if you wanted to retrieve a specific Card object from the deck, you would just call the "valueOf" method. My question now is, what's the prevent you with calling the valueOf method as many times as you like? Wouldn't that lead to the same problem as making the original private constructor public? Thanks.

    Read the article

  • Item 2, Scott Myers Effective C++ question

    - by user619818
    In Item2 on page 16, (Prefer consts, enums, and inlines to #defines), Scott says: 'Also, though good compilers won't set aside storage for const objects of integer types'. I don't understand this. If I define a const object, eg const int myval = 5; then surely the compiler must set aside some memory (of int size) to store the value 5? Or is const data stored in some special way? This is more a question of computer storage I suppose. Basically, how does the computer store const objects so that no storage is set aside?

    Read the article

  • Assign multiple test categories using TestCategoryAttribute

    - by Michael Freidgeim
    I am using TestCategoryAttribute to filter which tests to run during builds and wandered, how to -how to assign multiple test categories.According to constructor documentation only single category can be specified.  However TestCategories Property (plural!)can return multiple categories.Grouping Tests into Test Categories: You can add an automated test to one or multiple test categories using a test attribute. Each test can belong to multiple test categories.The recommended approach from MSDN How to: Group and Run Automated Tests Using Test Categories is to specify multiple TestCategory attributes like the following[TestCategory("Nightly"), TestCategory("Weekly"), TestCategory("ShoppingCart"), TestMethod()]public Void DebitTest() { }Article http://toddmeinershagen.blogspot.com.au/2010/09/create-custom-test-category-attributes.htmlshows how enums can be used instead of strings.It also explains, that TestCategories Property can be used in derived custom attributes.v

    Read the article

  • Case Class naming convention

    - by KChaloux
    In my recent adventures in Scala, I've found case classes to be a really nice alternative to enums when I need to include a bit of logic or several values with them. I often find myself writing structures that look like this, however: object Foo{ case class Foo(name: String, value: Int, other: Double) val BAR = Foo("bar", 1, 1.0) val BAZ = Foo("baz", 2, 1.5) val QUUX = Foo("quux", 3, 1.75) } I'm primarily worried here about the naming of the object and the case class. Since they're the same thing, I end up with Foo.Foo to get to the inner class. Would it be wise to name the case class something along the lines of FooCase instead? I'm not sure if the potential ambiguity might mess with the type system if I have to do anything with subtypes or inheritance.

    Read the article

  • Dynamically loading Assemblies to reduce Runtime Depencies

    - by Rick Strahl
    I've been working on a request to the West Wind Application Configuration library to add JSON support. The config library is a very easy to use code-first approach to configuration: You create a class that holds the configuration data that inherits from a base configuration class, and then assign a persistence provider at runtime that determines where and how the configuration data is store. Currently the library supports .NET Configuration stores (web.config/app.config), XML files, SQL records and string storage.About once a week somebody asks me about JSON support and I've deflected this question for the longest time because frankly I think that JSON as a configuration store doesn't really buy a heck of a lot over XML. Both formats require the user to perform some fixup of the plain configuration data - in XML into XML tags, with JSON using JSON delimiters for properties and property formatting rules. Sure JSON is a little less verbose and maybe a little easier to read if you have hierarchical data, but overall the differences are pretty minor in my opinion. And yet - the requests keep rolling in.Hard Link Issues in a Component LibraryAnother reason I've been hesitant is that I really didn't want to pull in a dependency on an external JSON library - in this case JSON.NET - into the core library. If you're not using JSON.NET elsewhere I don't want a user to have to require a hard dependency on JSON.NET unless they want to use the JSON feature. JSON.NET is also sensitive to versions and doesn't play nice with multiple versions when hard linked. For example, when you have a reference to V4.4 in your project but the host application has a reference to version 4.5 you can run into assembly load problems. NuGet's Update-Package can solve some of this *if* you can recompile, but that's not ideal for a component that's supposed to be just plug and play. This is no criticism of JSON.NET - this really applies to any dependency that might change.  So hard linking the DLL can be problematic for a number reasons, but the primary reason is to not force loading of JSON.NET unless you actually need it when you use the JSON configuration features of the library.Enter Dynamic LoadingSo rather than adding an assembly reference to the project, I decided that it would be better to dynamically load the DLL at runtime and then use dynamic typing to access various classes. This allows me to run without a hard assembly reference and allows more flexibility with version number differences now and in the future.But there are also a couple of downsides:No assembly reference means only dynamic access - no compiler type checking or IntellisenseRequirement for the host application to have reference to JSON.NET or else get runtime errorsThe former is minor, but the latter can be problematic. Runtime errors are always painful, but in this case I'm willing to live with this. If you want to use JSON configuration settings JSON.NET needs to be loaded in the project. If this is a Web project, it'll likely be there already.So there are a few things that are needed to make this work:Dynamically create an instance and optionally attempt to load an Assembly (if not loaded)Load types into dynamic variablesUse Reflection for a few tasks like statics/enumsThe dynamic keyword in C# makes the formerly most difficult Reflection part - method calls and property assignments - fairly painless. But as cool as dynamic is it doesn't handle all aspects of Reflection. Specifically it doesn't deal with object activation, truly dynamic (string based) member activation or accessing of non instance members, so there's still a little bit of work left to do with Reflection.Dynamic Object InstantiationThe first step in getting the process rolling is to instantiate the type you need to work with. This might be a two step process - loading the instance from a string value, since we don't have a hard type reference and potentially having to load the assembly. Although the host project might have a reference to JSON.NET, that instance might have not been loaded yet since it hasn't been accessed yet. In ASP.NET this won't be a problem, since ASP.NET preloads all referenced assemblies on AppDomain startup, but in other executable project, assemblies are just in time loaded only when they are accessed.Instantiating a type is a two step process: Finding the type reference and then activating it. Here's the generic code out of my ReflectionUtils library I use for this:/// <summary> /// Creates an instance of a type based on a string. Assumes that the type's /// </summary> /// <param name="typeName">Common name of the type</param> /// <param name="args">Any constructor parameters</param> /// <returns></returns> public static object CreateInstanceFromString(string typeName, params object[] args) { object instance = null; Type type = null; try { type = GetTypeFromName(typeName); if (type == null) return null; instance = Activator.CreateInstance(type, args); } catch { return null; } return instance; } /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // Let default name binding find it type = Type.GetType(typeName, false); if (type != null) return type; // look through assembly list var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // try to find manually foreach (Assembly asm in assemblies) { type = asm.GetType(typeName, false); if (type != null) break; } return type; } To use this for loading JSON.NET I have a small factory function that instantiates JSON.NET and sets a bunch of configuration settings on the generated object. The startup code also looks for failure and tries loading up the assembly when it fails since that's the main reason the load would fail. Finally it also caches the loaded instance for reuse (according to James the JSON.NET instance is thread safe and quite a bit faster when cached). Here's what the factory function looks like in JsonSerializationUtils:/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) return JsonNet; lock (SyncLock) { if (JsonNet != null) return JsonNet; // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { var ass = AppDomain.CurrentDomain.Load("Newtonsoft.Json"); json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch (Exception ex) { if (throwExceptions) throw; return null; } } if (json == null) return null; json.ReferenceLoopHandling = (dynamic) ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return JsonNet; }This code's purpose is to return a fully configured JsonSerializer instance. As you can see the code tries to create an instance and when it fails tries to load the assembly, and then re-tries loading.Once the instance is loaded some configuration occurs on it. Specifically I set the ReferenceLoopHandling option to not blow up immediately when circular references are encountered. There are a host of other small config setting that might be useful to set, but the default seem to be good enough in recent versions. Note that I'm setting ReferenceLoopHandling which requires an Enum value to be set. There's no real easy way (short of using the cardinal numeric value) to set a property or pass parameters from static values or enums. This means I still need to use Reflection to make this work. I'm using the same ReflectionUtils class I previously used to handle this for me. The function looks up the type and then uses Type.InvokeMember() to read the static property.Another feature I need is have Enum values serialized as strings rather than numeric values which is the default. To do this I can use the StringEnumConverter to convert enums to strings by adding it to the Converters collection.As you can see there's still a bit of Reflection to be done even in C# 4+ with dynamic, but with a few helpers this process is relatively painless.Doing the actual JSON ConversionFinally I need to actually do my JSON conversions. For the Utility class I need serialization that works for both strings and files so I created four methods that handle these tasks two each for serialization and deserialization for string and file.Here's what the File Serialization looks like:/// <summary> /// Serializes an object instance to a JSON file. /// </summary> /// <param name="value">the value to serialize</param> /// <param name="fileName">Full path to the file to write out with JSON.</param> /// <param name="throwExceptions">Determines whether exceptions are thrown or false is returned</param> /// <param name="formatJsonOutput">if true pretty-formats the JSON with line breaks</param> /// <returns>true or false</returns> public static bool SerializeToFile(object value, string fileName, bool throwExceptions = false, bool formatJsonOutput = false) { dynamic writer = null; FileStream fs = null; try { Type type = value.GetType(); var json = CreateJsonNet(throwExceptions); if (json == null) return false; fs = new FileStream(fileName, FileMode.Create); var sw = new StreamWriter(fs, Encoding.UTF8); writer = Activator.CreateInstance(JsonTextWriterType, sw); if (formatJsonOutput) writer.Formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); writer.QuoteChar = '"'; json.Serialize(writer, value); } catch (Exception ex) { Debug.WriteLine("JsonSerializer Serialize error: " + ex.Message); if (throwExceptions) throw; return false; } finally { if (writer != null) writer.Close(); if (fs != null) fs.Close(); } return true; }You can see more of the dynamic invocation in this code. First I grab the dynamic JsonSerializer instance using the CreateJsonNet() method shown earlier which returns a dynamic. I then create a JsonTextWriter and configure a couple of enum settings on it, and then call Serialize() on the serializer instance with the JsonTextWriter that writes the output to disk. Although this code is dynamic it's still fairly short and readable.For full circle operation here's the DeserializeFromFile() version:/// <summary> /// Deserializes an object from file and returns a reference. /// </summary> /// <param name="fileName">name of the file to serialize to</param> /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param> /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param> /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param> /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns> public static object DeserializeFromFile(string fileName, Type objectType, bool throwExceptions = false) { dynamic json = CreateJsonNet(throwExceptions); if (json == null) return null; object result = null; dynamic reader = null; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var sr = new StreamReader(fs, Encoding.UTF8); reader = Activator.CreateInstance(JsonTextReaderType, sr); result = json.Deserialize(reader, objectType); reader.Close(); } catch (Exception ex) { Debug.WriteLine("JsonNetSerialization Deserialization Error: " + ex.Message); if (throwExceptions) throw; return null; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } return result; }This code is a little more compact since there are no prettifying options to set. Here JsonTextReader is created dynamically and it receives the output from the Deserialize() operation on the serializer.You can take a look at the full JsonSerializationUtils.cs file on GitHub to see the rest of the operations, but the string operations are very similar - the code is fairly repetitive.These generic serialization utilities isolate the dynamic serialization logic that has to deal with the dynamic nature of JSON.NET, and any code that uses these functions is none the wiser that JSON.NET is dynamically loaded.Using the JsonSerializationUtils WrapperThe final consumer of the SerializationUtils wrapper is an actual ConfigurationProvider, that is responsible for handling reading and writing JSON values to and from files. The provider is simple a small wrapper around the SerializationUtils component and there's very little code to make this work now:The whole provider looks like this:/// <summary> /// Reads and Writes configuration settings in .NET config files and /// sections. Allows reading and writing to default or external files /// and specification of the configuration section that settings are /// applied to. /// </summary> public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration> where TAppConfiguration: AppConfiguration, new() { /// <summary> /// Optional - the Configuration file where configuration settings are /// stored in. If not specified uses the default Configuration Manager /// and its default store. /// </summary> public string JsonConfigurationFile { get { return _JsonConfigurationFile; } set { _JsonConfigurationFile = value; } } private string _JsonConfigurationFile = string.Empty; public override bool Read(AppConfiguration config) { var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration; if (newConfig == null) { if(Write(config)) return true; return false; } DecryptFields(newConfig); DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage"); return true; } /// <summary> /// Return /// </summary> /// <typeparam name="TAppConfig"></typeparam> /// <returns></returns> public override TAppConfig Read<TAppConfig>() { var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig; if (result != null) DecryptFields(result); return result; } /// <summary> /// Write configuration to XmlConfigurationFile location /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { EncryptFields(config); bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile,false,true); // Have to decrypt again to make sure the properties are readable afterwards DecryptFields(config); return result; } }This incidentally demonstrates how easy it is to create a new provider for the West Wind Application Configuration component. Simply implementing 3 methods will do in most cases.Note this code doesn't have any dynamic dependencies - all that's abstracted away in the JsonSerializationUtils(). From here on, serializing JSON is just a matter of calling the static methods on the SerializationUtils class.Already, there are several other places in some other tools where I use JSON serialization this is coming in very handy. With a couple of lines of code I was able to add JSON.NET support to an older AJAX library that I use replacing quite a bit of code that was previously in use. And for any other manual JSON operations (in a couple of apps I use JSON Serialization for 'blob' like document storage) this is also going to be handy.Performance?Some of you might be thinking that using dynamic and Reflection can't be good for performance. And you'd be right… In performing some informal testing it looks like the performance of the native code is nearly twice as fast as the dynamic code. Most of the slowness is attributable to type lookups. To test I created a native class that uses an actual reference to JSON.NET and performance was consistently around 85-90% faster with the referenced code. That being said though - I serialized 10,000 objects in 80ms vs. 45ms so this isn't hardly slouchy. For the configuration component speed is not that important because both read and write operations typically happen once on first access and then every once in a while. But for other operations - say a serializer trying to handle AJAX requests on a Web Server one would be well served to create a hard dependency.Dynamic Loading - Worth it?On occasion dynamic loading makes sense. But there's a price to be paid in added code complexity and a performance hit. But for some operations that are not pivotal to a component or application and only used under certain circumstances dynamic loading can be beneficial to avoid having to ship extra files and loading down distributions. These days when you create new projects in Visual Studio with 30 assemblies before you even add your own code, trying to keep file counts under control seems a good idea. It's not the kind of thing you do on a regular basis, but when needed it can be a useful tool. Hopefully some of you find this information useful…© Rick Strahl, West Wind Technologies, 2005-2013Posted in .NET  C#   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Dynamically loading Assemblies to reduce Runtime Dependencies

    - by Rick Strahl
    I've been working on a request to the West Wind Application Configuration library to add JSON support. The config library is a very easy to use code-first approach to configuration: You create a class that holds the configuration data that inherits from a base configuration class, and then assign a persistence provider at runtime that determines where and how the configuration data is store. Currently the library supports .NET Configuration stores (web.config/app.config), XML files, SQL records and string storage.About once a week somebody asks me about JSON support and I've deflected this question for the longest time because frankly I think that JSON as a configuration store doesn't really buy a heck of a lot over XML. Both formats require the user to perform some fixup of the plain configuration data - in XML into XML tags, with JSON using JSON delimiters for properties and property formatting rules. Sure JSON is a little less verbose and maybe a little easier to read if you have hierarchical data, but overall the differences are pretty minor in my opinion. And yet - the requests keep rolling in.Hard Link Issues in a Component LibraryAnother reason I've been hesitant is that I really didn't want to pull in a dependency on an external JSON library - in this case JSON.NET - into the core library. If you're not using JSON.NET elsewhere I don't want a user to have to require a hard dependency on JSON.NET unless they want to use the JSON feature. JSON.NET is also sensitive to versions and doesn't play nice with multiple versions when hard linked. For example, when you have a reference to V4.4 in your project but the host application has a reference to version 4.5 you can run into assembly load problems. NuGet's Update-Package can solve some of this *if* you can recompile, but that's not ideal for a component that's supposed to be just plug and play. This is no criticism of JSON.NET - this really applies to any dependency that might change.  So hard linking the DLL can be problematic for a number reasons, but the primary reason is to not force loading of JSON.NET unless you actually need it when you use the JSON configuration features of the library.Enter Dynamic LoadingSo rather than adding an assembly reference to the project, I decided that it would be better to dynamically load the DLL at runtime and then use dynamic typing to access various classes. This allows me to run without a hard assembly reference and allows more flexibility with version number differences now and in the future.But there are also a couple of downsides:No assembly reference means only dynamic access - no compiler type checking or IntellisenseRequirement for the host application to have reference to JSON.NET or else get runtime errorsThe former is minor, but the latter can be problematic. Runtime errors are always painful, but in this case I'm willing to live with this. If you want to use JSON configuration settings JSON.NET needs to be loaded in the project. If this is a Web project, it'll likely be there already.So there are a few things that are needed to make this work:Dynamically create an instance and optionally attempt to load an Assembly (if not loaded)Load types into dynamic variablesUse Reflection for a few tasks like statics/enumsThe dynamic keyword in C# makes the formerly most difficult Reflection part - method calls and property assignments - fairly painless. But as cool as dynamic is it doesn't handle all aspects of Reflection. Specifically it doesn't deal with object activation, truly dynamic (string based) member activation or accessing of non instance members, so there's still a little bit of work left to do with Reflection.Dynamic Object InstantiationThe first step in getting the process rolling is to instantiate the type you need to work with. This might be a two step process - loading the instance from a string value, since we don't have a hard type reference and potentially having to load the assembly. Although the host project might have a reference to JSON.NET, that instance might have not been loaded yet since it hasn't been accessed yet. In ASP.NET this won't be a problem, since ASP.NET preloads all referenced assemblies on AppDomain startup, but in other executable project, assemblies are just in time loaded only when they are accessed.Instantiating a type is a two step process: Finding the type reference and then activating it. Here's the generic code out of my ReflectionUtils library I use for this:/// <summary> /// Creates an instance of a type based on a string. Assumes that the type's /// </summary> /// <param name="typeName">Common name of the type</param> /// <param name="args">Any constructor parameters</param> /// <returns></returns> public static object CreateInstanceFromString(string typeName, params object[] args) { object instance = null; Type type = null; try { type = GetTypeFromName(typeName); if (type == null) return null; instance = Activator.CreateInstance(type, args); } catch { return null; } return instance; } /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // Let default name binding find it type = Type.GetType(typeName, false); if (type != null) return type; // look through assembly list var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // try to find manually foreach (Assembly asm in assemblies) { type = asm.GetType(typeName, false); if (type != null) break; } return type; } To use this for loading JSON.NET I have a small factory function that instantiates JSON.NET and sets a bunch of configuration settings on the generated object. The startup code also looks for failure and tries loading up the assembly when it fails since that's the main reason the load would fail. Finally it also caches the loaded instance for reuse (according to James the JSON.NET instance is thread safe and quite a bit faster when cached). Here's what the factory function looks like in JsonSerializationUtils:/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) return JsonNet; lock (SyncLock) { if (JsonNet != null) return JsonNet; // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { var ass = AppDomain.CurrentDomain.Load("Newtonsoft.Json"); json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch (Exception ex) { if (throwExceptions) throw; return null; } } if (json == null) return null; json.ReferenceLoopHandling = (dynamic) ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return JsonNet; }This code's purpose is to return a fully configured JsonSerializer instance. As you can see the code tries to create an instance and when it fails tries to load the assembly, and then re-tries loading.Once the instance is loaded some configuration occurs on it. Specifically I set the ReferenceLoopHandling option to not blow up immediately when circular references are encountered. There are a host of other small config setting that might be useful to set, but the default seem to be good enough in recent versions. Note that I'm setting ReferenceLoopHandling which requires an Enum value to be set. There's no real easy way (short of using the cardinal numeric value) to set a property or pass parameters from static values or enums. This means I still need to use Reflection to make this work. I'm using the same ReflectionUtils class I previously used to handle this for me. The function looks up the type and then uses Type.InvokeMember() to read the static property.Another feature I need is have Enum values serialized as strings rather than numeric values which is the default. To do this I can use the StringEnumConverter to convert enums to strings by adding it to the Converters collection.As you can see there's still a bit of Reflection to be done even in C# 4+ with dynamic, but with a few helpers this process is relatively painless.Doing the actual JSON ConversionFinally I need to actually do my JSON conversions. For the Utility class I need serialization that works for both strings and files so I created four methods that handle these tasks two each for serialization and deserialization for string and file.Here's what the File Serialization looks like:/// <summary> /// Serializes an object instance to a JSON file. /// </summary> /// <param name="value">the value to serialize</param> /// <param name="fileName">Full path to the file to write out with JSON.</param> /// <param name="throwExceptions">Determines whether exceptions are thrown or false is returned</param> /// <param name="formatJsonOutput">if true pretty-formats the JSON with line breaks</param> /// <returns>true or false</returns> public static bool SerializeToFile(object value, string fileName, bool throwExceptions = false, bool formatJsonOutput = false) { dynamic writer = null; FileStream fs = null; try { Type type = value.GetType(); var json = CreateJsonNet(throwExceptions); if (json == null) return false; fs = new FileStream(fileName, FileMode.Create); var sw = new StreamWriter(fs, Encoding.UTF8); writer = Activator.CreateInstance(JsonTextWriterType, sw); if (formatJsonOutput) writer.Formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); writer.QuoteChar = '"'; json.Serialize(writer, value); } catch (Exception ex) { Debug.WriteLine("JsonSerializer Serialize error: " + ex.Message); if (throwExceptions) throw; return false; } finally { if (writer != null) writer.Close(); if (fs != null) fs.Close(); } return true; }You can see more of the dynamic invocation in this code. First I grab the dynamic JsonSerializer instance using the CreateJsonNet() method shown earlier which returns a dynamic. I then create a JsonTextWriter and configure a couple of enum settings on it, and then call Serialize() on the serializer instance with the JsonTextWriter that writes the output to disk. Although this code is dynamic it's still fairly short and readable.For full circle operation here's the DeserializeFromFile() version:/// <summary> /// Deserializes an object from file and returns a reference. /// </summary> /// <param name="fileName">name of the file to serialize to</param> /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param> /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param> /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param> /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns> public static object DeserializeFromFile(string fileName, Type objectType, bool throwExceptions = false) { dynamic json = CreateJsonNet(throwExceptions); if (json == null) return null; object result = null; dynamic reader = null; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var sr = new StreamReader(fs, Encoding.UTF8); reader = Activator.CreateInstance(JsonTextReaderType, sr); result = json.Deserialize(reader, objectType); reader.Close(); } catch (Exception ex) { Debug.WriteLine("JsonNetSerialization Deserialization Error: " + ex.Message); if (throwExceptions) throw; return null; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } return result; }This code is a little more compact since there are no prettifying options to set. Here JsonTextReader is created dynamically and it receives the output from the Deserialize() operation on the serializer.You can take a look at the full JsonSerializationUtils.cs file on GitHub to see the rest of the operations, but the string operations are very similar - the code is fairly repetitive.These generic serialization utilities isolate the dynamic serialization logic that has to deal with the dynamic nature of JSON.NET, and any code that uses these functions is none the wiser that JSON.NET is dynamically loaded.Using the JsonSerializationUtils WrapperThe final consumer of the SerializationUtils wrapper is an actual ConfigurationProvider, that is responsible for handling reading and writing JSON values to and from files. The provider is simple a small wrapper around the SerializationUtils component and there's very little code to make this work now:The whole provider looks like this:/// <summary> /// Reads and Writes configuration settings in .NET config files and /// sections. Allows reading and writing to default or external files /// and specification of the configuration section that settings are /// applied to. /// </summary> public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration> where TAppConfiguration: AppConfiguration, new() { /// <summary> /// Optional - the Configuration file where configuration settings are /// stored in. If not specified uses the default Configuration Manager /// and its default store. /// </summary> public string JsonConfigurationFile { get { return _JsonConfigurationFile; } set { _JsonConfigurationFile = value; } } private string _JsonConfigurationFile = string.Empty; public override bool Read(AppConfiguration config) { var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration; if (newConfig == null) { if(Write(config)) return true; return false; } DecryptFields(newConfig); DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage"); return true; } /// <summary> /// Return /// </summary> /// <typeparam name="TAppConfig"></typeparam> /// <returns></returns> public override TAppConfig Read<TAppConfig>() { var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig; if (result != null) DecryptFields(result); return result; } /// <summary> /// Write configuration to XmlConfigurationFile location /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { EncryptFields(config); bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile,false,true); // Have to decrypt again to make sure the properties are readable afterwards DecryptFields(config); return result; } }This incidentally demonstrates how easy it is to create a new provider for the West Wind Application Configuration component. Simply implementing 3 methods will do in most cases.Note this code doesn't have any dynamic dependencies - all that's abstracted away in the JsonSerializationUtils(). From here on, serializing JSON is just a matter of calling the static methods on the SerializationUtils class.Already, there are several other places in some other tools where I use JSON serialization this is coming in very handy. With a couple of lines of code I was able to add JSON.NET support to an older AJAX library that I use replacing quite a bit of code that was previously in use. And for any other manual JSON operations (in a couple of apps I use JSON Serialization for 'blob' like document storage) this is also going to be handy.Performance?Some of you might be thinking that using dynamic and Reflection can't be good for performance. And you'd be right… In performing some informal testing it looks like the performance of the native code is nearly twice as fast as the dynamic code. Most of the slowness is attributable to type lookups. To test I created a native class that uses an actual reference to JSON.NET and performance was consistently around 85-90% faster with the referenced code. This will change though depending on the size of objects serialized - the larger the object the more processing time is spent inside the actual dynamically activated components and the less difference there will be. Dynamic code is always slower, but how much it really affects your application primarily depends on how frequently the dynamic code is called in relation to the non-dynamic code executing. In most situations where dynamic code is used 'to get the process rolling' as I do here the overhead is small enough to not matter.All that being said though - I serialized 10,000 objects in 80ms vs. 45ms so this is hardly slouchy performance. For the configuration component speed is not that important because both read and write operations typically happen once on first access and then every once in a while. But for other operations - say a serializer trying to handle AJAX requests on a Web Server one would be well served to create a hard dependency.Dynamic Loading - Worth it?Dynamic loading is not something you need to worry about but on occasion dynamic loading makes sense. But there's a price to be paid in added code  and a performance hit which depends on how frequently the dynamic code is accessed. But for some operations that are not pivotal to a component or application and are only used under certain circumstances dynamic loading can be beneficial to avoid having to ship extra files adding dependencies and loading down distributions. These days when you create new projects in Visual Studio with 30 assemblies before you even add your own code, trying to keep file counts under control seems like a good idea. It's not the kind of thing you do on a regular basis, but when needed it can be a useful option in your toolset… © Rick Strahl, West Wind Technologies, 2005-2013Posted in .NET  C#   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Named arguments (parameters) as a readability aid

    - by Damian Mehers
    A long time ago I programmed a lot in ADA, and it was normal to name arguments when invoking a function - SomeObject.DoSomething(SomeParameterName = someValue); Now that C# supports named arguments, I'm thinking about reverting to this habit in situations where it might not be obvious what an argument means. You might argue that it should always be obvious what an argument means, but if you have a boolean argument, and callers are passing in "true" or "false" then qualifying the value with the name makes the call site more readable. contentFetcher.DownloadNote(note, manual : true); I guess I could create Enums instead of using true or false (Manual, Automatic in this case). What do you think about occasionally using named arguments to make code easier to read?

    Read the article

  • What happened this type of naming convention?

    - by Smith
    I have read so many docs about naming conventions, most recommending both Pascal and Camel naming conventions. Well, I agree to this, its ok. This might not be pleasing to some, but I am just trying to get you opinion why you name you objects and classes in a certain way. What happened to this type of naming conventions, or why are they bad? I want to name a struct, and i prefix it with struct. My reason, so that in IntelliSense, I see all the struct in one place, and anywhere I see the struct prefix, I know it's a struct: structPerson structPosition anothe example is the enum, although I may not prefix it with "enum", but maybe with "enm": enmFruits enmSex again my reason is so that in IntelliSense, I see all my enums in one place. Because, .NET has so many built in data structures, I think this helps me do less searching. Please I used .NET in this example, but I welcome language agnostic answers.

    Read the article

  • Error when updating enumerated value?

    - by igrad
    Once upon a time, there was a Player class (simplified version) enum animState{RUNNING,JUMPING,FALLING,IDLING}; class Player { public: Player(int x, int y); void handle(); void show(); ~Player(); private: int m_x; int m_y; animState playerAnimState; } There was also a "handle" function-member, which took care of all movement and collisions for the player: #include "player.h" void Player::handle() { if(/*Player presses 'D' key*/) { m_x++; playerAnimState = RUNNING; } //Other stuff that is just there to look nice Through lots of experimentation with "//" and "/**/", I've found that I consistently get an error at "playerAnimState = RUNNING." Have I broken some enumeration rule? Does my laptop really suck that bad? I hate to post a "fix my code for me" question, but I'm not very seasoned with enums.

    Read the article

  • facebook application using iframe on Facebook Developer Toolkit 3.0

    - by adveb
    hey i am trying to build facebook iframe application using the Facebook Developer Toolkit 3.01 asp.net c#. i am working by the ifrmae sample of the toolkit can be download here. www.facebooktoolkit.codeplex.com/releases/view/39727 this is my facebook application that is the same as the iframe sample. http://apps.facebook.com/alefbet/ this is my code, it has 2 pages, master page and default. this 2 pages are the same as the iframe sample. 1) this is the master page. public partial class IFrameMaster : Facebook.Web.CanvasIFrameMasterPage { public IFrameMaster() { RequireLogin = true; } } 2) this is the default.aspx public partial class Default : System.Web.UI.Page { private const string SCRIPT_BLOCK_NAME = "dynamicScript"; protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { if (Master.Api.Users.HasAppPermission(Enums.ExtendedPermissions.email)) { SendThankYouEmail(); } Response.Redirect("ThankYou.aspx"); } else { if (Master.Api.Users.HasAppPermission(Enums.ExtendedPermissions.email)) { emailPermissionPanel.Visible = false; } CreateScript(); } } private void SendThankYouEmail() { var subject = "Thank you for telling us your favorite color"; var body = "Thank you for telling us what your favorite color is. We hope you have enjoyed using this application. Encourage your friends to tell us their favorite color as well!"; this.Master.Api.Notifications.SendEmail(this.Master.Api.Session.UserId.ToString(), subject, body, string.Empty); } private void CreateScript() { var saveColorScript = @" function saveColor(color) { document.getElementById('" + colorInput.ClientID + @"').value = color; } function submitForm() { document.getElementById('" + form.ClientID + @"').submit(); } "; if (!ClientScript.IsClientScriptBlockRegistered(SCRIPT_BLOCK_NAME)) { ClientScript.RegisterClientScriptBlock(this.GetType(), SCRIPT_BLOCK_NAME, saveColorScript); } } } my directory structure is 1)the master page is in the root. 2)the default.aspx is in the root/alfbet directory. 3)i have also have the xd_receiver.htm inside root/channel directory. that inside the master page their is the folowing line: <script type="text/javascript"> FB_RequireFeatures(["XFBML"], function() { FB.Facebook.init("c81f17ee4d4ffc5113c55f8b99fdcab5", "channel/xd_receiver.htm"); }); </script> the problem is that the applicatin dosent work apps.facebook.com/alefbet/default.aspx why it dosent work ? please help me and others who also obstacle in this issue. i tryied lots of things, one of them was to display the user id. for that i put label in the default.aspx and wrote lblTest.Text = Master.Api.Users.GetInfo().uid.ToString(); and it dosent event get to this line. i know it because it keeps display in the label.text the word "label" thank you very much.

    Read the article

  • redeclaration of enumerator

    - by robUK
    Hello, gcc 4.1.2 c99 I have the following enum's in this file ccsmd.h : enum options_e { acm = 0, anm, smd, OPTIONS_LAST_ENTRY, OPTIONS_ENTRY_COUNT = OPTIONS_LAST_ENTRY }; enum function_mode_e { play = 0, record, bridge, MODE_LAST_ENTRY, MODE_ENTRY_COUNT = MODE_LAST_ENTRY }; error: redeclaration of enumerator ‘LAST_ENTRY’ error: previous definition of ‘LAST_ENTRY’ was here error: redeclaration of enumerator ‘ENTRY_COUNT’ error: previous definition of ‘ENTRY_COUNT’ was here I have the LAST_ENTRY so that I can use that as the index of an array. So I like to keep it the same across all enums. Many thanks for any advice,

    Read the article

  • Why does the proxy generated code create the wrong class namespace when a MessageContract is in my W

    - by DaleyKD
    I have created two WCF Services (Shipping & PDFGenerator). They both, along with my ClientApp, share an assembly named Kyle.Common.Contracts. Within this assembly, I have three classes: namespace Kyle.Common.Contracts { [MessageContract] public class PDFResponse { [MessageHeader] public string fileName { get; set; } [MessageBodyMember] public System.IO.Stream fileStream { get; set; } } [MessageContract] public class PDFRequest { [MessageHeader] public Enums.PDFDocumentNameEnum docType { get; set; } [MessageHeader] public int? pk { get; set; } [MessageHeader] public string[] emailAddress { get; set; } [MessageBodyMember] public Kyle.Common.Contracts.TrackItResult[] trackItResults { get; set; } } [DataContract(Name = "TrackResult", Namespace = "http://kyle")] public class TrackResult { [DataMember] public int SeqNum { get; set; } [DataMember] public int ShipmentID { get; set; } [DataMember] public string StoreNum { get; set; } } } My PDFGenerator ServiceContract looks like: namespace Kyle.WCF.PDFDocs { [ServiceContract(Namespace="http://kyle")] public interface IPDFDocsService { [OperationContract] PDFResponse GeneratePDF(PDFRequest request); [OperationContract] void GeneratePDFAsync(Kyle.Common.Contracts.Enums.PDFDocumentNameEnum docType, int? pk, string[] emailAddress); [OperationContract] Kyle.Common.Contracts.TrackResult[] Test(); } } If I comment out the GeneratePDF stub, the proxy generated by VS2010 realizes that Test returns an array of Kyle.Common.Contracts.TrackResult. However, if I leave GeneratePDF there, the proxy refuses to use Kyle.Common.Contracts.TrackResult, and instead creates a new class, ClientApp.PDFDocServices.TrackResult, and uses that as the return type of Test. Is there a way to force the proxy generator to use Kyle.Common.Contracts.TrackResult whenever I use a MessageContract? Perhaps there's a better method for using a Stream and File Name as return types? I just don't want to have to create a Copy method to copy from ClientApp.PDFDocServices.TrackResult to Kyle.Common.Contracts.TrackResult, since they should be the exact same class. Thanks in advance, Kyle

    Read the article

  • Why does the proxy generated code create a new class when a MessageContract is in my WCF Service?

    - by DaleyKD
    I have created two WCF Services (Shipping & PDFGenerator). They both, along with my ClientApp, share an assembly named Kyle.Common.Contracts. Within this assembly, I have three classes: namespace Kyle.Common.Contracts { [MessageContract] public class PDFResponse { [MessageHeader] public string fileName { get; set; } [MessageBodyMember] public System.IO.Stream fileStream { get; set; } } [MessageContract] public class PDFRequest { [MessageHeader] public Enums.PDFDocumentNameEnum docType { get; set; } [MessageHeader] public int? pk { get; set; } [MessageHeader] public string[] emailAddress { get; set; } [MessageBodyMember] public Kyle.Common.Contracts.TrackItResult[] trackItResults { get; set; } } [DataContract(Name = "TrackResult", Namespace = "http://kyle")] public class TrackResult { [DataMember] public int SeqNum { get; set; } [DataMember] public int ShipmentID { get; set; } [DataMember] public string StoreNum { get; set; } } } My PDFGenerator ServiceContract looks like: namespace Kyle.WCF.PDFDocs { [ServiceContract(Namespace="http://kyle")] public interface IPDFDocsService { [OperationContract] PDFResponse GeneratePDF(PDFRequest request); [OperationContract] void GeneratePDFAsync(Kyle.Common.Contracts.Enums.PDFDocumentNameEnum docType, int? pk, string[] emailAddress); [OperationContract] Kyle.Common.Contracts.TrackResult[] Test(); } } If I comment out the GeneratePDF stub, the proxy generated by VS2010 realizes that Test returns an array of Kyle.Common.Contracts.TrackResult. However, if I leave GeneratePDF there, the proxy refuses to use Kyle.Common.Contracts.TrackResult, and instead creates a new class, ClientApp.PDFDocServices.TrackResult, and uses that as the return type of Test. Is there a way to force the proxy generator to use Kyle.Common.Contracts.TrackResult whenever I use a MessageContract? Perhaps there's a better method for using a Stream and File Name as return types? I just don't want to have to create a Copy method to copy from ClientApp.PDFDocServices.TrackResult to Kyle.Common.Contracts.TrackResult, since they should be the exact same class. Thanks in advance, Kyle

    Read the article

  • Best method to store Enum in Database

    - by LnDCobra
    What is the best method of storing an Enum in a Database using C# And Visual Studio and MySQL Data Connector. I am going to be creating a new project with over 100 Enums, and majority of them will have to be stored in the database. Creating converters for each one would be a long winded process therefore I'm wondering if visual studio or someone has any methods for this that I haven't heard off.

    Read the article

  • How to represent different entities that have identical behavior?

    - by Dominik
    I have several different entities in my domain model (animal species, let's say), which have a few properties each. The entities are readonly (they do not change state during the application lifetime) and they have identical behavior (the differ only by the values of properties). How to implement such entities in code? Unsuccessful attempts: Enums I tried an enum like this: enum Animals { Frog, Duck, Otter, Fish } And other pieces of code would switch on the enum. However, this leads to ugly switching code, scattering the logic around and problems with comboboxes. There's no pretty way to list all possible Animals. Serialization works great though. Subclasses I also thought about where each animal type is a subclass of a common base abstract class. The implementation of Swim() is the same for all Animals, though, so it makes little sense and serializability is a big issue now. Since we represent an animal type (species, if you will), there should be one instance of the subclass per application, which is hard and weird to maintain when we use serialization. public abstract class AnimalBase { string Name { get; set; } // user-readable double Weight { get; set; } Habitat Habitat { get; set; } public void Swim(); { /* swim implementation; the same for all animals but depends uses the value of Weight */ } } public class Otter: AnimalBase{ public Otter() { Name = "Otter"; Weight = 10; Habitat = "North America"; } } // ... and so on Just plain awful. Static fields This blog post gave me and idea for a solution where each option is a statically defined field inside the type, like this: public class Animal { public static readonly Animal Otter = new Animal { Name="Otter", Weight = 10, Habitat = "North America"} // the rest of the animals... public string Name { get; set; } // user-readable public double Weight { get; set; } public Habitat Habitat { get; set; } public void Swim(); } That would be great: you can use it like enums (AnimalType = Animal.Otter), you can easily add a static list of all defined animals, you have a sensible place where to implement Swim(). Immutability can be achieved by making property setters protected. There is a major problem, though: it breaks serializability. A serialized Animal would have to save all its properties and upon deserialization it would create a new instance of Animal, which is something I'd like to avoid. Is there an easy way to make the third attempt work? Any more suggestions for implementing such a model?

    Read the article

  • C++ enum in foreach

    - by Spencer
    I've have a card class for a blackjack game with the following enums: enum Rank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }; enum Suit { Clubs, Diamonds, Hearts, Spades }; When I create the deck I want to write the code like this: // foreach Suit in Card::Suit // foreach Rank in Card::Rank // add new card(rank, suit) to deck I believe there is no foreach in c++. However, how do I traverse an enum? Thanks, Spencer

    Read the article

  • In Objective C, is there a way to call reference a typdef enum from another class?

    - by Adrian Harris Crowne
    It is my understanding that typedef enums are globally scoped, but if I created an enum outside of the @interface of RandomViewController.h, I can't figure out how to access it from OtherViewController.m. Is there a way to do this? So... "RandomViewController.h" #import <UIKit/UIKit.h> typedef enum { EnumOne, EnumTwo }EnumType; @interface RandomViewController : UIViewController { } and then... "OtherViewController.m" -(void) checkArray{ BOOL inArray = [randomViewController checkArray:(EnumType)EnumOne]; }

    Read the article

  • Strongly typed `enum`s in VS10?

    - by Motti
    This question pointed to a wiki page for C++0x support which lists Strongly typed enums as Partially supported in VS10. However this creates a compilation error: enum class boolean { no, yes, maybe }; Any idea what constitutes partial support when the basic syntax isn't accepted?

    Read the article

  • Which Java version do you mostly (have to) work with?

    - by ferdystschenko
    While from version 5 on, Java provides many extremely useful features like annotations, enums, generics, etc., 1.4 is still in use in many enterprise projects. So I'm wondering what the chances are that you still have to work with 1.4, thus being forced to go without JPA, EJB3 etc. In your answer, please also state the branch of company you work for. Which are the reasons for not switching to Java 5? Thanks, Armin

    Read the article

  • Silverlight3 bind checkbox list to a datagrid

    - by Stester
    I have a enum, like public enum TestType { Red = 1, Blue = 2, Green = 3, Black = 4 } I want to attach those values to a datagrid as checkboxes in silverlight 3. (I would like to bind to a listview, but its not exists in silverlight) Manage to get the enums to a ObservableCollection, any help to bind to datagrid? I tried with ItemsSource="{Binding Path=nameOfTheObservableCollection, }"

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >