FHIR: Multiple Classes with same name in a Project using (.Net) - c#

I am attempting to generate c# classes of FHIR Resources, How handle Multiple classes with same name? For Example -> In Organization and Patient resources there are Composed classes with same name "Contact" and Contact is one Complex date Type too. etc... Please Help
http://www.hl7.org/implement/standards/fhir/organization.html
http://www.hl7.org/implement/standards/fhir/datatypes.html#Contact
Regards

I don't think the XSD.exe tool is capable of doing this, your best bet maybe to manually nest those classes where this is a problem, and then using the serialization attributes (most notable XmlTypeAttribute) to change the name of the types in the XSD if at all necessary.
Please note that a completely generated set of classes is part of the .NET reference implementation for FHIR (http://www.github.com/ewoutkramer/fhir-net-api). We'll soon have the class generator for this available as part of this project, including a set of support functions to serialize them correctly to FHIR XML and FHIR Json.

The full class name of organization contact is actually Organization.contact.

Related

Is it possible to generate C# class by deserialization some protocol?

I need to generate or define new class based on deserialization serialized class. So I want to transfer class definition from server to client to have access to it's properties later.
Is it possible and how?
Proper way to do it would be to either expose a schema definition for your service for clients to consume & generate strongly type class definitions from that or provide a DLL with your DTO contract definitions (class/interface definitions) to the client.
If you chose neither of those approaches (no schema & no dll with interfaces) but still
want to generate a class definition, you can in an improper way generate .cs class definitions, from a sample data of the service (call the services couple of times and intercept the responses or use some http client). However this approach does not guarantee that you will get an accurate or/and complete generation. Basically you can go from:
XML->XSD->C# cs class file (or even XML to C# cs file directly)or JSON->C# class file
And deserializing object to dynamic especially when you don't own both the server & client code is pretty much the worst thing you can do. And this way you didn't transfer you class definition to the client. Deserializng to dynamic objects is actually no desrialization at all as matter of fact, it gives you a dictionary of strings with syntactical sugar to access them as properties at runtime with not compile time support which can be equal to a disaster. In short don't do it unless you own all the code (not that it's a good idea then either but maybe you could get by somehow)
One portable way to transfer the property definitions and the data itself is to use the JSON serializer.
You can deserialize into a dynamic object using JSON.Net
Deserialize json object into dynamic object using Json.net

WCF Attribute Weaver

Is there a weaver for WCF that auto implements the DataContract and DataMember attribute to my entity class?
We are migrating the local back-end of our system to a WCF Service. We have too many entity class and it will really take an awful lot of time to add that attribute in each of our entity class.
Please refer to this link for reference of a weaver, It is for INotifyPropertyChange for WPF and it really does help.
My code is in C#, framework 4.0, build in Visual Studio 2010 Pro.
Any help will be greatly appreciated.
Thanks in advance.
Depending on what technology you use, you may decide not to directly expose your entity classes. For instance, it's not a good idea to expose Entity Framework entities, as this will also serialize the base classes, which you probably don't want.
I recommend you try serializing one of your entities, then look at the resulting client code to see if anything undesirable comes across the wire.
If there is a problem, then you may want to design Data Transfer Objects to correspond to each of your entities. This might be done using code generation, so you don't have to do it all by hand.
You do not have to apply DataContract/DataMember attributes on all entities.
By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized.
Source: Using Data Contracts

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.

Converting from One Class to another Class using Xml Serialization in C#

In our project we are consuming WCF webservices exposed at Central location as services with basicHttpBinding.
In client desktop application we need consume those webservices. I am able to generate proxy class using WSDL.exe.
But, I need to convert data/class given by the webservice into my local class, for that now I am xmlserialzing those class/objects given by webservice and deserializing into my local classes as both classes schema matches exactly same.
Is there any better way that I can follow?
or
Do I need to assign each property from one class to another?
thanks
nRk.
declare class manually instead of generating. This is the most DRY solution.
try Automapper
If you have control on your local classes (they are not generated code; or you are generating them, yourself) you can use xml attributes to decorate your class, so you can serialize and deserialize it to that xml you work with and you do not have to have specific names for your properties. In addition to this, you may have additional properties on your local class.
If you have not control on defining your local classes, then you have to define a converter or as elder_george mentioned, use AutoMapper.
Using a manual written converter IMO is the fastest way and you can define them as implicit converter operators on your local class.
I've done the serialize/deserialize thing myself just as you had. If your classes have the same properties as the proxy classes you could write a helper method that uses reflection to iterate through the properties of the proxy and set the corresponding properties of your class. As long as the property names are the same, that one method should work on all classes.
A few thoughts:
use assembly sharing via WCF; this allows you to use the same actual assembly at both ends. As long as this is a DTO assembly, this is fine (not hugely portable, though). This is /reference (also /r) in svcutil.exe, or you can do it via the IDE
use DataContractSerializer and round-trip (like you are already; just that WCF maps most closely to DataContractSerializer, not XmlSerializer)

