I am trying to develop this iOS app that can communicate with a C# web service under the local network. I am using AFNetworking to achieve the communication. Now I have achieved reading xml data from the web service with the help of this tutorial, which means my app can connect to the web service, I think. But what I really want to do is, passing data from the app to the web service. I have write some sample code:
AFmyAPIClient *myClient = [AFmyAPIClient sharedClient];
NSMutableDictionary *requestArray = [NSMutableDictionary new];
NSString *details = [_listOfItems description];
float tempF= [_listOfItems totalPrice];
NSString *price = [NSString stringWithFormat:#"%f",tempF];
int tempI = 1;
NSString *table = [NSString stringWithFormat:#"%u",tempI];
[requestArray setObject:details forKey:#"details"];
[requestArray setObject:price forKey:#"price"];
[requestArray setObject:table forKey:#"table"];
[myClient postPath:#"setOrderDetails" parameters:requestArray success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
After I build and run this app, it generates this error message:
2013-11-03 16:25:48.654 HLR[16149:70b] <?xml version="1.0" encoding="utf-8"?>
<int xmlns="http://localhost/service/Service1.asmx">3</int>
2013-11-03 16:25:48.844 HLR[16149:70b] Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 500" UserInfo=0x8b5b140 {NSLocalizedRecoverySuggestion=Missing parameter: orderDetails.
, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0x8b5bb70> { URL: http://10.0.0.111/service/Service1.asmx/setOrderDetails }, NSErrorFailingURLKey=http://10.0.0.111/service/Service1.asmx/setOrderDetails, NSLocalizedDescription=Expected status code in (200-299), got 500, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8b4e910> { URL: http://10.0.0.111/service/Service1.asmx/setOrderDetails } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 34;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Sun, 03 Nov 2013 05:25:34 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "2.0.50727";
"X-Powered-By" = "ASP.NET";
} }}
At my C# web service side, I have Web Methods like:
[Web Method]
public void setOrderDetails(String orderDetails)
{
//store orderDetails into a text file.
}
I am new to iOS developing, I don't understand what did I really pass to the web service when I invoke this method:
[myClient postPath:#"setOrderDetails" parameters:requestArray success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
Did i just pass a NSDictionary as a parameter to the C# web service? If that is what it is, what can I do with this NSDictionary at the web service side?
I don't know whether this is the right way to achieve passing data to the web service. What I really want to do here is to pass some strings to the web service, how can I achieve that?
Any suggestions would be much appreciated!
You are passing the XML content as URL parameters. You need to pass it in the body of the request. Here are a couple of questions addressing posting XML using AFNetworking:
Example on using AFNetworking to post XML?
AFNetworking - Making an XML POST request to REST service? How to form NSDictionary parameters?
Related
TL;DR:
I am calling a WebApi, the WebApi authenticates against the CRM and use the IOrganizationService, so my request is a JObject and not an Entity or EntityReference, it gives me this error:
Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.
Context:
I built a web application in angular and I built a WebApi so I can call some custom actions in CRM:
Angular APP | WebApi | OnPremise CRM
So, when I call the WebApi, there is a controller that turns my request into a OrganizationRequest:
Request for WebApi:
{
"ActionName": "custom_actionname",
"Parameters":
[
{
"Key": "EntityInputParameter1",
"Value": {"#odata.type":"Microsoft.Dynamics.CRM.any_entity"}
}
]
}
I read this request on my WebApi and turn that into a request for CRM
Request for CRM:
OrganizationRequest request = new OrganizationRequest("custom_actionname");
request.Parameters["EntityInputParameter1"] = {"#odata.type":"Microsoft.Dynamics.CRM.any_entity"} // This is a JObject
OrganizationResponse response = service.Execute(request);
When I make the request, it gives me the following error:
Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.
If I make the request directly to the action it works, but I cannot do that due security policies.
One option could be turn the request into a valid CRM request (parsing {"#odata.type":"Microsoft.Dynamics.CRM.any_entity} into a Entity type) but CRM has a lot of parsing escenarios and could be very complex.
Another option could be sending the request through web and stop using the IOrganizationService but I cannot change that.
I am making this question so anybody that has this error can find the "solution" because I searched a lot and nobody refers this behavior directly.
I am probably turning my InputEntityParameter into string, and I will send the JSON, so I can parse the JSON on my action, but I was looking if anybody else had this error or another approach.
I tested it on one of my Dev Environment with Entity as Parameter.
Below is the code I used in console application to fire Action with Entity as parameter. It ran successfully
var request = new OrganizationRequest("new_test");
//request.Parameters.Add("Target", xAccountReference);
request.Parameters.Add("Param2", "abc");
request.Parameters.Add("Param1", new Entity("account",Guid.Parse("2fe32f22-d01d-ea11-80fa-005056936c69")));
Service.Execute(request);
Below is the Javascript code which used CRM Webapi to execute Action with Parameter. Ignore the XRM.Webapi command but interesting for you would be passing parameters in webapi.
var parameters = {};
parameters.Param2 = "abcd";
var param1 = {};
param1.accountid = "2fe32f22-d01d-ea11-80fa-005056936c69"; //Delete if creating new record
param1["#odata.type"] = "Microsoft.Dynamics.CRM.account";
parameters.Param1 = param1;
var new_testRequest = {
Param2: parameters.Param2,
Param1: parameters.Param1,
getMetadata: function() {
return {
boundParameter: null,
parameterTypes: {
"Param2": {
"typeName": "Edm.String",
"structuralProperty": 1
},
"Param1": {
"typeName": "mscrm.account",
"structuralProperty": 5
}
},
operationType: 0,
operationName: "new_test"
};
}
};
Xrm.WebApi.online.execute(new_testRequest).then(
function success(result) {
if (result.ok) {
//Success - No Return Data - Do Something
}
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
I can confirm that you are mixing Webapi and orgservice call. You can definitely call Action from Webapi of Dynamics. I just used Postman to call Action and I was successful. Blog reference to use Postman for CRM webapi
Below Body as json in Postman and I get Action to run.
{
"Param1":"string test",
"Param2":{
"accountid":"b6b35fd0-b9c3-e311-88e2-00505693000c",
"#odata.type":"Microsoft.Dynamics.CRM.account"
}
}
I have build a http post web api in asp which return the following string in Json
RootObject rootObject = new RootObject()
{
status = "User Registered"
};
msg = JsonConvert.SerializeObject(rootObject);
Below is my angular js controller in which I am consuming that web api
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.signup=function(data){
var link = 'http://xxxxxxxxxxxxxxxxxxxxxx/api/Home/RegisterUser';
//using http post
//passing values to parameter
$http.post(link, {RegisterName : data.name, RegisterUserName : data.username, RegisterPassword : data.password , RegisterEmail: data.mail , RegisterMobile : data.mobile})
.then(function (res){ //if a response is recieved from the server.
$scope.response = res; //contains Register Result
console.log($scope.response);
});
}
})
With the above code I am getting following result in google chrome console
I am try to get that status only to match it value but I am unable to do so.
The doubt I am having is that json format
console.log(JSON.stringify($scope.response)) will do what you need.
If you're wanting those particular value, you can just access those and pass them to log.
console.log($scope.response.data['status']);
you get the json as :
$scope.response = res.data;
might be you require JSON.parse(res.data) or $.parseJSON(res.data) for getting json object
I got a .net project from client. Right now, I need to make a WebRequest to a WebService (.asmx). The problem is i dont know how call the method in that web service using web request from c#.
my code :
RunRoutines.aspx
string UseAddress = "http://localhost:31952/api/RunRoutines.asmx";
string address = string.Format(UseAddress);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(address);
RunRoutines.asmx
public class RunRoutines : System.Web.Services.WebService
{
[WebMethod]
public string RunRR1()
{
return "Hello World";
}
}
I need to access the RunRR1() method from the web request in RunRoutines.aspx. Please advise. Thanks!
Well you can access it using the name of the reference you have given while adding service reference.
For example if it is localHost then you can try below code:
var yourService = new localHost.WebService();
yourService.RunRR1();
For more details have a look here:
Image ref: http://www.c-sharpcorner.com/UploadFile/0c1bb2/consuming-web-service-in-Asp-Net-web-application/
Which is here for more details .
I am trying to use a web service in my asp.net project. I add the web reference and trying to use the some of the functions of that service.I am trying to fetch some values from the web service.For this process First I am sending some data to web service for process.This is the code which I am trying to use
wsezp.ApiService ws = new wsezp.ApiService();
ws.Recharge("589746656", "608669", "1234567890", "5", "10", "12345");
wsezp.Result rs = new wsezp.Result();
string Requestid = rs.reqid;
string Status = rs.status;
Response.Write("Status of Requestid " + Requestid + "is " + Status);
As per my Document I will get my result like this
<recharge>
<reqid>0000<reqid/>
<status>SUCCESS</status>
<remark>recharge_transaction_id</remark>
<balance>your api balance</balance>
<mn>mobile number</mn>
<field1>operator transaction id</field1>
</recharge>
But I am getting null in the strings which I declare. Please tell me how can I use the web service for post the request and get back the result from the web service
Looks to me as if you are creating a new result. Are sure the call to recharge doesn't return the result you are looking for ? That would make sense.
wsezp.Result rs = ws.Recharge(...
I have a problem passing a large JSON string to a web service from the client side with a jQuery function. When the lenth of the string increases to 1000 characters, the web service throw an exception "Unspecified Network Error". Please let me know how to pass a large JSON value to a web service using [webinvoke].
Can we increase the size of url or whatever to fix this problem?
You can serialize your Json as object:
page.asp
var data1 = {
IdTest: ('<%= miAspVar %>'),
fono: telefono,
etc, etc
};
var strData = YAHOO.lang.JSON.stringify(data1)
callService(testLlamada, strData, EstadoLlamada, onError2);
function onError2(result) {
alert(result);
}
function EstadoLlamada(result) {
...
}