In SendEmail MSGRAPH API InternalServerError,Object reference not set to an instance of an object - asp.net-core

Tried to use Microsoft Graph Email API, BUT getting following error.
ODATA Payload
"message": {
"subject": "Send email",
"body": {
"contentType": "text",
"content": "wuirbmndf"
},
"toRecipients": [
{
"emailAddress": {
"address": "emailid"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
],
"from": {
"emailAddress": {
"address": "sender email id"
}
}
}
My Code Looks Like ->
client.BaseUrl = new Uri(String.Format("https://graph.microsoft.com/v1.0/me/sendmail"));
RestRequest request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("Authorization", string.Format("Bearer " + emailObj.AccessToken), ParameterType.HttpHeader);
request.AddParameter("application/json", json, ParameterType.RequestBody);
//request.AddHeader("ContentType", "application/json");
//request.JsonSerializer.ContentType = "string";
var result = client.Execute(request);
And I am Getting InternalServerError with error Object reference not set to an instance of an object.
{
"error": {
"code": "InternalServerError",
"message": "Object reference not set to an instance of an object.",
"innerError": {
"request-id": "22ec4d88-2140-497f-bf28-80c83d7aa6a9",
"date": "2020-05-27T04:24:14"
}
}
}
thanks in advance.

Related

Unable to Post values via RestAssured

Am newbee. Developing code using Restassured
Below is my code
JSONObject request = new JSONObject(); // created an object
request.put("Name", "this is a");
request.put("ID", "012");
given().
header("Content-Type","application/json").
body(request.toJSONString()).
when().
post("http://localhost:3000/Shop").
then().
statusCode(201).
log().ifError();
My JSON File:
{
"Shop":[
{
"ID": "001",
"Name": "ABC"
},
{
"ID": "002",
"Name": "XYZ"
}
]
}
Am getting exception message as
Expected status code <201> but was <500>.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
Can any one let me know what is wrong in my code?
As far as I understand, your created json is
{
"ID": "012",
"Name": "this is a"
}
but it requires
{
"Shop":[
{
"ID": "001",
"Name": "ABC"
},
{
"ID": "002",
"Name": "XYZ"
}
]
}
So you need to change the object of post body. My quick fix for this case is
Map<String, Object> item = new HashMap<>();
item.put("Name", "this is a");
item.put("ID", "012");
JSONObject shop = new JSONObject();
shop.put("shop", Collections.singleton(item));
given().log().all()
.contentType(ContentType.JSON)
.body(shop.toJSONString()).
.when()
.post("your-url")
.then()
.statusCode(201)
.log().ifError();

How generate swagger json with additionalProperties false for object?

I have the following object with swagger description:
/**
* Response about request failure
*/
#Schema(description = "Response about request failure")
data class ErrorDtoRs(
#field:Schema(description = "Error type", maxLength = 64)
val type: String? = null,
#field:Schema(description = "Error message", maxLength = 255)
val message: String?)
Swagger json for this object:
"components": {
"schemas": {
"ErrorDtoRs": {
"type": "object",
"properties": {
"type": {
"maxLength": 64,
"type": "string",
"description": "Error type"
},
"message": {
"maxLength": 255,
"type": "string",
"description": "Error message"
}
},
"description": "Response about request failure"
},
How generate swagger json with additionalProperties false for object, like this:
"components": {
"schemas": {
"ErrorDtoRs": {
"type": "object",
"additionalProperties": "false",
"properties": {
"type": {
"maxLength": 64,
"type": "string",
"description": "Error type"
},
"message": {
"maxLength": 255,
"type": "string",
"description": "Error message"
}
},
"description": "Response about request failure"
},
Swagger: 2.1.4
OpenApi: 3.0.1
If you are using sprindoc-openapi you can use GroupedOpenApi to add a OpenApiCustomier and set additional properties to FALSE like this:
#Bean
public OpenApiCustomiser openApiCustomiser() {
return openApi ->
openApi
.getComponents()
.getSchemas()
.values()
.forEach(schema -> schema.setAdditionalProperties(false));
}
#Bean
public GroupedOpenApi coreOpenApi() {
return GroupedOpenApi.builder()
.group("NAME")
.pathsToMatch("/**")
.addOpenApiCustomiser(this.openApiCustomiser())
.build();
}
This will also prevent the Security Issue ID:v3-schema-request-object-additionalproperties-true

INVALID_ARGUMENT error with Google Analytics Reporting API

I'm trying to do a request to the userActivity.search method,
this is the payload that I'm trying to do:
{
"viewId": "<VIEW ID>",
"dateRange": {
"startDate": "7daysAgo",
"endDate": "today"
},
"user": {
"type": "CLIENT_ID",
"userId": "<USER ID>"
}
}
But I'm stuck getting this error:
{
"error": {
"code": 400,
"message": "CLIENT_ID: <ID> not found.",
"status": "INVALID_ARGUMENT"
}
}
The ClientId I get previously at other GA endpoint that list the ClientIds that I need to get more details.
What am I doing wrong?

RestSharp How to display json on page

I have a call to a service that returns some json.
{
"channels": {
"22802056": {
"id": "22802056",
"title": "TV Live 1",
"url": "http://www.ustream.tv/channel/XBccccHefj",
"tiny_url": "http://ustre.am/1xss6",
"broadcast_urls": [
"rtmp://sjc-uhs-omega06.ustream.tv/ustreamVideo/22802ccc",
"rtmp://sjc-uhs-omega13.ustream.tv/ustreamVideo/22802ccc",
"rtmp://sjc-uhs-omega15.ustream.tv/ustreamVideo/22802ccc"
],
"status": "offline",
"description": "",
"owner": {
"id": "37134940",
"username": "xxxx_align",
"picture": "https://ustvstaticcdn1-a.akamaihd.net/images/defaults/user_48x48:3.png"
},
"authority": {
"reason": "own"
},
"default": true
},
"22802058": {
"id": "22802058",
"title": "TV Live 2",
"url": "http://www.ustream.tv/channel/DjAccczbPJ",
"tiny_url": "http://ustre.am/1ssR8",
"broadcast_urls": [
"rtmp://sjc-uhs-omega06.ustream.tv/ustreamVideo/228020ccc",
"rtmp://sjc-uhs-omega13.ustream.tv/ustreamVideo/228020ccc",
"rtmp://sjc-uhs-omega15.ustream.tv/ustreamVideo/228020ccc"
],
"status": "offline",
"description": "",
"owner": {
"id": "37134940",
"username": "xxxx_align",
"picture": "https://ustvstaticcdn1-a.akamaihd.net/images/defaults/user_48x48:3.png"
},
"authority": {
"reason": "own"
}
}
},
"paging": {
"actual": {
"href": "https://api.ustream.tv/users/self/channels.json?p=1"
}
}
}
This gets me the JSON:
IRestResponse jsonResponse = client.Execute(request);
In the example above there are only two channels displayed. In reality there are dozens of channels. How can I use this object and display all the channels and future channels on a page? If I paste this as a class in Visual Studio it creates a seperate class for each channel?
Any help is appreciated!
I had to use NewtonSoft json.net to get this to work for me.
string jsonResult = LoadJson();
dynamic objStreams = JObject.Parse(jsonResult);
var channelsData = ((JObject)objStreams.channels).Children();
foreach(JToken channelToken in channelsData)
{
var channeldeatils = channelToken.Children();
foreach (JToken properties in channeldeatils)
{
lstBox.Items.Add("ID : " + properties["id"].ToString());
lstBox.Items.Add("Title : " + properties["title"].ToString());
lstBox.Items.Add("URL : " + properties["url"].ToString());
lstBox.Items.Add("--------------------------------------------");
}
}

Unable to use IdentityManager API from Postman

I am using postman and I am trying to get the users list from identity Manager. But I am unable to configure the app correctly. I try to get the users from https://localhost/idm/api/users
I get the token with the API+idmgr+openid scopes and I have the Administrator role in my claims.
Here is the startup file:
namespace WebHost
{
internal class Startup
{
public void Configuration(IAppBuilder app)
{
LogProvider.SetCurrentLogProvider(new NLogLogProvider());
string connectionString = ConfigurationManager.AppSettings["MembershipRebootConnection"];
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
Authority = "https://localhost/ids",
ClientId = "postman",
RedirectUri = "https://localhost",
ResponseType = "id_token",
UseTokenLifetime = false,
Scope = "openid idmgr",
SignInAsAuthenticationType = "Jwt",
Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
return Task.FromResult(0);
}
}
});
X509Certificate2 cert = Certificate.Get();
app.Map("/idm", adminApp =>
{
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new string[] { "https://localhost/ids" + "/resources" },
AuthenticationType = "Jwt",
IssuerSecurityTokenProviders = new[] {
new X509CertificateSecurityTokenProvider("https://localhost/ids", cert)
},
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
});
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
var securityConfig = new ExternalBearerTokenConfiguration
{
Audience = "https://localhost/ids" + "/resources",
BearerAuthenticationType = "Jwt",
Issuer = "https://localhost/ids",
SigningCert = cert,
Scope = "openid idmgr",
RequireSsl = true,
};
adminApp.UseIdentityManager(new IdentityManagerOptions()
{
Factory = factory,
SecurityConfiguration = securityConfig
});
});
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = "Login",
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true
};
core.UseIdentityServer(options);
});
}
}
}
What Am I missing?
For those who may want to know how I did it, well I made a lot of search about Owin stuff and how Identity Server works and find out my problem was not that far.
I removed the JwtSecurityTokenHandler.InboundClaimTypeMap
I removed the UseOpenId stuff (don't remove it if you are using an openId external login provider (if you are using google, facebook or twitter, there is classes for that, just install the nuget, it's pretty straight forward)
This section let you configure the bearer token which is the default type token i used in my app(I decided to use password authentication to simplify Postman request to do automatic testing but I still user Code authentication in my apps)
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["AuthorityUrl"],
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { ConfigurationManager.AppSettings["ApiScope"] }
});
I have disabled the IdentityManagerUi interface as I was planning to use the API
app.Map(ConfigurationManager.AppSettings["IdentityManagerSuffix"].ToString(), idmm =>
{
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
idmm.UseIdentityManager(new IdentityManagerOptions()
{
DisableUserInterface = true,
Factory = factory,
SecurityConfiguration = new HostSecurityConfiguration()
{
HostAuthenticationType = Constants.BearerAuthenticationType
}
});
});
And I configure the Identity Server like this:
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = ConfigurationManager.AppSettings["SiteName"],
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true,
};
core.UseIdentityServer(options);
});
In IdentityServerServiceFactory I call this chunk of code:
var clientStore = new InMemoryClientStore(Clients.Get());
And the code for the Client should be something like:
public static Client Get()
{
return new Client
{
ClientName = "PostMan Application",
ClientId = "postman",
ClientSecrets = new List<Secret> {
new Secret("ClientSecret".Sha256())
},
Claims = new List<Claim>
{
new Claim("name", "Identity Manager API"),
new Claim("role", IdentityManager.Constants.AdminRoleName),
},
**Flow = Flows.ResourceOwner**, //Password authentication
PrefixClientClaims = false,
AccessTokenType = AccessTokenType.Jwt,
ClientUri = "https://www.getpostman.com/",
RedirectUris = new List<string>
{
"https://www.getpostman.com/oauth2/callback",
//aproulx - 2015-11-24 -ADDED This line, url has changed on the postman side
"https://app.getpostman.com/oauth2/callback"
},
//IdentityProviderRestrictions = new List<string>(){Constants.PrimaryAuthenticationType},
AllowedScopes = new List<string>()
{
"postman",
"IdentityManager",
ConfigurationManager.AppSettings["ApiScope"],
Constants.StandardScopes.OpenId,
IdentityManager.Constants.IdMgrScope,
}
};
}
On the postman side just do:
POST /ids/connect/token HTTP/1.1
Host: local-login.net
Cache-Control: no-cache
Postman-Token: 33e98423-701f-c615-8b7a-66814968ba1a
Content-Type: application/x-www-form-urlencoded
client_id=postman&client_secret=SecretPassword&grant_type=password&scope=APISTUFF&username=apiViewer&password=ICanUseTheApi
Hope that it will help somebody
Shaer,
I saw your comment and because of that I've created a project (make sure you clone the postmanexample branch) where you can see a working example related to Alegrowin's post. The idea is use postman to access the IdentityManager Api.
Steps
Open postman and choose the POST verb
Put this as url: https://localhost:44337/ids/connect/token
In header put key = Content-Type and value = application/x-www-form-urlencoded
In the body, choose raw and paste this client_id=postman&client_secret=ClientSecret&grant_type=password&scope=idmgr&username=admin&password=admin
Hit send
After this you are going to receive something like this
{"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg",
"expires_in": 3600,
"token_type": "Bearer"}
Copy the access token and create a GET request
Put this as url: https://localhost:44337/idm/api/users?count=10&start=0
Into the headers put key = Authorization and value = Bearer [paste the token]
Example
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg
Hit send
You should receive something like this
{
"data": {
"items": [
{
"data": {
"subject": "081d965f-1f84-4360-90e4-8f6deac7b9bc",
"username": "alice",
"name": "Alice Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc",
"delete": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc"
}
},
{
"data": {
"subject": "5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"username": "bob",
"name": "Bob Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"delete": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306"
}
},
{
"data": {
"subject": "e3c7fd2b-3942-456f-8871-62e64c351e8c",
"username": "xoetuvm",
"name": "Uylocms Xcyfhpc"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c",
"delete": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c"
}
},
{
"data": {
"subject": "0777d8de-91be-41e2-82ae-01c4576c7aca",
"username": "xdbktbb",
"name": "Qbcqwrg Mypxduu"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca",
"delete": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca"
}
},
{
"data": {
"subject": "10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"username": "acrkkzf",
"name": "Qcmwcha Kdibtke"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"delete": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9"
}
},
{
"data": {
"subject": "5e16f086-a487-4429-b2a6-b05a739e1e71",
"username": "wjxfulk",
"name": "Eihevix Bjzjbwz"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71",
"delete": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71"
}
},
{
"data": {
"subject": "256e23de-410a-461d-92cc-55684de8be6f",
"username": "zputkfb",
"name": "Vhwjjpd Stfpoum"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f",
"delete": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f"
}
},
{
"data": {
"subject": "725cc088-96c3-490d-bc66-a376c8ca34ff",
"username": "teshydj",
"name": "Tirsnex Tdlkfii"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff",
"delete": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff"
}
},
{
"data": {
"subject": "ac773092-e3db-4711-9c95-a2a57c1ff25f",
"username": "blulsuj",
"name": "Puuncng Lbmlcsb"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f",
"delete": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f"
}
},
{
"data": {
"subject": "81f878b1-016e-4fea-9929-54e3b1d55cce",
"username": "yeqwlfy",
"name": "Qtfimdr Sxvgizd"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce",
"delete": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce"
}
}
],
"start": 0,
"count": 10,
"total": 18806,
"filter": null
},
"links": {
"create": {
"href": "https://localhost:44337/idm/api/users",
"meta": [
{
"type": "username",
"name": "Username",
"dataType": 0,
"required": true
},
{
"type": "password",
"name": "Password",
"dataType": 1,
"required": true
},
{
"type": "name",
"name": "Name",
"dataType": 0,
"required": true
},
{
"type": "Age",
"name": "Age",
"dataType": 4,
"required": true
},
{
"type": "IsNice",
"name": "IsNice",
"dataType": 5,
"required": true
},
{
"type": "role.admin",
"name": "Is Administrator",
"dataType": 5,
"required": true
}
]
}
}
}
Kind regards
Daniel