When I Post this Data Throw Postman To Web API((http://192.168.18.15/api/PostData)) it works for me and gives me 200 OK Success CODE
Method: POST,
Headers: Content-Type: application/json,
cache-control: no-cache
[
{
"Code": "900350491",
"FullName":"John Setalh",
"OrgCode": "13",
"OrgDescription": "Microsoft Services",
"RegCode": "11",
"DISTRICT_CODE": "900",
"ACCOUNT_NO": "00012043",
"BANK_ACCOUNT_NO": "00003043",
"DESCRIPTIONS": "just test the System",
"AMOUNT": "300",
"SUB_DETAILS":
[
{
"Unit": "73000",
"ReCode": "13300",
"ReDes":"Some Description",
"ReAmount": "0"
}
]
}
]
Now I want to Implement C# Code to Post this JSON data and I tried this Code:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer",mytoken);
client.BaseAddress = new Uri("http://192.168.18.15/");
MyModel r = new MyModel();
r.Code = "12354";
r.FullName = "FullName Here";
r.OrgCode = "73";
r.OrgDescription= "SomeDescription";
r.RegCode = "50";
r.DISTRICT_CODE = "230";
r.ACCOUNT_NO = "00012043";
r.BANK_ACCOUNT_NO = "00203043";
r.DESCRIPTIONS = "just test the System";
r.AMOUNT = "300";
r.SUB_DETAILS.Unit="73000";
r.SUB_DETAILS.ReCode="13300";
r.SUB_DETAILS.ReDes="Some Description";
r.SUB_DETAILS.ReAmount="300";
var sendData = client.PostAsJsonAsync("api/PostData", new List<MyModel> {r}).Result;
var result = sendData.Content.ReadAsStringAsync();
string TariffNos = result.Result;
}
it gives me an error Message: Wrong Attempt Status Code:400 Error: UnAuthorized
can anyone help me where is the Problems my Token is Correct why it give that Error
thanks
your model should be a collection, since you are using collection for postman. Try this model
var sendData = client.PostAsJsonAsync("api/PostData", new List<MyModel> {r}).Result;
and try to add a content type
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
Related
I I’m looking for a way to create a new priority value with the REST API.
In the documentation I found the following endpoint:
/rest/admin/customfield/bundle/{bundleName}/{fieldValue}?{description}&{colorIndex}
Calling this endpoint returns a 415 status code with the content:
{"value":"Unsupported Media Type"}
Here is my code:
var connection = YouTrackConnectionFactory.GetConnection();
var client = await connection.GetAuthenticatedHttpClient();
var priorityValue = "SomeNewPrio";
var enumerationName = "Priorities";
var queryString = new Dictionary<String, String>
{
{ "bundleName", enumerationName },
{ "fieldValue", priorityValue },
{ "description", WebUtility.UrlEncode( "Automatically created priority" ) },
{ "colorIndex", "9" }
};
var response = await client.PutAsync( $"/rest/admin/customfield/bundle/{enumerationName}/{priorityValue}", new FormUrlEncodedContent( queryString ) );
response.EnsureSuccessStatusCode();
Is there something wrong with my data or is there another endpoint I should be using?
I've read along the way that Salesforce (I'm extremely new to this 3rd party platform) has a FUEL SDK which one can use instead of the version (using HttpClient -- REST instead of SOAP).
Please correct me if using FUEL SDK is the only way to go about requesting Salesforce's endpoints. Currently I am attempting to hit ExactTargets's API endpoints using HttpClient. These are the tutorials I've been basing my code off of:
https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/messageDefinitionSends.htm
https://developer.salesforce.com/docs/atlas.en-us.mc-getting-started.meta/mc-getting-started/get-access-token.htm
Wanted Result:
To be able to request a Triggered Send email based off a template inside of ExactTarget.
Problem:
The Salesforce endpoint continuously returns a 404. I am able to receive the authorization token successfully. The GetAccessToken method is omitted for brevity
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
I do not understand why the 2nd POST request to //www.exacttargetapis.com/..... returns a 404 but the authorization works. This leads me to believe that I do not have to use the FUEL SDK to accomplish triggering a welcome email.
Code:
private const string requestTokenUrl = "https://auth.exacttargetapis.com/v1/requestToken";
private const string messagingSendUrl = "https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends";
private string exactTargetClientId = ConfigurationManager.AppSettings["ExactTargetClientId"];
private string exactTargetClientSecret = ConfigurationManager.AppSettings["ExactTargetClientSecret"];
private string TriggerEmail(User model, string dbName)
{
var etExternalKeyAppSetting = ConfigurationManager.AppSettings.AllKeys.FirstOrDefault(x => x.Equals(dbName));
if (etExternalKeyAppSetting != null)
{
string etExternalKey = ConfigurationManager.AppSettings[etExternalKeyAppSetting];
HttpClient client = new HttpClient
{
BaseAddress = new Uri(string.Format(#"{0}/key:{1}/send", messagingSendUrl, etExternalKey)),
DefaultRequestHeaders =
{
Authorization = new AuthenticationHeaderValue("Bearer", this.GetAccessToken())
}
};
try
{
var postData = this.CreateExactTargetPostData(model.Email, etExternalKey);
var response = client.PostAsync(client.BaseAddress
, new StringContent(JsonConvert.SerializeObject(postData).ToString()
, Encoding.UTF8
, "application/json")).Result;
// get triggered email response
if (response.IsSuccessStatusCode)
{
dynamic result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
}
return "testing";
}
private object CreateExactTargetPostData(string email, string extKey)
{
var fromData = new
{
Address = ConfigurationManager.AppSettings["AwsSenderEmail"],
Name = "Test"
};
var subscriberAttributes = new { };
var contactAttributes = new
{
SubscriberAttributes = subscriberAttributes
};
var toData = new
{
Address = email,
//SubscriberKey = extKey,
//ContactAttributes = contactAttributes
};
var postData = new
{
From = fromData,
To = toData
};
return postData;
}
I have also tried using Advanced REST Client using the following:
URL:
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
POST
Raw Headers:
Content-Type: application/json
Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Raw Payload:
{
"From": {
"Address": "code#exacttarget.com",
"Name": "Code#"
},
"To": {
"Address": "example#example.com",
"SubscriberKey": "example#example.com",
"ContactAttributes": {
"SubscriberAttributes": {
"Region": "West",
"City": "Indianapolis",
"State": "IN"
}
}
},
"OPTIONS": {
"RequestType": "ASYNC"
}
}
Issue was my App in the AppCenter was pointing to the incorrect login for MarketingCloud =(
I am using
IDE : VS2012
Framework : 4.0
Google API: Youtube Data V3
Authentication: Outh 2.0
I am using Youtube Data API V3 to set watermark on youtube video . Here is my code
**my fiddler request** is : POST https://www.googleapis.com/youtube/v3/watermarks/set?channelId=UCyAn2aVZWNAugdlckOJKG5A
and my content body :
{
"position": {
"cornerPosition": "topRight",
"type": "corner"
},
"timing": {
"durationMs": "50000",
"offsetMs": "1000",
"type": "offsetFromStart"
},
"targetChannelId": "UCyAn2aVZWNAugdlckOJKG5A"
}
i am passing image content with stream object with set method ..
and Response is: Value cannot be null Parameter name: baseUri
public async Task setwatermark()
{
InvideoBranding ib = new InvideoBranding();
InvideoTiming it = new InvideoTiming();
InvideoPosition ip = new InvideoPosition();
Stream stream = null;
it.Type = "offsetFromStart";
it.OffsetMs = 1000;
it.DurationMs = 50000;
ip.Type = "corner";
ip.CornerPosition = "topRight";
string filepath = Server.MapPath("~/Images/orderedList0.png");
ib.TargetChannelId = "UCyAn2aVZWNAugdlckOJKG5A";
// ib.ImageUrl = filepath;
ib.Position = ip;
ib.Timing = it;
using (var fileStream = new FileStream(filepath, FileMode.Open))
{
stream = (Stream)fileStream;
var setrequest = youtubeService.Watermarks.Set(ib, "UCyAn2aVZWNAugdlckOJKG5A",stream,"image/*");
var resp =await setrequest.UploadAsync();
}
Below code is for unset watermarks using YouTube Data API V3.
It is response with --Error 503-backend error.
Fiddler Request :POST https://www.googleapis.com/youtube/v3/watermarks/unset?channelId=UCyAn2aVZWNAugdlckOJKG5A
**Fiddler response** :{
"error": {
"errors": [
{
"domain": "global",
"reason": "back end Error",
"message": "Back end Error"
}
],
"code": 503,
"message": "Back end Error"
}
}
private void Unsetwatermark()
{
var unsetrequest = youtubeService.Watermarks.Unset("UCyAn2aVZWNAugdlckOJKG5A");
var searchListResponse = unsetrequest.Execute();
}
Please tell me what i am doing wrong for both above mentioned api request ..
I am attempting to implement my own LRS for saving TinCanAPI statements and in order to do this I need to retrieve the values sent in the Request Payload which stores the details of the learning activity statement.
When viewing my WebAPI call in developer tools I can see the required values but I have been unable to find them using the Request object.
How Can I retrieve the Request Payload variables from the Request object? I have tried the request object and looked in the Content and Properties fields but I cannot seem to see a Request Payload property to reference in C#. My payload looks as follows:
{
"id": "d3d9aa2a-5f20-4303-84c3-1f6f5b4e9236",
"timestamp": "2014-06-26T11:00:41.432Z",
"actor": {
"objectType": "Agent",
"mbox": "mailto:name#company.com",
"name": "My Name"
},
"verb": {
"id": "http://adlnet.gov/expapi/verbs/attempted",
"display": {
"und": "attempted"
}
},
"context": {
"extensions": {
"http://tincanapi.com/JsTetris_TCAPI/gameId": "5686f104-3301-459d-9487-f84af3b3915c"
},
"contextActivities": {
"grouping": [
{
"id": "http://tincanapi.com/JsTetris_TCAPI",
"objectType": "Activity"
}
]
}
},
"object": {
"id": "http://tincanapi.com/JsTetris_TCAPI",
"objectType": "Activity",
"definition": {
"type": "http://adlnet.gov/expapi/activities/media",
"name": {
"en-US": "Js Tetris - Tin Can Prototype"
},
"description": {
"en-US": "A game of tetris."
}
}
}
}
I have tried using:
var test1 = Request.ToString(); **EMPTY STRING**
var test1 = Request.Content.ReadAsStringAsync().Result; **EMPTY STRING**
var test2 = Request.Content.ReadAsFormDataAsync().Result; **THROWS FORMATTER ERROR DESPITE config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); added in the webapiconfig.cs
I was able to retrieve the sent statement values by changing my WebAPI controller as follows:
public void Put([FromBody]TinCan.Statement statement)
{
var actor = statement.actor;
var context = statement.context;
var target = statement.target;
var timestamp = statement.timestamp;
var verb = statement.verb;
...................
try {
//String payloadRequest = getBody(request);
// System.out.println("payloadRequest : "+payloadRequest);
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println("payloadRequest : "+data);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Try this:
var value = Request["var_name"];
I can't really find a working example, maybe it is because its simply not possible?
I'd like to take a C# anonymous type object like the following:
var postBody = new
{
friend = new
{
name = "dave",
last ="franz"
},
id = "12345",
login = "mylogin"
};
and post it to my web service in a simple http POST with the following post body:
{
"friend" :
{
"name" : "dave",
"last" : "franz"
},
"id" : "12345",
"login" : "mylogin"
};
Pretty easy using Json.net. You can get it using the nuget package manager in VS.
var postBody = new
{
friend = new
{
name = "dave",
last ="franz"
},
id = "12345",
login = "mylogin"
};
var postString = Newtonsoft.Json.JsonConvert.SerializeObject(postBody);
using(var wc = new WebClient())
{
wc.Headers.Add("Content-Type", "application/json");
var responseString = wc.UploadString(serviceAddress, "POST", postString);
}
If you have HttpClient client:
var request = new HttpRequestMessage(HttpMethod.Post, "<URL>") {
Content = JsonContent.Create(new {
Prop = "Value"
})
};
var response = await client.SendAsync(request);