Why is this cost explorer code throwing this json error? - aws-sdk-net

I'm trying to run the following code:
var awsCredentials = new BasicAWSCredentials("SomeSecret","SomeKey");
var client = new AmazonCostExplorerClient(awsCredentials, Amazon.RegionEndpoint.USEast1);
var requestObject = new GetCostAndUsageWithResourcesRequest();
requestObject.Granularity = "DAILY";
var range = new DateInterval();
range.Start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
range.End = DateTime.Now.ToString("yyyy-MM-dd");
requestObject.TimePeriod = range;
GetCostAndUsageWithResourcesResponse costs = await client.GetCostAndUsageWithResourcesAsync(requestObject);
The routine seems to run then I get the error:
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
I'm not sure what I'm missing here to get the proper result.
Any thoughts are appreciated!
EDIT:
I got this working in case anyone needs it.
The issue was that I wasn't being smart with my code setup
The code above was being called in an async method and was incorrectly calling it in the consumer method.
Example:
Incorrect usage in consumer was:
public async Task<IActionResult> GetAwsCost()
{
var coster = new CostExplorerDash(_connectionInfo);
var res = coster.GetMonthlyCost();
return Ok(res);
}
Proper usage is:
public async Task<IActionResult> GetAwsCost()
{
var coster = new CostExplorerDash(_connectionInfo);
var res = coster.GetMonthlyCost(); //async method call
return Ok(res.Result);
}
The issue (I think) was just that I was trying to use an unfinished async task which caused a mess when .NET tried to do serialzation of the objects involved.

Related

Power BI REST API ExportToFileInGroup Not Working

I am able to programmatically log in to the PowerBI Client, gather my Workspaces as well as get a specific Report from a specific Workspace. I need to programmatically render that report to a .pdf or .xlsx file. Allegedly this is possible with the ExportToFileInGroup/ExportToFileInGroupAsync methods. I even created a very simple report without any parameters. I can embed this using the sample app from here. So that at least tells me that I have what I need setup in the backend. But it fails when I try to run the ExportToFileInGroupAsync method (errors below code.)
My Code is:
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {
PowerBiScopes.ReadReport,
PowerBiScopes.ReadDataset,
});
var userInfo = await graphServiceClient.Me.Request().GetAsync();
var userName = userInfo.Mail;
AuthDetails authDetails = new AuthDetails {
UserName = userName,
AccessToken = accessToken,
};
var credentials = new TokenCredentials($"{accessToken}", "Bearer");
PowerBIClient powerBIClient = new PowerBIClient(credentials);
var groups = await powerBIClient.Groups.GetGroupsAsync();
var theGroup = groups.Value
.Where(x => x.Name == "SWIFT Application Development")
.FirstOrDefault();
var groupReports = await powerBIClient.Reports.GetReportsAsync(theGroup.Id);
var theReport = groupReports.Value
.Where(x => x.Name == "No Param Test")
.FirstOrDefault();
var exportRequest = new ExportReportRequest {
Format = FileFormat.PDF,
};
string result = "";
try {
var response = await powerBIClient.Reports.ExportToFileInGroupAsync(theGroup.Id, theReport.Id, exportRequest);
result = response.ReportId.ToString();
} catch (Exception e) {
result = e.Message;
}
return result;
It gets to the line in the try block and then throws the following errors:
An error occurred while sending the request.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
UPDATE
Relating to #AndreyNikolov question, here is our Embedded capacity:
After this was implemented, no change. Same exact error.
Turns out the issue was on our side, more specifically, security/firewall settings. Here is the exact quote from our networking guru.
"After some more investigation we determined that our firewall was causing this issue when it was terminating the SSL connection. We were able to add a bypass for the URL and it is now working as expected."

Programatically Invoking LUIS Outside the Message Controler

