could not be mapped to a JSON object in Logansquare - realm

i am trying to fetch data from Realm and sending it to server using retrofit and for parsing and serializing i am using LoganSquare
client = new Retrofit.Builder()
.baseUrl(REST_ENDPOINT)
.client(okHttpClient)
.addConverterFactory(LoganSquareConverterFactory.create())
.build();
this is how i am accessing record
Appointment appointments = DB.getInstance(mContext).selectNotSyncAppointmentsData();
RestApi.AppointmentsDataApi service = getAppointmentsDataApi();
Call<APResponse> call = service.createUpdateAppointmentsData(appointments);
i am getting following error
createUpdateAppointmentData : onFailure Class io.realm.AppointmentRealmProxy could not be mapped to a JSON object. Perhaps it hasn't been annotated with #JsonObject?

I am not familiar with how LoganSquare works, but be aware that Realm works with something called proxy classes that extend all your model classes. You can recognise these as they are called <ModelClass>RealmProxy. It looks like you somehow have to find a way to configure LoganSquare to recognise these sub-classes.
Alternatively you can use realm.copyFromRealm(appointments). That will give you an in-memory copy of all the data which are of the correct class.

Related

Consume Web Service, Serialize XML response, save xml to database

I have this situation, I am creating a Web Service in C# where I need to consume a SOAP Web Service, which gives me an XML response back, I need to serialize this XML response and save it to a table in the database.
I have tried the to call the XML in Postman and it worked fine with a
200 OK status
, but I need how to serialize this reponse and save it to the database.
And then I have tried to write this:
public void CreateFilter(Student student)
{
var XML = XmlSerialization <Student> (student);
ConnectDataBase db = new ConnectDataBase();
SqlCommand cmd = new SqlCommand("sp_Student");
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = student.name;
cmd.Parameters.Add("#surname", SqlDbType.VarChar).Value = student.surname;
cmd.Parameters.Add("#subject", SqlDbType.VarChar).Value = student.subject;
cmd.Parameters.Add("#student", SqlDbType.Xml).Value = XML;
}
Any thoughts on how to get a response from the Web Service I have to consume, and then serialize the response I'm getting back and then save the serialization on the database?
Thank you in advance
Well, you have a couple of options really. Essentially, if you aren't leveraging an ORM (like Hibernate or some such), you want to:
Grab the XML payload
Get that deserialized into an object instance so you can work with it
Pick out the data you are interested in and persist it
Step 2 is essentially writing a class (or tree of classes) that mimmicks the field structure of the XML, then asking a library nicely to parse the XML state into an instance of that class. This then makes it easy to work with for you.
You can either leverage the the native deserialization as per:
https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=net-6.0
Or, just for arguments sake alternatively you could use a modern serialization library. There isn't much of a good choice when it comes to XML and C#, so the main one I can think of that will get you from point a to point b is Json.NET:
https://www.newtonsoft.com/json
This library, though predomenantly pushed as an all-in-one object mapper for JSON is also able to translate between XML and Json:
https://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm
Depending on how much of a fight the native deserializer puts up (defining the schema can be a bit of a pain, bloody SOAP am I right), it might be easier to use Json.NET to hoover up the XML, convert it to JSON, then deserialize that json as an object.
This gives you a 2-step deserialization process which isn't ideal, but it's not such a bad thing either as you get to work with the "nice" library and not have to fight the old baked in xml serialization stuff.
The choice is yours really. I'd give the first option a good go first then if that puts up too much of a fight you have Json.NET to fall back on :)

BreezeJS modified route not working

