Unauthorized on SendGrid Statistics - c#

I am trying to get the totals for each email statistic metrics for all sub users.
However I am getting an authorized required message:
I cannot figure out what is the issue. I have referenced the sendgrid api online and this should be the correct format.
https://github.com/sendgrid/sendgrid-csharp
Unauthorized {"errors":[{"field":null,"message":"authorization
required"}]} Connection: keep-alive Access-Control-Allow-Methods:
HEAD, GET, PATCH, PUT, POST, OPTIONS, DELETE Access-Control-Max-Age:
21600 Access-Control-Expose-Headers: Link Access-Control-Allow-Origin:
* Access-Control-Allow-Headers: AUTHORIZATION, Content-Type, On-behalf-of, x-sg-elas-acl Content-Security-Policy: default-src
https://api.sendgrid.com; frame-src 'none'; object-src 'none'
X-Content-Type-Options: nosniff Strict-Transport-Security:
max-age=31536000 Date: Wed, 02 Nov 2016 16:25:29 GMT Server: nginx
Here is the code I am using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SendGrid;
using Newtonsoft.Json; // You can generate your JSON string yourelf or with another library if you prefer
using System.Web.Script.Serialization;
using SendGrid.Helpers.Mail;
namespace SendGridSubStats
{
class Program
{
static void Main(string[] args)
{
Execute().Wait();
}
static async Task Execute()
{
string apiKey = Environment.GetEnvironmentVariable("APIKEY_GOES_HERE", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
// Retrieve the totals for each email statistic metric for all subusers.
// GET /subusers/stats/sums
string queryParams = #"{
'aggregated_by': 'day',
'end_date': '2016-04-01',
'limit': 1,
'offset': 1,
'sort_by_direction': 'asc',
'sort_by_metric': 'test_string',
'start_date': '2016-01-01'
}";
dynamic response = await sg.client.subusers.stats.sums.get(queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
}
}
}

Related

C# Hue Bridge PUT sending OK response. No API response [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
SO I've searched around and even asked on the neigh dead official forums. I've searched here but the responses are years old and oft contain dead links.
I'm simply trying to toggle a light in my house. I've auth'd via the debug tool already and gotten my "username" and then hardcoded it into this app. Again this is just me testing it. I've even copied a functional url (http://192.168.0.100/api/RjplsYoXQvdTl11DOVIo92SKNB7vYRfwZvqCzvDK/lights/2/) into other browsers and devices to ensure that i don't have to process through a reauth on different devices.
Yes also I know i'm moving from sync to async but unless that's the problem i'm not worried about hanging the program there. I'm just trying to toggle something in the API :)
So the problem is the response is just a generic HTTP 200 OK response and not an API response as expected.
I get:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Server: nginx
Date: Sun, 23 Sep 2018 18:37:44 GMT
Connection: close
Cache-Control: no-store, must-revalidate, no-cache, post-check=0, pre-check=0
Pragma: no-cache
Access-Control-Max-Age: 3600
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE, HEAD
Access-Control-Allow-Headers: Content-Type
Content-Type: application/json
Expires: Mon, 01 Aug 2011 09:00:00 GMT
}
when i expect
{"success":{"/lights/1/state/on":false}},
Here's the code. Can someone shine some light on this? Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static HttpClient client = new HttpClient();
static HttpResponseMessage response = new HttpResponseMessage();
public class StateO
{
public bool On { get; set; }
public int Bri { get; set; }
}
public class Light
{
public string Name { get; set; }
public StateO State { get; set; }
public Light()
{
State = new StateO();
}
}
static void Main(string[] args)
{
client.BaseAddress = new Uri("http://192.168.0.100/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
UpdateProductAsync().GetAwaiter().GetResult();
}
public static async Task<Light> UpdateProductAsync()
{
Light light = new Light();
light.State.On = false;
string json = JsonConvert.SerializeObject(light);
response = await client.PutAsJsonAsync(
$"api/RjplsYoXQvdTl11DOVIo92SKNB7vYRfwZvqCzvDK/lights/2/", json);
Console.WriteLine("potato: " + response.ToString());
response.EnsureSuccessStatusCode();
// light = await response.Content.ReadAsAsync<Light>();
return light;
}
}
}
Is that IP address the correct one for your bridge? Your response header is coming from an Nginx server.
Also seems like you are a little confused with the Hue API endpoints.
PUT request to /api/<username>/lights/<id> is to rename lights
PUT request to /api/<username>/lights/<id>/state is to change light state
Documentation is here

Unauthorized access to REST API

I am having a big problem when trying to authenticate to QuickBlox's server using a Token.
The method I use is:
public static async Task<LoginResponse> GetLoginResponseAsync(string email, string password)
{
LoginResponse result = null;
using (var client = new HttpClient())
{
string token = QbProvider.SessionResponse.Session.Token;
LoginRequest request = new LoginRequest()
{
Email = email,
Password = password
};
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, LoginUrlRequest))
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("QB-Token", token);
using (var response = await client.SendAsync(requestMessage))
{
string json = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<LoginResponse>(json);
}
}
}
return result;
}
The server's response is:
{"errors":["Token is required"]}
And the headers (debugging) in the client object are:
{
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Date: Thu, 01 Jun 2017 12:05:29 GMT
QuickBlox-REST-API-Version: 0.1.1
Server: openresty/1.9.15.1
Status: 401 Unauthorized
Strict-Transport-Security: max-age=31536000
WWW-Authenticate: OAuth realm=users
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 584a0dca-fc44-4114-9626-327ac1729f67
X-Runtime: 0.003430
X-XSS-Protection: 1; mode=block
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Content-Length: 32
}
}
When I use the Token in Postman, the server's response is successfull.
Do you know what am I doing wrong?
Thank you so much in advance!
Regards.
Try adding your token header using requestMessage.Headers.Add("QB-Token", token) instead of your Authorization one – by #dukedukes

