Build a WCF with generic type - c#

I want to build a service that will pass the data read from the database to the client in JSON format. I don't know the schema table and the types.
I thought about implementing the WCF over Dictionary but the JSON is very complicated and contains objects like "key = ...; value = ..." and i want just "key=value" and i need to return list of Dictionary objects. Sometimes from database i will receive a comma separated array, so i will insert in my Dictionary a key with a new Dictionary as value.
In PHP my boss said that it can be done through associative arrays. Please help me with some ideas or link because i don't know where to start to look.
If there is something that you didn't understood please comment and i will try another explanation.
Edits:
I need it to be a rest service, so JSON is mandatory.
How can i load data from the table ? What type can i use ?
Edit #2 : This is what i want to get : CorectJSON
Edit #3 : This is my current json :
stdClass Object
(
[areaGetStreetTypesResult] => stdClass Object
(
[responseMessage] => [{"name":"IMPASSE","street_type":"IMP"}{"name":"LOTISSEMENT","street_type":"LOT"}{"name":"ROUTE","street_type":"RTE"}{"name":"RUE","street_type":"RUE"}]
[response_status] => stdClass Object
(
[message] => Success : JSON created into the responseMessage variable !
[status] => 0
)
)
)
Is not containing some commas between so it cannot be decoded by php. What should i do ?
This is my method Code

I think that doing everything as a dictionary in webservice API is bad practice and I hate when I need to work with API's like this. If it is a WCF, it produces WSDL and WDSL describes the data is going in and out, so if everything is dictionary, WSDL can not provide anything meaningfull, so your datacontracts tell you nothing about the data.
If you need simply forward database data through webservice, WCF has DataServices http://msdn.microsoft.com/en-us/data/bb931106 although I think you should create API that fits your business needs and is not simple proxy between database and your client.