Attributes in C#

I know that C# (and .NET in general) is big on attributes. However, despite the fact I have programmed in C# for many years, I haven't found myself ever using them. Would someone get me started on them, and explain where is the best to use them?
Thanks
From Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition by Andrew Troelsen
Understanding Attributed Programming
One role of a .NET compiler is to generate metadata
descriptions for all defined and referenced types. In addition to this standard metadata contained
within any assembly, the .NET platform provides a way for programmers to embed additional
metadata into an assembly using attributes. In a nutshell, attributes are nothing more than code
annotations that can be applied to a given type (class, interface, structure, etc.), member (property,
method, etc.), assembly, or module.
The idea of annotating code using attributes is not new. COM IDL provided numerous predefined
attributes that allowed developers to describe the types contained within a given COM server.
However, COM attributes were little more than a set of keywords. If a COM developer needed to
create a custom attribute, he or she could do so, but it was referenced in code by a 128-bit number
(GUID), which was cumbersome at best.
Unlike COM IDL attributes (which again were simply keywords), .NET attributes are class types
that extend the abstract System.Attribute base class. As you explore the .NET namespaces, you will
find many predefined attributes that you are able to make use of in your applications. Furthermore,
you are free to build custom attributes to further qualify the behavior of your types by creating a
new type deriving from Attribute.
Understand that when you apply attributes in your code, the embedded metadata is essentially
useless until another piece of software explicitly reflects over the information. If this is not the case,
the blurb of metadata embedded within the assembly is ignored and completely harmless.
Attribute Consumers
As you would guess, the .NET 3.5 Framework SDK ships with numerous utilities that are indeed on
the lookout for various attributes. The C# compiler (csc.exe) itself has been preprogrammed to
discover the presence of various attributes during the compilation cycle. For example, if the C#
compiler encounters the [CLSCompliant] attribute, it will automatically check the attributed item to
ensure it is exposing only CLS-compliant constructs. By way of another example, if the C# compiler
discovers an item attributed with the [Obsolete] attribute, it will display a compiler warning in the
Visual Studio 2008 Error List window.
In addition to development tools, numerous methods in the .NET base class libraries are preprogrammed
to reflect over specific attributes. For example, if you wish to persist the state of an
object to file, all you are required to do is annotate your class with the [Serializable] attribute. If
the Serialize() method of the BinaryFormatter class encounters this attribute, the object is automatically
persisted to file in a compact binary format.
The .NET CLR is also on the prowl for the presence of certain attributes. Perhaps the most
famous .NET attribute is [WebMethod]. If you wish to expose a method via HTTP requests and automatically
encode the method return value as XML, simply apply [WebMethod] to the method and the
CLR handles the details. Beyond web service development, attributes are critical to the operation of
the .NET security system, Windows Communication Foundation, and COM/.NET interoperability
(and so on).
Finally, you are free to build applications that are programmed to reflect over your own custom
attributes as well as any attribute in the .NET base class libraries. By doing so, you are essentially
able to create a set of “keywords” that are understood by a specific set of assemblies.
Applying Attributes in C#
The .NET base class library provides a number of attributes in various
namespaces. Below is a snapshot of some—but by absolutely no means all—predefined
attributes.
A Tiny Sampling of Predefined Attributes
[CLSCompliant]
Enforces the annotated item to conform to the rules of the Common
Language Specification (CLS). Recall that CLS-compliant types are
guaranteed to be used seamlessly across all .NET programming languages.
[DllImport]
Allows .NET code to make calls to any unmanaged C- or C++-based code
library, including the API of the underlying operating system. Do note that
[DllImport] is not used when communicating with COM-based software.
[Obsolete]
Marks a deprecated type or member. If other programmers attempt to use
such an item, they will receive a compiler warning describing the error of
their ways.
[Serializable]
Marks a class or structure as being “serializable,” meaning it is able to persist
its current state into a stream.
[NonSerialized]
Specifies that a given field in a class or structure should not be persisted
during the serialization process.
[WebMethod]
Marks a method as being invokable via HTTP requests and instructs the CLR
to serialize the method return value as XML.
Building Custom Attributes
The first step in building a custom attribute is to create a new class deriving from System.Attribute. Example:
// A custom attribute.
public sealed class VehicleDescriptionAttribute : System.Attribute
{
private string msgData;
public VehicleDescriptionAttribute(string description)
{
msgData = description;
}
public VehicleDescriptionAttribute() { }
public string Description
{
get { return msgData; }
set { msgData = value; }
}
}
As you can see, VehicleDescriptionAttribute maintains a private internal string (msgData)
that can be set using a custom constructor and manipulated using a type property (Description).
Beyond the fact that this class derived from System.Attribute, there is nothing unique to this class
definition.
For security reasons, it is considered a .NET best practice to design all custom attributes as sealed. In
fact, Visual Studio 2008 provides a code snippet named Attribute that will dump out a new System.
Attribute-derived class into your code window.
Attributes get more use in code targeted to other programmers or between distinct parts of a program, rather than code targeted at end users.
For example, you could use attributes to import a dll, indicate how types would interact with visual studio (designer visible, intellisense helps, debugger step-through, etc), how to serialize them, indicate a type is obsolete, describe default values, descriptions, handle COM access, etc.
Those are things that are largely invisible to the end user and that a single programmer could put elsewhere in the source code. But they're useful when only the compiled binary is available and not the source.
I like to use attributes as metadata to my code. We have created some simple attributes that let us tag who wrote what code, when, and why. This lets us have both documented changes in code and in runtime. If there are any exceptions during runtime, we can inspect the callstack, look at any attributes on the methods along the way, and track down the people responsible:
[Author("Erich", "2009/04/06", Comment = "blah blah blah")]
public void MyFunction()
{
...
}
Of course, we could use our source control to look at who checked in what code, but this I've found makes the information more available in the place where you need it. Also, if we ever change source control, that information will not be lost since it is persisted in code.
Attributes are a form of declarative programming, 'similar' to creating your UI in XAML. It 'marks' pieces of code (classes, methods, properties, whatever) with an attribute so that you can later gather all those pieces marked in a specific way and then do something standard with all of them.
Eg. Consider the scenario where you have certain sections of code that you want to run once each time your app starts. In one model of programming (non-attribute) you go to your main method and explicitly call those init methods. With attributes you simply gather all methods which you've marked with your 'init' attribute, and call them via reflection.
The same pattern holds for actions like serialization, persistence and whatnot...
I believe you mean that you do not use (or frequently use) custom defined attributes ?
In my current project, I make heavy use of custom attributes, but, the fact that you need to keep in the back of your mind, is that using attributes should not be a goal on itself.
It is a tool / purpose to get to a given solution.
I sometimes use custom attributes in combination with a weaver like PostSharp, to decorate methods where some weaving should be applied to at compile-time.
In my current project, I also use attributes to decorate certain types with additional info ... But I believe I've posted about this here before:
Cool uses of Attributes or Annotations (CLR or Java)?
I use attributes for the following:
Communicating with a plug-in architecture
Telling another framework what to do with the code (NUnit, for instance)
Adding metadata for use with other code (See PropertyGrid)
Mapping objects to databases (See Castle ActiveRecord)
When writing my own APIs to allow users to communicate metadata
In framework code to tell the debugger to skip over it
Those are off the top of my head. I use them in many other places
Attributes are very good at describing some runtime behaviour of your code that is orthoganal to the code in question. For example, in a class called Customer you would model a customer, right? But you might not want to model or describe the way a Customer object is serialized.
Adding attributes to your Customer class allows you to tell some other part of the runtime how it should deal with your Customer.
MSTest and NUnit makes use of attributes to tell the test framework how it should use classes that define test fixtures.
ASP.NET MVC uses attribute to tell the mvc framework which methods on classes it should treat as controller actions.
So, any place where you have a runtime behaviour that you wish to model attributes can be useful.
Class Attribute definition is available here
ClassInterfaceAttribute : Indicates the type of class interface to be generated for a class exposed to COM, if an interface is generated at all.
ComDefaultInterfaceAttribute : Specifies a default interface to expose to COM. This class cannot be inherited.
ComVisibleAttribute: Controls accessibility of an individual managed type or member, or of all types within an assembly, to COM.

Categories

Resources