private static IForm<PizzaOrder> BuildForm()
        {
            var builder = new FormBuilder<PizzaOrder>();

            ActiveDelegate<PizzaOrder> isBYO = (pizza) => pizza.Kind == PizzaOptions.BYOPizza;
            ActiveDelegate<PizzaOrder> isSignature = (pizza) => pizza.Kind == PizzaOptions.SignaturePizza;
            ActiveDelegate<PizzaOrder> isGourmet = (pizza) => pizza.Kind == PizzaOptions.GourmetDelitePizza;
            ActiveDelegate<PizzaOrder> isStuffed = (pizza) => pizza.Kind == PizzaOptions.StuffedPizza;

            return builder
                // .Field(nameof(PizzaOrder.Choice))
                .Field(nameof(PizzaOrder.Size))
                .Field(nameof(PizzaOrder.Kind))
                .Field("BYO.Crust", isBYO)
                .Field("BYO.Sauce", isBYO)
                .Field("BYO.Toppings", isBYO)
                .Field(nameof(PizzaOrder.GourmetDelite), isGourmet)
                .Field(nameof(PizzaOrder.Signature), isSignature)
                .Field(nameof(PizzaOrder.Stuffed), isStuffed)
                .AddRemainingFields()
                .Confirm("Would you like a {Size}, {BYO.Crust} crust, {BYO.Sauce}, {BYO.Toppings} pizza?", isBYO)
                .Confirm("Would you like a {Size}, {&Signature} {Signature} pizza?", isSignature, dependencies: new string[] { "Size", "Kind", "Signature" })
                .Confirm("Would you like a {Size}, {&GourmetDelite} {GourmetDelite} pizza?", isGourmet)
                .Confirm("Would you like a {Size}, {&Stuffed} {Stuffed} pizza?", isStuffed)
                .Build()
                ;
        }
Esempio n. 2
0
        public void FormTitleShouldGetAndSetValues()
        {
            // Arrange
            var form = new FormBuilder().Build();
            var expected = "Test Form";

            // Act
            form.Title = expected;
            var actual = form.Title;

            // Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 3
0
        public void FormIdShouldGetAndSetValues()
        {
            // Arrange
            var form = new FormBuilder().Build();
            var expected = Guid.NewGuid();

            // Act
            form.Id = expected;
            var actual = form.Id;

            // Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 4
0
        public Form GetBasicSurvey()
        {
            var topic = new TopicMother()
                .GetDefaultTopic("Topic Name");

               var form = new FormBuilder()
                .WithRandomId()
                .WithTitle("Basic Survey")
                .WithTopic(topic)
                .Build();

               return form;
        }
Esempio n. 5
0
        public void Login(String email, String password)
        {
            Dictionary<String, String> fields = new Dictionary<String, String>
            {
                {"service", "sj"},
                {"Email",  email},
                {"Passwd", password},
            };

            FormBuilder builder = new FormBuilder();
            builder.AddFields(fields);
            builder.Close();

            client.UploadDataAsync(new Uri("https://www.google.com/accounts/ClientLogin"), builder.ContentType, builder.GetBytes(), 10000, GetAuthTokenComplete, null);
        }
Esempio n. 6
0
 public void AddInputTest()
 {
     FormBuilder target = new FormBuilder
     {
         Form = new Form
         {
             Elements = new List<IElement>()
         }
     };
     Type PropertyType = typeof(string);
     string Name = "DisplayName";
     string Value = "Test";
     FormBuilder Expected = target;
     Expected.Form.Elements.Add(new Input("text", Name, Value));
     target.AddInput(PropertyType, Name, Value);
     Assert.AreEqual(target, Expected);
 }
Esempio n. 7
0
        public void AddTopicToFormShouldWork()
        {
            // Arrange
            var expectedTopicTitle = "Test Topic";
            var expectedCount = 1;
            var form = new FormBuilder().Build();
            var topic = new TopicBuilder().WithTitle(expectedTopicTitle).Build();

            // Act
            form.Topics.Add(topic);
            var actualCount = form.Topics.Count();
            var actualTopic = form.Topics.FirstOrDefault();

            // Assert
            Assert.AreEqual(expectedCount, actualCount);
            Assert.AreSame(topic, actualTopic);
        }
Esempio n. 8
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<ISchedule>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, sch => sch.ObjectName))
                        .AddRow(
                            createLabel(Constants.OutOfServiceLabel),
                            bindEditor(obj, sch => sch.OutOfService))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 9
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<ICalendar>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, cal => cal.ObjectName))
                        .AddRow(
                            createLabel(Constants.PresentValueLabel),
                            bindEditor(obj, cal => cal.PresentValue))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 10
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<ITrendLog>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, tl => tl.ObjectName))
                        .AddRow(
                            createLabel(Constants.LogIntervalLabel),
                            bindEditor(obj, tl => tl.LogInterval),
                            createLabel(Constants.TotalRecordCountLabel),
                            bindEditor(obj, tl => tl.TotalRecordCount)
                        )
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 11
0
#pragma warning disable 1998
        public static IForm<StockOrder> MakeForm()
        {
            FormBuilder<StockOrder> _Order = new FormBuilder<StockOrder>();
            return _Order
                .Message("Welcome to the Stock Bot!")
                .Field("StockTicker", validate:
                async (state, value) =>
                {
                    ValidateResult vResult = new ValidateResult();
                    var str = value as string;

                    double? dblStock = await Yahoo.GetStockPriceAsync(str);
                    if (null == dblStock)
                    {
                        vResult.Feedback = string.Format("{0} is not a valid stock ticker.", str.ToUpper());
                        vResult.IsValid = false;
                    }
                    else
                    {
                        vResult.Feedback = string.Format("{0} is currently at {1}", str.ToUpper(), dblStock);
                        vResult.IsValid = true;
                    }

                    return vResult;
                })
                .Field(nameof(StockOrder.BuySell))
                .Field(nameof(StockOrder.OrderDate))
                .Field(nameof(StockOrder.NumberOfShares))
                .AddRemainingFields()
                .Confirm("Do you want to {BuySell} {NumberOfShares} shares of {StockTicker} on {OrderDate}? ")
                .OnCompletionAsync(async (session, StockOrder) =>
                {
                    Debug.WriteLine("{0}", StockOrder);
                })
                .Build();
        }
Esempio n. 12
0
        /// <summary>
        /// Gets all the songs
        /// </summary>
        /// <param name="continuationToken"></param>
        public void GetAllSongs(String continuationToken = "")
        {
            List<GoogleMusicSong> library = new List<GoogleMusicSong>();

            String jsonString = "{\"continuationToken\":\"" + continuationToken +  "\"}";

            JsonConvert.SerializeObject(jsonString);

            Dictionary<String, String> fields = new Dictionary<String, String>
            {
               {"json", jsonString}
            };

            FormBuilder builder = new FormBuilder();
            builder.AddFields(fields);
            builder.Close();

            client.UploadDataAsync(new Uri("https://play.google.com/music/services/loadalltracks"), builder, TrackListChunkRecv);
        }
