Deserialize variables in Azure Devops API in C# - azure-devops-rest-api

I am using Azure Devops API to read the variables groups in C#.
I am able to deserialize it into a custom object (with same properties) as long as i dont include the variables. Since variables seems like a dynamic object i am not able to deserialize it.
Here is my sample JSON reponse:
{
"id":77,
"type":"Vsts",
"variables":{
"key1":{"value":"value1"},
"key2":{"value":"value2"}
}
}
Here is my custom object
public class AzureVariableGroup
{
public string id { get; set; }
public string type { get; set; }
//public string variables { get; set; }
}
Is there an efficient way to deserialize the whole object including "variables"

Related

Pass Lists to MVC controller Action using POSTMan chrome extention

I am using Postman Chrome extension to test my MVC service API.
The model that I pass to the controller looks as follows:
public class ActivateBenefitRequestModel
{
public int BenefitID { get; set; }
public int MemberID { get; set; }
public string Token { get; set; }
public List<AdditionalBenefitField> BenefitAdditionalFields { get; set; }
}
with
public class AdditionalBenefitField
{
public int BenefitFieldId { get; set; }
public string Value { get; set; }
}
How should I go about passing in the BenefitAdditionalFields List ?
Is it even possible?
Assuming that all you're doing is building a POST request string (not familiar with the extension), I believe you can just format your request to specify individual list elements indexed with URL-encoded square brackets:
...&AdditionalBenefitFields%5B0%5D.BenefitFieldId=1&AdditionalBenefitFields%5B0%5D.Value=Foo
&AdditionalBenefitFields%5B1%5D.BenefitFieldId=2&AdditionalBenefitFields%5B1%5D.Value=Bar&...
This is how a POST request for a list of complex types looks in one of our MVC3 projects and I'm pretty sure we don't do anything special with it.
So I got it and it's pretty easy:
Just set separate text values in your form data in the PostMan extention
BenefitAdditionalFields[0].BenefitFieldId
BenefitAdditionalFields[0].Value
BenefitAdditionalFields[1].BenefitFieldId
BenefitAdditionalFields[1].Value

How do I send a state-only object containing another state-only object to a Web API controller?

I am trying to send a simple object (AjaxSubmission) from a form to a Web API controller used to edit tables.
AjaxSubmission always has the same fields. One field, "data" refers to another simple object with accessors for the specific table (Employees or Vendors examples below).
public class AjaxSubmission
{
public string action { get; set; }
public string table { get; set; }
public string id { get; set; }
// ...
//// The following may be any other custom class
public Employees data { get; set; } // Could be Vendors or whatever
}
// Stored in AjaxSubmission (or so I hope)
public class Employees
{
public string name { get; set; }
public float salary { get; set; }
public long id { get; set; }
}
// Stored in AjaxSubmission
public class Vendors
{
public string dba { get; set; }
public int accountNum { get; set; }
public int zipcode { get; set; }
}
My controller gets the data like so:
public EditorServerResponse Put(AjaxSubmission ajaxSubmission = null) {
// Handle the data
}
When I make "data" an Object or Dynamic, it shows up as an empty object. I can't "as" it to Employees or Vendors because it doesn't store anything.
I suspect this is a limitation of the serializer. MVC4 uses JSON.NET for JSON, but the data is sent as "Content-Type: application/x-www-form-urlencoded; charset=UTF-8".
I cannot easily change the way data is sent because that is how the Datatables editor plug-in does its business. I think it's a reasonable way to send data and a reasonable problem for .NET to be able to handle.
I can get the data I need if I make a distinct class for each data type that AjaxSubmission might contain, but each would be a duplicate other than one line of code. That horribly violates the DRY principle.
My question is: How can I send AjaxSubmission without Repeating Myself? Is .NET capable of such a thing?
Edit:
Fiddler says the data looks like:
action edit
table
id row_4
data[amu] 49
data[chemicalFormula] BF2
data[commonName] Boron difluoride
data[status] Y
data[notes]
The raw data is:
action=edit&table=&id=row_4&data%5Bamu%5D=49&data%5BchemicalFormula%5D=BF2&data%5BcommonName%5D=Boron+difluoride&data%5Bstatus%5D=Y&data%5Bnotes%5D=
(This is different from my simplified examples but similar)

Custom type serializing issue in ASP.NET MVC WebAPI

