I have implemented the Microsoft Example for Embed for your customers from Github, which works perfectly. Link
I am now extending it which there are articles showing using both V1 and V2 of the API, both result in the same error:
Operation returned an invalid status code 'BadRequest'
at
Microsoft.PowerBI.Api.ReportsOperations.GenerateTokenInGroupWithHttpMessagesAsync(Guid
groupId, Guid reportId, GenerateTokenRequest requestParameters,
Dictionary`2 customHeaders, CancellationToken cancellationToken)
[HttpGet]
public async Task<string> GetEmbedInfo()
{
try
{
// Validate whether all the required configurations are provided in appsettings.json
string configValidationResult = ConfigValidatorService.ValidateConfig(azureAd, powerBI);
if (configValidationResult != null)
{
HttpContext.Response.StatusCode = 400;
return configValidationResult;
}
EmbedParams embedParams = await pbiEmbedService.GetEmbedParams(new Guid(powerBI.Value.WorkspaceId), new Guid(powerBI.Value.ReportId));
//EmbedParams embedParams = await pbiEmbedService.GetEmbedToken4(new Guid(powerBI.Value.WorkspaceId), new Guid(powerBI.Value.ReportId));
return JsonSerializer.Serialize<EmbedParams>(embedParams);
}
catch (Exception ex)
{
HttpContext.Response.StatusCode = 500;
return ex.Message + "\n\n" + ex.StackTrace;
}
}
The above code is getting called and per the demo.
public async Task<EmbedParams> GetEmbedParams(Guid workspaceId, Guid reportId, [Optional] Guid additionalDatasetId)
{
PowerBIClient pbiClient = this.GetPowerBIClient();
// Get report info
var pbiReport = await pbiClient.Reports.GetReportInGroupAsync(workspaceId, reportId);
//var generateTokenRequestParameters = new GenerateTokenRequest("View", null, identities: new List<EffectiveIdentity> { new EffectiveIdentity(username: "**************", roles: new List<string> { "****", "****" }, datasets: new List<string> { "datasetId" }) });
//var tokenResponse = pbiClient.Reports.GenerateTokenInGroupAsync("groupId", "reportId", generateTokenRequestParameters);
// Create list of datasets
var datasetIds = new List<Guid>();
// Add dataset associated to the report
datasetIds.Add(Guid.Parse(pbiReport.DatasetId));
// Append additional dataset to the list to achieve dynamic binding later
if (additionalDatasetId != Guid.Empty)
{
datasetIds.Add(additionalDatasetId);
}
// Add report data for embedding
var embedReports = new List<EmbedReport>() {
new EmbedReport
{
ReportId = pbiReport.Id, ReportName = pbiReport.Name, EmbedUrl = pbiReport.EmbedUrl
}
};
// Get Embed token multiple resources
var embedToken = await GetEmbedToken4(workspaceId, reportId);
// Capture embed params
var embedParams = new EmbedParams
{
EmbedReport = embedReports,
Type = "Report",
EmbedToken = embedToken
};
return embedParams;
}
The above code is per the demo apart from one line, which is calling the next method:
var embedToken = await GetEmbedToken4(workspaceId, reportId);
public EmbedToken GetEmbedToken(Guid reportId, IList<Guid> datasetIds, [Optional] Guid targetWorkspaceId)
{
PowerBIClient pbiClient = this.GetPowerBIClient();
// Create a request for getting Embed token
// This method works only with new Power BI V2 workspace experience
var tokenRequest = new GenerateTokenRequestV2(
reports: new List<GenerateTokenRequestV2Report>() { new GenerateTokenRequestV2Report(reportId) },
datasets: datasetIds.Select(datasetId => new GenerateTokenRequestV2Dataset(datasetId.ToString())).ToList(),
targetWorkspaces: targetWorkspaceId != Guid.Empty ? new List<GenerateTokenRequestV2TargetWorkspace>() { new GenerateTokenRequestV2TargetWorkspace(targetWorkspaceId) } : null
);
// Generate Embed token
var embedToken = pbiClient.EmbedToken.GenerateToken(tokenRequest);
return embedToken;
}
The above code is per the example with no roles being passed in or EffectiveIdentity. This works.
public async Task<EmbedToken> GetEmbedToken4(Guid workspaceId, Guid reportId, string accessLevel = "view")
{
PowerBIClient pbiClient = this.GetPowerBIClient();
var pbiReport = pbiClient.Reports.GetReportInGroup(workspaceId, reportId);
string dataSet = pbiReport.DatasetId.ToString();
// Generate token request for RDL Report
var generateTokenRequestParameters = new GenerateTokenRequest(
accessLevel: accessLevel,
datasetId: dataSet,
identities: new List<EffectiveIdentity> { new EffectiveIdentity(username: "******", roles: new List<string> { "********" }) }
);
// Generate Embed token
var embedToken = pbiClient.Reports.GenerateTokenInGroup(workspaceId, reportId, generateTokenRequestParameters);
return embedToken;
}
This is the method to return the token with the roles and effective Identity. This results in the error, but no message or helpful feedback.
OK, after much research overnight the Bad Request response does hide an English message which is not show in the browser. The debugger doesn't have the symbols for the part that causes the error, but I found it by using Fiddler proxy when the actual API responded to the request. In my case, if you send an ID to enable RLS, but the version of the report on the server doesn't have it, this doesn't ignore it, it refuses to give a token to anything. From reading many posts, the Bad Request is just a poor error message when the actual response from the API itself (not the package or the example code that the sample uses with it presents). Hope this helps someone in the future.
Related
Here I have created my project on the standard .NET library to GET/POST invoices. But as I want to email the invoice to which it's being created on that name. Here is my sample code below to create invoice.
public async Task<ActionResult> Create(string Name, string LineDescription, string LineQuantity, string LineUnitAmount, string LineAccountCode)
{
var xeroToken = TokenUtilities.GetStoredToken();
var utcTimeNow = DateTime.UtcNow;
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
XeroConfiguration XeroConfig = new XeroConfiguration
{
ClientId = ConfigurationManager.AppSettings["XeroClientId"],
ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
CallbackUri = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
Scope = ConfigurationManager.AppSettings["XeroScope"],
State = ConfigurationManager.AppSettings["XeroState"]
};
if (utcTimeNow > xeroToken.ExpiresAtUtc)
{
var client = new XeroClient(XeroConfig, httpClientFactory);
xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);
TokenUtilities.StoreToken(xeroToken);
}
string accessToken = xeroToken.AccessToken;
string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();
//string xeroTenantId = xeroToken.Tenants[1].TenantId.ToString();
var contact = new Contact();
contact.Name = Name;
var line = new LineItem()
{
Description = LineDescription,
Quantity = decimal.Parse(LineQuantity),
UnitAmount = decimal.Parse(LineUnitAmount),
AccountCode = LineAccountCode
};
var lines = new List<LineItem>() { line };
//var lines = new List<LineItem>();
//for (int j = 0;j < 5;j++)
//{
// lines.Add(line);
//}
var invoice = new Invoice()
{
Type = Invoice.TypeEnum.ACCREC,
Contact = contact,
Date = DateTime.Today,
DueDate = DateTime.Today.AddDays(30),
LineItems = lines
};
var invoiceList = new List<Invoice>();
invoiceList.Add(invoice);
var invoices = new Invoices();
invoices._Invoices = invoiceList;
var AccountingApi = new AccountingApi();
var response = await AccountingApi.CreateInvoicesAsync(accessToken, xeroTenantId, invoices);
RequestEmpty _request = new RequestEmpty();
//trying this method to send email to specified invoice....
//var test = await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), null);
var updatedUTC = response._Invoices[0].UpdatedDateUTC;
return RedirectToAction("Index", "InvoiceSync");
}
Now as I learned that Xero allows sending email to that specified invoice, here is a link which I learned.
https://developer.xero.com/documentation/api/invoices#email
But as try to find method in the .NET standard library for Xero I stumble upon this method.
var test = await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), null);
How can I use this method to send email to a specified invoice ..?
It throws me an error regarding Cannot assign void to an implicitly-typed variable.
There is another method also in this library.
var test2 = await AccountingApi.EmailInvoiceAsyncWithHttpInfo(accessToken, xeroTenantId, Guid.NewGuid(), null);
As Guid.NewGuid() i have used is for only testing will add created GUID when I understand how these two methods operate.
Update 1:
Here is the method second method i used.
await AccountingApi.EmailInvoiceAsyncWithHttpInfo(accessToken, xeroTenantId, Guid.NewGuid(), null)
Update 2:
Here is the code i used.
public async Task EmailInvoiceTest(string accessToken,string xeroTenantId,Guid invoiceID, RequestEmpty requestEmpty)
{
var AccountingApi = new AccountingApi();
await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, invoiceID, requestEmpty).ConfigureAwait(false);
}
The return type of method EmailInvoiceAsync seems to be Task with return type void. If you await the task, there is no return type which could be assigned to a variable. Remove the variable assignment and pass a valid argument for parameter of type RequestEmpty to solve the problem.
RequestEmpty requestEmpty = new RequestEmpty();
await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), requestEmpty);
For an example test see here
IMPORTANT: According to the documentation (see section Emailing an invoice) the invoice must be of Type ACCREC and must have a valid status for sending (SUMBITTED, AUTHORISED or PAID).
I'm trying to get Facebook leadgen ad data.
1-)As seen below, facebook sends the data to me successfully and I receive it successfully.
Successful Process img
2-)But the submissions I made on just this page do not come. What could be the reason for this?
Failed Process img
*But only the opinions I made on this page are not coming. What could be the reason for this?
Facebook doesn't even post. As seen in the picture, Server failure (102) information is displayed. What is the reason of this?
3-)The code I received the incoming data
Asp.Net Api Method
public async Task<HttpResponseMessage> Post([FromBody] JsonData data)
{
try
{
dbmanager db = new dbmanager();
db.Jsonkaydetv2(data);
var entry = data.Entry.FirstOrDefault();
var change = entry?.Changes.FirstOrDefault();
if (change == null) return new HttpResponseMessage(HttpStatusCode.BadRequest);
//Generate user access token here https://developers.facebook.com/tools/accesstoken/
const string token = "XXXX";
var leadUrl = $"https://graph.facebook.com/v2.10/{change.Value.LeadGenId}?access_token={token}";
var formUrl = $"https://graph.facebook.com/v2.10/{change.Value.FormId}?access_token={token}";
using (var httpClientLead = new HttpClient())
{
var response = await httpClientLead.GetStringAsync(formUrl);
if (!string.IsNullOrEmpty(response))
{
var jsonObjLead = JsonConvert.DeserializeObject<LeadFormData>(response);
db.JsonkaydetLeadFormData(jsonObjLead);
//jsonObjLead.Name contains the lead ad name
//Jsonkaydet(jsonObjLead.Name+"x");
//If response is valid get the field data
using (var httpClientFields = new HttpClient())
{
var responseFields = await httpClientFields.GetStringAsync(leadUrl);
if (!string.IsNullOrEmpty(responseFields))
{
var jsonObjFields =JsonConvert.DeserializeObject<LeadData(responseFields);
db.JsonkaydetLeadData(jsonObjFields);
//jsonObjFields.FieldData contains the field value
}
}
}
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
Jsonkaydet(ex.ToString());
Trace.WriteLine($"Error-->{ex.Message}");
Trace.WriteLine($"StackTrace-->{ex.StackTrace}");
return new HttpResponseMessage(HttpStatusCode.BadGateway);
}
}
Can't find good example of auth flow for link unfurling. I managed to run oauth flow using this example. But after user provided login and password and bot hits OnTeamsAppBasedLinkQueryAsync second time GetUserTokenAsync still returns null. So I don't follow where should I get then token from when auth flow is finished. Should I persist it somehow? Will Teams send me the token on every request or how it should work?
So in my case following code always returns null:
var tokenResponse = await (turnContext.Adapter as IUserTokenProvider)
.GetUserTokenAsync(turnContext, _connectionName, default(string),
cancellationToken: cancellationToken);
It seems the 'state' field is not present on AppBasedLinkQuery. When the auth flow completes, OnTeamsAppBasedLinkQueryAsync will be called again and the turnContext.Activity.Value will contain the url and the 'state' (or magic code). We will get this field added to AppBasedLinkQuery (created an issue here: microsoft/botbuilder-dotnet#3429 ).
A workaround is to retrieve the state/magiccode directly from the Activity.Value Something like:
protected async override Task<MessagingExtensionResponse> OnTeamsAppBasedLinkQueryAsync(ITurnContext<IInvokeActivity> turnContext, AppBasedLinkQuery query, CancellationToken cancellationToken)
{
var magicCode = string.Empty;
var state = (turnContext.Activity.Value as Newtonsoft.Json.Linq.JObject).Value<string>("state");
if (!string.IsNullOrEmpty(state))
{
int parsed = 0;
if (int.TryParse(state, out parsed))
{
magicCode = parsed.ToString();
}
}
var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);
if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
{
// There is no token, so the user has not signed in yet.
// Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
return new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "auth",
SuggestedActions = new MessagingExtensionSuggestedAction
{
Actions = new List<CardAction>
{
new CardAction
{
Type = ActionTypes.OpenUrl,
Value = signInLink,
Title = "Bot Service OAuth",
},
},
},
},
};
}
var heroCard = new ThumbnailCard
{
Title = "Thumbnail Card",
Text = query.Url,
Images = new List<CardImage> { new CardImage("https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png") },
};
var attachments = new MessagingExtensionAttachment(HeroCard.ContentType, null, heroCard);
var result = new MessagingExtensionResult("list", "result", new[] { attachments });
return new MessagingExtensionResponse(result);
}
I have Telerik REST API and at client side i'm using html5 report-viewer. Report are generating successfully in a report viwer in html. Now i want to request for the reports from same API through c# console application. I have search but didn't fine any solution. Please suggest me a way how can i request a report using C# console application.
html5 report-viewer Library
Note: I'm very beginner in telerik reporting.
Update 1:
I have manage to send request to the server using this API documentation.
Telerik Document for Getting Report
on Server side i have written the CustomReportResolver . But now its now sending the InstanceId to the console client.
CustomReportResolver
public class CustomReportResolver : IReportResolver
{
public ReportSource Resolve(string reportJsonString)
{
var reportDto = JsonConvert.DeserializeObject<ReportDTO>(reportJsonString);
var connectionStringHandler = new CustomConnectionStringManager(reportDto.CompanyId);
var reportsPath = HttpContext.Current.Server.MapPath($"~/Reports/{reportDto.ReportPath}");
var sourceReportSource = new UriReportSource { Uri = reportsPath + reportDto.ReportName };
// sourceReportSource.Parameters.Add(new Telerik.Reporting.Parameter("companyId", reportDto.CompanyId));
var reportSource = connectionStringHandler.UpdateReportSource(sourceReportSource);
return reportSource;
}
}
Note if i use default ReportResolver self hosted telerik service sending the pdf report to console successfully but if i use CustomReportResolver it's not generating instanceId.
What could be the problem ?
After wasting a lot of time then found a solution how to get PDF(Or any other report format) documents from Telerik Self hosted Web Service. Following are the general steps to be followed.
Get Client Id
Get Instance Id
Get Document Id
Download Document
Below is a step wise code:
static HttpClient client = new HttpClient();
static string reportServerAddress = "http://localhost:60031/";
static string serverREStAPI = reportServerAddress + "api/";
static void Main(string[] args)
{
try
{
Console.WriteLine("Demo started");
RunAsync().Wait();
Console.WriteLine("Demo ended");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
}
static async Task RunAsync()
{
// readFile();
// return;
client.BaseAddress = new Uri(serverREStAPI);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
/*
* Steps To get PDF documents from Telerik Self hosted Web Service
* Step 1) Get Client Id,
* Step 2) Get Instance Id
* Step 3) Get Document Id
* Step 4) Download Document
*
* */
var clientId = await GetClientIdAsync(serverREStAPI + "reports/clients", "clientId");
var instanceId =
await GetInstanceAsync(serverREStAPI + $"reports/clients/{clientId}/instances", "instanceId");
var documentId =
await GetDocumentAsync(serverREStAPI + $"reports/clients/{clientId}/instances/{instanceId}/documents",
"documentId");
await DownloadPDF(serverREStAPI + $"reports/clients/{clientId}/instances/{instanceId}/documents/{documentId}", true);
}
static async Task<string> GetClientIdAsync(string path, string paramName)
{
HttpResponseMessage response = await client.PostAsJsonAsync(path, "");
response.EnsureSuccessStatusCode();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
return result[paramName];
}
static async Task<string> GetInstanceAsync(string path, string paramName)
{
/*
* For Default resolver in Service
* */
var paramterValues = new {CompanyId = 1};
// var data = new { report = "{ \"ReportName\":\"test.trdx\",\"CompanyId\":\"1\"}", parameterValues = "{\"CompanyId\": \"1\"}" };
var data = new
{
report = "{\"ReportName\":\"test.trdx\",\"CompanyId\":\"1\"}",
parameterValues = paramterValues
};
HttpResponseMessage response = await client.PostAsJsonAsync(path, data);
response.EnsureSuccessStatusCode();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
return result[paramName];
}
static async Task<string> GetDocumentAsync(string path, string paramName)
{
var data = new {format = "PDF"}; //PDF,XLS,MHTML
HttpResponseMessage response = await client.PostAsJsonAsync(path, data);
response.EnsureSuccessStatusCode();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
return result[paramName];
}
static async Task DownloadPDF(string path, bool asAttachment)
{
var queryString = "";
// if (asAttachment)
// {
// queryString += "?content-disposition=attachment";
// }
var filePathAndName = #"D:\testing\tet.html";
// File.Create(filePathAndName);
// string filePath = System.IO.Path.Combine(folderName, fileName);
//System.IO.File.WriteAllText(filePathAndName, result);
using (System.Net.WebClient myWebClient = new System.Net.WebClient())
{
await myWebClient.DownloadFileTaskAsync(new Uri(path + queryString), filePathAndName);
}
System.Diagnostics.Process.Start(filePathAndName);
}
StackOverflow Community!
I have a chatbot, and integrated LUIS.ai to make it smarter. One of the dialogues is about to Book an appointment with a Supervisor (Teacher)
Everything has been working fine, with literally the same code. A couple of hours ago I am experiencing some strange errors.
Exception: Type 'Newtonsoft.Json.Linq.JArray' in Assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' is not marked as serializable.
How to reproduce the error?
If the both Entity (Teacher and Date) is missing from the user's input it works FINE, the bot builds the Form, asking for missing inputs and presents the suggested meeting times.
If one of the Entity is missing it from input it will build a Form and asks for the missing Date or Teacher Entity and presents the suggested meeting times.
BUT
If the user's input contains both Entity: the Teacher and the Date too, then I am getting the error.
Here is my WebApiConfig class:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Json settings
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I am only experiencing this error when I am trying to get an Entity from the user utterance, which is a type of builtin.dateTimeV2.
This async method is called:
//From the LUIS.AI language model the entities
private const string EntityMeetingDate = "MeetingDate";
private const string EntityTeacher = "Teacher";
[LuisIntent("BookSupervision")]
public async Task BookAppointment(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
{
var message = await activity;
await context.PostAsync($"I am analysing your message: '{message.Text}'...");
var meetingsQuery = new MeetingsQuery();
EntityRecommendation teacherEntityRecommendation;
EntityRecommendation dateEntityRecommendation;
if (result.TryFindEntity(EntityTeacher, out teacherEntityRecommendation))
{
teacherEntityRecommendation.Type = "Name";
}
if (result.TryFindEntity(EntityMeetingDate, out dateEntityRecommendation))
{
dateEntityRecommendation.Type = "Date";
}
var meetingsFormDialog = new FormDialog<MeetingsQuery>(meetingsQuery, this.BuildMeetingsForm, FormOptions.PromptInStart, result.Entities);
context.Call(meetingsFormDialog, this.ResumeAfterMeetingsFormDialog);
}
Further methods for building a form:
private IForm<MeetingsQuery> BuildMeetingsForm()
{
OnCompletionAsyncDelegate<MeetingsQuery> processMeetingsSearch = async (context, state) =>
{
var message = "Searching for supervision slots";
if (!string.IsNullOrEmpty(state.Date))
{
message += $" at {state.Date}...";
}
else if (!string.IsNullOrEmpty(state.Name))
{
message += $" with professor {state.Name}...";
}
await context.PostAsync(message);
};
return new FormBuilder<MeetingsQuery>()
.Field(nameof(MeetingsQuery.Date), (state) => string.IsNullOrEmpty(state.Date))
.Field(nameof(MeetingsQuery.Name), (state) => string.IsNullOrEmpty(state.Name))
.OnCompletion(processMeetingsSearch)
.Build();
}
private async Task ResumeAfterMeetingsFormDialog(IDialogContext context, IAwaitable<MeetingsQuery> result)
{
try
{
var searchQuery = await result;
var meetings = await this.GetMeetingsAsync(searchQuery);
await context.PostAsync($"I found {meetings.Count()} available slots:");
var resultMessage = context.MakeMessage();
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Attachment>();
foreach (var meeting in meetings)
{
HeroCard heroCard = new HeroCard()
{
Title = meeting.Teacher,
Subtitle = meeting.Location,
Text = meeting.DateTime,
Images = new List<CardImage>()
{
new CardImage() {Url = meeting.Image}
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "Book Appointment",
Type = ActionTypes.OpenUrl,
Value = $"https://www.bing.com/search?q=easj+roskilde+" + HttpUtility.UrlEncode(meeting.Location)
}
}
};
resultMessage.Attachments.Add(heroCard.ToAttachment());
}
await context.PostAsync(resultMessage);
}
catch (FormCanceledException ex)
{
string reply;
if (ex.InnerException == null)
{
reply = "You have canceled the operation.";
}
else
{
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
}
await context.PostAsync(reply);
}
finally
{
context.Wait(DeconstructionOfDialog);
}
}
private async Task<IEnumerable<Meeting>> GetMeetingsAsync(MeetingsQuery searchQuery)
{
var meetings = new List<Meeting>();
//some random result manually for demo purposes
for (int i = 1; i <= 5; i++)
{
var random = new Random(i);
Meeting meeting = new Meeting()
{
DateTime = $" Available time: {searchQuery.Date} At building {i}",
Teacher = $" Professor {searchQuery.Name}",
Location = $" Elisagårdsvej 3, Room {random.Next(1, 300)}",
Image = $"https://placeholdit.imgix.net/~text?txtsize=35&txt=Supervision+{i}&w=500&h=260"
};
meetings.Add(meeting);
}
return meetings;
}
The strangest thing that this code has worked, and my shoutout and respect goes for the community on GitHub, because I think this is an awesome platform with a tons of documentation and samples.
This is known issue (also reported here and here).
Long story short, since the builtin.datetimeV2.* entities are not yet supported in BotBuilder, the Resolution dictionary of the EntityRecommendation ends up with an entry with a value of type JArray. The problem arises when you pass those entities to a FormDialog. Since the entities are a private field in the dialog and of course, as any other dialog, is being serialized, an exception is being thrown because the JArray class from Newtonsoft is not marked as serializable.
The request for adding support for datetimeV2 entities is here.
The workaround I can think of right now is to extract the value of the DateTime entity manually and assign it your Date field of your MeetingsQuery instance you are passing to the FormDialog and also to remove the DateTime entity from the result.Entities collection that you are passing to the FormDialog.
Update
This is already fixed in the SDK as you can see in this Pull Request.