Esempio n. 13
0
 public Director(FormBuilder builder)
 {
     this.builder = builder;
     this.parents = new Stack();
 }
Esempio n. 14
0
            /// <summary>
            /// Constructs a new device info tab panel
            /// </summary>
            /// <param name="info">The device to show information for</param>
            public Panel(ObjectInfo info)
            {
                var obj = client.With<IDevice>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, dev => dev.ObjectName, enabled: false))
                        .AddRow(
                            createLabel(Constants.VendorIdLabel),
                            bindEditor(obj, dev => dev.VendorIdentifier, enabled: false))
                        .AddRow(
                            createLabel(Constants.VendorNameLabel),
                            bindEditor(obj, dev => dev.VendorName, enabled: false)
                        )
                        .AddRow(
                            createLabel(Constants.ModelNameLabel),
                            bindEditor(obj, dev => dev.ModelName, enabled: false)
                        )
                        .AddRow(
                            createLabel(Constants.ApplicationSoftwareVersionLabel),
                            bindEditor(obj, dev => dev.ApplicationSoftwareVersion, enabled: false))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 15
0
        public static IForm <SandwichOrder> BuildLocalizedForm()
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            IForm <SandwichOrder> form;

            if (!_forms.TryGetValue(culture, out form))
            {
                OnCompletionAsyncDelegate <SandwichOrder> processOrder = async(context, state) =>
                {
                    await context.PostAsync(DynamicSandwich.Processing);
                };
                // Form builder uses the thread culture to automatically switch framework strings
                // and also your static strings as well.  Dynamically defined fields must do their own localization.
                var builder = new FormBuilder <SandwichOrder>()
                              .Message("Welcome to the sandwich order bot!")
                              .Field(nameof(Sandwich))
                              .Field(nameof(Length))
                              .Field(nameof(Bread))
                              .Field(nameof(Cheese))
                              .Field(nameof(Toppings),
                                     validate: async(state, value) =>
                {
                    var values = ((List <object>)value).OfType <ToppingOptions>();
                    var result = new ValidateResult {
                        IsValid = true, Value = values
                    };
                    if (values != null && values.Contains(ToppingOptions.Everything))
                    {
                        result.Value = (from ToppingOptions topping in Enum.GetValues(typeof(ToppingOptions))
                                        where topping != ToppingOptions.Everything && !values.Contains(topping)
                                        select topping).ToList();
                    }
                    return(result);
                })
                              .Message("For sandwich toppings you have selected {Toppings}.")
                              .Field(nameof(SandwichOrder.Sauces))
                              .Field(new FieldReflector <SandwichOrder>(nameof(Specials))
                                     .SetType(null)
                                     .SetActive((state) => state.Length == LengthOptions.FootLong)
                                     .SetDefine(async(state, field) =>
                {
                    field
                    .AddDescription("cookie", DynamicSandwich.FreeCookie)
                    .AddTerms("cookie", Language.GenerateTerms(DynamicSandwich.FreeCookie, 2))
                    .AddDescription("drink", DynamicSandwich.FreeDrink)
                    .AddTerms("drink", Language.GenerateTerms(DynamicSandwich.FreeDrink, 2));
                    return(true);
                }))
                              .Confirm(async(state) =>
                {
                    var cost = 0.0;
                    switch (state.Length)
                    {
                    case LengthOptions.SixInch: cost = 5.0; break;

                    case LengthOptions.FootLong: cost = 6.50; break;
                    }
                    return(new PromptAttribute(string.Format(DynamicSandwich.Cost, cost) + "{||}"));
                })
                              .Field(nameof(SandwichOrder.DeliveryAddress),
                                     validate: async(state, response) =>
                {
                    var result = new ValidateResult {
                        IsValid = true, Value = response
                    };
                    var address = (response as string).Trim();
                    if (address.Length > 0 && address[0] < '0' || address[0] > '9')
                    {
                        result.Feedback = DynamicSandwich.BadAddress;
                        result.IsValid  = false;
                    }
                    return(result);
                })
                              .Field(nameof(SandwichOrder.DeliveryTime), "What time do you want your sandwich delivered? {||}")
                              .Confirm("Do you want to order your {Length} {Sandwich} on {Bread} {&Bread} with {[{Cheese} {Toppings} {Sauces}]} to be sent to {DeliveryAddress} {?at {DeliveryTime:t}}?")
                              .AddRemainingFields()
                              .Message("Thanks for ordering a sandwich!")
                              .OnCompletion(processOrder);
                builder.Configuration.DefaultPrompt.ChoiceStyle = ChoiceStyleOptions.Auto;
                form            = builder.Build();
                _forms[culture] = form;
            }
            return(form);
        }
Esempio n. 16
0
        public void RemoveInexistentTopicShouldFail()
        {
            // Arrange
            var falseTopic = new TopicBuilder().Build();
            var topic = new TopicBuilder().Build();
            var form = new FormBuilder().WithTopic(topic).Build();

            // Act
            var actual = form.Topics.Remove(falseTopic);

            Assert.IsFalse(actual);
        }
