I'm developing windows phone 8 application.. i cannot use the dll using system.net.httpwebrequest; in windows phone 8, so i need to converet the http request to webclient can any one suggest how to convert it..?
private HttpWebResponse GetHttpWebResponse(HttpWebRequest webRequest)
{
HttpWebResponse response;
try
{
response = (HttpWebResponse)webRequest.GetResponse();
//GetResponse() produce error that System.Net.HttpRequest dll is missing,
//so im in need to conertr the http request to webclient.
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
return response;
}
my complete Json data
[
{
"id": 01,
"address": "12asdf",
"city": " chennai",
"contact1": "",
"contact2": "",
"country": " india",
"description": "",
"name": " david",
"region": "",
"state": " 033",
"website": "",
"image": "",
"PrayerTime": {
"id": 01,
"PrayerTime1": "00:52",
"PrayerTime2": "21:04",
"PrayerTime3": "12:27",
"PrayerTime4": "05:35",
"PrayerTime5": "21:04",
"created_at": null,
"PrayerTime6": "04:01",
"updated_at": null,
"organization_id": 001
}
},.............
}
I recommend that you use the HttpClient instead (nuget package), it's more convenient and is supported also on WinRT.
Here is an example from trying to fetch geo coded data from social medias (which is irrelevant itself, but its a real world example :) , using HttpClient
(you need Newtonsoft.Json to use JObject/JArray)
You can probably waive the part where I add the DefaultRequestHeaders in your own call
using (HttpClient client = new HttpClient())
{
string url = mediaConfig.RequestUrl + String.Format(mediaConfig.GeoCodeStringFormat, lat, lon, distance);
if (mediaConfig.MediaName == "Twitter")
client.DefaultRequestHeaders.Add(mediaConfig.BearerTokenParamName, mediaConfig.BearerToken);
else if (mediaConfig.MediaName == "Instagram")
url = url + "&" + mediaConfig.BearerTokenParamName + "=" + mediaConfig.BearerToken;
else if (mediaConfig.MediaName == "GooglePlaces")
url = url + "&" + mediaConfig.BearerTokenParamName + "=" + mediaConfig.BearerToken;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
}
responseString = await response.Content.ReadAsStringAsync();
Make sure your method signature has the async keyword, if you would to return "responseString":
public async Task<string> methodname(... params ...
to "consume" this method from a sync method:
var mytask = methodname();
mytask.ContinueWith(c =>
{
var jsonResponse = JObject.Parse(c.Result);
// or JArray
var jsonResponseArray = JArray.Parse(c.Result);
foreach (var item in jsonResponseArray)
{
var id = item.SelectToken("id").ToString();
// and so on...
}
var selectSomething = jsonResponse.SelectToken("somethinghere");
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// do your ui tasks, navigate etc...
});
});
Related
Currently I'm trying to create user activity from uwp application. But every time I encounter this response.
{
"error": {
"code": "AuthenticationError",
"message": "Error authenticating with resource",
"innerError": {
"date": "2022-12-28T09:20:16",
"request-id": "some id",
"client-request-id": "some id"
}
}
}
Here is my c# code example. Request content string was taken from microsoft docs
public sealed class UserActivityProvider : IUserActivityProvider
{
private const string activityId = "SendMessageUserActivity";
private static HttpClient httpClient = new HttpClient();
public UserActivityProvider()
{
}
private async Task<string> GetAccessTokenAsync(Account account)
{
var accessToken = string.Empty;
var publicClientApplication = PublicClientApplicationBuilder.Create(MicrosoftConstants.ClientId)
.WithRedirectUri(MicrosoftConstants.RedirectUri)
.Build();
var scopes = new string[]
{
"UserActivity.ReadWrite.CreatedByApp"
};
AuthenticationResult? authToken = null;
try
{
authToken = await publicClientApplication.AcquireTokenSilent(scopes, account.Email).ExecuteAsync();
}
catch (Exception)
{
authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
}
if (authToken != null)
{
accessToken = authToken.AccessToken;
}
return accessToken;
}
public async Task CreateUserActivityAsync(Account account, CreatingMessageUserActivityParameters userActivityParameters)
{
var accessToken = await GetAccessTokenAsync(account);
if (accessToken != string.Empty)
{
var contentForCreatingActivity = new StringContent("{\r\n \"appActivityId\": \"SendMessageUserActivity\",\r\n \"activitySourceHost\": \"https://www.contoso.com\",\r\n \"userTimezone\": \"Africa/Casablanca\",\r\n \"appDisplayName\": \"Contoso, Ltd.\",\r\n \"activationUrl\": \"https://www.contoso.com/article?id=12345\",\r\n \"contentUrl\": \"https://www.contoso.com/article?id=12345\",\r\n \"fallbackUrl\": \"https://www.contoso.com/article?id=12345\",\r\n \"contentInfo\": {\r\n \"#context\": \"https://schema.org\",\r\n \"#type\": \"Article\",\r\n \"author\": \"Jennifer Booth\",\r\n \"name\": \"How to Tie a Reef Knot\"\r\n },\r\n \"visualElements\": {\r\n \"attribution\": {\r\n \"iconUrl\": \"https://www.contoso.com/icon\",\r\n \"alternateText\": \"Contoso, Ltd.\",\r\n \"addImageQuery\": false\r\n },\r\n \"description\": \"How to Tie a Reef Knot. A step-by-step visual guide to the art of nautical knot-tying.\",\r\n \"backgroundColor\": \"#ff0000\",\r\n \"displayText\": \"Contoso How-To: How to Tie a Reef Knot\",\r\n \"content\": {\r\n \"$schema\": \"https://adaptivecards.io/schemas/adaptive-card.json\",\r\n \"type\": \"AdaptiveCard\",\r\n \"body\": [\r\n {\r\n \"type\": \"TextBlock\",\r\n \"text\": \"Contoso MainPage\"\r\n }\r\n ]\r\n }\r\n }\r\n}", Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await httpClient.PutAsync($"https://graph.microsoft.com/beta/me/activities/{activityId}", contentForCreatingActivity);
var stringifiedResponse = await response.Content.ReadAsStringAsync();
}
}
}
And here is also get method for retrieving all activities and it's also return bad request
public async Task<string?> IsUserActivityExistsAsync(Account account)
{
string? resultSubject = null;
var accessToken = await GetAccessTokenAsync(account);
if (accessToken != string.Empty)
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/activities");
var stringifiedResponse = await response.Content.ReadAsStringAsync();
}
return resultSubject;
}
All articles referencing that I have to provide correct scope but I took that scope from official microsoft docs and there wouldn't be a mistake.
Response for getting activities
{
"error": {
"code": "UnknownError",
"message": "{\"ErrorCode\":2,\"ErrorMessage\":\"Substrate operation failed. Url: https://substrate.office.com/api/v2.0/users('******(73)')/CurrentCollections('******(10)') Status: Unauthorized. Error Code: invalid_tenant Error Message: The tenant for tenant guid 'tenant' does not exist., SubstrateError: null\"}",
"innerError": {
"date": "2022-12-29T05:44:57",
"request-id": "id",
"client-request-id": "id"
}
}
}
Response for adding activities
{
"error": {
"code": "UnknownError",
"message": "{\"ErrorCode\":35,\"ErrorMessage\":\"General error occurred. Contact product team.\"}",
"innerError": {
"date": "2022-12-29T05:59:02",
"request-id": "id",
"client-request-id": "id"
}
}
}
Please make sure that UserActivity.ReadWrite.CreatedByApp MS Graph API permissions are assigned to your app in Azure AD as Delegated type (not Application)
UPDATED:
Not sure if you're using correct authentication provider, for delegated type (check options here https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS)
Try to acquire token by updating your code with the following changes
var publicClientApplication = PublicClientApplicationBuilder
.Create(MicrosoftConstants.ClientId)
.WithTenantId("YOUR_TENANT_ID")
.Build();
and
var authToken = await publicClientApplication
.AcquireTokenByIntegratedWindowsAuth(scopes)
.ExecuteAsync()
.Result;
Note: Execute code under user account belonging to organization
As you said you are getting empty data when you decoded the access token in jwt.ms , which means you are doing something wrong while acquiring access token , follow the doc to get token via Interactive provider , and then again check by decoding in jwt.ms .
var scopes = new[] { "User.Read" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
// Value from app registration
var clientId = "YOUR_CLIENT_ID";
// using Azure.Identity;
var options = new InteractiveBrowserCredentialOptions
{
TenantId = tenantId,
ClientId = clientId,
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
// MUST be http://localhost or http://localhost:PORT
// See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
RedirectUri = new Uri("http://localhost"),
};
// https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
var interactiveCredential = new InteractiveBrowserCredential(options);
var graphClient = new GraphServiceClient(interactiveCredential, scopes);
I am developing an app using instagram api to bring feed to my website. I have following code but when i try to access the access_token using the code provided by Instagram it's giving me `400 Bad request error. I would be much obliged if someone could help me to overcome this problem. Many Thanks
string code="";
public ActionResult Index()
{
if (!String.IsNullOrEmpty(Request["code"]))
{
code = Request["code"].ToString();
GetDataInstagramToken();
}
return View();
}
public ActionResult Instagram()
{
var client_id = ConfigurationManager.AppSettings["instagram.clientid"].ToString();
var redirect_uri = ConfigurationManager.AppSettings["instagram.redirecturi"].ToString();
string url = "https://api.instagram.com/oauth/authorize/?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=code";
Response.Redirect(url);
return View();
}
public void GetDataInstagramToken()
{
var json = "";
var page = HttpContext.CurrentHandler as Page;
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", ConfigurationManager.AppSettings["instagram.clientid"].ToString());
parameters.Add("client_secret", ConfigurationManager.AppSettings["instagram.clientsecret"].ToString());
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", ConfigurationManager.AppSettings["instagram.redirecturi"].ToString());
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
int id = (int)jsResult["user"]["id"];
//This code register id and access token to get on client side
page.ClientScript.RegisterStartupScript(this.GetType(), "GetToken", "<script> var instagramaccessid=\"" + #"" + id + "" + "\"; var instagramaccesstoken=\"" + #"" + accessToken + "" + "\";</script>");
}
catch (Exception ex)
{
throw;
}
}
I am getting exception at
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
In this line
client.UploadValues("https://api.instagram.com/oauth/access_token", "post", parameters);
You don't send any value to Instagram. If you check your parameter you can see your key but you cant see any value.
Try this:
public async void GetTokenFromCode()
{
var values = new Dictionary<string, string> {
{ "client_id","Your ChatId" },
{ "client_secret", "Your Client Secret" },
{ "grant_type", "authorization_code" },
{ "redirect_uri", "Your Redirect url"},
{ "code", "code" } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.instagram.com/oauth/access_token", content);
var responseString = await response.Content.ReadAsStringAsync();
}
Hi I am new to programming and I am still a student trying to learn C# and I am supposed to retrieve the response from the web service but I couldn't and it is unable to enter both the if and else statement. How do I resolve this error
.xaml.cs
private async void GetData(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://172.20.129.44/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//try
//{
HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
if (response.IsSuccessStatusCode)
{
string jsonString = await response.Content.ReadAsStringAsync();
dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
//string abc = dynamicObject["infoOpeningDays"].ToString();
// List<String[]> dynamicObject = JsonConvert.DeserializeObject<List<String[]>>(jsonString);
//Debug.WriteLine(dynamicObject[0].ToString());
//string abc = dynamicObject.IEnumerator.[0].IEnumerator.[0].IEnumerator.[0].IEnumerator.[5].Name;
try
{
// var abc = dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject);
String abc = (String)dynamicObject["infoOpeningDays"];
//JArray v = new JArray();
//v[0].data,tostring()
}
catch (Exception ex) { }
//Debug.WriteLine(abc.ToString());
// Debug.WriteLine((string)abc);
}
else
{
Debug.WriteLine("It entered else not if");
}
//}
//catch (Exception ex)
//{
// Debug.WriteLine(ex.ToString());
//}
}
.aspx
<Button Text="Get Data" TextColor="White" BackgroundColor="#4282bd" Clicked="GetData"/>
Web service
http://172.20.129.44/WebServices/information.svc/GetInformationJSON
Web service Data
{
"d": [
{
"__type": "Info:#website.Model",
"infoClosingDays": "Friday",
"infoClosingHours": "06:00:00 PM",
"infoID": 1,
"infoOpeningDays": "Monday",
"infoOpeningHours": "09:30:00 AM",
"infoStatus": "Open"
}
]
}
Someone Please Save me please
You can try using
HttpResponseMessage response = new HttpResponseMessage();
response.Content = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
This might solve your issue.
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 ..