I'm writting a bot application that uses a Prompt Dialog to interact with users.
The idea here is when a user selects a certain option a message should be sent to LUIS that will be processing the request via ML.
Thought about two ways to get it done.
1 - Invoke LUIS directly
2 - Simulate a user entry to make sure the message would pass by the Message Controller and finally the Root Dialog which will be making a LUIS call
Makes sense?
I've tried something like this but it didn't work.
public virtual async Task ChoiceReceivedAsync_MainMenuOption(IDialogContext context, IAwaitable<MainMenuOption> activity)
{
...
IMessageActivity message = Activity.CreateMessageActivity();
message.Text = "Como e a seguranca da escola?";
message.TextFormat = "plain";
message.Locale = "en-Us";
var luisAttributes = new LuisModelAttribute(BellaMain.GlobalVariable.LuisModelID, BellaMain.GlobalVariable.LuisSubscriptionKey);
var luisService = new LuisService(luisAttributes);
await Conversation.SendAsync(message, () => new Dialogs.RootDialog(luisService));
}
Any ideas?
Thanks
Trying to call LUIS by mocking up a new Activity to send to the bot is not recommended.
Instead you should call LUIS through a simple request using an HttpClient.
Here is a sample from the LUIS Endpoint API:
Copy-pasted example:
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["timezoneOffset"] = "{number}";
queryString["verbose"] = "{boolean}";
queryString["spellCheck"] = "{boolean}";
queryString["staging"] = "{boolean}";
queryString["bing-spell-check-subscription-key"] = "{string}";
queryString["log"] = "{boolean}";
var uri = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/{appId}?q={q}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}

ASP.NET Core, where is FindByID?

I have an ASP.NET Core 2.0 application and I'm trying to attach a user to a model:
var user = _userManager.FindByIdAsync(Model.Author);
var promotion = new Promotion()
{
Title = Model.Title,
User = user //error here,
Created = DateTime.Now
};
The problem with this code is that I can't assign user to promotion.User as user is the result of an async operation. I'd prefer not to use FindByIdAsync but for some reason I can't find FindById.
UserManager contains only async API and FindByIdAsync actually returns Task<User> instead of User. So you need to make your code async also and use FindByIdAsync like this:
var user = await _userManager.FindByIdAsync(Model.Author); // will return the User
Only if it is not possible leave your code synchronous, e.g. by calling Result property of the Task which will cause your thread to block until the result is available
var user = _userManager.FindByIdAsync(Model.Author).Result;

How do you get a syncfusion custom adapter to work with the feathers socket.io client

feathers-client 2.3.0
syncfusion-javascript 15.3.29
I have been trying for awhile to create a syncfusion custom adapter for the feathers socket.io version of it's client. I know I can use rest to get data but in order for me to do offline sync I need to use the feathers-offline-realtime plugin.
Also I am using this in an aurelia project so I am using es6 imports with babel.
Here is a code snippet I have tried, I can post the whole thing if needed.
I am also not sure if just using the Adapter vs UrlAdapter is correct as I need sorting and paging to hit the server and not just to do it locally. I think I can figure that part out if I can at least get some data back.
Note: Per Prince Oliver I am adding a clarification to the question I need to be able to call any methods of the adapter as well besides just proccessQuery such as onSort. When the datagrid calls the onSort method I need to be able to call my api using the feathers socket.io client since it handles socket.io in a special manner for offline capabilities.
import io from 'socket.io-client';
import * as feathers from 'feathers-client';
const baseUrl = 'http://localhost:3030';
const socket = io.connect(baseUrl);
const client = feathers.default()
.configure(feathers.hooks())
.configure(feathers.socketio(socket));
const customers = client.service('customers');
export class FeathersAdapter {
feathersAdapter = new ej.Adaptor().extend({
processQuery: function (ds, query) {
let results
makeMeLookSync(function* () {
results = yield customers.find();
console.log(results);
});
The result is undefined. I have tried several other ways but this one seems like it should work.
REVISED CODE:
I am now getting data but also strange error as noted in the picture when I call
let results = await customers.find();
The process then continues and I get data but when the result variable is returned there is still no data in the grid.
async processQuery(ds, query) {
let baseUrl = 'http://localhost:3030';
let socket = io.connect(baseUrl);
let client = feathers.default()
.configure(feathers.hooks())
.configure(feathers.socketio(socket));
let customers = client.service('customers');
let results = await customers.find();
var result = results, count = result.length, cntFlg = true, ret, key, agg = {};
for (var i = 0; i < query.queries.length; i++) {
key = query.queries[i];
ret = this[key.fn].call(this, result, key.e, query);
if (key.fn == "onAggregates")
agg[key.e.field + " - " + key.e.type] = ret;
else
result = ret !== undefined ? ret : result;
if (key.fn === "onPage" || key.fn === "onSkip" || key.fn === "onTake" || key.fn === "onRange") cntFlg = false;
if (cntFlg) count = result.length;
}
return result;
The processQuery method in the DataManager is used to process the parameter which are set in the ej.Query like skip, take, page before fetching the data. Then the data is fetched asynchronously based on these parameters and fetched data is processed in processResponse method to perform operations like filtering or modifying. The processQuery function operates synchronously and it does not wait for the asynchronous process to complete. Hence the returned data from the API did not get bound on the Grid and throws undefined error.
So, if you are using the socket.io to fetch the data from the API, then the data can be directly bound to the Grid control using the dataSource property. Once the dataSource is updated with the result, it will be reflected in Grid automatically through two-way binding.
[HTML]
<template>
<div>
<ej-grid e-data-source.bind="gridData" e-columns.bind="cols"> </ej-grid>
</div>
</template>
[JS]
let baseUrl = 'http://localhost:3030';
let socket = io.connect(baseUrl);
let client = feathers.default()
.configure(feathers.hooks())
.configure(feathers.socketio(socket));
let customers = client.service('customers');
let results = await customers.find();
this.gridData = results; // bind the data to Grid

Creating Asp.net Identity user in Seed method of Db Initializer

I have created my data layer with EF 6 code first and I am populating the db through Seed method of EvInitializer class inheriting from DropCreateDatabaseIfModelChanges. The implementation of Seed method is
protected override void Seed(EvContext context)
{
//Add other entities using context methods
ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser { Email = "admin#myemail.com" ,UserName = "admin#myemail.com"};
var result = await manager.CreateAsync(user, "Temp_123");//this line gives error. obviously await cannot be used in non- async method and I cannot make Seed async
}
My question is how I can add a user in Seed method using UserManager class. when I change
var result = awit manager.CreateAsync(user, "Temp_123");
to
var result = manager.CreateAsync(user, "Temp_123").Result; //or .Wait
the application hangs indefinitely
In asp.net-identity-2 usermanager has non async methods to create.
var user = new ApplicationUser { Email = "admin#myemail.com", UserName = "admin#myemail.com" };
manager.Create(user, "Temp_123");
Same for rolemanager if you want to create "admin" role.
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
roleManager.Create(new Role("admin"));
make the user admin
manager.AddToRole(user.Id, "admin");
Edit: As trailmax commented, Create() extension method comes in with Microsoft.AspNet.Identity namespace so do not forget using Microsoft.AspNet.Identity
TMG is correct - there are non-async methods available, and that's the easiest way in this particular case.
In general, however - when you you only have an async version of a function available to you, and you can't change the implementation of the method to be Async - you can create a task and wait for it synchronously.
So - instead of:
IdentityResult result = await manager.CreateAsync(user, "Temp_123");
You can code:
Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");
createTask.Wait();
Once the Wait has finished, the IdentityResult gets returned in
createTask.Result
You can also set a timeout on the Wait, like this:
Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");
if (!createTask.Wait(5000)) // Wait up to 5 seconds
{
// We've timed out waiting - Do some error handling
}
else if (!createTask.Result.Succeeded)
{
// Creating the user failed - Do some error handling
}