Esempio n. 17
0
        public static IForm<PizzaOrder> BuildForm(bool noNumbers = false, bool ignoreAnnotations = false, bool localize = false, ChoiceStyleOptions style = ChoiceStyleOptions.Auto)
        {
            var builder = new FormBuilder<PizzaOrder>(ignoreAnnotations);

            ActiveDelegate<PizzaOrder> isBYO = (pizza) => pizza.Kind == PizzaOptions.BYOPizza;
            ActiveDelegate<PizzaOrder> isSignature = (pizza) => pizza.Kind == PizzaOptions.SignaturePizza;
            ActiveDelegate<PizzaOrder> isGourmet = (pizza) => pizza.Kind == PizzaOptions.GourmetDelitePizza;
            ActiveDelegate<PizzaOrder> isStuffed = (pizza) => pizza.Kind == PizzaOptions.StuffedPizza;
            // form.Configuration().DefaultPrompt.Feedback = FeedbackOptions.Always;
            if (noNumbers)
            {
                builder.Configuration.DefaultPrompt.ChoiceFormat = "{1}";
                builder.Configuration.DefaultPrompt.ChoiceCase = CaseNormalization.Lower;
                builder.Configuration.DefaultPrompt.ChoiceParens = BoolDefault.False;
            }
            else
            {
                builder.Configuration.DefaultPrompt.ChoiceFormat = "{0}. {1}";
            }
            builder.Configuration.DefaultPrompt.ChoiceStyle = style;
            Func<PizzaOrder, double> computeCost = (order) =>
            {
                double cost = 0.0;
                switch (order.Size)
                {
                    case SizeOptions.Medium: cost = 10; break;
                    case SizeOptions.Large: cost = 15; break;
                    case SizeOptions.Family: cost = 20; break;
                }
                return cost;
            };
            MessageDelegate<PizzaOrder> costDelegate = async (state) =>
            {
                double cost = 0.0;
                switch (state.Size)
                {
                    case SizeOptions.Medium: cost = 10; break;
                    case SizeOptions.Large: cost = 15; break;
                    case SizeOptions.Family: cost = 20; break;
                }
                cost *= state.NumberOfPizzas;
                return new PromptAttribute(string.Format(DynamicPizza.Cost, cost));
            };
            var form = builder
                .Message("Welcome to the pizza bot!!!")
                .Message("Lets make pizza!!!")
                .Field(nameof(PizzaOrder.NumberOfPizzas))
                .Field(nameof(PizzaOrder.Size))
                .Field(nameof(PizzaOrder.Kind))
                .Field(new FieldReflector<PizzaOrder>(nameof(PizzaOrder.Specials))
                    .SetType(null)
                    .SetDefine(async (state, field) =>
                    {
                        var specials = field
                        .SetFieldDescription(DynamicPizza.Special)
                        .SetFieldTerms(DynamicPizza.SpecialTerms.SplitList())
                        .RemoveValues();
                        if (state.NumberOfPizzas > 1)
                        {
                            specials
                                .SetAllowsMultiple(true)
                                .AddDescription("special1", DynamicPizza.Special1)
                                .AddTerms("special1", DynamicPizza.Special1Terms.SplitList());
                        }
                        specials
                            .AddDescription("special2", DynamicPizza.Special2)
                            .AddTerms("special2", DynamicPizza.Special2Terms.SplitList());
                        return true;
                    }))
                .Field("BYO.HalfAndHalf", isBYO)
                .Field("BYO.Crust", isBYO)
                .Field("BYO.Sauce", isBYO)
                .Field("BYO.Toppings", isBYO)
                .Field("BYO.HalfToppings", (pizza) => isBYO(pizza) && pizza.BYO != null && pizza.BYO.HalfAndHalf)
                .Message("Almost there!!! {*filled}", isBYO)
                .Field(nameof(PizzaOrder.GourmetDelite), isGourmet)
                .Field(nameof(PizzaOrder.Signature), isSignature)
                .Field(nameof(PizzaOrder.Stuffed), isStuffed)

                .Message("What we have is a {?{Signature} signature pizza} {?{GourmetDelite} gourmet pizza} {?{Stuffed} {&Stuffed}} {?{?{BYO.Crust} {&BYO.Crust}} {?{BYO.Sauce} {&BYO.Sauce}} {?{BYO.Toppings}}} pizza")
                .Field("DeliveryAddress", validate:
                    async (state, value) =>
                    {
                        var result = new ValidateResult { IsValid = true, Value = value };
                        var str = value as string;
                        if (str.Length == 0 || str[0] < '1' || str[0] > '9')
                        {
                            result.Feedback = DynamicPizza.AddressHelp;
                            result.IsValid = false;
                        }
                        else
                        {
                            result.Feedback = DynamicPizza.AddressFine;
                        }
                        return result;
                    })
                .Message(costDelegate)
                .Confirm(async (state) => {
                    var cost = computeCost(state);
                    return new PromptAttribute(string.Format(DynamicPizza.CostConfirm, cost));
                })
                .AddRemainingFields()
                .Message("Rating = {Rating:F1} and [{Rating:F2}]")
                .Confirm("Would you like a {Size}, {[{BYO.Crust} {BYO.Sauce} {BYO.Toppings}]} pizza delivered to {DeliveryAddress}?", isBYO)
                .Confirm("Would you like a {Size}, {&Signature} {Signature} pizza delivered to {DeliveryAddress}?", isSignature, dependencies: new string[] { "Size", "Kind", "Signature" })
                .Confirm("Would you like a {Size}, {&GourmetDelite} {GourmetDelite} pizza delivered to {DeliveryAddress}?", isGourmet)
                .Confirm("Would you like a {Size}, {&Stuffed} {Stuffed} pizza delivered to {DeliveryAddress}?", isStuffed)
                .OnCompletion(async (session, pizza) => Console.WriteLine("{0}", pizza))
                .Build();
            if (localize)
            {
                using (var stream = new FileStream("pizza-" + Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName + ".resx", FileMode.Open))
                using (var reader = new ResXResourceReader(stream))
                {
                    IEnumerable<string> missing, extra;
                    form.Localize(reader.GetEnumerator(), out missing, out extra);
                }
            }
            return form;
        }
Esempio n. 18
0
        public static IForm <InterviewModel> BuildForm()
        {
            var builder = new FormBuilder <InterviewModel>()
                          .Field(new FieldReflector <InterviewModel>(nameof(CompanyName))
                                 .SetType(null)
                                 .SetPrompt(new PromptAttribute("Interviewing with:{||}")
            {
                ChoiceStyle = ChoiceStyleOptions.Carousel
            })
                                 .SetAllowsMultiple(false)
                                 .SetDefine(async(state, field) =>
            {
                var companies = await GetCompanies();
                foreach (var company in companies)
                {
                    field
                    .AddDescription(company.Id.ToString(), company.Name, company.Url)
                    .AddTerms(company.Id.ToString(), company.Id.ToString(), company.Name);
                }
                field.Template(TemplateUsage.EnumSelectOne).ChoiceStyle = ChoiceStyleOptions.Carousel;
                return(true);
            }))
                          .Field(new FieldReflector <InterviewModel>(nameof(Q1))
                                 .SetDefine(async(state, field) =>
            {
                field.SetPrompt(
                    new PromptAttribute(await GetQuestion(state.CompanyName, 1))
                {
                    ChoiceStyle = ChoiceStyleOptions.AutoText
                });
                return(true);
            }))

                          .Field(new FieldReflector <InterviewModel>(nameof(Q2))
                                 .SetDefine(async(state, field) =>
            {
                field.SetPrompt(
                    new PromptAttribute(await GetQuestion(state.CompanyName, 2))
                {
                    ChoiceStyle = ChoiceStyleOptions.AutoText
                });
                return(true);
            }))

                          .Field(new FieldReflector <InterviewModel>(nameof(Q3))
                                 .SetDefine(async(state, field) =>
            {
                field.SetPrompt(
                    new PromptAttribute(await GetQuestion(state.CompanyName, 3))
                {
                    ChoiceStyle = ChoiceStyleOptions.AutoText
                });
                return(true);
            }))

                          .Field(new FieldReflector <InterviewModel>(nameof(Q4))
                                 .SetDefine(async(state, field) =>
            {
                field.SetPrompt(
                    new PromptAttribute(await GetQuestion(state.CompanyName, 4))
                {
                    ChoiceStyle = ChoiceStyleOptions.AutoText
                });
                return(true);
            }))

                          //.Field(new FieldReflector<InterviewModel>(nameof(Q5))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 5))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))

                          //.Field(new FieldReflector<InterviewModel>(nameof(Q6))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 6))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))

                          //.Field(new FieldReflector<InterviewModel>(nameof(Q7))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 7))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))

                          //.Field(new FieldReflector<InterviewModel>(nameof(Q8))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 8))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          //.Field(new FieldReflector<InterviewModel>(nameof(Q9))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 9))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          //.Field(new FieldReflector<InterviewModel>(nameof(Q10))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 10))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          //.Field(new FieldReflector<InterviewModel>(nameof(Q11))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 11))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          //.Field(new FieldReflector<InterviewModel>(nameof(Q12))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 12))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          //.Field(new FieldReflector<InterviewModel>(nameof(Q13))
                          //    .SetDefine(async (state, field) =>
                          //    {
                          //        field.SetPrompt(
                          //            new PromptAttribute(await GetQuestion(state.CompanyName, 13))
                          //            {
                          //                ChoiceStyle = ChoiceStyleOptions.AutoText
                          //            });
                          //        return true;
                          //    }))
                          .AddRemainingFields()
                          .Confirm("Here is a short review of all your answers. Is this right?\n{*}{||}")
                          .OnCompletion(Process)
                          .Build();

            return(builder);
        }
