UCWA 2.0 Trying to add forward contact but getting ParameterValidationFailure - asp.net-mvc

I am using UCWA 2.0 for some Skype4Business integration in our intranet web application.
I can successfully connect and do some stuff for example: changing availability status or asking for callforwarding settings of the user.
What I like to do that does not work is set a forward contact for the user.
Documentation for this: click here
My code for the POST call:
using (var client = new HttpClient())
{
var param = new { target = "sip:user#domain.be" };
var paramJson = JsonConvert.SerializeObject(param, Formatting.Indented);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Referrer = new Uri(result4._links.xframe.href);
client.DefaultRequestHeaders.Add("Authorization", $"{result3.token_type} {result3.access_token}");
var url = $"https://ucwebext.domain.be/{applicationUrl}/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact";
var responseNew = await client.PostAsync(url, new StringContent(paramJson, Encoding.UTF8, "application/json"));
var responseString = await responseNew.Content.ReadAsStringAsync();
}
Same code using RestSharp:
var client = new RestClient($"https://ucwebext.domain.be/{applicationUrl}");
var restR = new RestRequest("/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact", Method.POST);
var param = new { target = "sip:user#domain.be" };
var jsonToSend = JsonConvert.SerializeObject(param, Formatting.Indented);
restR.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
restR.AddParameter("referer", result4._links.xframe.href);
restR.AddHeader("Authorization", $"{result3.token_type} {result3.access_token}");
restR.RequestFormat = DataFormat.Json;
var response = client.ExecuteAsPost(restR, "POST");
Request header from the call:
POST https://ucwebext.domain.be/ucwa/oauth/v1/applications/101024253230/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact HTTP/1.1
Accept: application/json
Referer: https://ucwebext.domain.be/Autodiscover/XFrame/XFrame.html
Authorization: Bearer cwt=AAEBHAEFAAAAAAAF...0Q_OXzsR4g4F-PpYaMGK10Pg
Content-Type: application/json; charset=utf-8
Host: ucwebext.domain.be
Content-Length: 48
Expect: 100-continue
{"target":"sip:user#domain.be"}
I get the following error:
{"code":"BadRequest","subcode":"ParameterValidationFailure","message":"Please check what you entered and try again.","parameters":[{"name":"target","reason":"MissingOrInvalid"}]}
I tried everything and don't understand why the parameter is not submitting or invalid.
Any help is much appreciated!