Using Zephyr for Jira Cloud's ZAPI with .Net

I've put together some my solution, and I'm finally able to get a response from Zephyr, but it is giving me a 404 response, when I know that it is available. Is anyone else trying to use ZAPI to report test data?
The secret and access key comes from the Jira page that Zephyr adds. The project key comes from Jira. Here is my code and the response it gives me:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Jira.SDK.Domain;
using JWT;
namespace WebPortalUITests.Controllers
{
[TestClass]
public class Reporting
{
static string User = "My.User.Name";
static string Password = "My.Password";
static string jiraBaseUrl = "https://mycompany.atlassian.net/";
static string zephyrBaseUrl = "https://prod-api.zephyr4jiracloud.com/connect";
static string Secret = "P1oihENe5PLUS_THE_REST_OF_MY_SECRET";
static string AccessKey = "amlyYTox_PLUS_THE_REST_OF_MY_KEY";
public async Task<bool> CycleExists(string Name)
{
//connect to Jira to get project and version IDs using the Jira.SDK library
Jira.SDK.Jira jira = new Jira.SDK.Jira();
jira.Connect(jiraBaseUrl, User, Password);
Project webPortal = jira.GetProject("WP");
long id = webPortal.ID;
long version = webPortal.ProjectVersions.Last<ProjectVersion>().ID;
//format the Zephyr request and use it to generate a JWT
string request = "/connect/public/rest/api/1.0/cycles/search?versionId=" + version + "&projectId=" + id;
string finalAPI = zephyrBaseUrl + request;
string token = JsonWebToken.Encode(finalAPI, Secret, JwtHashAlgorithm.HS256);
//put the JWT and the accesskeys in the header and request the info
using (var httpClient = new HttpClient { BaseAddress = new Uri(zephyrBaseUrl)})
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "JWT "+token);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("zapiaccesskey", AccessKey);
using (var response = httpClient.GetAsync(string.Format(request)).Result)
{
string responseData = await response.Content.ReadAsStringAsync();
}
return true;
}
}
}
}
response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
Date: Thu, 26 Jan 2017 20:34:01 GMT
Server: Apache-Coyote/1.1
Content-Length: 0
}} System.Net.Http.HttpResponseMessage

Can't rename folder in SharePoint 2013 using REST

