Disqualify lead in Dynamics CRM (iOS) - ios

How can i disqualify lead in Microsoft Dynamics CRM ? Is there any particular API for doing this from iOS platform?
I tried this :
for (id key in [details allKeys]) {
if([key isEqualToString:#"LeadState"])
{
[contactPostDict setObject:#"2" forKey:#"State"];
}
else if([key isEqualToString:#"LeadStatus"])
{
[contactPostDict setObject:#"6" forKey:#"Status"];
}
}
This is the error:
"error": {
"code": "", "message": {
"lang": "en-US", "value": "Error processing request stream. The property name 'Status' specified for type 'Microsoft.Crm.Sdk.Data.Services.Lead' is not valid."
}
}

I have never worked on the iOS platform but from the error that is being thrown, the error seems to be pretty straight forward.
You are looking for the keys "Status" & "State" but they don't exist. Instead you should be looking at their schema names which is as follows
Status = statuscode, State = statecode
Can you try modifying the code to use the above keys and see if you still gets the same error.

(BOOL)setLeadStatus:(NSString *)ID andDetails:(NSMutableDictionary *)details
{
NSString *uri = [MSDYNAMICS_AUTHENTICATION_CALL stringByAppendingPathComponent:[NSString stringWithFormat:#"LeadSet(guid'%#')/",ID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:uri]];
request.HTTPMethod = #"MERGE";
[request setValue:JSON_CONTENT_TYPE_PARAMETER forHTTPHeaderField:#"Content-Type"];
[request setValue:JSON_CONTENT_TYPE_PARAMETER forHTTPHeaderField:#"Accept"];
NSMutableDictionary *contactPostDict=[[NSMutableDictionary alloc]init];
for (id key in [details allKeys]) {
if([key isEqualToString:#"LeadState"])
{
[contactPostDict setObject:#"2" forKey:#"statecode"];
}
else if([key isEqualToString:#"LeadStatus"])
{
[contactPostDict setObject:#"6" forKey:#"statuscode"];
}
}
NSError *err;
NSData *postData=[NSJSONSerialization dataWithJSONObject:contactPostDict options:NSJSONWritingPrettyPrinted error:&err];
NSString* postString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
//NSString *postString = #"";
[request setValue:JSON_CONTENT_TYPE_PARAMETER forHTTPHeaderField:CONTENT_TYPE_PARAMETER];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
SURLConnection *conn = [[SURLConnection alloc] init];
NSData *responseData = [conn sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *err1 = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"error: %#",err1);
if(responseData.length==0 && [conn.response statusCode] == 204)
{
[self getLeadDetailsForID:ID];
return YES;
}
else{
NSString *err = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"error: %#",err);
}
return NO;
}

Related

Getting value from JSON stored as NSString for iOS in xCode

I have some JSON stored as an NSString and I am trying to convert this to a NSDictionary and get the value of 'EndDate' in my JSON.
I wanted to retrieve 'EndDate' from the JSON but due to the amount of levels i'm not quite sure how I should be achieving it.
Here is the JSON:
{ "GetResponse":{ "GetResult":{ "Faults":null, "Response":{ "Asset":{ "AssetParts":{ "#nil":"true" }, "CountryLookupCode":808, "Number”:24234, "Duplicate":"false", "Code":"`123”, "Channel”:”SR”, “Desc”:”Test”, "Number”:123, “Mandate”:{ "#nil":"true" }, “TestTime”:”True”, “Date”:”2010-08-12T19:00:00", “Results”:{ “Details”:[ { "EndDate":"2013-08-13T18:59:59", “Type”:”Taken”, "Item”:”902”, “Level”:”SL”, “Description”:”Timed”, “Group”:1, “Prov”:{ "#nil":"true" }, "StartDate":"2010-08-12T19:00:00" }, { "EndDate":"2013-08-13T18:59:59", “Machine”:”Dated”, “Country”:”UK”, "Code":"CCDD”, “Description”:”Addressed”, “Level”:2, "Provider":{ "#nil":"true" }, "StartDate":"2010-08-12T19:00:00" }, { "EndDate":"2013-08-13T18:59:59", "Type”:”Title”, "ItemNumber”:”1253”, "Service":"NEDD”, “Desc”:”Down”, “Grp”:5, "Provider":{ "#nil":"true" }, "StartDate":"2010-08-12T19:00:00" } ] } } } } } }
Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://192.168.0.20/test.json"]];
[request setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
//NSLog(#"requestReply: %#", requestReply);
//End
NSData *data = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *performersArray = [json objectForKey:#"GetResponse"];
for (NSDictionary *performerDic in performersArray) {
NSLog(#"%#", [performerDic objectForKey:#"EndDate"]);
}
Thanks
NSArray *detailsArray = json[#"GetResponse"][#"GetResult"][#"Response"][#"Asset"][#"Results"][#"Details"];
for (NSDictionary *detailsDict in detailsArray){
NSLog(#"%#",detailsDict[#"EndDate"]);
}
this should work

NSMutableURLRequest returning JSON with empty sub-arrays

I have created a method that uses NSMutableURLRequest to request and receive JSON from a RESTful API running on a remote machine. The request successfully returns some JSON, but the returned sub-arrays in the JSON (see tasks: []) are empty.
The JSON returned from the API is:
{
"error":false,
"tasks":[
{
"id":1,
"task":"Get Milk",
"status":0,
"createdAt":"2014-08-09 12:29:15"
},
{
"id":2,
"task":"Call Mom",
"status":0,
"createdAt":"2014-08-09 12:46:52"
},
{
"id":3,
"task":"Call Dad",
"status":0,
"createdAt":"2014-08-09 12:47:04"
},
{
"id":4,
"task":"Study",
"status":0,
"createdAt":"2014-08-09 12:47:08"
}
]
}
The method that utilizies NSMutableURLRequest (proper parameters being passed is assumed) is:
-(NSDictionary *) apiRequestWithEndpoint:(NSString *) endpoint
withParams:(NSDictionary *) params
withHTTPHeaders:(NSDictionary *) headers
withHTTPMethod:(NSString *) method
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:endpoint]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:method];
//set headers
for (id key in headers) {
[request setValue:[headers valueForKey:key] forHTTPHeaderField:key];
}
//set paramaters in request body
NSMutableString *requestBody = [[NSMutableString alloc] init];
int keyIndex = 0;
for (id key in params) {
if (keyIndex == 0) {
[requestBody appendFormat:#"%#=%#", key, [params valueForKey:key]];
} else {
[requestBody appendFormat:#"&%#=%#", key, [params valueForKey:key]];
}
keyIndex++;
}
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *NSURLError = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLError];
if (NSURLError) {
NSLog(#"Error: %# Cancelling operation.", NSURLError);
return nil;
}
NSError *NSJSONSerializationError = nil;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&NSJSONSerializationError];
if (NSJSONSerializationError) {
NSLog(#"Error: %# Cancelling operation.", NSJSONSerializationError);
return nil;
}
NSLog(#"Data: %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return responseJSON;
}
Notice the 4th last line that logs the returned NSData from the NSMutableURLRequest, the output is:
Data: {"error":false "tasks":[]}
The code that calls the above method:
NSString *getAllTasksEndpoint = #"http://developmentVPS.com/TaskList-API/v1/tasks";
NSString *apiKey = #"A Valid API Key";
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:apiKey, #"Authorization", nil];
NSDictionary *responseJSON = [self apiRequestWithEndpoint:getAllTasksEndpoint
withParams:nil
withHTTPHeaders:headers
withHTTPMethod:#"GET"];
It is my understanding that the entire data returned from the request should be logged in that NSLog call, but "tasks" is empty. I am new to iOS development, so I may be missing something simple. Does anybody see anything I am missing here?

Sending JSON to Schematic Ipsum

I'trying to get some random JSON from http://schematic-ipsum.herokuapp.com/ but I'm getting a response code 400.
Here is the code I'm using
+ (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
NSArray *dataToReturn;
// if urlString is nil, we default it to our server
if(!urlString) urlString = JSON_SERVER;
// of course we need to turn the string into a valid array
NSURL *url = [NSURL URLWithString:urlString];
/*
prepare the post
*/
// we need to catch possible errors
NSError *error;
// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];
// we need the post' length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// create the url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
// here we'll check the server response
NSHTTPURLResponse *response = nil;
// here's our data from the server
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
// all good, let's see what we've got
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
// parse the response into a friendly format
dataToReturn = [[NSArray alloc] initWithArray:[self returnJSONFromData:urlData]];
} else {
// somethin went wrong
NSLog(#"Response code: %ld", (long)[response statusCode]);
// check if it's our fault
if (error) {
NSLog(#"Server error: %#", [error localizedDescription]);
}
}
// return our formatted array or nil
return dataToReturn;
}
+ (NSArray *)returnJSONFromData:(NSData *)urlData
{
NSArray *dataToReturn;
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", [e localizedDescription]);
dataToReturn = #[e];
} else {
dataToReturn = [[NSArray alloc] initWithArray:jsonArray];
NSLog(#"data from json: %#", dataToReturn);
}
return dataToReturn;
}
and I'm calling it like this, using a demo JSON from their website:
NSDictionary *post = #{ #"type": #"object", #"properties": #{ #"id": #{ #"type": #"string", #"ipsum": #"id" }, #"name": #{ #"type": #"string", #"ipsum": #"name" }, #"email": #{ #"type": #"string", #"format": #"email" } }};
[RetrieveDataFromServer postData:post toServer:#"http://schematic-ipsum.herokuapp.com/"];
You need to respect the syntax of "Form Data" that the server takes. To obtain this, you can use Google Chrome "Inspect Element", choose "Network" tab then do a request and you'll see this:
Look at "Form Data" section and you'll find out your problem, it's because you didn't pass the right structure to server so that the server doesn't understand.
I took the defaults parameters of server which is:
{
"type": "object",
"properties": {
"id": {
"type": "string",
"ipsum": "id"
},
"name": {
"type": "string",
"ipsum": "name"
},
"email": {
"type": "string",
"format": "email"
},
"bio": {
"type": "string",
"ipsum": "sentence"
},
"age": {
"type": "integer"
},
"avatar": {
"type": "string",
"ipsum": "small image"
}
}
}
So the data must be structured like this:
type:object
properties[id][type]:string
properties[id][ipsum]:id
properties[name][type]:string
properties[name][ipsum]:name
properties[email][type]:string
properties[email][format]:email
properties[bio][type]:string
properties[bio][ipsum]:sentence
properties[age][type]:integer
properties[avatar][type]:string
properties[avatar][ipsum]:small image
And don't forget to encode with percentage before sending it to server or you will fail again.
I tried to implement a method that take your dictionary and return the formatted form data, it works fine for this case but I'm not sure in a more general context. I'll post it here for you as a reference, it's really a mess, sorry for that but I don't have enough time for commenting.
- (NSString *)formatFormData:(NSDictionary *)dictionary
{
NSMutableArray *arrayPrefix = [NSMutableArray array];
NSMutableArray *arrayResult = [NSMutableArray array];
[self structureString:dictionary arrayPrefix:arrayPrefix arrayResult:arrayResult];
return [arrayResult componentsJoinedByString:#"&"];;
}
- (void)structureString:(NSDictionary *)dictionay arrayPrefix:(NSMutableArray *)arrayPrefix arrayResult:(NSMutableArray *)arrayResult
{
for(NSString *key in dictionay.allKeys)
{
NSObject *obj = [dictionay objectForKey:key];
if([obj isKindOfClass:[NSDictionary class]])
{
[arrayPrefix addObject:key];
[self structureString:(NSDictionary *)obj arrayPrefix:arrayPrefix arrayResult:arrayResult];
}
else
{
NSMutableString *string = [[NSMutableString alloc] initWithString:#""];
for(int i = 0; i < arrayPrefix.count; i++)
{
NSString *eachPrefix = arrayPrefix[i];
if(i == 0)
{
[string appendString:eachPrefix];
}
else
{
[string appendString:[NSString stringWithFormat:#"[%#]", eachPrefix]];
}
}
if(arrayResult.count == 0)
{
[string appendString:[NSString stringWithFormat:#"%#=%#", key, obj]];
}
else
{
[string appendString:[NSString stringWithFormat:#"[%#]=%#", key, obj]];
}
[arrayResult addObject:string];
}
}
}
And in your current method, add these lines:
- (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString
{
// omitted
// turn our arguments into NSData
NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error];
NSString *stringTemp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
stringTemp = [self formatFormData:arguments];
// encode form date before sending to server
stringTemp = [stringTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
postData = [stringTemp dataUsingEncoding:NSUTF8StringEncoding];
// omitted
}

getting error when calling objectFromJSONString using JSONKit

I use the following code to create a dictionary based on a JSON string received from the server. (I have downloaded JSONKit and embedded it into the project). The code below returns a legal JSON string from the server (parsed well on Android) but crashes when I try to convert it to a dictionary.
- (IBAction)submit
{
bool useSSL = true;
char *c_url="http://(rest of URL)";
NSString* url = [NSString stringWithFormat:#"%s" , c_url];
url = [NSString stringWithFormat:#"%#%#%s", url, self.label.text, "/keys"];
NSString * response = [self getDataFrom:url];
NSDictionary *dict = [response objectFromJSONString]; //generates SIGABRT!!
NSLog(#"%#",dict);
NSString *success = [dict valueForKey:#"success"];
}
- (NSString *) getDataFrom:(NSString *)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:url]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(#"Error getting %#, HTTP status code %i", url, [responseCode statusCode]);
return nil;
}
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
THANKS,
Simon
Found an answer here.
Answer says: "Figured it out... I had JSONKIt.h included in the project but for some weird reason, JSONKit.m was not included in the 'Compile Sources' under 'Build Phases' - once I added it manually it started working fine."

iOS Check for Token

I'm making an app that requires you to login in. I"m using JSON. So far I've been able send a POST request with the Username and Password and I get a token back (it shows up in the console). When I don't enter in the correct username/password combination, I don't get a token back. What I would like to happen is to proceed to the next view controller if I get a token back. I think that I need to use an if statement (I'll put the code for switching view controllers into it) but I don't know what parameters I need in order to check if I get a token back.
Here is the code I'm using in the implementation file. It is in a method that runs when a button is pressed:
#try {
if([[usernameTextField text] isEqualToString:#""] || [[passTextField text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[usernameTextField text],[passTextField text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://beta.network360.com/tokens"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#""];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#""];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#""];
//[[PSearchViewController new] performSegueWithIdentifier:#"loginCancel" sender:self];
}
Also, here is what I get in the console output when I put in the correct username/password combination (BTW I tried to change all the stuff that showed up in the console that was confidential, so if some stuff doesn't quite match, it should be fine. I just wanted to show that I get a token back):
2013-07-28 13:23:21.607 Empyrean[28283:c07] PostData: username=username#gmail.com&password=password
2013-07-28 13:23:22.300 Empyrean[28283:c07] Response code: 200
2013-07-28 13:23:22.301 Empyrean[28283:c07] Response ==> {"token":"scFDzxSAVk2sxQBShEGS","user":{"id":300230,"username":"username#gmail.com","display_name":"FirstName LastName","unconfirmed_email":null,"email":"username#gmail.com","confirmation_email":"username#gmail.com","client_identifier":null,"client_id":138,"is_admin":false,"support_email":"support#supportemail.com","application_name":"AppName","show_project_vintage_date":false,"is_anonymous":false,"is_active":true,"is_confirmed":true,"pending_reconfirmation":false,"can_resend_confirmation":false,"client_name":"Broker","show_advertisements":true,"header_logo":"/foo/headerlogo.gif","report_footer_logo":"/stuff/foo/footerlogo.png","authorized_features":["find_stuff","do_stuff","stuff_stuff","settings","menu","manage_stuff","measure_stuff","export_stuff"],"url":"https://www.website.com/stuff/numbersdsjkflds"}}
2013-07-28 13:23:22.304 Empyrean[28283:c07] {
token = dlsfkasdfDfdsklfdDsa;
user = {
"application_name" = "Application Name";
"authorized_features" = (
"find_stuff",
"do_stuff",
"stuff_stuff",
settings,
menu,
"manage_stuff",
"measure_stuff",
"export_stuff"
);
"can_resend_confirmation" = 0;
"client_id" = 138;
"client_identifier" = "<null>";
"client_name" = Broker;
"confirmation_email" = "username#gmail.com";
"display_name" = "FirstName LastName";
email = "username#gmail.com";
"url" = "https://www.website.com/stuff/numbersdsjkflds";
"header_logo" = "/foo/headerlogo.gif";
id = 300230;
"is_active" = 1;
"is_admin" = 0;
"is_anonymous" = 0;
"is_confirmed" = 1;
"pending_reconfirmation" = 0;
"report_footer_logo" = "/stuff/foo/footerlogo.png";
"show_advertisements" = 1;
"show_project_vintage_date" = 0;
"support_email" = "support#supportemail.com";
"unconfirmed_email" = "<null>";
username = "username#gmail.com";
};
}
NSDictionary *jsonData is a dictionary. Therefore, you can see if the token key exists.
if (jsonData[#"token"])
{
// Token exists, so move on.
[self.navigationController pushViewController:nextController animated:YES];
}
else
{
// Tell the user they messed it up.
}

Resources