SOLUTION
Instead of using JSON I added the parameter as querystring which worked!
var client = new RestClient($"https://ucwebext.domain.be/{applicationUrl}");
var restR = new RestRequest($"/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact{Url.Encode("?target=sip:user#domain.be")}", Method.POST);
restR.AddParameter("referer", result4._links.xframe.href);
restR.AddHeader("Authorization", $"{result3.token_type} {result3.access_token}");
var response = client.ExecuteAsPost(restR, "POST");

Related

QuickBooks Authentication error when getting basic company information

I'm writing a simple desktop application to get information from QuickBooks(developer account using demo account(UK) data) and in this regard I've been able to go past the OAuth flow. However, I've not been able to get the basic company information
The below is a capture of the Fiddler request and response:
GET https://quickbooks.api.intuit.com/v3/company/123145829830639/companyInfo/123145829830639 HTTP/1.1
Authorization: oauth_token="****", oauth_nonce="z4x0a196", oauth_consumer_key="****", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1499283607", oauth_version="1.0", oauth_signature="EGw6Ty%2BKFAawrH1%2FSxQuFwaMcEo%3D"
Content-Type: application/json
Host: quickbooks.api.intuit.com
The generation of the header is similar to https://developer.intuit.com/v2/apiexplorer?apiname=V3QBO#?id=CompanyInfo but I end up getting the following response(Fiddler partial response) based on the request
intuit_tid: gw-c4e19f89-df78-42a5-ae7e-216187421143
Set-Cookie: JSESSIONID=21BF1FFEE48B39538E82485FD25C4280.c51-pprdsbxas901; Path=/; Secure; HttpOnly
QBO-Version: 1706.912
ErrorCode: 100
ErrorCause: AuthenticationErrorGeneral: SRV-110-Authentication Failure , statusCode: 401
Message: General Authentication Error
The code to access company information is as below:
string companyInfo = String.Format("company/{0}/companyInfo/{0}", authenticator.OAuthProfile.realmId);
string ciUrl = BASE_URL + companyInfo; //https://quickbooks.api.intuit.com/v3/
var sb = new System.Text.StringBuilder();
sb.AppendFormat("oauth_token=\"{0}\", oauth_nonce=\"{1}\", oauth_consumer_key=\"{2}\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"{3}\", oauth_version=\"1.0\", oauth_signature=\"{4}\"",
Manager.UrlEncode(_token),
Manager.UrlEncode(_nonce),
Manager.UrlEncode(_consumer_key),
Manager.UrlEncode(_timestamp),
Manager.UrlEncode(_signature));
var authorisationHeader = sb.ToString().TrimEnd(' ').TrimEnd(',');
// Request Company Information
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ciUrl);
request.Headers.Add("Authorization", authorisationHeader);
request.Method = "GET";
request.ContentType = "application/json";
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
// get 401
}
Used sandbox URL and added minorversion to the base URL
I attempted setting BASE_URL set to the sandbox url(https://sandbox-quickbooks.api.intuit.com/v3) and also set minorversion to be 4.
Any help is much appreciated.
Hopefully this helps, but here is a Java snippet using their SDK that works for me:
OAuthAuthorizer oauth = new OAuthAuthorizer(System.env.QB_OAUTH_CONSUMER_KEY, System.env.QB_OAUTH_CONSUMER_SECRET,
vendor.intuitOAuthAccessToken, vendor.intuitOAuthAccessSecret);
UUID trackingID = UUID.randomUUID()
log.info("About to init Context companyID=" + vendor.realmId + ", app_token=" + System.env.QB_APP_TOKEN + ", uuid=" + trackingID.toString())
Context context = new Context(oauth, System.env.QB_APP_TOKEN, ServiceType.QBO, vendor.realmId)
context.setMinorVersion("4")
context.setTrackingID(trackingID)
log.info("About to set BaseURL")
Config.setProperty(Config.BASE_URL_QBO, System.env.QB_BASE_URL + "/v3/company");
log.info("About to init DataService")
// get all customers
log.info("About to executeQuery")
DataService service = new DataService(context)
QueryResult queryResult = service.executeQuery("select * from customer");
In my case, QB_BASE_URL=https://sandbox-quickbooks.api.intuit.com
*NOTE there isn't a trailing slash
vendor.intuitOAuthAccessToken and vendor.intuitOAuthAccessSecret are the values you get back after the oauth flow

How to pass JSON string to another api using RESTSharp?

Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body

Xamarin__HttpClient__HttpResponseMessage-Content --- Getting HTML instead of JSON

HttpClient myClient = new HttpClient();
myClient.BaseAddress = new Uri(URL);
Base address already specified on client it's URL.
var encodedObject = JsonConvert.SerializeObject(Obj);
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await myClient.PostAsync("test.php/yourAPI",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var responseContent = response.ToString();
var responsebody = response.Content.ToString();
Stream receiveStream = response.GetResponseStream();
string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
}
Could be a content negotiation issue. Try clearing the Accept header before adding the json media type
myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//...other code removed for brevity.
this code sets the Accept header to "application/json", which tells the server to send data in JSON format.
Reference source: Calling a Web API From a .NET Client in ASP.NET Web API 2
the Method PostAsync has as first argument the complete URI of The API. Therefore, it should be like follow :
HttpResponseMessage response = await myClient.PostAsync("http://bla-bla-bla/test.php/test",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
And there is no need to define the BaseAddress.

RestSharp / MailChimp 'API key missing' error

When I post a campaign on Mailchimp using RestSharp, it tells me my API key is missing, but when I click "Get Campaign", it successfully shows me all the campaign data.
Can anyone tell me where I'm going wrong? Here's my code:
public MailChimpPostModel PostCampaign(MailChimpPostModel post)
{
var auth = _userBusinessObject.GetUserWebsiteAuthorizationByWebsite(_userId,
_websiteId,
_linkvanaNetworkSiteId);
ApiBaseUrl = <url> ;
if (auth == null)
throw new RestRequestResponseException { Error = RestErrorsEnum.NotAuthenticated };
var request = new RestRequest(3.0/campaigns, Method.POST);
request.AddParameter("access_token", <Token>);
request.AddParameter("apikey", <Token> + "-" + <dc>);
request.AddHeader("content-type", "application/json");
request.AddBody(post);
var response = Execute<MailChimpPostModel>(request);
return response;
}
// replace usX to match the last 3 of your API
var client = new RestClient("https://usX.api.mailchimp.com/3.0/");
client.Authenticator = new HttpBasicAuthenticator("user", APIKey);

Actionscript 3 Air iOS POST data not sending with URLLoader

I have the following code to send POST data to my server:
var headers:Array = [
new URLRequestHeader("api_access_token", ACCESS_TOKEN),
new URLRequestHeader("api_secret", SECRET),
new URLRequestHeader("Content-type", "application/json")
];
var base_url = "http://example.com/";
var complete_func:Function;
function postRequest(url:String, params:Object, response_func:Function){
complete_func = response_func;
var request = new URLRequest(base_url+url);
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.data = JSON.stringify(params);
// Handlers
var postLoader = new URLLoader();
postLoader.addEventListener(Event.COMPLETE, parseResponse);
postLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent){ trace(e); });
postLoader.load(request);
}
function parseResponse(e:Event){
var data = e.target.data;
trace(data);
var json_data = JSON.parse(data);
complete_func(json_data);
}
Problem is, on my server, when I use var_dump($_POST) nothing but an empty array is returned. I don't know why this is the case. I have done traces on params and url parameters which contain relavent data.
The params I am sending are:
var customerDetails:Object = new Object();
customerDetails.first_name = firstNameField.text;
customerDetails.last_name = lastNameField.text;
customerDetails.dob = dobField.text;
customerDetails.email = emailField.text;
The headers retrieved by PHP's list_headers() returns:
array(6) { [0]=> string(24) "X-Powered-By: PHP/5.4.30" [1]=> string(38) "Expires: Thu, 19 Nov 1981 08:52:00 GMT" [2]=> string(77) "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" [3]=> string(16) "Pragma: no-cache" [4]=> string(44) "api_secret: example_secret" [5]=> string(50) "api_access_token: example_access" }
I am using Air 16.0 for iOS with ActionScript 3
Any help would be great. I don't know if this is a cross-domain policy issue.
P.S. Works fine with a GET request.
Use the right dataFormat:
loader.dataFormat = URLLoaderDataFormat.VARIABLES
As3 code is valid. You need improve from server side php code.. Please try this ..
<?php
$body = #file_get_contents('php://input');
$jsn = json_decode($body);
echo $jsn->first_name;
echo $jsn->last_name;
echo $jsn->dob;
echo $jsn->email;
?>

Resources