Esempio n. 19
0
            public Panel(ObjectInfo info)
            {
                this._info = info;

                var obj = client.With<IAnalogInput>(_info.DeviceInstance, _info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, ai => ai.ObjectName))
                        .AddRow(
                            createLabel(Constants.DeviceTypeLabel),
                            bindEditor(obj, ai => ai.DeviceType, enabled: true))
                        .End()
                    .AddGroup(Constants.AdditionalPropertiesHeader)
                        .AddRow(
                            createLabel(Constants.PresentValueLabel),
                            bindEditor(obj, ai => ai.PresentValue),
                            createLabel(Constants.UnitsLabel),
                            bindEditor(obj, ai => ai.Units))
                        .AddRow(
                            createLabel(Constants.CovIncrementLabel),
                            bindEditor(obj, ai => ai.CovIncrement),
                            createLabel(Constants.DeadbandLabel),
                            bindEditor(obj, ai => ai.Deadband))
                        .AddRow(
                            createLabel(Constants.LowLimitLabel),
                            bindEditor(obj, ai => ai.LowLimit),
                            createLabel(Constants.HighLimitLabel),
                            bindEditor(obj, ai => ai.HighLimit))
                        .AddRow(
                            createLabel(Constants.MinPresValueLabel),
                            bindEditor(obj, ai => ai.MinPresValue, enabled: false),
                            createLabel(Constants.MaxPresValueLabel),
                            bindEditor(obj, ai => ai.MaxPresValue, enabled: false))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 20
0
        //IForm class to ask users for unprovided information
        private static IForm <DeviceOrder2> BuildForm()
        {
            var builder = new FormBuilder <DeviceOrder2>();

            /*
             * //Check whether has(feature) variables defined in Device.cs are "yes"
             * ActiveDelegate<DeviceOrder> hasBrand = (device) => device.hasBrand == PreferenceOptions.yes;
             *
             * ActiveDelegate<DeviceOrder> hasPrice = (device) => device.hasPrice== PreferenceOptions.yes;
             * ActiveDelegate<DeviceOrder> noPrice = (device) => device.hasPrice == PreferenceOptions.no;
             * ActiveDelegate<DeviceOrder> needPrice = (device) => device.needPrice == PreferenceOptions.yes;
             *
             * ActiveDelegate<DeviceOrder> hasRAM = (device) => device.hasRAM == PreferenceOptions.yes;
             * ActiveDelegate<DeviceOrder> noRAM = (device) => device.hasRAM == PreferenceOptions.no;
             * ActiveDelegate<DeviceOrder> needRAM = (device) => device.needRAM == PreferenceOptions.yes;
             *
             * ActiveDelegate<DeviceOrder> hasHD = (device) => device.hasHD == PreferenceOptions.yes;
             * ActiveDelegate<DeviceOrder> noHD = (device) => device.hasHD == PreferenceOptions.no;
             * ActiveDelegate<DeviceOrder> needHD = (device) => device.needHD == PreferenceOptions.yes;
             *
             * ActiveDelegate<DeviceOrder> hasProcessor = (device) => device.hasProcessor == PreferenceOptions.yes;
             */

            //MessageDelegate<DeviceOrder> confirm_message = (device) => Task< new PromptAttribute(device.ToString())>;

            return(builder
                   //.Field("hasBrand")
                   .Field("Brand_value")

                   //.Field(nameof(DeviceOrder.model))

                   //.Field("hasPrice")
                   //.Field("price_relation", hasPrice)
                   //.Field("price_value", hasPrice)

                   //.Field("needPrice",noPrice)
                   .Field("price_range")
                   .Field("type_value")
                   //.Field("hasProcessor")
                   //.Field("Processor_value", hasProcessor)

                   //.Field("hasRAM")
                   //.Field("RAM_relation", hasRAM)
                   //.Field("RAM_value", hasRAM)

                   //.Field("needRAM", noRAM)
                   //.Field("RAM_range", needRAM)

                   //.Field("hasHD")
                   //.Field("HD_relation", hasHD)
                   //.Field("HD_value", hasHD)

                   //.Field("needHD", noHD)
                   //.Field("HD_range", needHD)

                   //.Field("hasGC")

                   //.Field(nameof(DeviceOrder.usage))
                   //.AddRemainingFields()
                   .Confirm("你滿意啱啱輸入嘅要求? 滿意,輸入'yes',要修改,輸入'no'")
                   //.Confirm("Would you like a\r\n Brand: {Brand_value},\r\n Model: {model},\r\n Price: {price_relation} {price_value},\r\n Processor: {Processor_value},\r\n RAM: {RAM_relation} {RAM_value},\r\n RAM Size Range: {RAM_range},\r\n Hard Disk: {HD_relation} {HD_value},\r\n Graphic Card: {hasGC},\r\n Usage: {usage} device?", hasPrice)
                   //.Confirm("Would you like a\r\n Brand: {Brand_value},\r\n Model: {model},\r\n Price Range: {price_range},\r\n Processor: {Processor_value},\r\n RAM: {RAM_relation} {RAM_value},\r\n RAM Size Range: {RAM_range},\r\n Hard Disk: {HD_relation} {HD_value},\r\n Graphic Card: {hasGC},\r\n Usage: {usage} device?",noPrice)

                   /*
                    * .Confirm((state) =>
                    * {
                    *  return new PromptAttribute($"Total for your sandwich is {cost:C2} is that ok?");
                    *
                    * })
                    */

                   .Build()
                   );
        }
