I have a method collecting user data from MS Teams, while this code works as intended, with this method added it makes a previously working method crash.
public async void GetUsers()
{
string teamId = "TeamsID";
string tenantId = "TenantID";
var connector = new ConnectorClient(new Uri(Instance.Activity.ServiceUrl));
members = await connector.Conversations.GetTeamsConversationMembersAsync(teamId, tenantId);
Instance.EmailList.Clear();
foreach (var member in members)
{
Instance.EmailList.Add(member.Email);
}
}
I believe that the Line:
members = await connector.Conversations.GetTeamsConversationMembersAsync(teamId, tenantId);
While receiving the user information, makes the bot think that a user is inputing, causing my later methods to trigger without user input, and crashing because there is no input or because the input if the chunk of data that is the user data.
This is just my theory and I may be incorrect.
The following is the method that crashes:
async Task ReplyToQuestions(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var AnswerHolder = await argument;
Answers.Add(AnswerHolder.Text);
Answers[AnswerCounter] = Answers[AnswerCounter].First().ToString().ToUpper() + Answers[AnswerCounter].Substring(1);
var isQuit = AnswerHolder.Text;
var isQuit2 = Regex.Match(isQuit, #"\b(Quit|quit|QUIT)\b").Value;
Regex rgx = new Regex(#"\b(Quit|quit|QUIT)\b");
if (rgx.IsMatch(isQuit2)) // checks for the user trying to quit/restart bot
{
await context.PostAsync(string.Format("Exiting current process. Restarting."));
context.Done(isQuit); // returns to the start of dialog (StartAsync)
}
else
{
if (QuestionCounter < 5)
{
await context.PostAsync(string.Format($"Question {QuestionCounter + 1}: {Question[QuestionCounter]}"));
}
AnswerCounter += 1;
QuestionCounter += 1;
if (AnswerCounter < 5)
{
context.Wait(ReplyToQuestions);
}
else if (AnswerCounter == 5)
{
PostToChannel($"{Name}'s answers to the questions are as follows: \n\nQuestion1 Answer: {Answers[0]} \n\nQuestion2 Answer: {Answers[1]} \n\n" +
$"Question3 Answer: {Answers[2]} \n\nQuestion4 Answer: {Answers[3]} \n\nQuestion5 Answer: {Answers[4]} \n\n", context);
await context.PostAsync(string.Format("Your answers have been posted to the 'What's Up' channel."));
AnswerCounter = 0;
QuestionCounter = 1;
context.Done(Answers[4]);
}
else
{
await context.PostAsync($"{AnswerCounter}");
await context.PostAsync(string.Format("Oh no! it appears something has gone wrong. please try re-entering your answers"));
AnswerCounter = 0;
QuestionCounter = 1;
context.Wait(ReplyToQuestions);
}
}
}
And the code that calls it:
async Task Choice(IDialogContext context, IAwaitable<IMessageActivity> argument) // this method recives and validates a question
{
var Choice = await argument;
var isQuit = Choice.Text;
var isQuit2 = Regex.Match(isQuit, #"\b(Quit|quit|QUIT)\b").Value;
Regex rgx = new Regex(#"\b(Quit|quit|QUIT)\b");
var isEnter = Regex.Match(isQuit, #"\b(Enter|ENTER|enter)\b").Value;
Regex rgx2 = new Regex(#"\b(Enter|ENTER|enter)\b");
var isReply = Regex.Match(isQuit, #"\b(Reply|REPLY|reply)\b").Value;
Regex rgx3 = new Regex(#"\b(Reply|REPLY|reply)\b");
GetUsers();
if (rgx.IsMatch(isQuit2)) // if the user choses to quit
{
await context.PostAsync(string.Format("Exiting current process. Restarting."));
context.Done(isQuit); // restarts the program, calls the first method
}
else if (rgx2.IsMatch(isEnter)) // if the user choses to quit
{
await context.PostAsync(string.Format("Please enter your custom question."));
context.Wait(EnterQuestion);
}
else if (rgx3.IsMatch(isReply)) // if the user choses to quit
{
Answers.Clear();
await context.PostAsync(string.Format("Please answer the following questions:"));
await context.PostAsync(string.Format($"Question 1: {Question[0]}"));
context.Wait(ReplyToQuestions);
}
else
{
await context.PostAsync(string.Format("sorry this was not a choice, try again."));
}
}
Does anyone know a way I can fix this? As I have spent 2 full days on this without success.
I'm not sure what error you are seeing. But, the method being used to retrieve conversation members has been deprecated: https://msdn.microsoft.com/en-us/microsoft-teams/botapis#net-example The note on that page should state:
you should migrate your code to use GetConversationMembersAsync(conversationId)
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
var members = await connector.Conversations.GetConversationMembersAsync(activity.Conversation.Id);
Related
I have a web page that I'm trying to call a web service and I'm having it skip out of the process when called.
Here's what I'm referring to...
When I call this method after the customer enters in their check information:
public CheckInfo SubmitCheck(CheckInfo checkInfo)
{
try
{
var check = new Check();
check.account_number = checkInfo.CheckAccountNumber;
check.transit_number = checkInfo.CheckRoutingNumber;
check.amount = checkInfo.Amount.ToString();
check.check_number = checkInfo.CheckNumber;
check.bill_to_city = checkInfo.City;
check.bill_to_country = "US";
check.bill_to_postal_code = checkInfo.Zip;
check.bill_to_street = checkInfo.Street;
check.bill_to_state = checkInfo.State;
check.name_on_check = checkInfo.NameOnCheck;
check.transaction_type = "sale";
check.account_type = checkInfo.AccountType;
check.check_type = checkInfo.CheckType;
var ent = new SuburbanPortalEntities();
var gatewaySettings = (from x in ent.GatewayUsers
where x.TokenId == CurrentCustomerSession.Current.TokenId &&
x.Gateway.Name == "DirectAch2"
select x).FirstOrDefault();
var credentials = new Authentication();
credentials.password = gatewaySettings.Password;
credentials.username = gatewaySettings.UserName;
var response = Process.SubmitCheck(credentials, check).Result;
The public class that calls the private class:
public static async Task<Response> SubmitCheck(Authentication authentication, Check check)
{
return await Submit(authentication, check, PaymentTypes.Check);
}
The SubmitCheck Method:
private static async Task<Response> Submit(Authentication authentication, Object payment, PaymentTypes paymentType)
{
var resp = new Response();
try
{
var client = new HttpClient();
var bodyjson = JsonConvert.SerializeObject(authentication);
var bodycontent = new StringContent(bodyjson, Encoding.UTF8, "application/json");
var authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
var bodyResponseJson = await authenticationPost.Content.ReadAsStringAsync();
When I get to this line, it just returns out of the method and it doesn't continue on with anything, it's like I never executed this method.
var authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
No other code is executed after this line. It just stops and the web page becomes available again. I have the method wrapped in a try catch but the catch isn't.. catching anything.
I'm at a loss at this poing, any suggestions?
EDIT#1
I wrapped the line in a try catch as suggested.
try
{
authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
It's stepping out of the try/catch and never executing any more code after that. No exception is caught, nothing, it just runs the line and leaves the method.
Here's your problem:
var response = Process.SubmitCheck(credentials, check).Result;
Don't block on async code, as I describe on my blog. This is a common mistake for those new to async/await. Instead of Result, use await:
public async Task<CheckInfo> SubmitCheck(CheckInfo checkInfo)
{
...
var response = await Process.SubmitCheck(credentials, check);
Note that you'd then need to await the call to SubmitCheck, and so on. It's async all the way.
Side note: I recommend using the standard pattern of *Async suffixes on your method names; it makes it clearer in the code that their return values need to be awaited:
public async Task<CheckInfo> SubmitCheckAsync(CheckInfo checkInfo)
{
...
var response = await Process.SubmitCheckAsync(credentials, check);
static void Main(string[] args)
{
token objtoken = new token();
var location = AddLocations();
OutPutResults outPutResultsApi = new OutPutResults();
GCPcall gCPcall = new GCPcall();
OutPutResults finaloutPutResultsApi = new OutPutResults();
var addressdt = new AddressDataDetails();
finaloutPutResultsApi.addressDatas = new List<AddressDataDetails>();
Console.WriteLine("Hello World!");
List<string> placeId = new List<string>();
var baseUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?";
var apiKey = "&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".Trim();
foreach (var itemlocations in location)
{
var searchtext = "query=" + itemlocations.Trim();
var finalUrl = baseUrl + searchtext + apiKey;
gCPcall.RecursiveApiCall(finalUrl, ref placeId, objtoken.NextToken);
}
var ids = gCPcall.myPalceid;
}
public List<string> RecursiveApiCall(string finalUrl, ref List<string> placeId, string nextToken = null)
{
try
{
var token = "&pagetoken=" + nextToken;
using (var client = new HttpClient())
{
var responseTask = client.GetAsync(finalUrl + token);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
var students = readTask.Result;
Rootobject studentsmodel = JsonConvert.DeserializeObject<Rootobject>(students);
nextToken = studentsmodel.next_page_token;
foreach (var item in studentsmodel.results)
{
placeId.Add(item.place_id);
}
}
}
if (nextToken != null)
{
RecursiveApiCall(finalUrl, ref placeId, nextToken);
}
return placeId;
}
catch (Exception ex)
{
throw;
}
}
My recursive method has some issue. Here whenever I am debugging this code it work fine. It goes in recursive call twice.
As debugging result I am getting list place_id with 20 items in first call and next call 9 items total 29 items in place_id object which is correct in static main method.
But if I run without debugging mode I am getting only 20 place_id. next recursive iteration data is missing even if it has next valid token.
I don't have any clue why this is happening. Can someone tell me what is the issue with my code?
Here are my suggestions, which may or may not solve the problem:
// First of all, let's fix the signature : Go async _all the way_
//public List<string> RecursiveApiCall(string finalUrl, ref List<string> placeId, string nextToken = null)
// also reuse the HttpClient!
public async Task ApiCallAsync(HttpClient client, string finalUrl, List<string> placeId, string nextToken = null)
{
// Loop, don't recurse
while(!(nextToken is null)) // C# 9: while(nextToken is not null)
{
try
{
var token = "&pagetoken=" + nextToken;
// again async all the way
var result = await client.GetAsync(finalUrl+token);
if (result.IsSuccessStatusCode)
{
// async all the way!
var students = await result.Content.ReadAsStringAsync();
Rootobject studentsmodel = JsonConvert.DeserializeObject<Rootobject>(students);
nextToken = studentsmodel.next_page_token;
foreach (var item in studentsmodel.results)
{
// Will be reflected in main, so no need to return or `ref` keyword
placeId.Add(item.place_id);
}
}
// NO recursion needed!
// if (nextToken != null)
// {
// RecursiveApiCall(finalUrl, ref placeId, nextToken);
// }
}
catch (Exception ex)
{
// rethrow, only is somewhat useless
// I'd suggest using a logging framework and
// log.Error(ex, "Some useful message");
throw;
// OR remove try/catch here all together and wrap the call to this method
// in try / catch with logging.
}
}
Mind that you'll need to make your main :
async Task Main(string[] args)
and call this as
await ApiCallAsync(client, finalUrl, placeId, nextToken);
Also create an HttpClient in main and reuse that:
"HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors." - Remarks
... which shouldn't do much harm here, but it's a "best practice" anyhow.
Now, as to why you get only 20 instead of expected 29 items, I cannot say if this resolves that issue. I'd highly recommend to introduce a Logging Framework and make log entries accordingly, so you may find the culprid.
How to run an async Task without blocking other tasks?
I have one function that iterates though a List but the problem is that when the function is called other functions won't work again until the first function is done. What are the ways of making the HandleAsync function non-blocking ?
public static async Task HandleAsync(Message message, TelegramBotClient bot)
{
await Search(message, bot); // This should be handled without working other possible functions. I have a function similar to this but which doesn't iterate though any list.
}
private static async Task Search(Message message, TelegramBotClient bot)
{
var textSplit = message.Text.Split(new[] {' '}, 2);
if (textSplit.Length == 1)
{
await bot.SendTextMessageAsync(message.From.Id, "Failed to fetch sales. Missing game name. ",
ParseMode.Html);
}
else
{
var search = await Program.itad.SearchGameAsync(textSplit[1], limit: 10, cts: Program.Cts);
if (search.Data != null)
{
var builder = new StringBuilder();
foreach (var deal in search.Data.List)
{
var title = deal.Title;
var plain = deal.Plain;
var shop = deal.Shop != null ? deal.Shop.Name : "N/A";
var urls = deal.Urls;
var priceNew = deal.PriceNew;
var priceOld = deal.PriceOld;
var priceCut = deal.PriceCut;
builder.AppendLine($"<b>Title:</b> {title}");
builder.AppendLine($"<b>Shop:</b> {shop}");
builder.AppendLine();
builder.AppendLine($"<b>Price:</b> <strike>{priceOld}€</strike> | {priceNew}€ (-{priceCut}%)");
var buttons = new[]
{
new[]
{
InlineKeyboardButton.WithUrl("Buy", urls.Buy.AbsoluteUri),
InlineKeyboardButton.WithUrl("History",
urls.Game.AbsoluteUri.Replace("info", "history"))
}
};
var keyboard = new InlineKeyboardMarkup(buttons);
var info = await Program.itad.GetInfoAsync(plain, cts: Program.Cts);
var image = info.Data.GameInfo.Image;
if (image == null) image = new Uri("https://i.imgur.com/J7zLBLg.png");
await TelegramBot.Bot.SendPhotoAsync(message.From.Id, new InputOnlineFile(image.AbsoluteUri),
builder.ToString(), ParseMode.Html, replyMarkup: keyboard,
cancellationToken: Program.Cts.Token);
builder.Clear();
}
}
else
{
await bot.SendTextMessageAsync(message.From.Id, "Failed to fetch sales. Game not found. ",
ParseMode.Html);
}
}
I had this piece of code that initially worked fine. However, After adding it to a class where I store my methods that are reused, it keeps failing. The exception that is caught states that the CancellationTokenSource has been Disposed. Can someone point me in the right direction?
I have tried creating a new client and Adding CancellationToken.None to the PutAsync() method from HTTPClient Class but it still fails with the CancellationTokenSource Disposed exception.
public async void AddProduct(Product product)
{
string storeId = "";
try
{
var storeData = JObject.Parse(Connect.Json).SelectToken("store").ToString();
var stores = JsonConvert.DeserializeObject<List<Store>>(storeData);
var store = stores[0];
storeId = store.Id;
store.Products.Add(product);
ProdInfo info = new Info();
foreach(Product p in store.Products)
{
info.AddedProducts = + p.Id;
}
var content = JsonConvert.SerializeObject(info);
using (Connect.Client)
using (var response = await Connect.Client.PutAsync(_url + "/stores/" + storeId, new StringContent(content)))
{
var cont = response.Content;
string result = await cont.ReadAsStringAsync();
if ((int)response.StatusCode == 200)
{
this.JobResult = result;
//this.JobResult = "Store has been successfully updated";
}
else
{
this.JobResult = result;
//this.JobResult = "Store was not updated!";
}
}
}
catch (Exception ex)
{
//this.JobResult = "Store has not been updated due to an error.";
this.JobResult = ex.Message;
}
}
I was able to solve this by simple removing 'using(Connect.Client)' from all of my methods. As #sellotape stated, They were disposing of the HttpClient before I was able to use it again. Thank you all for your contributions.
Is there a proper way for bot to start a conversation with PromptDialog.Choice in the Direct Line channel?
I am trying an ugly hack with catching the fist ConversationUpdate activity and creating a fake message from user to initialize the dialog like this:
IMessageActivity greetingMessage = Activity.CreateMessageActivity();
greetingMessage.From = message.Recipient;//from bot
greetingMessage.Recipient = userAccount;//to user
greetingMessage.Conversation = message.Conversation;
greetingMessage.Text = "Hello, I am a bot";
greetingMessage.Locale = "en-us";
greetingMessage.Id = Guid.NewGuid().ToString();
await connector.Conversations.SendToConversationAsync((Activity)greetingMessage);
IMessageActivity dialogEntryMessage = Activity.CreateMessageActivity();
dialogEntryMessage.Recipient = message.Recipient;//to bot
dialogEntryMessage.From = message.From;//from user
dialogEntryMessage.Conversation = message.Conversation;
dialogEntryMessage.Text = "any text";
dialogEntryMessage.Locale = "en-us";
dialogEntryMessage.ChannelId = message.ChannelId;
dialogEntryMessage.ServiceUrl = message.ServiceUrl;
dialogEntryMessage.Id = Guid.NewGuid().ToString();
dialogEntryMessage.ReplyToId = greetingMessage.Id;
await Conversation.SendAsync(dialogEntryMessage, () => new Dialogs.RootDialog());
Where message is a ConversationUpdate message from. In the RootDialog I start with a PromptDialog.Choice.
It works in the emulator, but in Direct Line channel bot doesn't remember the dialog state and when user choose one of dialog options and send his first real message, root dialog starts again from the PromptDialog.Choice, so it appears twice.
Update
I found a relevant blogpost from Microsoft: https://blog.botframework.com/2018/07/12/how-to-properly-send-a-greeting-message-and-common-issues-from-customers/
in Direct Line channel bot doesn't remember the dialog state and when user choose one of dialog options and send his first real message, root dialog starts again from the PromptDialog.Choice, so it appears twice.
I can reproduce same issue on my side, and I find that ConversationUpdate handler will be executed when both bot and user is added to the conversation.
To solve the issue, you can refer to the following code sample.
In MessagesController:
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
if (update.MembersAdded != null && update.MembersAdded.Any())
{
foreach (var newMember in update.MembersAdded)
{
if (newMember.Name == "{your_botid_here}")
{
IMessageActivity greetingMessage = Activity.CreateMessageActivity();
//...
//your code logic
//...
IMessageActivity dialogEntryMessage = Activity.CreateMessageActivity();
dialogEntryMessage.Recipient = message.Recipient;//to bot
dialogEntryMessage.From = message.From;//from user
dialogEntryMessage.Conversation = message.Conversation;
dialogEntryMessage.Text = "show choices";
dialogEntryMessage.Locale = "en-us";
dialogEntryMessage.ChannelId = message.ChannelId;
dialogEntryMessage.ServiceUrl = message.ServiceUrl;
dialogEntryMessage.Id = System.Guid.NewGuid().ToString();
dialogEntryMessage.ReplyToId = greetingMessage.Id;
await Conversation.SendAsync(dialogEntryMessage, () => new Dialogs.RootDialog());
}
}
}
}
In RootDialog:
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
var mes = activity.Text.ToLower();
string[] choices = new string[] { "choice 1", "choice 2" };
if (Array.IndexOf(choices, mes) > -1)
{
await context.PostAsync($"You selected {mes}");
}
else if(mes == "show choices")
{
PromptDialog.Choice(context, resumeAfterPrompt, choices, "please choose an option.");
}
else
{
await context.PostAsync($"You sent {activity.Text} which was {length} characters.");
context.Wait(MessageReceivedAsync);
}
}
private async Task resumeAfterPrompt(IDialogContext context, IAwaitable<string> result)
{
string choice = await result;
await context.PostAsync($"You selected {choice}");
}
Test result: