예제 #1
0
파일: Interactor.cs 프로젝트: xeno-by/elf4b
		public static string Prompt(string info, string value)
		{
			var f = new PromptDialog {Info = info, Value = value};

			if (f.ShowDialog() == DialogResult.OK)
			{
				if (f.Value != value)
					return f.Value;
			}

			return null;
		}
        public void Save()
        {
            if (! File.Exists(_fileToSave))
            {
                PromptDialog prompt = new PromptDialog("Save to?", _fileToSave) {RequireValue = true};

                if (prompt.ShowDialog() == DialogResult.OK)
                {
                    _fileToSave = prompt.Value;

                    File.WriteAllText(_fileToSave, _view.DiagramText);
                }
            }
            else
            {
                File.WriteAllText(_fileToSave, _view.DiagramText);
            }
        }
예제 #3
0
 public async Task PromptSuccess_Confirm_Maybe()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None,
                                                                        options: new string[] { "maybe", "no" }, patterns: new string[][] { new string[] { "maybe" }, new string[] { "no" } }),
                              "maybe", true);
 }
예제 #4
0
 public async Task PromptSuccess_Confirm_No_CaseInsensitive()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None), "No", false);
 }
예제 #5
0
 public async Task PromptSuccess_Confirm_Yes()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None), "yes", true);
 }
예제 #6
0
        public async Task PromptSuccess_Attachment()
        {
            var jpgAttachment = new Attachment {
                ContentType = "image/jpeg", Content = "http://a.jpg"
            };
            var bJpgAttachment = new Attachment {
                ContentType = "image/jpeg", Content = "http://b.jpg"
            };
            var pdfAttachment = new Attachment {
                ContentType = "application/pdf", Content = "http://a.pdf"
            };
            var toBot = MakeTestMessage();

            toBot.Attachments = new List <Attachment>
            {
                jpgAttachment,
                pdfAttachment
            };
            await PromptSuccessAsync <IEnumerable <Attachment> >((context, resume) => PromptDialog.Attachment(context, resume, PromptText), toBot, actual => new[] { jpgAttachment, pdfAttachment }.SequenceEqual(actual));
            await PromptSuccessAsync <IEnumerable <Attachment> >((context, resume) => PromptDialog.Attachment(context, resume, PromptText, new[] { "image/jpeg" }), toBot, actual => new[] { jpgAttachment }.SequenceEqual(actual));
            await PromptSuccessAsync <IEnumerable <Attachment> >((context, resume) => PromptDialog.Attachment(context, resume, PromptText, new[] { "application/pdf" }), toBot, actual => new[] { pdfAttachment }.SequenceEqual(actual));
            await PromptSuccessAsync <IEnumerable <Attachment> >((context, resume) => PromptDialog.Attachment(context, resume, PromptText, new[] { "image/jpeg", "application/pdf" }), toBot, actual => new[] { jpgAttachment, pdfAttachment }.SequenceEqual(actual));

            toBot.Attachments.Add(bJpgAttachment);
            await PromptSuccessAsync <IEnumerable <Attachment> >((context, resume) => PromptDialog.Attachment(context, resume, PromptText, new[] { "image/jpeg" }), toBot, actual => new[] { jpgAttachment, bJpgAttachment }.SequenceEqual(actual));
        }
예제 #7
0
 private async Task Registrarse1(IDialogContext context, IAwaitable <string> result)
 {
     Nombres = await result;
     PromptDialog.Text(context, Registrarse2, $"Por favor escriba su correo...");
 }
예제 #8
0
 private async Task After_Pregunta0Prompt(IDialogContext context, IAwaitable <string> result)
 {
     currentCurso = await result;
     PromptDialog.Text(context, After_PreguntaPrompt, "Ahora escriba una pregunta...");
 }
예제 #9
0
 public System.Windows.Forms.DialogResult ShowAssetUsageDialog(string title, string caption, TickerWeight[] inputweights, TickerWeight[] outputweights, out TickerWeight[] userinputweights)
 {
     decimal minfraction = System.Math.Max(System.Math.Min((
         from x in inputweights
         select (decimal)Game.State.PortfolioTable.Rows.Find(x.Ticker)["Position"] / x.Weight).Min(), 1m), 0m);
     System.Windows.Forms.NumericUpDown[] udcontrols = inputweights.Select(delegate(TickerWeight x)
     {
         System.Windows.Forms.NumericUpDown numericUpDown = new System.Windows.Forms.NumericUpDown();
         numericUpDown.Maximum = x.Weight;
         numericUpDown.Value = x.Weight * minfraction;
         numericUpDown.Increment = x.Weight / MathHelper.GreatestCommonFactor(MathHelper.GreatestCommonFactor((
             from y in inputweights
             select y.Weight).ToArray<decimal>()), MathHelper.GreatestCommonFactor((
             from y in outputweights
             select y.Weight).ToArray<decimal>()));
         return numericUpDown;
     }).ToArray<System.Windows.Forms.NumericUpDown>();
     System.Windows.Forms.Control[] second = new System.Windows.Forms.Control[]
     {
         new System.Windows.Forms.PictureBox
         {
             SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize,
             Image = Resources.arrow_down,
             Anchor = System.Windows.Forms.AnchorStyles.None
         }
     };
     System.Windows.Forms.TextBox[] tbcontrols = (
         from x in outputweights
         select new System.Windows.Forms.TextBox
         {
             Text = System.Math.Round(x.Weight * minfraction).ToString("0"),
             ReadOnly = true
         }).ToArray<System.Windows.Forms.TextBox>();
     decimal[] weights = (
         from x in inputweights
         select x.Weight).Concat(
         from x in outputweights
         select x.Weight).ToArray<decimal>();
     for (int j = 0; j < udcontrols.Length; j++)
     {
         udcontrols[j].TextChanged += delegate(object sender, System.EventArgs e)
         {
             if (!((System.Windows.Forms.NumericUpDown)sender).Focused)
             {
                 return;
             }
             for (int j = 0; j < weights.Length; j++)
             {
                 if (j < udcontrols.Length)
                 {
                     udcontrols[j].Value = System.Convert.ToInt64(weights[j]) * System.Convert.ToInt64(((System.Windows.Forms.NumericUpDown)sender).Value) / System.Convert.ToInt64(((System.Windows.Forms.NumericUpDown)sender).Maximum);
                 }
                 else
                 {
                     tbcontrols[j - udcontrols.Length].Text = (System.Convert.ToInt64(weights[j]) * System.Convert.ToInt64(((System.Windows.Forms.NumericUpDown)sender).Value) / System.Convert.ToInt64(((System.Windows.Forms.NumericUpDown)sender).Maximum)).ToString("0");
                 }
             }
         };
     }
     System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
     list.AddRange(
         from x in inputweights
         select x.Ticker);
     list.Add(null);
     list.AddRange(
         from x in outputweights
         select x.Ticker);
     PromptDialog f = new PromptDialog(title, caption, udcontrols.Cast<System.Windows.Forms.Control>().Concat(second).Concat(tbcontrols).ToArray<System.Windows.Forms.Control>(), list.ToArray());
     System.Windows.Forms.DialogResult dialogResult = f.ShowDialog();
     if (dialogResult == System.Windows.Forms.DialogResult.OK)
     {
         userinputweights = inputweights.Select((TickerWeight x, int i) => new TickerWeight
         {
             Ticker = x.Ticker,
             Weight = f.GetValue<decimal>(i)
         }).ToArray<TickerWeight>();
     }
     else
     {
         userinputweights = null;
     }
     return dialogResult;
 }
예제 #10
0
 public override Task OnStart(IDialogContext context)
 {
     PromptDialog.Confirm(context, AfterAreYouStillInterested, string.Format(messageProvider.GetMessage("StillInterestedPrompt"), question));
     return(Task.CompletedTask);
 }