I want to return a result from a method in my ASP.NET MVC WebAPI application with the following signature:
public class Result
{
public int ResultCode { get; set; }
public MapFeatureViewModel Params { get; set; }
public string Message { get; set; }
}
and the MapFeatureViewModel type signature is
public class MapFeatureViewModel
{
public long Id { get; set; }
public string Uuid { get; set; }
public string Feature { get; set; }
public long MapId { get; set; }
}
Everything works fine till now; but if I try to change the type of Params in Result class to "object" or "dynamic" in order to use it for all other methods I receive the following error message:
"You must write an attribute 'type'='object' after writing the attribute with local name '__type'."
Any idea how to make WebAPI serialize non-strongly typed properties?
The in-the-box formatters don't know how to deal with dynamics or object. You can however create a custom formatter (MediaTypeFormatter) that can write them out using custom logic. In the formatter add MediaTypeHeaderValue instances for "application/json" and "text/json" to the SupportedMediaTypes collection. You'll also want to override CanWriteType to limit the formatter to only work for the type you are serializing i.e. MapFeatureViewModel. You'll need to insert that formatter at the beginning of the collection so that it runs as opposed to the default formatter. You can do this by accessing the formatters collection on the configuration object.
There are couple alternatives to consider. In Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client. visit for more info
However, you may Deserialize JSON into C# dynamic object. How to do that, well there is a good post on this topic. visit for more info

How does one encode a model in x-www-form-urlencoded format so it can be consumed by an ASP.NET MVC action?

Assume I have an ASP.NET MVC 3 Controller that looks like this
public class MyController : Contoller
{
public ActionResult Edit(MyModel model)
{
/* doing some stuff with the model */
}
}
The model looks like this
public class MyModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public ThatModel Property1 { get; set; }
public List<ThisModel> BunchOfThisModel { get; set; }
}
public class ThatModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property4 { get; set; }
public string Property5 { get; set; }
public string Property6 { get; set; }
}
public class ThisModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
Does ASP.NET MVC or .NET (v4 is ok, v4.5 not) provide any built-in means to encode a model (say MyModel in this case) so that it can be sent to an action as form url encoded (aka x-www-form-urlencoded)? An example would be "property1=abc&property2=def". However, ASP.NET MVC has its own way to deal with nested models etc when decoding the request back to the model. Assume I'm simulating a browser using the WebRequest/WebResponse APIs provided since .NET 1.1.
In essence, I'd like to build up requests in tests to verify that
some data is excluded through binding, if needed
the anti forgery token is set, if needed
malicious data is handled accordingly
Note: ASP.NET Web API is not being used at this stage. Because I'm writing (integration) tests for an existing application, sending the model as JSON, XML or another alternative format isn't applicabile to the question.
I hope I've understood this question correctly, but provided you are 'POST'ing that data (from JSON?) then it is able to build up the model using a best-guess process.
Property names are matched, so if you sent (guessing the duplicate Property1 is actually Property3 here)
{
Property1="this",
Property2="that",
Property3={Property1="this3", ....},
BunchOfThisModel=[{Property1="bunchthis"},{....}]
}
This would populate your POCO with whatever names matched. If you left out a property (i.e. Property2) it would take on it's default(T) value.
Sending your object model in a GET request would be much more complicated, you could base64 the JSON string, and then parse it on server which is popular approach, but given it's a complex model POST might work best for your intentions.
You can also use a CustomBinder (a good article is here). You can also control which properties are bound to your POCO object by using the BindAttribute with the Exclude/Include options.
Hope I haven't missed the point and this proves useful :)

MVC4 De/Serialization with JSON / JSON.NET - List<BaseClass> and derived types inside

I am trying to do some basic communication with MVC4 Controllers over JSON.
I need to send and receive data at both points. For the client am using RestSharp.
My Problem is, that the List of TheObjectIWantToTransfer has no values, when it is transmitted to the server.
Thats why i started playing around with Json.NET on the controller side as well.
These are example class, how the stuff looks like i want to transfer.
public class TheObjectIWantToTransfer
{
public int JustAGeneralNumber { get; set; }
[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
public List<MyBaseType> Data { get; set; }
public TheObjectIWantToTransfer()
{
Data = new List<MyBaseType>();
}
}
// class of the list
[KnownType(typeof(MyDerivedTypeA))]
[KnownType(typeof(MyDerivedTypeB))]
public abstract class MyBaseType
{
public string SomeGeneralStuff { get; set; }
}
public class MyDerivedTypeA : MyBaseType
{
public int Foo { get; set; }
}
public class MyDerivedTypeB : MyBaseType
{
public int Bar { get; set; }
public string IamYourFather { get; set; }
}
I also tried using the
var settings = new JsonSerializerSettings()
{TypeNameHandling = TypeNameHandling.All};
with JsonConvert Serialize/Deserialize. The output changed, but i still didn't got it working. He was unable to find the referenced types, and i have no idea how to receive a
TypeNameHandling.All Json.NET Object at a Controller.
I have created the JsonNetResult which gives me the possibility to serialize with TypeNameHandling.All and send the data to the client. But i can't receive/deserialize with Json.NET?
public JsonNetResult MyAction(MyClassType blub)
{
// blub ?? is beeing deserialized by the default JSON deserializer of MVC.
}
I just need a solution. I Would be happy to keep the normal Json() method of MVC if this is possible.
I can't believe its not working with derived types in an array. There must be some kind attribute or hack to activate this.
Or i am doing something crazy really really wrong..
Thx !

Resources