What is the reason why you need to pass JSON? If you want to create a WCF REST service, it is sufficient to tell WCF to create JSON messages as described here: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
If you access the service from a C# application, you don't need to care about how data is passed back and forth. Just take "normal" method parameters and use return values like you'd do locally and you're set.
Example:
string[] GetResultStrings(List<Rectangle> sourceRectangles);
If you really need to pass JSON strings, just pass strings and use the JSON serializer and deserializer to encode the reply and decode the parameters.
For example:
string GetJSONString(string jsonRequest);
The following information may help on using the JSON serializer and deserializer: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
EDIT
I'm using the following method to serialize serializable objects to JSON:
public static string SerializeJSON(this object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
This works just fine for any DataContract class like:
[DataContract]
public class MyJSONReturnableClass
{
[DataMember]
public string ThisBecomesANamedString;
[DataMember]
public MyJSONReturnableClass[] AndWorksAlsoForNestedArrays;
}

Populate your dictionary, then serialize it using JSon.
Pass it to your client using WCF or RabbitMq...
JsonConvert.SerializeObject(yourDict);
Download the NewtonSoft.dll
Put using:
using Newtonsoft.Json;

Related

Issues deserializing with service stack

I am having issues getting a list of an object out of redis using servicestack. The error is 'Type definitions should start with a '{' array....'
using (var redis = _redisService.GetClient())
{
redis.Set(key, myListOfThings.SerializeToString());
}
Appears to be valid formattable JSON in the cache:
[{"id":34,"someid":1012,"stuff":"blah"},{"id":33,"someid":1012,"stuff":"dfsfd"}]
But I am getting an error thrown in retrieval:
using (var redis = _redisService.GetClient())
{
return redis.Get<List<MyThing>>(key);
}
"Additional information: Type definitions should start with a '{',
expecting serialized type 'MyThing', got string starting with: [my
json string from cache]"
I even wrapped it so that the list is a child of a main object, which made the JSON start with a '{' but I still got the same error...
I also tried deserializing to an array, and various methods to deserialize but all within the servicestack library,
Any ideas?
EDIT for anyone else's info
GetValue method should go hand in hand with SetValue and not Set because of the way it does encoding. I still don't know why Get with a type does not deserialize.
redis.Get<DataResponse>(key);
This method seems to do the trick:
redis.Get<string>(key).FromJson<DataResponse>()
Your API usage is unbalanced:
If you're serializing the POCO's yourself and saving the POCO as a string you should be retrieving the value as a string and deserializing it yourself, e.g:
redis.SetValue(key, myListOfThings.ToJson());
var dtos = redis.GetValue(key).FromJson<List<MyThing>>();
If you want to instead let the Redis Client serialize it, then you should be using the equivalent typed API's for doing that instead, e.g:
redis.Set(key, myListOfThings);
var dtos = redis.Get<List<MyThing>>(key);

How to explicitly call the ASP.NET json serializer

So I have a small asp.net app which returns Json objects that are serialized from C# objects. If I just create a function:
[HttpGet(getTheObj)]
public SomeObj GetTheObject()
{
return new SomeObj() { SomeProperty = 1 };
}
Then it works fine and I can do an HttpRequest for the Json object. However I also want to save some these serialized objects into a database for later use. So I'm wondering, can I explicitly call the Json serializer? I understand that several different serializers can be used with ASP.NET, how do I figure out which one I am using (I didn't create the project).
string json = JsonConvert.SerializeObject(_data.ToArray());
you can save this in database. you can again retrive this object from database and deserialize this object.

Which C# general structure is recommended to convert a PHP Array to C#?

We are consuming a PHP Web Service.
We have generated the WSDL using Add Web Service Reference in Visual Studio.
The getOurRequest Service method expects a "object" type of input parameter.
The PHP Documentation for this method has the following array declared in PHP.
$getOurRequest =>array(
`aaaa`=> ‘1111’,
`bbbb`=> ‘2222’,
`ccccArray`=> array(
‘cccc3333’
,‘cccc4444‘
),
`ddddArray`=>array(
'dddd5555'
,'dddd6666'
)
);
How do we convert it into C# for use to call the PHP Web Service ?
Any ideas to help with the solution or general serializable structure preferred to pass to the Web Service would be appreciated.
#quetzalcoatl Thank you for the var c# declaration sample. It was helpful but it does not serialize over the service call.
Answering your question directly, the nearest possible structure in C# is a Dictionary, or rather, Dictionary<string, object>
$getOurRequest => array(
`aaaa`=> ‘1111’,
`bbbb`=> ‘2222’,
`ccccArray`=> array( ‘cccc3333’, ‘cccc4444‘ ),
`ddddArray`=>array( 'dddd5555','dddd6666' )
);
I actually do not understand notation $getOurRequest => array(...);. Shouldn't it be plain = instead of => here ?
Either way, in C# analogous variable declaration would be:
var getOurRequest = new Dictionary<string, object>
{
{"aaaa", "1111"},
{"bbbb", "2222"},
{"ccccArray", new string[] { "cccc3333", "cccc4444" } },
{"ddddArray", new string[] { "dddd5555", "dddd6666" } }
);
However, I think that will not solve your problem of sending a HTTP request. For this, you will need HttpWebRequest object, just as Jensen answered, and all the "keys" and "values" from the hashmap/array/dictionary above will need to be provided as the query parameters.
#SOAP: If you can emit WSDL for the web service, then VisualStudio/C#/svcutil can generate a series of proxy classes that will simplify calling the web service very much. If you can do it, drop a note and we'll give you links to how to do that.. or just search the google on "C# call webservice"..
Out of curiosity - if you don't know C# and know PHP well, why do you ask for C# code?
Edit:
In the comments, you've said about "object parameter". In PHP or JS there is a little difference between objects and keyed arrays. In C# it's a big difference because the "dictionary" or any other hashmap will be serialized most probably as a "series of keys and values" - not as an object with fields/keys with values.. If you indeed need to pass an "object", you need to actually have a class and object instance.
//[DataContract] - pick one of them
//[Serializable] - they are required, but without seeing your code, it is hard to tell which one
public class MyWebServiceParameter
{
public string aaaa {get;set;} // those must be properties, not fields
public string bbbb {get;set;}
public string[] ccccArray {get;set;}
public string[] ddddArray {get;set;}
}
....
var tmp = new MyWebServiceParameter
{
aaaa = "1111", bbbb = "2222",
ccccArray = new string[] { "....", "...." },
ddddArray = new string[] { "....", "...." }
};
Just be sure to uncomment one of the "attribtues" - datacontract/serializable. Both of them tell the C# runtime that this class is allowed to be serialized, but each of them comes from a different library or rather, era of networking approach in .Net. In general, each of them could be OK, but one will be better depending on how/what has been generated from the WSDL and what .Net and what extra libraries you are using. If you are using 'state-of-art' .Net, then pick DataContract.
Now, you say you have WSDL? So right-click on your project and choose "Add service reference" or "add web reference" and in the popup dialog enter the URL to your WSDL. The creator should be able to parse it and it will generate a series of support classes for that webservice. Lets say they got called "MyPHPService" and it defines an operation called 'TheServiceMethodName':
var serv = new MyPHPService();
serv.TheServiceMethodName( tmp ); // just pass the object you have created earlier. Or a dictionary, or other..
if your WSDL is OK and if the creator understood it right, then for a call to the SOAP service only those two lines are needed!
I don't know how you're calling your PHP service, so my answer is based on a personal project.
I had no interest into creating a SOAP service and whatnot because C# was not the only language I was communicating with and I wanted to keep things simple. Just use an HttpWebRequest to call a web-server and analyze the page output.
So, I used JSON. There's a powerful library from James Newton-King called Json.NET. It can both convert objects to and from JSON.
On the PHP side, these functions are build into the PHP interpreter: json_encode and json_decode.

Is there a way to pass a list of JSON objects from JS to C#?

Something I'm confusing.
The Javascript is going to produce the following JSON data.
{type:"book" , author: "Lian", Publisher: "ABC"}
{type:"Newspaper", author: "Noke"}
This is only an example, actually I've got more than this.
Since I have common fields between different JSON data, so I don't know is it possible to pass this to C# at one time.
What I want to do is pass this to c# then do some processing, what is the best way to do? I'm using ASP.NET MVC2.
Thanks for your answer or hints.
The combination of the 2 JSON statements above are, together, not valid JSON. That being said, you will not be able to use the JavaScriptSerializer class to deserialize that data into c# structure directly. Instead you will have to do some manual parsing first, to either break it down into valid JSON or just do full on manual parsing.
What I would actually recommend is sending over valid JSON instead. You can accomplish this by doing something like this:
{list: [
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"} ]
Hard to say exactly, since only you know the details of your use case. You can send this data over using a traditional 'ajax' request. This is very easy to do with out any of the many JS libraries out there, but I would recommend just going with one anyway - they offer higher level constructs that are easier to use (and address cross-browser idiosyncrasies).
Since you are using ASP.NET MVC2, I would recommend jQuery. Microsoft is now backing jQuery as their JS library of choice and even make it default for new web projects.
Once you pass the above JSON to C#, you can deserialize it by doing something like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var result = serialzer.Deserialize<Dictionary<string, object>>(postedJSONData);
Your result will then have a structure that looks like this, in C#:
Dictionary<string, object> result =>
{ "list" => object },
object => List<object>,
List<object> => Dictionary<string, object>
{ "type" => "book", "author" => "Lian" } // etc
[
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"}
]
Is still valid JSON (well actually keys need to be enclosed in " as well), so you can .push() into an array each time you create a JSON record.
var list = [];
// code doing other stuff
list.push({type:"book" , author: "Lian", Publisher: "ABC"});
// more code doing other stuff
list.push({type:"Newspaper", author: "Noke"})
Once your JSON list is constructed, you can send that list to the backend in one go.
You can also use the JavaScriptSerializer to deserialize your own custom type. Esentially you make a very simple type with all the properties of your json objects then call
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyType result = serialzer.Deserialize<MyType>(JsonData);
You can also deserialize an array
MyType[] result = serialzer.Deserialize<MyType[]>(JsonData);

Working with JSON on the Server-Side in ASP.NET and C#

I have an ASP.NET web form that is using JQuery on the client-side. I have a user interface that is building a collection of objects and storing them in JSON. With my client-side implementation complete, I need to now work with that information when the user clicks a button. When this button is clicked, I need to loop through that JSON collection and validate the entries. My problem is, I'm not sure how to do it.
// Client-Side Code
var myCollection = {
"data": [
]
};
// Server-Side Code
protected void myButton_Click(object sender, EventArgs e)
{
// Parse JSON
}
Each item in the collection is stored in the "data" property. How do I loop through the JSON collection on the server-side? I thought about putting the JSON data in a Hidden HTML Element, but this didn't sound good and I could think of a good way to do it.
Thank you
How you send it to the server is up to you - a hidden field, an AJAX call, whatever you prefer. Once you've got the string on the server, you'll need 2 things:
A C# server-side representation
of that object
A converter to go
from JSON to that C# representation.
Let's adjust your example a bit, because "myCollection" in your example is an object, not a collection. So we'll call it myObject. Secondly, we'll assume that "data" is an array of strings. It could be anything, but we'll keep it simple.
var myObject = {
data: ["string1","string2"]
};
We'll also assume you're using the DataContractJsonSerializer, so you can easily map the two different case-styles...JavaScript is typically camelCase, and C# is typically ProperCase. So, in C#, this would be:
[DataContract(Name="myObjectType")]
public class MyObjectType{
[DataMember(Name="data")]
public string[] Data { get; set; }
}
Now you have two representations of the same structure, one in c#, one in JavaScript. To convert from one to the other, we can use the built-in DataContractJsonSerializer, like this:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
...resulting in a final call of:
MyObjectType myObject = Deserialize<MyObjectType>(incomingString);
JSON in the Hidden Field is a valid way to do it, as the data would then be posted to the server. You could then use the System.Web.Script.Serialization.JavaScriptSerializer component to deserialize the data (to a dictionary) and access the data that way. Not 100% sure hhow array data comes out of that process. THere are also other tools like JSON.NET too to parse JSON.
Another way is via a web service call, but that doesn't go through the page lifecycle.
HTH.

Categories

Resources