C# How to create objects without class definitions? - c#

Is it possible to create objects at designtime without having to have hard coded class definitions, then populate properties with primitives or even strongly typed data types?
This might sound confusing, so I will attempt to give you a use case scenario.
Use case:
You have an XML config file that could hold configuration values for connecting to various systems in an SOA application. In C# the XML file is read, but for each system the configuration properties are different (e.g: SQL might have a connection string, while SharePoint might need a username + password + domain + url, while yet an smtp server would need username + password + port + url)
So instead of creating static classes as follows
public class SharePointConfiguration or public class SQLConfiguration, then have each class with custom properties (this is cumbersome)
or
using a 1990's method, an ArrayList or some named collection
Is there not a more preferred way to achieve this? Taking advantage of new language features, that can still offer design time intellisense, which would make the code easier to maintain and less prone to error.
I guess I am looking for some kind of multipurpose .net 4 property holder.
Thanks

Use this sample implementation of a PropertyBag.
If property doesn't exist, create it on the fly...
http://www.codeproject.com/KB/recipes/propertybag.aspx

If you want emit code at runtime?
Checkout the Reflection.Emit namespace
OR better
RunSharp - nicer API

What you want is XML, based on a schema. This will give you IntelliSense, including code snippets, at the same time as providing flexibility.

Based on your question (and assuming I'm reading it right), that would be impossible. The closest you could get would be to use the 'dynamic' type and assign your values to properties at runtime on it - the problem being, that dynamic has no Intellisense support, and even with some other kind of solution, the Intellisense would not be available because the properties would only be attached at runtime.
Am I confused on what you are asking?

Related

Is there a better way of managing localized strings?

I work on a product where we have to worry a bit about localization. Currently, this is the workflow for when I have to use(or add) a localized string:
Search resources.resx file(which has hundreds of items)
If found, then copy the name. Otherwise, add a new string and copy the name
Then, use ResourceFactory.ResourceMgr.GetString("MY_MAGIC_STRING") (where ResourceMgr is just a static field to a ResourceManager)
This 3 step process for any strings is a real pain. Are there any patterns or ways to make this process easier?
Auto-generated files with access to each individual string are much easier to use - set "Custom tool" for RESX file to PublicResXFileCodeGenerator.
Code would look like:
using MyProject.Resources;
...
localizedText = Resources.SomeReasonableName;
Side notes:
having multiple RESX files along with auto-generated IDs have additional benefit of intellisense giving you reasonable number of choices.
depending on how translation is handled you may be better not worrying about duplicated text in RESX file (except maybe OK/cancel kind of strings). It may be easier to deal with duplicated strings at translation time.
There is this Java solution that might give you some ideas:
http://rodionmoiseev.github.com/c10n/
The idea is to store translations in the source code itself, using annotations on interface methods. Then, by using a special utility, you can dynamically create proxies (classes dynamically implementing the interface) that would return localised string value when invoking the interface method.
This way, "MY_MAGIC_STRING" is replaced with a call to MyMagicString() method, which gives you some spelling/type safety and makes it more refactoring friendly.

Why would you use 'custom attributes' in your code (.NET)

Could anyone explain the benefits (or reasons) to use custom attributes in your code. Of course I use (and understand the purpose of) defined attributes in certain scenarios (WCF, Serialization etc.), but I cannot imagine any algorithms where I would need to create and use my own custom attributes. Could someone provide a real-world case where usages of custom defined attributes bring something to a project.
The same reason as for WCF etc, but something that's specific to your project - you want to add some metadata to some members (types, fields, methods, whatever) to specify something about the mechanism involved, and it's not something which is covered by existing attributes.
For example, NUnit wanted to add their own indication that a particular type contained unit tests - there was no such existing attribute, so they created TestFixtureAttribute.
It's a relatively rare event, sure - but it can happen.
If you want to write your own system like WCF, Serialization, etc...
If you write code that iterates over types or members and does things with them, you will frequently want to use your own custom attributes to mark some members as being different or special.
I regularly use custom .Net attributes to support tooling in my infrastructure. One example was from very early in the .Net days (C# 1.0 to be exact). I was working on a research project which had a native C++ front and a brand new C# back end written by yours truly.
The front and back end shared a very similar object model which was evolving very rapidly. Not wanting to have to hand code both a C++ front end model, C++ serialization mechanism and a C# serialization mechanism I chose instead to attribute my C# types with custom attributes. They told me the parts of the model which were shared between the front and back end.
Once those attributes were in place I wrote a quick and dirty tool which
Parsed out the attributes to construct the core shared model
Generated the C# serialization code
Generated the C++ code
Generated the C++ serialization code
This made it dirt simple to keep my model up to date between my 2 projects. Just change the C# code, compile and re-run my tool.
I have used annotations in a custom AOP (Aspect-Oriented Programming) system I developed a while back. Attributes are also very useful for controlling orthogonal concerns like code generation.
Custom validation is a very good use case and can be seen from these links:
http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx
How to create Custom Data Annotation Validators
They can be used for marking tests, as in MBUnit for example. They can also be useful for code that inspects and loads classes (like a Plugin system) to provide meta-information.
They are really useful in building object mappers / ORM tools as well. If you ever decide to roll your own mapping system they are almost "required" to get all the functionality one would need. It's used more for making methods / classes more generic and using reflection to determine how to handle objects / select objects /etc...
To give you a specific case where I've used them. I once had to interact with a Mainframe screenscraper. I created a custom attribute to annotate which fields I wanted to send from my classes to the Mainframe, names that fell outside of conventions, special rules to deal with formatting and collections. I then had a class which was able to reflect over instances and realise which subset of fields were needed to interact with the mainframe screen scraper appropriately.

Is it possible to define an alias for a class in .NET?

The name of one of my classes was changed and I can't change it back. I have to mantain backwards compatibility and I don't want to write an wrapper with the old name.
Is there any easy way to give a class 2 names or to give it an alias?
Lifted from a comment by the OP:
Don't tell me to use the using directive since it must be done in the consumer side, and I don't want to change the projects that are using my library.
Arguably, your best option is to use a refactoring tool (like Resharper) to help you automate the conversion from the old name to the new name. However, if this is untenable to you for some reason, here are some alternatives:
If the types are in different assemblies you may be able to use a Type Forwarder. These allow you to redirect all references for a given type to an assembly ... but if IIRC, they can also redirect them to a new name as well.
Otherwise, within a single .cs source file you can apply a using statement:
using OldClassName = SomeNameSpace.NewClassName
This doesn't solve the problem globally, however, as it may become painful to change many .cs files to include this using statement.
Another alternative, may be to create a sub-class of the new type and name it the old name:
public class OldClassName : NewClassName
This gives you aliasing for the new class, but will require that you create duplicate public constructors and proxy static method calls to the renamed type. This is far from ideal ... and I generally don't recommend this.
Unfortunately, as the library author, the only way is X inherits Y, which has certain caveats.
It's possible but unlikely you could cheat with IL assembly.

Where's the best place to store a commonly-used variable?

What are the best way to store variables in a silverlight application?
Need to transfer store a customer ID throught the application but im not sure what is the best way
Disclaimer: This is a purely subjective answer. Others might object or have better suggestions.
I work mostly in VB.NET and over there, we've got the My.Application namespace where we can keep global variables. VB.NET users also have the option of using a Module for such purposes.
A Module, if I remember right, is equivalent to a static sealed class in C# so you can essentially do something of that sort.
To replicate VB.NET's functionality when I work in C#, I create a static class, with access level set to internal so its members are accessible from within the entire application.
Thus, when I assign a value to a member of the static class, it is accessible from all other classes in the application.
Hope this helps
Store the variable in a place where those things that need to get to it, can; and those things that don't need to get to it, can't. Can't say anything more specific without more information.
If you were following an MVVM pattern then I would have said as a property of the Customer model, with an instance of the customer model being accessed via the ViewModel.
Even if you aren't I would say within the application code and use binding where its needed in the UI. Otherwise you run the risk of changes to your UI causing the loss of customer ID storage at somepoint in the future.
If needed in more than one place then just create a repository that stores all of your data and have that accessed as needed (this way you can decouple your UIs from each other even if they use the same data source.
You may look at using InitParams, without knowing the situation I can't say much more.
http://msdn.microsoft.com/en-us/library/cc838255(VS.95).aspx

.NET Reflection Create Class Properties

I am fairly new to reflection and I would like to know, if possible, how to create an instance of a class then add properties to the class, set those properties, then read them later. I don't have any code as i don't even know how to start going about this. C# or VB is fine.
Thank You
EDIT: (to elaborate)
My system has a dynamic form creator. one of my associates requires that the form data be accessible via web service. My idea was to create a class (based on the dynamic form) add properties to the class (based on the forms fields) set those properties (based on the values input for those fields) then return the class in the web service.
additionally, the web service will be able to set the properties in the class and eventually commit those changes to the db.
If you mean dynamically create a class, then the two options are:
Reflection.Emit - Difficult, Fast to create the class
CodeDom - Less Difficult, Slower to create the class
If you mean create an instance of an existing class, then start with Activator.CreateInstance to create an instance of the object, and then look at the methods on Type such as GetProperty which will return a PropertyInfo that you can call GetValue and SetValue on.
Update: For the scenario you describe, returning dynamic data from a web service, then I'd recommend against this approach as it's hard for you to code, and hard for statically-typed languages to consume. Instead, as suggested in the comments and one of the other answers, some sort of dictionary would likely be a better option.
(Note that when I say return some sort of dictionary, I am speaking figuratively rather than literally, i.e. return something which is conceptually the same as a dictionary such as a list of key-value pairs. I wouldn't recommend directly returning one (even if you're using WCF which does support this) because it's typically better to have full control over the XML you return.)
I know this is being overly simplified by why not just KISS and generate the required Xml to return through the Web Service and then parse the returned Xml to populate the database.
My reasoning is that for the expanded reason you suggest doing this I can see the value or reason for wanting a dynamic class?
The Execution-Time Code Generation chapter of Eric Gunnerson's book (A Programmer's Introduction to C#) has some great information on this topic. See page 14 and onwards in particular. He outlines the two main methods of accomplishing dynamic class/code generation (CodeDOM and the Reflection.Emit namespace). It also discusses the difficulty and performance of the two approaches. Have a read through that, and you ought to find everything you might need.
The real question is, what do you need to use those properties for?
What are gonna be the use cases? Do you need to bind those properties to the UI somehow? Using what kind of technology? (WPF, Windows Forms?)
Is it just that you need to gather a set of key/value pairs at runtime? Then maybe a simple dictionary would do the trick.
Please elaborate if you can on what it is you need, and I'm sure people here can come up with plenty of ways to help you, but it's difficult to give a good answer without more context.

Categories

Resources