Esempio n. 21
0
        public static IForm<MillionaireGame> BuildForm()
        {
            IForm<MillionaireGame> formGame = new FormBuilder<MillionaireGame>()
                .Message("Let's play, \"Who wants to be a millionaire?\"")
                .Message("Oh the irony...")
                .Field(nameof(QuestionOne), validate: async (state, response) =>
                {
                    QuestionOneEnum choice = (QuestionOneEnum)response;

                    var result = new ValidateResult()
                    {
                        IsValid = choice == QuestionOneEnum.Tax,
                        Feedback = choice == QuestionOneEnum.Tax ? "That's the correct answer!" : "That's incorrect I'm afraid..",
                        Value = response
                    };

                    if (!result.IsValid)
                    {
                        throw new FormCanceledException("1", null);
                    }

                    return result;
                })
                .Field(nameof(QuestionTwo), validate: async (state, response) =>
                {
                    QuestionTwoEnum choice = (QuestionTwoEnum)response;

                    var result = new ValidateResult()
                    {
                        IsValid = choice == QuestionTwoEnum.Terminator,
                        Feedback = choice == QuestionTwoEnum.Terminator ? "You are doing well!" : "That's incorrect I'm afraid..",
                        Value = response
                    };

                    if (!result.IsValid)
                    {
                        throw new FormCanceledException("2", null);
                    }

                    return result;
                })
                .Field(nameof(QuestionThree), validate: async (state, response) =>
                {
                    QuestionThreeEnum choice = (QuestionThreeEnum)response;

                    var result = new ValidateResult()
                    {
                        IsValid = choice == QuestionThreeEnum.Cables,
                        Feedback = choice == QuestionThreeEnum.Cables ? "Well that answer was obvious. Congratulations!" : "That's incorrect I'm afraid..",
                        Value = response
                    };

                    if (!result.IsValid)
                    {
                        throw new FormCanceledException("3", null);
                    }

                    return result;
                })
                .Field(nameof(QuestionFour), validate: async (state, response) =>
                {
                    QuestionFourEnum choice = (QuestionFourEnum)response;

                    var result = new ValidateResult()
                    {
                        IsValid = choice == QuestionFourEnum.Elbow,
                        Feedback = choice == QuestionFourEnum.Elbow ? "We have a genius here! That's correct!" : "That's incorrect I'm afraid..",
                        Value = response
                    };

                    if (!result.IsValid)
                    {
                        throw new FormCanceledException("4", null);
                    }

                    return result;
                })
                .Field(nameof(QuestionFive), validate: async (state, response) =>
                {
                    QuestionFiveEnum choice = (QuestionFiveEnum)response;

                    var result = new ValidateResult()
                    {
                        IsValid = choice == QuestionFiveEnum.Pun,
                        Feedback = choice == QuestionFiveEnum.Pun ? "Well this has been pun. You've done really well!" : "That's incorrect I'm afraid..",
                        Value = response
                    };

                    if (!result.IsValid)
                    {
                        throw new FormCanceledException("5", null);
                    }

                    return result;
                })
                .AddRemainingFields()
                .Build();

            return formGame;
        }
Esempio n. 22
0
        public virtual JObject GetAlpaca(DataSourceContext context, bool schema, bool options, bool view)
        {
            var fb = new FormBuilder(new FolderUri(context.TemplateFolder));

            return(fb.BuildForm("", context.CurrentCultureCode));
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            // TestValidate();
            var callDebug =
                Chain
                .From(() => new PromptDialog.PromptString("Locale?", null, 1))
                .ContinueWith <string, Choices>(async(ctx, locale) =>
            {
                Locale = await locale;
                CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(Locale);
                CultureInfo.CurrentCulture   = CultureInfo.CurrentUICulture;
                return(new FormDialog <Choices>(new Choices(), () =>
                {
                    var builder = new FormBuilder <Choices>();
                    builder.Configuration.DefaultPrompt.ChoiceStyle = ChoiceStyleOptions.AutoText;
                    return builder.AddRemainingFields().Build();
                }
                                                , FormOptions.PromptInStart));
            })
                .ContinueWith <Choices, object>(async(context, result) =>
            {
                Choices choices;
                try
                {
                    choices = await result;
                }
                catch (Exception error)
                {
                    await context.PostAsync(error.ToString());
                    throw;
                }

                switch (choices.Choice)
                {
                case DebugOptions.AnnotationsAndNumbers:
                    return(MakeForm(() => PizzaOrder.BuildForm()));

                case DebugOptions.AnnotationsAndNoNumbers:
                    return(MakeForm(() => PizzaOrder.BuildForm(noNumbers: true)));

                case DebugOptions.AnnotationsAndButtons:
                    return(MakeForm(() => PizzaOrder.BuildForm(style: ChoiceStyleOptions.Auto)));

                case DebugOptions.NoAnnotations:
                    return(MakeForm(() => PizzaOrder.BuildForm(noNumbers: true, ignoreAnnotations: true)));

                case DebugOptions.NoFieldOrder:
                    return(MakeForm(() => new FormBuilder <PizzaOrder>().Build()));

                case DebugOptions.WithState:
                    return(new FormDialog <PizzaOrder>(new PizzaOrder()
                    {
                        Size = SizeOptions.Large, Kind = PizzaOptions.BYOPizza
                    },
                                                       () => PizzaOrder.BuildForm(),
                                                       options: FormOptions.PromptInStart | FormOptions.PromptFieldsWithValues,
                                                       entities: new Luis.Models.EntityRecommendation[] {
                        new Luis.Models.EntityRecommendation("DeliveryAddress", entity: "2"),
                        new Luis.Models.EntityRecommendation("Signature", entity: "Hawaiian"),
                        new Luis.Models.EntityRecommendation("BYO.Toppings", entity: "onions"),
                        new Luis.Models.EntityRecommendation("BYO.Toppings", entity: "peppers"),
                        new Luis.Models.EntityRecommendation("BYO.Toppings", entity: "ice"),
                        new Luis.Models.EntityRecommendation("NumberOfPizzas", entity: "5"),
                        new Luis.Models.EntityRecommendation("NotFound", entity: "OK")
                    }
                                                       ));

                case DebugOptions.Localized:
                    {
                        var form = PizzaOrder.BuildForm();
                        using (var stream = new FileStream("pizza.resx", FileMode.Create))
                            using (var writer = new ResXResourceWriter(stream))
                            {
                                form.SaveResources(writer);
                            }
                        Process.Start(new ProcessStartInfo(@"RView.exe", "pizza.resx -c " + Locale)
                        {
                            UseShellExecute = false, CreateNoWindow = true
                        }).WaitForExit();
                        return(MakeForm(() => PizzaOrder.BuildForm(false, false, true)));
                    }

                case DebugOptions.SimpleSandwichBot:
                    return(MakeForm(() => FormTest.Models.SimpleSandwich.SandwichOrder.BuildForm()));

                case DebugOptions.AnnotatedSandwichBot:
                    return(MakeForm(() => FormTest.Models.AnnotatedSandwich.AnnotatedSandwichOrder.BuildLocalizedForm()));

                case DebugOptions.JSONSandwichBot:
                    return(MakeForm(() => FormTest.Models.AnnotatedSandwich.AnnotatedSandwichOrder.BuildJsonForm()));

                default:
                    throw new NotImplementedException();
                }
            })
                .Do(async(context, result) =>
            {
                try
                {
                    var item = await result;
                    Debug.WriteLine(item);
                }
                catch (FormCanceledException e)
                {
                    if (e.InnerException == null)
                    {
                        await context.PostAsync($"Quit on {e.Last} step.");
                    }
                    else
                    {
                        await context.PostAsync($"Exception {e.Message} on step {e.Last}.");
                    }
                }
            })
                .DefaultIfException()
                .Loop();

            Interactive(callDebug).GetAwaiter().GetResult();
        }