예제 #11
0
        private async Task EndDialog(IDialogContext context, IAwaitable <string> response)
        {
            var seleccion = await response;
            var reply     = context.MakeMessage();

            if (seleccion.ToLower().Contains("nada") || seleccion.ToLower().Contains("no") || seleccion.Equals("Salir"))
            {
                await context.PostAsync("Fue un gusto atenderte, que la fuerza te acompañe.");

                reply.Attachments.Add(new Microsoft.Bot.Connector.Attachment()
                {
                    ContentUrl  = "https://thumbs.gfycat.com/PhonyMarvelousEchidna-small.gif",
                    ContentType = "image/gif",
                    Name        = "May the Fourth be with you."
                });
                await context.PostAsync(reply);
            }
            else if (!seleccion.Equals(MenuInicial[1]))
            {
                await context.PostAsync($"Disculpa, estoy aprendiendo y por el momento no tengo la funcionalidad de {seleccion}.");

                PromptDialog.Choice(context, EndDialog, MenuInicial, "¿Te puedo ayudar en algo más?");
            }
            else
            {
                List <string> recomendacion = new List <string>();
                try
                {
                    using (Recomendador recomendador = new Recomendador())
                    {
                        recomendacion = await recomendador.InvokeRequestResponseService(_calificacion.UserID, _calificacion.MovieID, _calificacion.Rating.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error: {ex.Message}");
                }
                try
                {
                    if (recomendacion.Count > 1)
                    {
                        await context.PostAsync("Te voy a hacer una oferta que no podrás rechazar.");

                        reply.Attachments.Add(new Microsoft.Bot.Connector.Attachment()
                        {
                            ContentUrl  = "https://media.giphy.com/media/26h0pkvcgnFIpvU1a/giphy.gif",
                            ContentType = "image/gif",
                            Name        = "El Padrino"
                        });
                        await context.PostAsync(reply);

                        reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                        reply.Attachments      = await GetCarousel(recomendacion);

                        await context.PostAsync(reply);
                    }
                    else
                    {
                        await context.PostAsync("Mmmm, has visto pocas películas. ¡Te recomiendo ver muchas más!, de esta forma me ayudas a conocerte mejor y poder ofrecerte películas que seguramente te encantarán.");

                        context.Wait(MessageReceivedAsync);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: " + ex.Message);
                }

                PromptDialog.Choice(context, EndDialog, MenuInicial, "¿Te puedo ayudar en algo más?");
            }
        }
예제 #12
0
 private async Task ResumeAfterTemplateNameClarification(IDialogContext context, IAwaitable <string> result)
 {
     Template_Name = await result;
     PromptDialog.Text(context, ResumeAfterVMNameClarification, "And give this VM a name of your choice ");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #13
0
 private async Task ResumeAfterVMHostIPClarification(IDialogContext context, IAwaitable <string> result)
 {
     VMHost_IP = await result;
     PromptDialog.Text(context, ResumeAfterDatastoreClarification, "Datastore name please");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #14
0
 private async Task ResumeAfterAdminPasswordClarification(IDialogContext context, IAwaitable <string> result)
 {
     Admin_Password = await result;
     PromptDialog.Text(context, ResumeAfterVMHostIPClarification, "Give me VM Host IP please ");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #15
0
 private async Task ResumeAfterAdminUsernameClarification(IDialogContext context, IAwaitable <string> result)
 {
     Admin_Username = await result;
     PromptDialog.Text(context, ResumeAfterAdminPasswordClarification, "Can I have password for the same ");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #16
0
 private void customToolStripMenuItem_Click(object sender, System.EventArgs e)
 {
     PromptDialog promptDialog = new PromptDialog("Custom Group Size", "", new System.Windows.Forms.Control[]
     {
         new System.Windows.Forms.NumericUpDown
         {
             Minimum = 1m,
             Increment = 10m,
             Maximum = 2147483647m,
             Value = this.CurrentGrouping
         }
     }, new string[]
     {
         "Group Size"
     });
     if (promptDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
     {
         this.SetSecurityGrouping(System.Convert.ToInt32(promptDialog.Values[0]));
     }
 }
예제 #17
0
 public async Task StartAsync(IDialogContext context)
 {
     PromptDialog.Text(context, ResumeAfterSamNameClarification, "Please give me your sam account name");
 }
예제 #18
0
 private async Task ResumeAfterPortClarification(IDialogContext context, IAwaitable <string> result)
 {
     Port = await result;
     PromptDialog.Text(context, ResumeAfterAdminUsernameClarification, "Please enter your admin username below ");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #19
0
 private async Task ResumeAfterOrgNameClarification(IDialogContext context, IAwaitable <string> result)
 {
     oname = await result;
     PromptDialog.Text(context, ResumeAfterSamNameClarification, "May I know sam name for your account");
     //await context.PostAsync($"I see you want to order {food}.");
 }
예제 #20
0
 private async Task After_PreguntaPrompt(IDialogContext context, IAwaitable <string> result)
 {
     currentPregunta = await result;
     PromptDialog.Text(context, After_RespuestaPrompt, $"Ahora escriba una respuesta de la pregunta {currentPregunta}.");
 }
예제 #21
0
 private async Task ResumeAfterSamNameClarification(IDialogContext context, IAwaitable <string> result)
 {
     sname = await result;
     PromptDialog.Text(context, ResumeAfterDispNameClarification, "What name you would like on display?");
     //await context.PostAsync($"You entered {sname}.");
 }
예제 #22
0
 private async Task Registrarse2(IDialogContext context, IAwaitable <string> result)
 {
     Correo = await result;
     PromptDialog.Text(context, Member, $"Por favor escriba su contraseña...");
 }
예제 #23
0
 private async Task ResumeAfterDispNameClarification(IDialogContext context, IAwaitable <string> result)
 {
     dname = await result;
     PromptDialog.Text(context, ResumeAfterUserNameClarification, "Enter username of your choice");
     //await context.PostAsync($"You entered {sname}.");
 }
예제 #24
0
 public async Task PromptSuccess_Text()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Text(context, resume, PromptText), "lol wut", "lol wut");
 }
예제 #25
0
 private async Task ResumeAfterUserNameClarification(IDialogContext context, IAwaitable <string> result)
 {
     uname = await result;
     PromptDialog.Text(context, ResumeAfterPasswordClarification, "And what password would you like to set?");
     //await context.PostAsync($"You entered {sname}.");
 }
예제 #26
0
 public async Task PromptSuccess_Confirm_Yes_WithLocale()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None), "seguro", true, "es-ES");
 }
예제 #27
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;

            if (message.Attachments != null && message.Attachments.Count > 0)
            {
                var attachment = message.Attachments[0];

                if (attachment.ContentType == "image/png" || attachment.ContentType == "image/jpeg")
                {
                    var contentStream = await ImageStream.GetImageStream(attachment.ContentUrl);

                    dynamic json = await FaceAPI.GetFaceAPIJson(contentStream);

                    if (json.Count > 0)
                    {
                        var face = json[0]["faceAttributes"];
                        this.user.gender = face["gender"].ToString();
                        this.user.age    = decimal.Parse(face["age"].ToString());

                        this.user.smile     = decimal.Parse(face["smile"].ToString());
                        this.user.glasses   = face["glasses"].ToString();
                        this.user.anger     = decimal.Parse(face["emotion"]["anger"].ToString());
                        this.user.eyeMakeup = Convert.ToBoolean(face["makeup"]["eyeMakeup"].ToString());
                        this.user.lipMakeup = Convert.ToBoolean(face["makeup"]["lipMakeup"].ToString());

                        this.user.hair = face["hair"].ToString();
                        this.user.bald = decimal.Parse(face["smile"].ToString());
                        var hairColor = face["hair"]["hairColor"];
                        if (hairColor.Count > 0)
                        {
                            this.user.hairColor = hairColor[0]["color"].ToString();
                        }
                        else
                        {
                            this.user.hairColor = "";
                        }
                        this.user.moustache = decimal.Parse(face["facialHair"]["moustache"].ToString());
                        this.user.beard     = decimal.Parse(face["facialHair"]["beard"].ToString());
                        this.user.emotion   = face["emotion"].ToString();

                        if (this.user.gender == "male")
                        {
                            this.user.genderThai = "ท่านหมื่น";
                        }
                        else
                        {
                            this.user.genderThai = "แม่หญิง";
                        }

                        if (this.user.eyeMakeup || this.user.lipMakeup)
                        {
                            this.user.makeupStr = "ชอบการแต่งตัว";
                        }
                        else
                        {
                            this.user.makeupStr = "เป็นคนง่ายๆ สบายๆ";
                        }

                        if (this.user.smile > 0.0M)
                        {
                            this.user.smileStr = "รักความสนุกสนาน";
                        }
                        else
                        {
                            if (this.user.eyeMakeup || this.user.lipMakeup)
                            {
                                this.user.smileStr = "ชอบความเรียบง่าย";
                            }
                            else
                            {
                                this.user.smileStr = "ชอบความโก้หรู";
                            }
                        }

                        if (this.user.anger > 0.7M)
                        {
                            this.user.angerStr = "ชอบความปราดเปรียว";
                        }
                        else
                        {
                            this.user.angerStr = "";
                        }

                        var quiz = $"ข้าเห็นหน้าออเจ้าแล้ว ออเจ้าเป็น{this.user.genderThai} ใช่หรือไม่";
                        PromptDialog.Choice(context, this.OnGenderSelected, yesNoOptions, quiz, "ออเจ้าเลือกไม่ถูกต้อง", 3);
                    }
                    else
                    {
                        --attempts;
                        await context.PostAsync($"ออเจ้าไม่ได้ส่งรูปใบหน้าของออเจ้ามา ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                        context.Wait(MessageReceivedAsync);
                    }
                }
                else
                {
                    --attempts;
                    await context.PostAsync($"ออเจ้าไม่ได้ส่งรูปใบหน้าของออเจ้ามา ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                    context.Wait(MessageReceivedAsync);
                }
            }
            else
            {
                --attempts;
                await context.PostAsync($"ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                context.Wait(MessageReceivedAsync);
            }

            if (attempts <= 0)
            {
                context.Fail(new TooManyAttemptsException("รูปที่ออเจ้าส่งมาไม่ถูกต้อง"));
            }
        }
예제 #28
0
 public async Task PromptSuccess_Confirm_No_WithLocale()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None), "nop", false, "es-ES");
 }
        public async Task AuthenticateIntent(IDialogContext context, LuisResult result)
        {
            object formattedValues = null;
            var    entity          = result.Entities.FirstOrDefault(x =>
                                                                    x.Type == "builtin.datetimeV2.date" ||
                                                                    x.Type == "builtin.datetimeV2.daterange" ||
                                                                    x.Type == "builtin.datetimeV2.timerange" ||
                                                                    x.Type == "builtin.datetimeV2.time" ||
                                                                    x.Type == "builtin.datetimeV2.datetime" ||
                                                                    x.Type == "builtin.datetimeV2.datetimerange");

            entity?
            .Resolution?
            .TryGetValue("values", out formattedValues);

            // If no date indication, please ask for a date.
            if (entity == null)
            {
                await context.PostAsync($"When are you home to receive a mechanic?");

                context.Wait(MessageReceived);
                return;
            }

            // Als date time --> plan dan afspraak in in dynamics.
            // Als date time in verleden, zeg dan dat het lastig wordt om langs te komen.
            // Als geen date time en wel vraag gesteld, stel dan zelf een datum voor (random).

            Chronic.Parser       parser = new Chronic.Parser();
            EntityRecommendation date   = new EntityRecommendation();

            Chronic.Span resultSpan = null;

            result.TryFindEntity(entity.Type, out date);
            resultSpan = parser.Parse(date.Entity);

            // If we would have used a scheduling service, we could just feed it the dates and it would come up with a suggestion...
            if (!resultSpan.Start.HasValue && !resultSpan.End.HasValue)
            {
                await context.PostAsync($"When are you home to receive a mechanic?");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value <= DateTime.Now && resultSpan.End.Value <= DateTime.Now)
            {
                await context.PostAsync($"I understand you want this issue to be resolved already, but we can't go back in time to send a mechanic.");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.Date != resultSpan.End.Value.Date)
            {
                // We got a date range, let's pick a random date (and time).
                await context.PostAsync($"Date range, let's pick a random date");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours == 0)
            {
                // Midnight, assume that we didn't recieve a time frame and suggest some random times a day.
                // GIVE TWO OPTIONS
                await context.PostAsync($"Single time on a day.");

                context.Wait(MessageReceived);
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours == resultSpan.Start.Value.TimeOfDay.Hours)
            {
                // We got a single time on that day
                await context.PostAsync($"Sorry, there is no mechanic available at " + resultSpan.Start.Value.TimeOfDay.Hours + ".");

                this.suggestedDate = resultSpan.Start.Value.AddHours(1);
                PromptDialog.Confirm(context, this.ConfirmMechanicDateTime, $"There is one available at " + (resultSpan.Start.Value.TimeOfDay.Hours + 1) + ", should I schedule that for you?");
                return;
            }
            else if (resultSpan.Start.Value.TimeOfDay.Hours != resultSpan.Start.Value.TimeOfDay.Hours)
            {
                // Just have some fun, pick a random time on this day
                await context.PostAsync($"Timeframe on a day, pick a random time");

                context.Wait(MessageReceived);
                return;
            }
            else
            {
                // Yeah, what else?
                await context.PostAsync($"Yeah, what else? =(");

                context.Wait(MessageReceived);
                return;
            }
        }
예제 #30
0
 public async Task PromptSuccess_Confirm_Maybe_WithLocale()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None,
                                                                        options: new string[] { "quizás", "nunca" }, patterns: new string[][] { new string[] { "quizás" }, new string[] { "nunca" } }),
                              "quizás", true, "es-ES");
 }