My application has two databases with exactly the same schema. Basically, I need to change the DbContext based on what data I'm accessing. Two countries are in one Db and 4 countries in the other. I want the client to decide which context is being used. I tried changing my BreezeWebApiConfig file so that the route looks like this:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "breeze/{dbName}/{controller}/{action}/{id}",
defaults: new {id=RouteParameter.Optional,dbName="db1"}
);
I added the string to the controller actions:
[HttpGet]
public string Metadata(string dbName="")
{
return _contextProvider.Metadata();
}
And changed the entityManager service Name.
Now when the client spins up, it accesses the corrent metadata action and I get a message:
Error: Metadata query failed for: /breeze/clienthistory/kenya/Metadata. Unable to either parse or import metadata: Type .... already exists in this MetadataStore
When I go to the metadata url from the browser, I get the correct metadata (exactly the same as when I remove the {dbName} segment from the route). If I remove the {dbName} segment from the route I get no error and everything works fine
(I have not started implementing the multiple contexts yet -- I am just trying to make the additional segment work).
Thanks.
I think the problem is that your Breeze client is issuing two separate requests for the same metadata, once under each of the two "serviceNames". Breeze tries to blend them both into the same EntityManager.metadataStore ... and can't because that would mean duplication of EntityType names.
One approach that should work is to begin your application by fetching the metadata immediately upon app start and then adding all the associated "DataServiceNames" to the MetadataStore.
Try something along these lines (pseudo-code):
var manager;
var store = new breeze.MetadataStore();
return store.fetchMetadata(serviceName1)
.then(gotMetadata)
.catch(handleFail);
function gotMetadata() {
// register the existing metadata with each of the other service names
store.addDataService(new breeze.DataService(serviceName2));
... more services as needed ...
manager = new breeze.EntityManager({
dataService: store.getDataService(serviceName1), // service to start
metadataStore: store
});
return true; // return something
}
Alternative
Other approaches to consider don't involve 'db' placeholder in the base URL nor any toying with the Web API routes. Let's assume you stay vanilla in that respect with your basic service name
var serviceName = '/breeze/clienthistory/';
..
For example, you could add an optional parameter to your routes (let's call it db) as needed via a withParameters clause.
Here is a query:
return new breeze.EntityQuery.from('Clients')
.where(...)
.withParameters({db: database1}); // database1 == 'kenya'
.using(manager).execute()
.then(success).catch(failed);
which produces a URL like:
/breeze/clienthistory/Clients/?$filter=...&db=kenya
It makes an implicit first-time-only metadata request that resolves to:
/breeze/clienthistory/Metadata
Your server-side Web API query methods can expect db as an optional parameter:
[HttpGet]
public string Metadata(string db="")
{
... do what is right ...
}
Saves?
I assume that you also want to identify the target database when you save. There are lots of ways you can include that in the save request
in a custom HTTP header via a custom AJAX adapter (you could do this for queries too)
in a query string parameter or hash segment on the saveChanges POST request URL (again via a custom AJAX adapter).
in the tag property of the saveOptions object (easily accessed by the server implementation of SaveChanges)
in the resourceName property of the saveOptions object (see "named save")
You'll want to explore this variety of options on your own to find the best choice for you.

JSON + SOAP - Is DataContract necessary?

Here's my problem.
I'm using SOAP to retrieve information from a third-party web service.
Response time is too high, so I was planning on using JSON instead, at least in a couple of methods.
For this I'm using DataContractJsonSerializer, but I seem to be having some trouble.
For example, in SOAP there's a method called getAvailablePublic with returns an object of type getAvailablePublicResponse.
There's an equivalent for this method in JSON, which also returns a an object of type getAvailablePublicResponse.
In order to deserialize the information I needed to create a couple of data contracts, and here are my concerns:
Do I really need to create a DataContract? Why can't I use getAvailablePublicResponse object from asmx?
The problem is that if I create a DataContract, I need to use a different name other than getAvailablePublicResponse, as I would have two objects with the same name (the one created by me, and the one from SOAP), and this would require making several changes in my solution.
Hope this makes sense.
Thanks.
Can you post your client code that is making the call to the web service? I don't know what you are using now, but I'm a fan of RestSharp for making remote calls and serializing JSON to C# classes. Something like this:
RestClient client = new RestClient("http://some.domain.com/someservice?someparam=yes");
var results = client.Execute<MyGreatDTOClass>(new RestRequest(Method.GET));

Modifying a Biztalk message from custom code

Disclaimer: I am a complete biztalk newbie.
I need to be able to read and potentially edit 4 nodes in a biztalk message; preferably this needs to be done from a c# helper class as I am making a service call and also have unit tests written for this.
I already have this class wired up and it works with the XLANGMessage class, the problem I am running into is at this point in the orchestration the message is a Schema based type and doesn't seem to have any way for me to modify it.
I've done some reading and found a few ideas but have not been able to confirm if any of these can work from custom code.
1 write a map to transform the incoming message to the desired type
or
2 write something like this in your helper component to transform the message
public XmlDocument TransformMessage(XLANGMessage message)
Then pass the result document to a biztalk message in a message assignment shape.
responseMessage = xmlDocument;
You may get better performance if you pass streams instead of messages around.
You can pass messages into and out of C# helper classes easily. The simplest way is just to treat input parameters and return values as of type System.Xml.XmlDocument. The XLANG/s engine will safely cast back and forth from the XLANGMessage type to XmlDocument.
As you are essentially creating a "new" instance of the message (messages are immutable in BizTalk), the call to your helper class needs to be performed in a Message Assignment shape, with the outer Construct shape constructing the copy of your original message.
public static XmlDocument UpdateMyMessage(XmlDocument sourceMessage)
{
/* Do stuff to your Message here */
return sourceMessage;
}
A best-practice to consider is to declare all your C# helper methods as Static. This will avoid any issues with de/serialisation of your helper class during dehydration.
Are BizTalk messages immutable?
Generally speaking they are however, by creating a “corrective” orchestration and using a pass by reference option on the incoming message parameter, an existing message can be modified.

Getting progress on POST using HTTPService in Flex/AS3

I'm using HTTPService with a POST operation to submit a Base64 encoded file (taken from bitmap data within the app) but I could really do with getting some idea of the progress of the POST operation (e.g. like the FileReference.upload()).
I don't think this is possible, but it would be awesome if it is (via any means, I'm willing to change my setup to get this).
Do not use HTTPService. Use URLRequest, URLLoader, and URLVariables.
If your using an HTTPService tag, get ride of it and replace it with a Script tag filled with something like ...
private function forYou() : void{
var req : URLRequest = new URLRequest("PUT YOUR URL HERE")
var loader : URLLoader = new URLLoader();
var params : URLVariables = new URLVariables();
params.WHATEVER = WHATEVER YOU WANT IT TO BE;
req.data = params;
req.method = URLRequestMethod.POST;
loader.addEventListener(ProgressEvent.PROGRESS, YOUR LISTENER FUNCTION NAME);
loader.load(req);
}
Assign this function name to the creationComplete attribute of the root tag.
If your not using an HTTPService tag, just get ride of the HTTPService object in your actionscript and use the above code.
This worked well for me to consume a REST web service:
http://code.google.com/p/as3httpclient/wiki/Links
Example
This isn't possible with HTTPService. Its only events are result, fault, and invoke (other than the non-relevant inherited events of activate and deactivate).
To get progress information on an upload process, the server would have to provide the information, which would require a means of communication between the server and the client during the operation, which isn't there for a regular HTTP POST operation.
One option might be to create an object on the server that would be instantiated whenever the server began receiving POST data from your client. It would then keep track of the progress and expose that data to the rest of your server-side application. Your client could then initiate a polling system that would request the value of that particular variable.
Seems like kind of a far-fetched option, though...

Resources