public static IActivity GetActivity(string ID) { if (String.IsNullOrEmpty(ID)) { throw new ArgumentNullException("ID cant be null"); } IActivity activityResult = null; ActivityFactory activityFactory = ActivityFactory.GetInstance; try { using (DatabaseEntities context = new DatabaseEntities()) { Activity query = (from activity in context.Activity where (activity.ID == ID) select activity).SingleOrDefault(); switch (query.activityName) { case "Go Kart": activityResult = activityFactory.CreateActivity(ActivityTypes.GO_KART, query.ID, query.cost); break; case "Wall Climbing": activityResult = activityFactory.CreateActivity(ActivityTypes.WALL_CLIMBING, query.ID, query.cost); break; case "Meditation and Mindfulness": activityResult = activityFactory.CreateActivity(ActivityTypes.MEDITATION_AND_MINDFULLNESS, query.ID, query.cost); break; case "Team Building and Problem Solving": activityResult = activityFactory.CreateActivity(ActivityTypes.TEAM_BUILDING_AND_PROBLEM_SOLVING, query.ID, query.cost); break; case "Choclate Producing and Marketing": activityResult = activityFactory.CreateActivity(ActivityTypes.CHOCOLATE_PRODUCING_AND_MARKETING, query.ID, query.cost); break; default: throw new Exception("Activity doesn't exist."); } } } catch (Exception exception) { ShowErrorMessage(exception); } return(activityResult); }
public async Task TestReceiptCardTemplate() { var context = await GetTurnContext("NormalStructuredLG.lg"); var languageGenerator = context.TurnState.Get <ILanguageGenerator>(); var data = new JObject { ["receiptItems"] = JToken.FromObject(new List <ReceiptItem> { new ReceiptItem( "Data Transfer", price: "$ 38.45", quantity: "368", image: new CardImage(url: "https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png")), new ReceiptItem( "App Service", price: "$ 45.00", quantity: "720", image: new CardImage(url: "https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png")), }), ["type"] = "ReceiptCard" }; var lgStringResult = await languageGenerator.Generate(context, "@{ReceiptCardTemplate()}", data : data).ConfigureAwait(false); var activity = ActivityFactory.CreateActivity(lgStringResult); AssertReceiptCardActivity(activity); }
private Activity InternalGenerateActivity(string templateName, object data, string locale) { var iLocale = locale == null ? "" : locale; if (TemplateEnginesPerLocale.ContainsKey(iLocale)) { return(ActivityFactory.CreateActivity(TemplateEnginesPerLocale[locale].EvaluateTemplate(templateName, data).ToString())); } var locales = new string[] { string.Empty }; if (!LangFallBackPolicy.TryGetValue(iLocale, out locales)) { if (!LangFallBackPolicy.TryGetValue(string.Empty, out locales)) { throw new Exception($"No supported language found for {iLocale}"); } } foreach (var fallBackLocale in locales) { if (TemplateEnginesPerLocale.ContainsKey(fallBackLocale)) { return(ActivityFactory.CreateActivity(TemplateEnginesPerLocale[fallBackLocale].EvaluateTemplate(templateName, data).ToString())); } } return(new Activity()); }
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(credentialProvider) { // combine path for cross platform support string[] paths = { ".", "Resources", "AdapterWithErrorHandler.lg" }; string fullPath = Path.Combine(paths); _lgEngine = new TemplateEngine().AddFile(fullPath); OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync(ActivityFactory.CreateActivity(_lgEngine.EvaluateTemplate("SomethingWentWrong", exception).ToString())); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { // Actions to include in the welcome card. These are passed to LG and are then included in the generated Welcome card. var actions = new { actions = new List <Object>() { new { title = "Get an overview", url = "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0" }, new { title = "Ask a question", url = "https://stackoverflow.com/questions/tagged/botframework" }, new { title = "Learn how to deploy", url = "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0" } } }; foreach (var member in membersAdded) { // Greet anyone that was not the target (recipient) of this message. // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details. if (member.Id != turnContext.Activity.Recipient.Id) { await turnContext.SendActivityAsync(ActivityFactory.CreateActivity(_lgEngine.EvaluateTemplate("WelcomeCard", actions).ToString())); } } }
public void TestFactoryCreateActivityReturnsInstanceOfRegisteredActivityType() { ActivityFactory factory = ActivityFactory.GetInstance; factory.Register(ActivityTypes.GO_KART, new GoKartActivity()); Assert.IsInstanceOfType(factory.CreateActivity(ActivityTypes.GO_KART, "An ID", 10.0M), typeof(GoKartActivity)); }
public void TestFactoryCreateActivityRaisesArguementException() { ActivityFactory factory = ActivityFactory.GetInstance; PrivateObject privateAccessor = new PrivateObject(factory); privateAccessor.SetField("activityTable", new Hashtable()); factory.CreateActivity(ActivityTypes.GO_KART, "An ID", 10.0M); }
public void TestInlineActivityFactory() { var lgResult = GetTemplateEngine().Evaluate("text").ToString(); var activity = ActivityFactory.CreateActivity(lgResult); Assert.AreEqual(ActivityTypes.Message, activity.Type); Assert.AreEqual("text", activity.Text); Assert.AreEqual("text", activity.Speak); }
public async Task TestNotSupportStructuredType() { var context = await GetTurnContext("NormalStructuredLG.lg"); var languageGenerator = context.TurnState.Get <ILanguageGenerator>(); var lgStringResult = await languageGenerator.Generate(context, "@{notSupport()}", null).ConfigureAwait(false); var result = ActivityFactory.CreateActivity(lgStringResult); }
public void TestAudioCardTemplate() { dynamic data = new JObject(); data.type = "audiocard"; var lgResult = GetTemplateEngine().EvaluateTemplate("AudioCardTemplate", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertAudioCardActivity(activity); }
public void TestEventActivity() { dynamic data = new JObject(); data.text = "textContent"; var lgResult = GetTemplateEngine().EvaluateTemplate("eventActivity", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertEventActivity(activity); }
public void TestExternalAdaptiveCardActivity() { dynamic data = new JObject(); data.adaptiveCardTitle = "test"; var lgResult = GetLGFile().EvaluateTemplate("externalAdaptiveCardActivity", data).ToString(); var activity = ActivityFactory.CreateActivity(lgResult); AssertAdaptiveCardActivity(activity); }
public void TestVideoCardTemplate() { dynamic data = new JObject(); data.type = "videocard"; var lgResult = GetLGFile().EvaluateTemplate("VideoCardTemplate", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertVideoCardActivity(activity); }
public void TestAdaptivecardActivityWithAttachmentStructure() { dynamic data = new JObject(); data.adaptiveCardTitle = "test"; var lgResult = GetLGFile().EvaluateTemplate("adaptivecardActivityWithAttachmentStructure", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertAdaptiveCardActivity(activity); }
public void TestActivityWithMultiStringSuggestionActions() { dynamic data = new JObject(); data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("activityWithMultiStringSuggestionActions", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertActivityWithMultiStringSuggestionActions(activity); }
public void TestHandoffActivity() { dynamic data = new JObject(); data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("handoffActivity", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertHandoffActivity(activity); }
public void TestSuggestedActionsReference() { dynamic data = new JObject(); data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("SuggestedActionsReference", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertSuggestedActionsReferenceActivity(activity); }
/// <summary> /// Create an activity through Language Generation using the thread culture or provided override. /// </summary> /// <param name="templateName">Langauge Generation template.</param> /// <param name="data">Data for Language Generation to use during response generation.</param> /// <param name="localeOverride">Optional override for locale.</param> /// <returns>Activity.</returns> /// <remarks> /// The InputHint property of the returning activity is set to be null if it's acceptingInput so /// when the activity is being used in a prompt it'll be set to expectingInput. /// </remarks> public Activity GenerateActivityForLocale(string templateName, object data = null, string localeOverride = null) { if (templateName == null) { throw new ArgumentNullException(nameof(templateName)); } // By default we use the locale for the current culture, if a locale is provided then we ignore this. var locale = localeOverride ?? CultureInfo.CurrentUICulture.Name; // Do we have a template engine for this locale? if (TemplateEnginesPerLocale.ContainsKey(locale)) { var activity = ActivityFactory.CreateActivity(TemplateEnginesPerLocale[locale].EvaluateTemplate(templateName, data).ToString()); // Set the inputHint to null when it's acceptingInput so prompt can override it when expectingInput if (activity.InputHint == InputHints.AcceptingInput) { activity.InputHint = null; } return(activity); } else { // We don't have a set of matching responses for this locale so we apply fallback policy to find options. languageFallbackPolicy.TryGetValue(locale, out string[] locales); { // If no fallback options were found then we fallback to the default and log. if (!languageFallbackPolicy.TryGetValue(localeDefault, out locales)) { throw new Exception($"No LG responses found for {locale} or when attempting to fallback to '{localeDefault}'"); } } // Work through the fallback hierarchy to find a response foreach (var fallBackLocale in locales) { if (TemplateEnginesPerLocale.ContainsKey(fallBackLocale)) { var activity = ActivityFactory.CreateActivity(TemplateEnginesPerLocale[fallBackLocale].EvaluateTemplate(templateName, data).ToString()); // Set the inputHint to null when it's acceptingInput so prompt can override it when expectingInput if (activity.InputHint == InputHints.AcceptingInput) { activity.InputHint = null; } return(activity); } } } throw new Exception($"No LG responses found for {locale} or when attempting to fallback to '{localeDefault}'"); }
public void TestSigninCardTemplate() { dynamic data = new JObject(); data.signinlabel = "Sign in"; data.url = "https://login.microsoftonline.com/"; var lgResult = GetLGFile().EvaluateTemplate("SigninCardTemplate", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertSigninCardActivity(activity); }
public void TestMessageActivityAll() { dynamic data = new JObject(); data.title = "titleContent"; data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("messageActivityAll", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertMessageActivityAll(activity); }
public void TestHerocardActivityWithAttachmentStructure() { dynamic data = new JObject(); data.title = "titleContent"; data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("activityWithMultiAttachments", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertActivityWithMultiAttachments(activity); }
public void TestHerocardWithCardAction() { dynamic data = new JObject(); data.title = "titleContent"; data.text = "textContent"; var lgResult = GetLGFile().EvaluateTemplate("HerocardWithCardAction", data).ToString(); var activity = ActivityFactory.CreateActivity(lgResult); AssertCardActionActivity(activity); }
/// <summary> /// Deserializes an Activity Sequence XAML into a List of Activity objects. /// </summary> /// <param name="xaml"></param> /// <returns></returns> public static List <Activity> Deserialize(string xaml) { List <Activity> result = null; var sequence = ActivityFactory.CreateActivity(xaml) as Sequence; if (sequence != null) { result = sequence.Activities.ToList(); } return(result); }
public void TestActivityWithHeroCardAttachment() { dynamic data = new JObject(); data.title = "titleContent"; data.text = "textContent"; var lgResult = GetTemplateEngine().EvaluateTemplate("activityWithHeroCardAttachment", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertActivityWithHeroCardAttachment(activity); }
private async Task <DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { stepContext.Values["name"] = (string)stepContext.Result; // We can send messages to the user at any point in the WaterfallStep. await stepContext.Context.SendActivityAsync(ActivityFactory.CreateActivity(_lgEngine.EvaluateTemplate("AckName", new { Result = stepContext.Result }).ToString()), cancellationToken); // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog. return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = ActivityFactory.CreateActivity(_lgEngine.EvaluateTemplate("AgeConfirmPrompt").ToString()) }, cancellationToken)); }
public void TestOAuthCardTemplate() { dynamic data = new JObject(); data.signinlabel = "Sign in"; data.url = "https://login.microsoftonline.com/"; data.connectionName = "MyConnection"; var lgResult = GetTemplateEngine().EvaluateTemplate("OAuthCardTemplate", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertOAuthCardActivity(activity); }
public void TestHerocardAttachment() { dynamic data = new JObject(); data.type = "imBack"; data.title = "taptitle"; data.value = "tapvalue"; var lgResult = GetLGFile().EvaluateTemplate("herocardAttachment", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertActivityWithHeroCardAttachment(activity); }
public override object CreateNewInstance(SelectItem item) { OperatorEntry operatorEntry = item.Value as OperatorEntry; ActivityFactory factory = Parent.EditingContext.Services.GetService <ActivityFactory>(); Activity _operator = factory.CreateActivity(operatorEntry.Create, Parent.GetModelProperty()); // Create InArgument instance wrapping the activity Type genericType = typeof(InArgument <>).MakeGenericType(operatorEntry.ReturnType); InArgument argument = Activator.CreateInstance(genericType, _operator) as InArgument; return(argument); }
public async Task TestInlineActivityFactory() { var context = GetTurnContext(new MockLanguageGenerator()); var languageGenerator = context.TurnState.Get <ILanguageGenerator>(); var lgStringResult = await languageGenerator.Generate(context, "text", data : null).ConfigureAwait(false); var activity = ActivityFactory.CreateActivity(lgStringResult); Assert.AreEqual(ActivityTypes.Message, activity.Type); Assert.AreEqual("text", activity.Text); Assert.AreEqual("text", activity.Speak); }
public void TestMultiExternalAdaptiveCardActivity() { dynamic data = new JObject(); data.titles = new JArray() { "test0", "test1", "test2" }; var lgResult = GetLGFile().EvaluateTemplate("multiExternalAdaptiveCardActivity", data); var activity = ActivityFactory.CreateActivity(lgResult); AssertMultiAdaptiveCardActivity(activity); }