Change Datamember name dynamically for a parameter (includes $ in parameter name) - c#

I have a problem where i need to output an object from a wcf restful service with a $ in it. I've tried outputting a dictionary but when that serializes to JSON the $gets encoded. The service i am communicating with requires the object to look like this [{$name : value}]
Is it possible to change the Name in the data member attribute on a parameter at runtime?
[DataMember(Name = "RenameMe")]
public string Values { get; set; }
public Variable(string name, string values)
{
this.Values = values;
[set the name attribute to : "$name"]
}

Related

How to use c# 'DisplayNameAttribute' with dynamic values?

Want to display Name & country field in localized language.
In our application, we support various language based on the user preferred language, the translation has to happen for below model properties. Thought of encapsulating the translation with the "custom attribute" class but how to get the "Name", "Country" properties values in the custom attributes, so that I can find the translation word match for the given property value and assign to the 'DisplayName' property of 'DisplayNameAttribute' type.
If 'DisplayNameAttribute' type can't be used for dynamic displayname value, suggest me how the localization can be achieved using c# attributes or there better way to do localization.
P.S: our translation files are stored in the Azure bolob as .json files not as .resx files as part of app build package
class Sample
{
[LocalizedDisplayName()]
public string Name { get; set; }
[LocalizedDisplayName()]
public string Country{ get; set; }
}
internal sealed class LocalizedDisplayName : DisplayNameAttribute
{
private readonly string _dependentPropValue; //how to get this??
private string displayName;
public LocalizedDisplayName(string dependentPropValue)
{
_dependentPropValue = dependentPropValue;
}
public override string DisplayName
{
get
{
return displayName = DoTranslation(dependentPropValue);
}
}
}

How to fetch value from an ExtensionDataObject of a wcf reponse

I have a WCF service which returns ExtensionDataObject during runtime as attached snapshot:
Im struck with fetching value for these objects. Could anyone please help here:
Have tried with below code using reflection, which throws Parameter count missing exception
List<System.Runtime.Serialization.ExtensionDataObject> extData = temp.Select(x => x.ExtensionData).ToList();
var GetCountry = extData.GetType().GetProperties();
string Country = string.Empty;
foreach (var property in GetCountry)
{
string name = property.Name;
object value = property.GetValue(extData, null);
if (name == "Country")
Country = value.ToString();
}
The Extensiondataobject field is generated to control the data contract incompatibility between the server and the client, so it will return a field named extensiondataobject. In other words, your client data contract implements the IExtensionDataObject interface.
[DataContract(Namespace="abcd")]
public class Product: IExtensibleDataObject
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
public ExtensionDataObject ExtensionData { get ; set ; }
}
If we capture this request through Fiddle, you can even see all the data directly.
In a word, you only need to add the Country property to the Data class of X object. It will be deserialized automatically. This class should be your client-side data contract class, instead of the server-side data class.
Finally, it seems that the value of these fields is null. We should ensure that the server and client data contracts have the same namespace. It cannot be the default value(http://tempuri.org). As I defined above, this namespace attribute should be consistent with the server-side value.
Feel free to let me know if there is anything I can help with.

MVC Web API ignores XmlSerializerFormat and uses DataContractSerliazer instead

I have a DTO and a Domain project in my solution and an MVC front end with web api to expose data.
I have the web api controller set up and the action is getting my DTO object back from the DataService. That's all great, however, I want xml to be returned and I want some of the values to be in xml attributes e.g.
<root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<lookups>
<lookup category="General" field="Alert Type" value="Lack of Transparency" entityid="2273"/>
<lookup category="General" field="Alert Type" value="Unfair Terms " entityid="2274"/>
<lookup category="General" field="Alert Type" value="Operator Concerns" entityid="2275"/>
...
</lookups>
<paymentmethods />
<affiliates />
</root>
The Lookup class is as follows:
[Serializable]
[XmlSerializerFormat]
public class Lookup
{
[XmlAttribute("category")]
public String Category { get; set; }
[XmlAttribute("field")]
public String Field { get; set; }
[XmlAttribute("value")]
public String Value { get; set; }
[XmlAttribute("entityid")]
public String EntityId { get; set; }
public Lookup(String Category, String Field, String Value, int? EntityId = null)
{
this.Category = Category;
this.Field = Field;
this.Value = Value;
this.EntityId = (EntityId != null ? EntityId.ToString() : null);
}
public Lookup() { }
}
initially I had my DTO objects (e.g Lookup, PaymentMethod and Affiliates) with my viewmodels, but moved them into my DTO project.
I have set UseXmlSerializer = true in my global.asax
Before moving the objects from hy viewmodels folder to the DTO project, it was working and I was getting the desired XML. AFTER moving, it appears to be ignoring the XmlSerializerFormat and using DataContractSerliazer.
So using DataMember attributes, I can format the xml, but obviously I can't set some properties to be serialised as xml attributes
Any thoughts on why it seems to be ignoring the [XmlSerializerFormat] and [XmlAttribute("field")] attributes?
I've read a few SO posts like:
XmlSerializer ignores [XmlAttribute] in WebApi and
How can you control .NET DataContract serialization so it uses XML attributes instead of elements?
I found the solution to this here:
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml_pertype
Setting the xml Serializer in the Global.asax to work on a specific type worked for me :
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
xml.SetSerializer<FullResponseRoot>(new XmlSerializer(typeof(FullResponseRoot)));
where FullResponseRoot is the name of the object that I am serialising (the classes mentioned above are properties of FullResponseRoot)
FullResponseRoot forms the root node of the generated xml

Null value after json deserialization on windows phone

I am using the Json.DeserializeObject method in windows phone, inorder to deserialize json, the problem I am having is one of the variable names, in the json has a space and I just can't get it to deserialize. it returns a null the whole time, and if I view the raw json it does contain a value
part of raw json:
\"Service Provider\":Test\"
When I try to generate a class for the json into which it needs to be deserialized, the Service Provider section tells me "Invalid Name" and that obviously doesn't work in C# as a variable name, but I believe the variable name can be anything:
public string __invalid_name__Service Provider { get; set; }
current code:
public string Service_Provider { get; set; }
Using Json.Net, Just decorate your property with "JsonProperty" Attribute
string json = #"{""Service Provider"":""Test""}";
var obj = JsonConvert.DeserializeObject<TempObject>(json);
public class TempObject
{
[JsonProperty("Service Provider")]
public string ServiceProvider;
}

Order of returned WCF JSON

I have a WCF service that returns some JSON from a serialized object:
public class Response
{
public string Token { get; set; }
public int UserId { get; set; }
...
}
I've added some extra properties to this class, but now some of the implementations fails because they read it like:
string[] ResultLoginValues = e.Result.ToString().Split(',');
and it's returned in alphabetically order instead of the old order with the new properties last.
Is there any way I can change the order, or should they rewrite the clients?
For solution refer WCF DataContract DataMember order

Categories