예제 #31
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var userText = context.Activity.From.Name;

            try
            {
                userText = (await result).Text;
            }
            catch (Exception)
            {
                // Swallow exception for the demo purpose
                // TODO log the exception
            }

            string detectedLanguageIsoCode = await MessageTranslator.IdentifyLangAsync(userText);

            context.UserData.SetValue(Constants.Shared.UserLanguageCodeKey, detectedLanguageIsoCode);
            var userData = _userDataRepository.GetUserData(context.Activity.From.Id);

            if (userData == null)
            {
                userData        = new UserData();
                userData.UserId = context.Activity.From.Id;
                userData.NativeLanguageIsoCode = detectedLanguageIsoCode;
            }

            _userDataRepository.UpdateUserData(userData);

            if (MessageTranslator.DEFAULT_LANGUAGE.Equals(detectedLanguageIsoCode))
            {
                await context.PostAsync(BotPersonality.UserNameQuestion);

                // detected it's english language
                context.Wait(this.UserNameReceivedAsync);
            }
            else
            {
                // detected user language

                CultureInfo[] allCultures     = CultureInfo.GetCultures(CultureTypes.AllCultures);
                CultureInfo   detectedCulture =
                    allCultures
                    .FirstOrDefault(cultureInfo => (detectedLanguageIsoCode.Contains(cultureInfo.TwoLetterISOLanguageName)));

                string detectedLanguageName = CultureInfo.GetCultureInfo(MessageTranslator.DEFAULT_LANGUAGE).DisplayName;

                if (detectedCulture != null)
                {
                    detectedLanguageName = detectedCulture.DisplayName;
                }

                var translationInputTextlist = new List <string>(capacity: 4);
                translationInputTextlist.AddRange(YesNoChoices);
                translationInputTextlist.AddRange(new string[] { $"Do you want to switch to {detectedLanguageName}", Shared.DoNotUnderstand });

                var translatedList = await MessageTranslator.TranslateTextAsync(translationInputTextlist, detectedLanguageIsoCode);

                var translatedSwitchQuestion = translatedList.ElementAt(2);
                var translatedDontUnderstand = translatedList.ElementAt(3);
                var translatedChoices        = translatedList.Take(2);

                PromptDialog.Choice(
                    context,
                    this.AfterChoosingLanguageSwitch,
                    translatedChoices,
                    translatedSwitchQuestion,
                    translatedDontUnderstand,
                    attempts: Shared.MaxPromptAttempts
                    );
            }
        }