I'm having trouble renaming a folder inside a document library using the REST api provided by SharePoint 2013. Here is the code I'm using below.
string digest = String.Empty;
using (var response = await connector.HttpClient.PostAsync("_api/contextinfo", null, token))
{
response.EnsureSuccessStatusCode();
var obj = await response.ReadObject("d");
digest = obj["GetContextWebInformation"].Value<string>("FormDigestValue");
}
using (var request = new HttpRequestMessage(HttpMethod.Post, String.Format("/_api/Web/GetFolderByServerRelativeUrl('{0}')", operation.Path.FullName)))
{
request.Headers.Add("X-HTTP-Method", "MERGE");
request.Headers.Add("IF-MATCH", "*");
request.Headers.Add("X-RequestDigest", digest);
//{ '__metadata': { 'type': 'SP.Folder' }, 'Name': 'New name' }
dynamic obj = new JObject();
obj.__metadata = new JObject();
obj.__metadata.type = "SP.Folder";
obj.Name = operation.DesiredName;
request.Content = new ODataJObjectContent(obj);
using (var response = await connector.HttpClient.SendAsync(request, token))
{
response.EnsureSuccessStatusCode();
await response.ReadText();
}
}
In Fiddler here is the request:
POST http://2013.blah.com/_api/Web/GetFolderByServerRelativeUrl('/Shared%20Documents/Test') HTTP/1.1
X-HTTP-Method: MERGE
IF-MATCH: *
X-RequestDigest: 0xA7C057B3AECE805B7313909570F64B8EACD7A677014B8EBE7F75CC5A7C081F87973D94E7CC22346964ECAB1FE3C6B326DA3B67DF7A646FE6F47E9B1E686C3985,11 Apr 2013 15:13:05 -0000
Accept: application/json; odata=verbose
Content-Type: application/json; odata=verbose
Host: 2013.skysync.com
Content-Length: 50
Expect: 100-continue
{"__metadata":{"type":"SP.Folder"},"Name":"Test2"}
And then the response:
HTTP/1.1 204 No Content
Cache-Control: private, max-age=0
Expires: Wed, 27 Mar 2013 15:13:15 GMT
Last-Modified: Thu, 11 Apr 2013 15:13:15 GMT
Server: Microsoft-IIS/8.0
X-SharePointHealthScore: 0
SPClientServiceRequestDuration: 15
X-AspNet-Version: 4.0.30319
SPRequestGuid: 53bd109c-43bb-2064-4a1b-82298b670ece
request-id: 53bd109c-43bb-2064-4a1b-82298b670ece
X-RequestDigest: 0x9CDB4F31CC5F3877C4383657C12BEC6CFF10FC28AB6A0BB2D9D38B4279187CBD1450359BDFF07F0E63FF550BFF96C46E0476FB895CDA104348AC066D86246BC6,11 Apr 2013 15:13:15 -0000
X-FRAME-OPTIONS: SAMEORIGIN
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4420
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: Thu, 11 Apr 2013 15:13:15 GMT
Everything looks good until I go back to SharePoint and the Test folder is still the same name. I'm following the guidelines from here and I've seen other very similar examples. I can rename it through the interface without any problem.
Thanks in advance for any help!
The following example demonstrates how to rename Folder via SharePoint 2013 REST service
Scenario: rename Archive folder to 2015 located in Documents
library
using (var client = new SPHttpClient(webUri, userName, password))
{
RenameFolder(client, webUri.ToString(),"Documents/Archive","2015");
}
where
private static void RenameFolder(SPHttpClient client, string webUrl,string folderUrl,string folderName)
{
var folderItemUrl = webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/ListItemAllFields";
var data = client.ExecuteJson(folderItemUrl);
var itemPayload = new {
__metadata = new { type = data["d"]["__metadata"]["type"] },
Title = folderName,
FileLeafRef = folderName,
};
var itemUrl = data["d"]["__metadata"]["uri"];
var headers = new Dictionary<string, string>();
headers["IF-MATCH"] = "*";
headers["X-HTTP-Method"] = "MERGE";
client.ExecuteJson((string)itemUrl, HttpMethod.Post, headers, itemPayload);
}
Note:
SPHttpClient class - inherits from HttpClient and provides some additional SharePoint specific functionaly such as getting
request digest
SPHttpClientHandler class - hides all the intricacies related to SharePoint Online authentication
Try to add list in your manifest file. It seems like a permissions problem, and when you have to "trust" an application then choose the list which you want to operate with.

ETag not being returned by WebResponse Header in c#

I am trying to extract the ETag from the response header. It does exist in the response. I can see it using firebug and I can see it in the response object using the inspector:
Status: 200 OK
X-Api-Version: 1.3.2
Access-Control-Allow-Origin: *
X-Runtime: 0.151298
Connection: keep-alive
Content-Length: 8185
Cache-Control: public, max-age=11216
Content-Type: application/json; charset=utf-8
Date: Fri, 09 Mar 2012 01:40:05 GMT
Expires: Fri, 09 Mar 2012 04:47:01 GMT
ETag: "bd3fe1123a8f55e01ca859f4804e8fbe"
Last-Modified: Fri, 09 Mar 2012 00:47:01 GMT
Server: nginx/1.0.11
All the other code is working fine, making the HttpWebRequest, getting the respose etc. The only problem is I always get null when trying to get the ETag (which does existing in the response header).
Here is the simplified code:
var request = (HttpWebRequest)WebRequest.Create(validUri);
SetHeaders(); // helper function to set basic headers.
var response = request.GetResponse();
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
var result = reader.ReadToEnd();
var etag = response.Headers.Get("ETag");
Anyone know why I can't seem to extract the existing ETag?
Your code does not reproduce the problem you are describing. Your problem is in something that you have not mentioned. Here is a short complete program based on your code, that executes and does print out the value of ETag without a problem:
using System;
using System.IO;
using System.Net;
namespace SO9628006
{
class Program
{
static void Main()
{
var request = (HttpWebRequest)WebRequest.Create("http://www.fiddler2.com/Fiddler/Fiddler.css");
var response = request.GetResponse();
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
var result = reader.ReadToEnd();
var etag = response.Headers.Get("ETag");
Console.WriteLine(etag);
}
}
}
Output:
"6c3673ba919ec71:243"
Could you please provide short but complete program that illustrates your issue?

Categories

Resources