Esempio n. 24
0
        /// <summary>
        /// Creates a playlist with given name
        /// </summary>
        /// <param name="playlistName">Name of playlist</param>
        public void AddPlaylist(String playlistName)
        {
            String jsonString = "{\"title\":\"" + playlistName + "\"}";

            JsonConvert.SerializeObject(jsonString);

            Dictionary<String, String> fields = new Dictionary<String, String>
            {
               {"json", jsonString}
            };

            FormBuilder builder = new FormBuilder();
            builder.AddFields(fields);
            builder.Close();

            client.UploadDataAsync(new Uri("https://play.google.com/music/services/addplaylist"), builder, PlaylistCreated);
        }
Esempio n. 25
0
        //{"deleteId":"c790204e-1ee2-4160-9e25-7801d67d0a16"}
        public void DeletePlaylist(String id)
        {
            String jsonString = "{\"id\":\"" + id + "\"}";

            JsonConvert.SerializeObject(jsonString);

            Dictionary<String, String> fields = new Dictionary<String, String>
            {
               {"json", jsonString}
            };

            FormBuilder builder = new FormBuilder();
            builder.AddFields(fields);
            builder.Close();

            client.UploadDataAsync(new Uri("https://play.google.com/music/services/deleteplaylist"), builder, PlaylistDeleted);
        }
Esempio n. 26
0
        public void RemoveTopicToFormShouldWork()
        {
            // Arrange
            var expectedCount = 0;
            var topic = new TopicBuilder().Build();
            var form = new FormBuilder().WithTopic(topic).Build();

            // Act
            form.Topics.Remove(topic);
            var actualCount = form.Topics.Count();
            var actualTopic = form.Topics.FirstOrDefault();

            // Assert
            Assert.AreEqual(expectedCount, actualCount);
            Assert.AreSame(null, actualTopic);
        }
Esempio n. 27
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<IAnalogValue>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, av => av.ObjectName)
                        )
                        .Split()
                        .AddRow(
                            createLabel(Constants.PresentValueLabel),
                            bindEditor(obj, av => av.PresentValue),
                            createLabel(Constants.UnitsLabel),
                            bindEditor(obj, av => av.Units))
                        .End()
                    .AddGroup(Constants.AdditionalPropertiesHeader)
                        .AddRow(
                            createLabel(Constants.LowLimitLabel),
                            bindEditor(obj, av => av.LowLimit),
                            createLabel(Constants.HighLimitLabel),
                            bindEditor(obj, av => av.HighLimit))
                        .AddRow(
                            createLabel(Constants.DeadbandLabel),
                            bindEditor(obj, av => av.Deadband, enabled: false),
                            createLabel(Constants.CovIncrementLabel),
                            bindEditor(obj, av => av.CovIncrement, enabled: false))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 28