예제 #32
0
        string Prompt(string text)
        {
            var dialog = new PromptDialog { PromptText = text };

            dialog.ShowDialog();

            return dialog.ResultText;
        }
예제 #33
0
        public async Task teachLanguage(IDialogContext context, LuisResult result)
        {
            if (result.Entities.Count == 0)
            {
                await context.PostAsync("Hi there! I'm TRPlate Bot 🤖, please feel free to ask me any question 😊");
            }
            else
            {
                foreach (var searchEntity in result.Entities)
                {
                    if (searchEntity.Type == "CityName")
                    {
                        if (searchEntity.Entity == "Ä°stanbul" || searchEntity.Entity == "istanbul")
                        {
                            /* await context.PostAsync("Ä°stanbul Ãœniversitesi \n\n"
                             + "Ä°stanbul Teknik Ãœniversitesi\n\n"
                             + "Galatasaray Ãœniversitesi\n\n"
                             + "Marmara Ãœniversitesi\n\n"
                             + "Boğaziçi Üniversitesi\n\n"
                             + "Acıbadem Üniversitesi\n\n"
                             + "Bahçeşehir Üniversitesi\n\n"
                             + "Beykent Ãœniversitesi\n\n"
                             + "Bezmialem Vakıf Üniversitesi\n\n"
                             + "DoÄŸuÅŸ Ãœniversitesi");*/
                            PromptDialog.Choice(context, this.OnOptionSelected, new List <string>()
                            {
                                "show Ä°stanbul university",
                                "show Ä°stanbul Teknik university",
                                "show Galatasaray university",
                                "show Marmara university",
                                "show Boğaziçi university",
                                "show Acıbadem university",
                                "show Bahçeşehir university",
                                "show Beykent university",
                                "show Bezmialem Vakıf university",
                                "show DoÄŸuÅŸ university"
                            },
                                                "Ä°stambul'daki Ãœniversitelerin Listesi", "Not a valid option", 3);
                        }

                        if (searchEntity.Entity == "Ankara" || searchEntity.Entity == "ankara")
                        {
                            /*  await context.PostAsync("Ankara Ãœniversitesi\n\n"
                             + "Ankara Sosyal Bilimler Ãœniversitesi\n\n"
                             + "Gazi Ãœniversitesi\n\n"
                             + "Hacettepe Ãœniversitesi\n\n"
                             + "Orta DoÄŸu Teknik Ãœniversitesi\n\n"
                             +
                             + "Anka Teknoloji Ãœniversitesi\n\n"
                             + "Atılım Üniversitesi\n\n"
                             + "BaÅŸkent Ãœniversitesi\n\n"
                             + "Bilkent Ãœniversitesi\n\n"
                             + "Çankaya Üniversitesi");*/

                            PromptDialog.Choice(context, this.OnOptionSelected, new List <string>()
                            {
                                "show Ankara university",
                                "show Sosyal Bilimler Teknik university",
                                "show Gazi university",
                                "show Hacettepe university",
                                "show Orta DoÄŸu Teknik university",
                                "show Anka Teknoloji university",
                                "show Atılım university",
                                "show BaÅŸkent university",
                                "show Bilkent Vakıf university",
                                "show Çankaya university"
                            },
                                                "Ankara'daki Ãœniversitelerin Listesi", "Not a valid option", 3);
                        }

                        if (searchEntity.Entity == "Ä°zmir" || searchEntity.Entity == "izmir")
                        {
                            await context.PostAsync("Dokuz Eylül Üniversitesi\n\n"
                                                    + "Ege Ãœniversitesi\n\n"
                                                    + "Ä°zmir Demokrasi Ãœniversitesi\n\n"
                                                    + "İzmir Kâtip Çelebi Üniversitesi\n\n"

                                                    + "Ä°zmir Ekonomi Ãœniversitesi\n\n"
                                                    + "Türk Hava Kurumu Üniversitesi\n\n"
                                                    + "YaÅŸar Ãœniversitesi");

                            PromptDialog.Choice(context, this.OnOptionSelected, new List <string>()
                            {
                                "show Dokuz Eylül university",
                                "show Ege university",
                                "show Ä°zmir Demokrasi university",
                                "show İzmir Kâtip Çelebi university",
                                "show Ä°zmir Ekonomi university",
                                "show Türk Hava Kurumu university",
                                "show YaÅŸar university"
                            },
                                                "Ä°zmir'deki Ãœniversitelerin Listesi", "Not a valid option", 3);
                        }
                    }
                }
            }
        }