0
        //private static ConcurrentDictionary<CultureInfo, IForm<AppoinmentForm>> _forms = new ConcurrentDictionary<CultureInfo, IForm<AppoinmentForm>>();

        public static IForm <AppoinmentForm> BuildForm()
        {
            OnCompletionAsyncDelegate <AppoinmentForm> processOrder = async(context, state) =>
            {
                await context.PostAsync("We will send you the status.");
            };
            CultureInfo ci = new CultureInfo("en");

            Thread.CurrentThread.CurrentCulture   = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
            FormBuilder <AppoinmentForm> form = new FormBuilder <AppoinmentForm>();

            return(form.Message("Fill the information for schedule an appoinment, please")
                   .Field("Office", validate:
                          async(state, value) =>
            {
                ValidateResult vResult = new ValidateResult();
                List <ACFAppointment> listAppoinments = await Services.AppoinmentService.GetAppoinments();
                StringBuilder response = new StringBuilder();
                if (listAppoinments.Count <= 0)
                {
                    response.Append("No se encontraron items ").ToString();
                    vResult.Feedback = string.Format(response.ToString());
                    vResult.IsValid = false;
                }
                else
                {
                    foreach (ACFAppointment item in listAppoinments)
                    {
                        response.Append(item.Name + ", \n");
                    }
                    //vResult.Feedback = string.Format(response.ToString());
                    vResult.Feedback = "sdas";
                    vResult.Value = "asdas";
                    vResult.IsValid = true;
                }
                return vResult;
            })
                   .Field(new FieldReflector <AppoinmentForm>(nameof(Service))
                          .SetType(null)
                          .SetDefine((state, field) =>
            {
                string office;
                if (!String.IsNullOrEmpty(state.Office))
                {
                    office = state.Office.ToString();
                }
                if (GetServicesOtempues().Count > 0)
                {
                    foreach (var prod in GetServicesOtempues())
                    {
                        field
                        .AddDescription(prod.Name, prod.Name)
                        .AddTerms(prod.Name, prod.Name);
                    }
                    return Task.FromResult(true);
                }
                else
                {
                    return Task.FromResult(false);
                }
            }))
                   .Field("StartDate", validate:
                          async(state, response) =>
            {
                ValidateResult vResult = new ValidateResult();
                var result = new ValidateResult {
                    IsValid = true, Value = response
                };
                var address = (response as string).Trim();

                List <OTempus.Library.Class.Calendar> listCalendars = new List <OTempus.Library.Class.Calendar>();
                if (GetServicesOtempues().Count > 0)
                {
                    //Service two and date...
                    listCalendars = GetCalendar("2", DateTime.Today);
                }
                List <ACFAppointment> listAppoinments = await Services.AppoinmentService.GetAppoinments();
                List <CalendarGetSlotsResults> listGetAvailablesSlots = new List <CalendarGetSlotsResults>();
                StringBuilder responses = new StringBuilder();
                responses.Append("No existen slots").ToString();
                vResult.Feedback = string.Format(responses.ToString());

                vResult.IsValid = false;
                if (listCalendars.Count > 0)
                {
                    listGetAvailablesSlots = AppoinmentService.GetAvailablesSlots(listCalendars[0].Id);
                    bool availablesSlots = true;
                    foreach (OTempus.Library.Class.CalendarGetSlotsResults calendarSlots in listGetAvailablesSlots)
                    {
                        //The status 0 is available, the status 4 is locked, 1 reserved
                        if (calendarSlots.Status != 0)
                        {
                            availablesSlots = false;
                            //In the example here we reserve the first that we find
                            //AppoinmentService.ReserveSlots(listCalendars[0].Id,calendarSlots.OrdinalNumber,1);

                            /*Example to freeup slots*/
                            AppoinmentService.FreeUpSlots(listCalendars[0].Id, calendarSlots.OrdinalNumber);
                            /*Example to lock slots*/
                            //AppoinmentService.LockSlots(listCalendars[0].Id, calendarSlots.OrdinalNumber);
                        }
                    }
                    if (availablesSlots)
                    {
                        vResult.Feedback = "Si hay slots";
                        vResult.Value = "slot 1";
                        vResult.IsValid = true;
                    }
                    else
                    {
                        responses.Append("No existen slots disponibles").ToString();
                        vResult.Feedback = string.Format(response.ToString());
                        vResult.IsValid = false;
                    }
                }
                return vResult;
            })
                   .Field(new FieldReflector <AppoinmentForm>(nameof(Calendar))
                          .SetType(null)
                          .SetDefine((state, field) =>
            {
                string date;
                string service;
                if (!String.IsNullOrEmpty(state.StartDate) && !String.IsNullOrEmpty(state.Service))
                {
                    date = state.StartDate.ToString();
                    service = state.Service.ToString();
                    if (GetServicesOtempues().Count > 0)
                    {
                        // foreach (var prod in GetCalendar("2", "9/19/2017"))
                        foreach (var prod in GetCalendar(service, DateTime.Today))
                        {
                            field
                            .AddDescription(prod.CalendarDate.ToString(), prod.CalendarDate.ToString())
                            .AddTerms(prod.CalendarDate.ToString(), prod.CalendarDate.ToString());
                        }
                        return Task.FromResult(true);
                    }
                    else
                    {
                        return Task.FromResult(false);
                    }
                }

                return Task.FromResult(false);
            }))

                   /*.Field(nameof(Calendar),validate: async (state, value) =>
                    * {
                    * ValidateResult vResult = new ValidateResult();
                    * var values = ((List<object>)value).OfType<Appoinment>();
                    * var result = new ValidateResult { IsValid = true, Value = values };
                    *
                    *
                    * List<Appoinment> listAppoinments = await AppoinmentService.GetAppoinments();
                    * StringBuilder response = new StringBuilder();
                    * //vResult.Feedback = string.Format(response.ToString());
                    * // vResult.Feedback = state.Office.ToString();
                    * vResult.IsValid = true;
                    * vResult.Value = state.Office.ToString() + " " + state.Service.ToString();
                    * vResult.Feedback = state.Office.ToString() + " " + state.Service.ToString();
                    * return vResult;
                    * })*/
                   .Field("Test", validate:
                          async(state, value) =>
            {
                string office = state.Calendar.ToString();
                ValidateResult vResult = new ValidateResult();
                List <ACFAppointment> listAppoinments = await AppoinmentService.GetAppoinments();
                StringBuilder response = new StringBuilder();
                //vResult.Feedback = string.Format(response.ToString());
                // vResult.Feedback = state.Office.ToString();
                vResult.IsValid = true;
                vResult.Value = state.Office.ToString() + " " + state.Service.ToString();
                vResult.Feedback = state.Office.ToString() + " " + state.Service.ToString();
                return vResult;
            })
                   .Field(nameof(Color))

                   .Confirm("Are you selected the office: {Office} \n, the color: {Color}  \n  And the Service {Service}? (yes/no)")
                   .AddRemainingFields()
                   .Message("The process for create the appoinment has been started!")
                   .OnCompletion(processOrder)
                   .Build());
        }
Esempio n. 29
0
 public void AddSelectTest()
 {
     FormBuilder target = new FormBuilder
     {
         Form = new Form
         {
             Elements = new List<IElement>()
         }
     };
     string Name = "Test";
     FormBuilder Expected = target;
     Expected.Form.Elements.Add(new Select(Name));
     target.AddSelect(Name);
     Assert.AreEqual(target, Expected);
 }
 public static IForm<SandwichOrder> BuildLocalizedForm()
 {
     var culture = Thread.CurrentThread.CurrentUICulture;
     IForm<SandwichOrder> form;
     if (!_forms.TryGetValue(culture, out form))
     {
         OnCompletionAsyncDelegate<SandwichOrder> processOrder = async (context, state) =>
                         {
                             await context.PostAsync(DynamicSandwich.Processing);
                         };
         // Form builder uses the thread culture to automatically switch framework strings
         // and also your static strings as well.  Dynamically defined fields must do their own localization.
         form = new FormBuilder<SandwichOrder>()
                 .Message("Welcome to the sandwich order bot!")
                 .Field(nameof(Sandwich))
                 .Field(nameof(Length))
                 .Field(nameof(Bread))
                 .Field(nameof(Cheese))
                 .Field(nameof(Toppings),
                     validate: async (state, value) =>
                     {
                         var values = ((List<object>)value).OfType<ToppingOptions>();
                         var result = new ValidateResult { IsValid = true, Value = values };
                         if (values != null && values.Contains(ToppingOptions.Everything))
                         {
                             result.Value = (from ToppingOptions topping in Enum.GetValues(typeof(ToppingOptions))
                                             where topping != ToppingOptions.Everything && !values.Contains(topping)
                                             select topping).ToList();
                         }
                         return result;
                     })
                 .Message("For sandwich toppings you have selected {Toppings}.")
                 .Field(nameof(SandwichOrder.Sauces))
                 .Field(new FieldReflector<SandwichOrder>(nameof(Specials))
                     .SetType(null)
                     .SetActive((state) => state.Length == LengthOptions.FootLong)
                     .SetDefine(async (state, field) =>
                         {
                             field
                                 .AddDescription("cookie", DynamicSandwich.FreeCookie)
                                 .AddTerms("cookie", Language.GenerateTerms(DynamicSandwich.FreeCookie, 2))
                                 .AddDescription("drink", DynamicSandwich.FreeDrink)
                                 .AddTerms("drink", Language.GenerateTerms(DynamicSandwich.FreeDrink, 2));
                             return true;
                         }))
                 .Confirm(async (state) =>
                     {
                         var cost = 0.0;
                         switch (state.Length)
                         {
                             case LengthOptions.SixInch: cost = 5.0; break;
                             case LengthOptions.FootLong: cost = 6.50; break;
                         }
                         return new PromptAttribute(string.Format(DynamicSandwich.Cost, cost));
                     })
                 .Field(nameof(SandwichOrder.DeliveryAddress),
                     validate: async (state, response) =>
                     {
                         var result = new ValidateResult { IsValid = true, Value = response };
                         var address = (response as string).Trim();
                         if (address.Length > 0 && address[0] < '0' || address[0] > '9')
                         {
                             result.Feedback = DynamicSandwich.BadAddress;
                             result.IsValid = false;
                         }
                         return result;
                     })
                 .Field(nameof(SandwichOrder.DeliveryTime), "What time do you want your sandwich delivered? {||}")
                 .Confirm("Do you want to order your {Length} {Sandwich} on {Bread} {&Bread} with {[{Cheese} {Toppings} {Sauces}]} to be sent to {DeliveryAddress} {?at {DeliveryTime:t}}?")
                 .AddRemainingFields()
                 .Message("Thanks for ordering a sandwich!")
                 .OnCompletion(processOrder)
                 .Build();
         _forms[culture] = form;
     }
     return form;
 }
Esempio n. 31
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<IBinaryInput>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, bi => bi.ObjectName)
                        )
                        .AddRow(
                            createLabel(Constants.DeviceTypeLabel),
                            bindEditor(obj, bi => bi.DeviceType)
                        )
                        .Split()
                        .AddRow(
                            createLabel(Constants.PresentValueLabel),
                            bindEditor(obj, bi => bi.PresentValue),
                            createLabel(Constants.OutOfServiceLabel),
                            bindEditor(obj, bi => bi.OutOfService))
                        .End()
                    .AddGroup(Constants.AdditionalPropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ChangeOfStateCountLabel),
                            bindEditor(obj, bi => bi.ChangeOfStateCount, enabled: false),
                            createLabel(Constants.ChangeOfStateTimeLabel),
                            bindEditor(obj, bi => bi.ChangeOfStateTime, enabled: false))
                        .AddRow(
                            createLabel(Constants.ActiveTextLabel),
                            bindEditor(obj, bi => bi.ActiveText),
                            createLabel(Constants.InactiveTextLabel),
                            bindEditor(obj, bi => bi.InactiveText))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 32
0
 public HttpWebRequest UploadDataAsync(Uri address, FormBuilder builder, RequestCompletedEventHandler complete, int timeout = 10000)
 {
     return UploadDataAsync(address, builder.ContentType, builder.GetBytes(), timeout, complete, null);
 }
Esempio n. 33
0
            public Panel(ObjectInfo info)
            {
                var obj = client.With<IAnalogOutput>(
                    info.DeviceInstance,
                    info.ObjectIdentifier);

                var form = new FormBuilder()
                    .AddGroup(Constants.CorePropertiesHeader)
                        .AddRow(
                            createLabel(Constants.ObjectNameLabel),
                            bindEditor(obj, ao => ao.ObjectName)
                        )
                        .AddRow(
                            createLabel(Constants.DeviceTypeLabel),
                            bindEditor(obj, ao => ao.DeviceType)
                        )
                        .Split()
                        .AddRow(
                            createLabel(Constants.PresentValueLabel),
                            bindEditor(obj, ao => ao.PresentValue),
                            createLabel(Constants.UnitsLabel),
                            bindEditor(obj, ao => ao.Units))
                        .End()
                    .AddGroup(Constants.AdditionalPropertiesHeader)
                        .AddRow(
                            createLabel(Constants.LowLimitLabel),
                            bindEditor(obj, ao => ao.LowLimit),
                            createLabel(Constants.HighLimitLabel),
                            bindEditor(obj, ao => ao.HighLimit))
                        .AddRow(
                            createLabel(Constants.MinPresValueLabel),
                            bindEditor(obj, ao => ao.MinPresValue, enabled: false),
                            createLabel(Constants.MaxPresValueLabel),
                            bindEditor(obj, ao => ao.MaxPresValue, enabled: false))
                        .AddRow(
                            createLabel(Constants.ResolutionLabel),
                            bindEditor(obj, ao => ao.Resolution, enabled: false),
                            createLabel(Constants.CovIncrementLabel),
                            bindEditor(obj, ao => ao.CovIncrement, enabled: false))
                        .End()
                    .End();

                this.Content = form.Root;
            }
Esempio n. 34
0
        public static IForm <ChooseFilmForm> BuildMoviesForm()
        {
            IFormBuilder <ChooseFilmForm> builder = new FormBuilder <ChooseFilmForm>()
                                                    .Message("Вот фильмы идущие на этой неделе:")
                                                    .Field(new FieldReflector <ChooseFilmForm>(nameof(MovieName)
                                                                                               )
                                                           .SetType(null)
                                                           .SetDefine((state, field) =>
            {
                foreach (var prod in GetMovies())
                {
                    field
                    .AddDescription(prod, prod)
                    .AddTerms(prod, prod);
                }
                var exit = "Выход";
                field.AddDescription(exit, exit).AddTerms(exit, exit);
                return(Task.FromResult(true));
            })
                                                           .SetActive((state) =>
            {
                string s = state.MovieName;
                return(true);
            })
                                                           .SetNext((value, state) =>
            {
                var nextStep = new NextStep();
                return(nextStep);
            })
                                                           .SetValidate(
                                                               validate: async(state, response) =>
            {
                var result = new ValidateResult {
                    IsValid = false, Value = response
                };
                var movie = (response as string);
                foreach (var movieName in GetMovies())
                {
                    if (movie.Contains(movieName))
                    {
                        result.Feedback = "Запрос корректен";
                        result.IsValid  = true;
                        break;
                    }
                    if (movie.Contains("Выход"))
                    {
                        result.Feedback = "Произвожу выход...";
                        result.IsValid  = true;
                        break;
                    }
                }
                if (!result.IsValid)
                {
                    result.Feedback = "Случилась непредвиденная ошибка!!! Производится выход";
                    throw new OperationCanceledException();
                }
                return(result);
            })
                                                           )
                                                    .AddRemainingFields();

            return(builder.Build());
        }