예제 #34
0
 private void exponentialMovingAverageToolStripMenuItem_Click(object sender, System.EventArgs e)
 {
     PromptDialog promptDialog = new PromptDialog("Exponential Moving Average Span", "", new System.Windows.Forms.Control[]
     {
         new System.Windows.Forms.NumericUpDown
         {
             Minimum = 1m,
             Increment = 1m,
             Maximum = 2147483647m,
             Value = 10m
         }
     }, new string[]
     {
         "# of Bars"
     });
     if (promptDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
     {
         this.AddEMA(System.Convert.ToInt32(promptDialog.Values[0]));
     }
 }
 private void ShowHotelOption(IDialogContext context)
 {
     PromptDialog.Choice(context, this.OnHotelSelected2, hotelOptions, "Which one would you like to select?" /*, "Not a valid option", 3*/);
 }
예제 #36
0
        private async Task Member(IDialogContext context, IAwaitable <string> result)
        {
            try
            {
                Contrasena = await result;

                if (OpcionLoginSignUp == "Iniciar Sesión")
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string tramaJson        = "";

                    LogIn logIn = new LogIn
                    {
                        access_token = "LmTXw9oHsVZhhjgllFQphiZfXXJJGVwF"
                    };

                    string postdata = js.Serialize(logIn);

                    byte[] dataBytes = Encoding.UTF8.GetBytes(postdata);

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://loginrestapi.herokuapp.com/auth");

                    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    request.ContentLength          = dataBytes.Length;
                    request.ContentType            = "application/json";
                    request.Method = "POST";

                    string authInfo = Correo + ":" + Contrasena;
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

                    request.Headers.Add("Authorization", "Basic " + authInfo);

                    using (Stream requestBody = request.GetRequestStream())
                    {
                        requestBody.Write(dataBytes, 0, dataBytes.Length);
                    }

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                tramaJson = reader.ReadToEnd();
                            }

                    UsuarioObtenido usuarioObtenido = js.Deserialize <UsuarioObtenido>(tramaJson);

                    token = usuarioObtenido.token;

                    string[] opciones = { "Consultar Pregunta", "Crear Pregunta" };

                    var options      = opciones;
                    var descriptions = opciones;
                    PromptDialog.Choice <string>(context, ConsultaCreaPregunta,
                                                 options, $"Hola {usuarioObtenido.user.name}, ahora escoge entre consultar o crear pregunta:", descriptions: descriptions);
                }

                else if (OpcionLoginSignUp == "Registrarse")
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string tramaJson        = "";

                    SignUp signUp = new SignUp
                    {
                        access_token = "LmTXw9oHsVZhhjgllFQphiZfXXJJGVwF",
                        email        = Correo,
                        password     = Contrasena,
                        name         = Nombres,
                        picture      = "",
                        role         = ""
                    };

                    string postdata = js.Serialize(signUp);

                    byte[] dataBytes = Encoding.UTF8.GetBytes(postdata);

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://loginrestapi.herokuapp.com/users");

                    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    request.ContentLength          = dataBytes.Length;
                    request.ContentType            = "application/json";
                    request.Method = "POST";

                    using (Stream requestBody = request.GetRequestStream())
                    {
                        requestBody.Write(dataBytes, 0, dataBytes.Length);
                    }

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                tramaJson = reader.ReadToEnd();
                            }

                    UsuarioObtenido usuarioObtenido = js.Deserialize <UsuarioObtenido>(tramaJson);

                    token = usuarioObtenido.token;

                    string[] opciones = { "Consultar Pregunta", "Crear Pregunta" };

                    var options      = opciones;
                    var descriptions = opciones;
                    PromptDialog.Choice <string>(context, ConsultaCreaPregunta,
                                                 options, $"Hola {usuarioObtenido.user.name}, ahora escoge entre consultar o crear pregunta:", descriptions: descriptions);
                }
            }

            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    if (((HttpWebResponse)wex.Response).StatusCode.ToString() == "Unauthorized")
                    {
                        await context.PostAsync($"El usuario o contraseña ingresada no es correcta.");

                        context.Wait(MessageReceived);
                    }
                    else
                    {
                        using (var errorResponse = (HttpWebResponse)wex.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                string error                      = reader.ReadToEnd();
                                JavaScriptSerializer js           = new JavaScriptSerializer();
                                UsuarioError         usuarioError = js.Deserialize <UsuarioError>(error);
                                await context.PostAsync($"Error en: {usuarioError.message}");

                                context.Wait(MessageReceived);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await context.PostAsync($"{ex.Message.ToString()}");

                context.Wait(MessageReceived);
            }
        }
예제 #37
0
 private void newWorkspaceToolStripMenuItem_Click(object sender, System.EventArgs e)
 {
     PromptDialog promptDialog = new PromptDialog("New Workspace", "Enter a unique name for the new workspace.", new System.Windows.Forms.Control[]
     {
         new System.Windows.Forms.TextBox()
     }, new string[]
     {
         "Name"
     });
     if (promptDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         try
         {
             TTSFormManager.Instance.AddWorkspace((string)promptDialog.Values[0], true);
         }
         catch (System.Exception ex)
         {
             DialogHelper.ShowError(ex.Message, "Error");
         }
     }
 }