Example #1
0
        public void AddOptions_Enum_SelectedValues()
        {
            var tag = new SelectTag()
                      .AddOptions(
                OptionsList.CreateForEnum <Enum1>()
                .SelectedValues(new string[]
            {
                Enum1.Option2.ToString()
            })
                .Configure((x, op) => op.Data("customdata", x.Value)));

            Assert.Equal(2, tag.Children.Count());

            var firstChild  = tag.Children.First();
            var secondChild = tag.Children.Skip(1).First();

            Assert.Equal("Option1", firstChild.Text());
            Assert.True(firstChild.ValueIsEqual(Enum1.Option1.ToString()));
            Assert.False(firstChild.HasAttr("selected"));
            Assert.Equal(1, firstChild.Data("customdata"));
            Assert.Equal("Option2", secondChild.Text());
            Assert.True(secondChild.ValueIsEqual(Enum1.Option2.ToString()));
            Assert.True(secondChild.HasAttr("selected"));
            Assert.Equal(2, secondChild.Data("customdata"));
        }
        public void Select_Null_DefaultValue()
        {
            var model = new Model1()
            {
                PropInt = null
            };
            var helper = new HtmlTagHelper(model);

            var name = "PropInt";
            var tag  = helper.Select(
                name,
                OptionsList.CreateForEnum <Enum1>(),
                defaultValue: 2);

            AssertValid(tag, "select", name);

            var firstChild  = tag.Children.First();
            var secondChild = tag.Children.Skip(1).First();
            var thirdChild  = tag.Children.Skip(2).First();

            Assert.Equal("Option1", firstChild.Text());
            Assert.True(firstChild.ValueIsEqual(1));
            Assert.False(firstChild.HasAttr("selected"));
            Assert.Equal("Option2", secondChild.Text());
            Assert.True(secondChild.ValueIsEqual(2));
            Assert.True(secondChild.HasAttr("selected"));
            Assert.Equal("Option3", thirdChild.Text());
            Assert.True(thirdChild.ValueIsEqual(3));
            Assert.False(thirdChild.HasAttr("selected"));
        }
Example #3
0
        public User()
        {
#if DEBUG
            Console.WriteLine("User.New");
#endif
            Name   = "NONAME";
            Team   = null;
            TeamId = -1;

            // TODO
            //live_game_reset(&new.live_game, NULL, FALSE);

            Events  = new List <Event>();
            History = new List <UserHistory>();
            Options = new OptionsList();
            //TODO Options.list = null;
            //TODO Options.datalist = null;

            Sponsor = new UserSponsor();

            // TODO
            //new.youth_academy.players = g_array_new(FALSE, FALSE, sizeof(Player));
            //new.youth_academy.pos_pref = PLAYER_POS_ANY;
            //new.youth_academy.coach = QUALITY_AVERAGE;

            MemMatchesFile = null;
            MemMatches     = new List <MemMatch>();

            Bets[0]      = new List <BetUser>();
            Bets[1]      = new List <BetUser>();
            DefaultTeam  = new List <int>();
            DefaultStyle = 0;
            DefaultBoost = 0;
        }
        public void AddOptions_Enum_Localized()
        {
            var prevResource = Resources.Current;

            try
            {
                Resources.Register(new TypedClassResourceProvider(typeof(Enum1Resources)));

                var tag = new CheckBoxListTag(DEFAULT_NAME)
                          .AddOptions(
                    OptionsList.CreateForEnum <Enum1>()
                    .SelectedValue(2)
                    .Configure((x, op) => op.Data("customdata", x.Value)));

                Assert.Equal(2, tag.Options.Count());

                var firstChild  = tag.Options.First();
                var secondChild = tag.Options.Skip(1).First();

                AssertValidOption(firstChild, name: DEFAULT_NAME, display: "Option 1", value: 1, isChecked: false);
                AssertValidOption(secondChild, name: DEFAULT_NAME, display: "Option2", value: 2, isChecked: true);

                Assert.Equal(1, firstChild.Data("customdata"));
                Assert.Equal(2, secondChild.Data("customdata"));
            }
            finally
            {
                Resources.Register(prevResource);
            }
        }
Example #5
0
        public int Process()
        {
            //NumExpert = OptionsList[0].Count;
            //NumCriteria = PairComparisonList[0].Matrix.GetLength(0);
            //NumOptions = OptionsList[0][0].Matrix.GetLength(0);
            // Step3
            // калькуляция сводной таблицы
            double[,] summaryTable = CalculateSummaryTable(PairComparisonList);
            //Локальные приоритеты критериев
            var localPriority = CalculateLocalPriority(summaryTable);

            //Step4
            Validate(summaryTable, localPriority);
            //Step6
            List <double[]> summaryLocalPriorityOptions = OptionsList.Select(x => CalculateLocalPriority(CalculateSummaryTable(x))).ToList();
            var             result = summaryLocalPriorityOptions.Select((x, i) =>
                                                                        new
            {
                Val = x.Select(
                    (el, j) => el * localPriority[j]).Sum(),
                Index = i
            }).OrderByDescending(item => item.Val).FirstOrDefault()?.Index;

            return(result ?? -1);
        }
Example #6
0
 protected override bool Handle(ArgumentsList args, OptionsList opts)
 {
     logger.Debug($"Reloading the scene: {SceneManager.GetActiveScene().name}");
     SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
     logger.Debug($"Scene reloaded!");
     return(true);
 }
Example #7
0
        public void AddOptions_Enum_Localized()
        {
            var prevResource = Resources.Current;

            try
            {
                Resources.Register(new TypedClassResourceProvider(typeof(Enum1Resources)));

                var tag = new SelectTag()
                          .AddOptions(
                    OptionsList.CreateForEnum <Enum1>()
                    .SelectedValue(Enum1.Option2.ToString())
                    .Configure((x, op) => op.Data("customdata", x.Value)));

                Assert.Equal(2, tag.Children.Count());

                var firstChild  = tag.Children.First();
                var secondChild = tag.Children.Skip(1).First();

                Assert.Equal("Option 1", firstChild.Text());
                Assert.True(firstChild.ValueIsEqual(Enum1.Option1.ToString()));
                Assert.False(firstChild.HasAttr("selected"));
                Assert.Equal(1, firstChild.Data("customdata"));
                Assert.Equal("Option2", secondChild.Text());
                Assert.True(secondChild.ValueIsEqual(Enum1.Option2.ToString()));
                Assert.True(secondChild.HasAttr("selected"));
                Assert.Equal(2, secondChild.Data("customdata"));
            }
            finally
            {
                Resources.Register(prevResource);
            }
        }
        public void SelectFor_NotNull_DefaultValue()
        {
            var model = new Model1()
            {
                PropInt = 1
            };
            var helper = new HtmlTagHelper <Model1>(model);

            var propExpression = Expr((Model1 m) => m.PropInt);
            var tag            = helper.SelectFor(
                propExpression,
                OptionsList.CreateForEnum <Enum1>(),
                defaultValue: 2);

            AssertValid(tag, "select", "PropInt");

            var firstChild  = tag.Children.First();
            var secondChild = tag.Children.Skip(1).First();
            var thirdChild  = tag.Children.Skip(2).First();

            Assert.Equal("Option1", firstChild.Text());
            Assert.True(firstChild.ValueIsEqual(1));
            Assert.True(firstChild.HasAttr("selected"));
            Assert.Equal("Option2", secondChild.Text());
            Assert.True(secondChild.ValueIsEqual(2));
            Assert.False(secondChild.HasAttr("selected"));
            Assert.Equal("Option3", thirdChild.Text());
            Assert.True(thirdChild.ValueIsEqual(3));
            Assert.False(thirdChild.HasAttr("selected"));
        }
        public void Setup()
        {
            _ws.DefaultFontName = "Arial";
            _ws.DefaultFontSize = 30;
            _sourceChoices      = new OptionsList();
            AddSourceChoice("one", "1");
            AddSourceChoice("two", "2");
            AddSourceChoice("three", "3");
            AddSourceChoice("four", "4");
            AddSourceChoice("five", "5");

            _chosenItems = new OptionRefCollection(this);

            List <IWritingSystemDefinition> writingSystems = new List <IWritingSystemDefinition>();

            writingSystems.Add(_ws);

            _control = new ReferenceCollectionEditor <Option, string, OptionRef>(
                _chosenItems.Members,
                _sourceChoices.Options,
                writingSystems,
                CommonEnumerations.VisibilitySetting.Visible,
                new OptionDisplayAdaptor(_sourceChoices, _ws.Id),
                null);

            _control.Name = "refcontrol";
            _control.AlternateEmptinessHelper = _chosenItems;
        }
Example #10
0
        /** Load a file containing name - value pairs into
         * the specified array. */
        public static OptionsList LoadOptFile(string filename, bool sort)
        {
            // _logger.Debug("FileHelper.LoadOptFile");

            var    optionsList = new OptionsList();
            string path        = FindSupportFile(filename, false);

            string[] lines = File.ReadAllLines(path);
            foreach (string line in lines)
            {
                string optName = null, optValue = null;
                if (ParseOptLine(line, ref optName, ref optValue))
                {
                    optionsList.Add(optName, optValue);

                    if ((optName.EndsWith("_unix") && Variables.os_is_unix) ||
                        (optName.EndsWith("_win32") && !Variables.os_is_unix))
                    {
                        optName = optName.Remove(optName.IndexOf(Variables.os_is_unix ? "_unix" : "_win32"));
                        optionsList.Add(optName, optValue);
                    }
                }
            }

            if (sort)
            {
                optionsList.Sort();
            }

            return(optionsList);
        }
Example #11
0
        protected override bool Handle(ArgumentsList args, OptionsList opts)
        {
            logger.Log($"Loading scene {args["sceneName"]}");
            SceneManager.LoadScene(args["sceneName"]);

            return(true);
        }
Example #12
0
        private void WriteDisplayNameFieldForOption(IValueHolder <string> optionRef, string fieldName)
        {
            OptionsList list = WeSayWordsProject.Project.GetOptionsList(fieldName);

            if (list != null)
            {
                Option posOption = list.GetOptionFromKey(optionRef.Value);
                if (posOption == null)
                {
                    return;
                }
                if (posOption.Name == null)
                {
                    return;
                }

                LanguageForm[] labelForms =
//                        posOption.Name.GetOrderedAndFilteredForms(
                    posOption.Abbreviation.GetOrderedAndFilteredForms(
                        _viewTemplate.GetField(fieldName).WritingSystemIds);

                if (labelForms != null && labelForms.Length > 0)
                {
                    Writer.WriteStartElement("field");
                    Writer.WriteAttributeString("type",
                                                fieldName == "POS" ? "grammatical-info" : fieldName);
                    WriteLanguageFormsInWrapper(labelForms, "form", false);
                    Writer.WriteEndElement();
                }
            }
        }
Example #13
0
        public void SaveToFile()
        {
            Option x = new Option();

            x.Abbreviation.SetAlternative("a", "aabrev");
            x.Abbreviation.SetAlternative("b", "babrev");
            x.Key = "akey";
            x.Name.SetAlternative("a", "aname");
            x.Name.SetAlternative("b", "bname");

            Option y = new Option();

            y.Abbreviation.SetAlternative("a", "aabrev");
            y.Abbreviation.SetAlternative("b", "babrev");
            y.Key = "akey";
            y.Name.SetAlternative("a", "aname");
            y.Name.SetAlternative("b", "bname");

            OptionsList list = new OptionsList();

            list.Options.Add(x);
            list.Options.Add(y);

            string path = Path.GetTempFileName();

            list.SaveToFile(path);

            // Debug.WriteLine(xml);
            Load(path);
            Assert.AreEqual("aname", list.Options[1].Name.GetBestAlternative("a"));
        }
        public override void DataBind()
        {
            OptionsList.DataSource = this.FieldOptions;
            OptionsList.DataBind();

            base.DataBind();
        }
        public void Setup()
        {
            _ws = WritingSystemDefinition.Parse("qaa-x-qaa");
            _ws.DefaultFontName = "Arial";
            _ws.DefaultFontSize = (float)55.9;
            //            _createNewClickedFired=false;
            //            _valueChangedFired = false;
            _sourceChoices = new OptionsList();
            _choiceKeys    = new List <string>();
            AddSourceChoice("one", "1", "Notice, this is not the number two.");
            //nb: key 'two' in there
            AddSourceChoice("two", "2", "A description of two which includes the word duo.");
            AddSourceChoice("three",
                            "3",
                            "A description of this which includes the word trio and is not two.");

            _displayAdaptor = new OptionDisplayAdaptor(_sourceChoices, _ws.Id);
            _control        =
                new AutoCompleteWithCreationBox <Option, string>(
                    CommonEnumerations.VisibilitySetting.Visible, null);
            _control.Name             = "autobox";
            _control.Box.Items        = _sourceChoices.Options;
            _control.Box.ItemFilterer = _displayAdaptor.GetItemsToOffer;

            //leave for individual tests _control.CreateNewClicked += new EventHandler<CreateNewArgs>(_control_CreateNewClicked);
            _control.Box.ItemDisplayStringAdaptor = _displayAdaptor;
            _control.Box.WritingSystem            = _ws;
            _control.GetKeyValueFromValue         = _displayAdaptor.GetOptionFromKey;
            _control.GetValueFromKeyValue         = _displayAdaptor.GetKeyFromOption;
            _control.ValueChanged += _control_ValueChanged;

            _dataBeingEditted = new OptionRef();
        }
Example #16
0
        public void LoadFromFile()
        {
            string path = Path.GetTempFileName();

            File.WriteAllText(path,
                              @"<?xml version='1.0' encoding='utf-8'?><optionsList>
		                <option>
                            <key>verb</key>
			                <name>
				                <form ws='en'>verb</form>
				                <form ws='xy'>xyverb</form>
			                </name>
		                </option>
		                <option>
			                <key>noun</key>
			                <name>
				                <form ws='en'>noun</form>
				                <form ws='fr'>nom</form>
				                <form ws='es'>nombre</form>
				                <form ws='th'>นาม</form>
			                </name>
		                </option>
                 </optionsList>");

            OptionsList list = Load(path);

            File.Delete(path);
            Assert.AreEqual("verb", list.Options[0].Key);
            Assert.AreEqual("verb", list.Options[0].Name.GetBestAlternative("en"));
            Assert.AreEqual("xyverb", list.Options[0].Name.GetBestAlternative("xy"));
            Assert.AreEqual("noun", list.Options[1].Name.GetBestAlternative("en"));
        }
Example #17
0
        protected override bool Handle(ArgumentsList args, OptionsList opts)
        {
            StringBuilder str = new StringBuilder();

            var commandList = DevConsole.CommandList
                              .Where(x => !x.Value.IsSecretCommand)
                              .OrderBy(x => x.Key)
                              .ToDictionary(k => k.Key, v => v.Value);


            if (string.IsNullOrEmpty(args[""]))
            {
                var maxWidth = commandList
                               .Select(x => x.Key)
                               .OrderByDescending(x => x.Count())
                               .First()
                               .Length;

                foreach (var reg in commandList)
                {
                    str.AppendLine($"{reg.Key.PadRight(maxWidth)} - {reg.Value.Description}");
                }
            }
            else if (commandList.ContainsKey(args[""]))
            {
                str.AppendLine(commandList[args[""]].Help);
            }


            logger.Log(str.ToString());
            return(true);
        }
Example #18
0
        private static Control MakeOptionCollectionWidget(PalasoDataObject target, Field field)
        {
            OptionsList         availableOptions = WeSayWordsProject.Project.GetOptionsList(field, false);
            OptionRefCollection refsOfChoices    =
                target.GetOrCreateProperty <OptionRefCollection>(field.FieldName);
            IList <IWritingSystemDefinition> writingSystems =
                BasilProject.Project.WritingSystemsFromIds(field.WritingSystemIds);
            IChoiceSystemAdaptor <Option, string, OptionRef> displayAdaptor;

            if (field.FieldName == LexSense.WellKnownProperties.SemanticDomainDdp4)
            {
                displayAdaptor = new DdpOptionDisplayAdaptor(availableOptions, field.WritingSystemIds[0]);
            }
            else
            {
                displayAdaptor = new OptionDisplayAdaptor(availableOptions, field.WritingSystemIds[0]);
            }


            ReferenceCollectionEditor <Option, string, OptionRef> control =
                new ReferenceCollectionEditor <Option, string, OptionRef>(refsOfChoices.Members,
                                                                          availableOptions.
                                                                          Options,
                                                                          writingSystems,
                                                                          field.Visibility,
                                                                          displayAdaptor,
                                                                          WeSayWordsProject.Project.ServiceLocator);

            control.AlternateEmptinessHelper = refsOfChoices;
            return(control);
        }
 public LexEntryFromLiftBuilder(MemoryDataMapper <LexEntry> dataMapper, OptionsList semanticDomainsList)
 {
     ExpectedOptionTraits            = new List <string>();
     _expectedOptionCollectionTraits = new List <string>();
     _dataMapper          = dataMapper;
     _semanticDomainsList = semanticDomainsList;
 }
Example #20
0
 /// <summary>
 /// Constructor of option button
 /// </summary>
 /// <param name="spriteYes">the sprite for the button, when option is set to yes</param>
 /// <param name="spriteNo">the sprite for the button, when option is set to no</param>
 /// <param name="center">the center of the button</param>
 public MenuButton(Texture2D spriteYes, Texture2D spriteNo, Vector2 center, OptionsList typeOfOption)
 {
     isOptionButton    = true;
     this.spriteYes    = spriteYes;
     this.spriteNo     = spriteNo;
     this.typeOfOption = typeOfOption;
     Initialize(center);
 }
Example #21
0
        public void Setup()
        {
            _dataMapper = new MemoryDataMapper <LexEntry>();
            OptionsList pretendSemanticDomainList = new OptionsList();

            pretendSemanticDomainList.Options.Add(new Option("4.2.7 Play, fun", new MultiText()));
            _builder = new LexEntryFromLiftBuilder(_dataMapper, pretendSemanticDomainList);
        }
Example #22
0
 protected override bool Handle(ArgumentsList args, OptionsList opts)
 {
     logger.Debug("Reseting player prefs.");
     PlayerPrefs.DeleteAll();
     PlayerPrefs.Save();
     logger.Debug("Player Prefs cleaned!");
     return(true);
 }
Example #23
0
        void MergeOptions(OptionsList list)
        {
            if (list.Item1 != null)
            {
                if (options == null)
                {
                    options = list.Item1;
                }
                else
                {
                    Throw("WithMergeOptions");
                }
            }

            if (list.Item2 != null)
            {
                if (mode == null)
                {
                    mode = list.Item2;
                }
                else
                {
                    Throw("WithExecutionMode");
                }
            }

            if (list.Item3 != null)
            {
                if (token == null)
                {
                    token = list.Item3;
                }
                else
                {
                    Throw("WithCancellationToken");
                }
            }

            if (list.Item4 != -1)
            {
                if (degreeOfParallelism == null)
                {
                    degreeOfParallelism = list.Item4;
                }
                else
                {
                    Throw("WithDegreeOfParallelism");
                }
            }

            // That one is treated specially
            if (list.Item5 != null)
            {
                implementerToken = implementerToken.Chain(list.Item5);
            }
        }
Example #24
0
 public OptionCollectionControl(OptionRefCollection optionRefCollection,
                                OptionsList list,
                                string idOfPreferredWritingSystem)
 {
     _optionRefCollection = optionRefCollection;
     _list = list;
     _idOfPreferredWritingSystem = idOfPreferredWritingSystem;
     InitializeComponent();
     LoadDisplay();
 }
Example #25
0
        public static void CreateUpdateRemoveList()
        {
            var chartService          = new ChartService();
            var optionsCreateNewChart = new OptionsCreateNewChart
            {
                ChartId      = "CreateUpdateRemoveListChart",
                TemplateName = "Berlin"
            };
            var resultChart = chartService.Create(optionsCreateNewChart);

            if (!resultChart.IsSuccess)
            {
                Console.WriteLine(resultChart.Error);
            }

            var optionsUpdateChart = new OptionsUpdateChart
            {
                NewChartId      = "CreateUpdateRemoveListChartNewUpdated",
                NewTemplateName = "London",
                OldChartId      = "CreateUpdateRemoveListChart"
            };

            resultChart = chartService.Update(optionsUpdateChart);
            if (!resultChart.IsSuccess)
            {
                Console.WriteLine(resultChart.Error);
            }

            var optionsList = new OptionsList
            {
                Skip = 0,
                Take = 10,
                WildcardSearchPattern = "*NewUpdated*"
            };

            var resultList = chartService.ListDescriptors(optionsList);


            if (!resultList.IsSuccess)
            {
                Console.WriteLine(resultList.Error);
            }

            var optionsChart = new OptionsChart
            {
                ChartId = "CreateUpdateRemoveListChartNewUpdated"
            };

            var resultRemove = chartService.Remove(optionsChart);

            if (!resultRemove.IsSuccess)
            {
                Console.WriteLine(resultRemove.Error);
            }
        }
        public static OptionsList <EnumOption <TEnum, int> > GetOptionsListFor <TModel, TEnum>(
            this HtmlHelper <TModel> helper,
            Expression <System.Func <TModel, TEnum[]> > nameExpression,
            Func <EnumOption <TEnum, int>, string> display = null) where TEnum : struct, IConvertible
        {
            var selectedValues    = nameExpression.Compile().Invoke(helper.ViewData.Model);
            var selectedValuesInt = selectedValues == null ? null : selectedValues.Cast <int>();

            return(OptionsList.CreateForEnum <TEnum>(display: display)
                   .SelectedValues(selectedValuesInt));
        }
Example #27
0
        /// <summary>
        /// Read a Localized List file.
        /// </summary>
        public int ReadListFile()
        {
            _pathToList = GetListFileName(SemanticDomainWs);
            XmlTextReader reader = null;

            _keys = new List <string>();
            _questionDictionary = new Dictionary <string, List <string> >();
            _optionsList        = new OptionsList();
            int retCount = 0;

            try
            {
                reader = new XmlTextReader(_pathToList);
                reader.MoveToContent();
                // True if parsing localized list
                if (reader.IsStartElement("Lists"))
                {
                    reader.ReadToDescendant("List");
                    while (reader.IsStartElement("List"))
                    {
                        string itemClass = reader.GetAttribute("itemClass").Trim();
                        if (itemClass == "CmSemanticDomain")
                        {
                            retCount = ParsePossibilities(reader);
                        }
                        reader.ReadToFollowing("List");
                    }
                }
                // true if parsing SemDom.xml
                else if (reader.IsStartElement("LangProject"))
                {
                    retCount = ParsePossibilities(reader);
                }
                else
                {
                    //what are we going to do when the file is bad?
                    Logger.WriteEvent("Bad lists file format, expected Lists element: " + _pathToList);
                    Debug.Fail("Bad lists file format, expected Lists element: " + _pathToList);
                }
            }
            catch (XmlException e)
            {
                // log this;
                Logger.WriteEvent("XMLException on parsing Semantic Domain file: " + _pathToList + " " + e.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return(retCount);
        }
Example #28
0
 /// <summary>
 /// Changes the option
 /// </summary>
 /// <param name="option">State of option</param>
 public static void ChangeOption(OptionsList typeOfOption, bool option)
 {
     if (typeOfOption == OptionsList.AllowDuplicates)
     {
         allowDuplicates = option;
     }
     else if (typeOfOption == OptionsList.PlutoIsPlanet)
     {
         plutoIsPlanet = option;
     }
 }
Example #29
0
        /// <summary>
        /// Moves an item in the given direction
        /// </summary>
        /// <param name="direction">positive number to move down, negative number to move down.</param>
        private void MoveItem(int direction)
        {
            int newIndex = OptionsList.SelectedIndex + direction;

            EntityItem selected = OptionsList.SelectedItem as EntityItem;

            ((EntityItem)AttributesList.SelectedItem).Children.RemoveAt(OptionsList.SelectedIndex);
            ((EntityItem)AttributesList.SelectedItem).Children.Insert(newIndex, selected);
            ((EntityItem)AttributesList.SelectedItem).Changed = true;

            OptionsList.SetSelected(newIndex, true);
        }
Example #30
0
        public OptionsModel(IdeCollection <IdeBaseItem> source) : base(source) // new item
        {
            _options = new OptionsList();

            Items = new IdeCollection <IdeBaseItem>(this, typeof(OptionModel));
            Items.CollectionChanged += (a, b) =>
            {
                BuildOptionsDef(b);
            };
            Items.Add(new OptionModel(Items));
            AddOptionCommand = new RelayCommand(AddOption);
        }
Example #31
0
        private readonly ShoppingCart _shoppingCart; // The users shopping card

        #endregion Fields

        #region Constructors

        public Midterm2()
        {
            _books = new List<Book>
            {
                new Book("Object Oriented Programming in C#", 45.5),
                new Book("Web Programming in PHP", 24.9),
                new Book("ASP.NET Web Application Development", 30.0),
                new Book("Java Programming in 21 Days", 37.0),
                new Book("Advanced Database Topics", 19.9)
            };

            // Make the options list
            _bookOptions = new OptionsList();
            _books.ForEach(book => _bookOptions.Add(book.Title));

            // Instantiate the Shopping card
            _shoppingCart = new ShoppingCart();

            // Instantiate the console
            _console = new ExtConsole("Algonquin College Online Book Store");
        }
Example #32
0
        private void BankerConsoleInterface(Customer customer, OptionsList accountOptions, OptionsList transferOptions,
            OptionsList transactionOptions)
        {
            int selection;
            do
            {
                int accountSelection;
                double amount;

                selection = _console.ReadFromOptions(
                    "Account Options",
                    "Select an option",
                    "Invalid option",
                    transactionOptions
                );

                switch (selection)
                {
                    case 1:
                        DepositOption(accountOptions, customer, out accountSelection, out amount);
                        break;
                    case 2:
                        WithdrawOption(accountOptions, customer, out accountSelection, out amount);
                        break;
                    case 3:
                        TransferOption(transferOptions, customer, out accountSelection, out amount);
                        break;
                    case 4:
                        TransactionSummaryOption(customer);
                        break;
                    case 5:
                        AccountBalanceOption(customer);
                        break;
                }
            } while (selection != transactionOptions.ContinueOption);
            _console.Pause(String.Format("Thank you for using the Algonquin Banking System {0}\n",Helpers.UppercaseFirst(customer.Name)));
        }
Example #33
0
        private void TransferOption(OptionsList transferOptions, Customer customer, out int accountSelection, out double amount)
        {
            do
                accountSelection = _console.ReadFromOptions(
                    "Transfer Options",
                    "Select an Option",
                    "Invalid Option",
                    transferOptions, false
                    ); while (!transferOptions.IsValid(accountSelection));

            amount = _console.ReadValidDouble("Enter the amount", "Invalid amount");

            try
            {
                switch (accountSelection)
                {
                    case 1:
                        customer.TransferFunds(AccountType.Saving, AccountType.Checking, amount);
                        break;
                    case 2:
                        customer.TransferFunds(AccountType.Checking, AccountType.Saving, amount);
                        break;
                }
                _console.WriteASuccessLine("Transfer complete");
            }
            catch (Exceptions.InsufficientFunds)
            {
                _console.WriteAErrorLine("Insufficient Funds");
            }
        }
Example #34
0
        private void DepositOption(OptionsList accountOptions, Customer customer, out int accountSelection, out double amount)
        {
            do
                accountSelection = _console.ReadFromOptions(
                    "Deposit into Which account?",
                    "Select an account",
                    "Invalid account",
                    accountOptions, false
                ); while (!accountOptions.IsValid(accountSelection));

            amount = _console.ReadValidDouble("Amount", "Invalid Amount");

            switch (accountSelection)
            {
                case 1:
                    customer.DepositTo(AccountType.Checking, amount);
                    _console.WriteASuccessLine("Deposit to Checkings successful");
                    break;
                case 2:
                    customer.DepositTo(AccountType.Saving, amount);
                    _console.WriteASuccessLine("Deposit to Savings successful");
                    break;
            }
        }
Example #35
0
		void MergeOptions (OptionsList list)
		{
			if (list.Item1 != null) {
				if (options == null)
					options = list.Item1;
				else
					Throw ("WithMergeOptions");
			}

			if (list.Item2 != null) {
				if (mode == null)
					mode = list.Item2;
				else
					Throw ("WithExecutionMode");
			}

			if (list.Item3 != null) {
				if (token == null)
					token = list.Item3;
				else
					Throw ("WithCancellationToken");
			}

			if (list.Item4 != -1) {
				if (degreeOfParallelism == null)
					degreeOfParallelism = list.Item4;
				else
					Throw ("WithDegreeOfParallelism");
			}

			// That one is treated specially
			if (list.Item5 != null) {
				implementerToken = implementerToken.Chain (list.Item5);
			}
		}
Example #36
0
 public int ReadFromOptions(string header, string prompt, string error, OptionsList options,
     bool optionToContinue = true)
 {
     PrintIfExists();
     WriteOptions(header, options, optionToContinue);
     int selection;
     var looped = false;
     do
     {
         if (looped)
             WriteAErrorLine(error);
         selection = ReadAValidatedInt(prompt, error);
         looped = true;
     } while (!options.IsValid(selection) && (optionToContinue && selection != options.ContinueOption));
     return selection;
 }
 public void Add(string key, OptionsList value)
 {
     Dictionary.Add(key.ToUpper(), value);
 }
Example #38
0
        private void TransferOption(OptionsList transferOptions, out int accountSelection, out double amount)
        {
            // Get Selected Options from the user
            do
                accountSelection = _console.ReadFromOptions( "Transfer Options", "Select an Option", "Invalid Option", transferOptions, false);
            while (!transferOptions.IsValid(accountSelection));

            // Get Amount from the user
            amount = _console.ReadValidDouble("Enter the amount", "Invalid amount");

            // Transfer the funds, catching any Inssfuicent funds Exceptions
            try
            {
                switch (accountSelection)
                {
                    case 1: // From Savings, to checkings
                        CustomerServices.TransferFunds(_customer, AccountType.Saving, AccountType.Checking, amount);
                        break;
                    case 2: // From Checkings to Savings
                        CustomerServices.TransferFunds(_customer, AccountType.Checking, AccountType.Saving, amount);
                        break;
                }
                // Let the user know the transfer completed
                _console.WriteASuccessLine("Transfer complete");
            }
            // Catch any Insufficent Funds Exceptions
            catch (InsufficientFunds)
            {
                // Alert the user
                _console.WriteAErrorLine("Insufficient Funds");
            }
        }
Example #39
0
        private void BankerConsoleInterface(OptionsList accountOptions, OptionsList transferOptions,
            OptionsList transactionOptions)
        {
            int selection;
            do
            {
                // Current selected account OUT refrence variable
                int accountSelection;
                // Current selected amount OUT refrence variable
                double amount;

                // Build the console framework selector unit
                selection = _console.ReadFromOptions( "Account Options", "Select an option", "Invalid option", transactionOptions);

                // Processes the users selection
                switch (selection)
                {
                    case 1:
                        DepositOption(accountOptions, out accountSelection, out amount);
                        break;
                    case 2:
                        WithdrawOption(accountOptions, out accountSelection, out amount);
                        break;
                    case 3:
                        TransferOption(transferOptions, out accountSelection, out amount);
                        break;
                    case 4:
                        TransactionSummaryOption();
                        break;
                    case 5:
                        AccountBalanceOption();
                        break;
                    case 6:
                        DeleteBankAccountFile();
                        break;
                }
            } while (selection != transactionOptions.ContinueOption);

            // Save The customer
            ExportCustomer();

            // Display Good bye message and wait for a
            _console.Pause(String.Format("Thank you for using the Algonquin Banking System {0}\nPress any key to Exit...", Helpers.UppercaseFirst(_customer.CustomerName)));
        }
Example #40
0
        private void WithdrawOption(OptionsList accountOptions, Customer customer, out int accountSelection, out double amount)
        {
            do
                accountSelection = _console.ReadFromOptions(
                    "Withdraw from Which account?",
                    "Select an account",
                    "Invalid account",
                    accountOptions, false
                ); while (!accountOptions.IsValid(accountSelection));

            amount = _console.ReadValidDouble("Amount", "Invalid Amount");
            try
            {
                switch (accountSelection)
                {
                    case 1:
                        customer.WidthdrawFrom(AccountType.Checking, amount);
                        break;
                    case 2:
                        customer.WidthdrawFrom(AccountType.Saving, amount);
                        break;
                }
                _console.WriteASuccessLine("Transaction complete");
            }
            catch (Exceptions.InsufficientFunds)
            {
                _console.WriteAErrorLine("Insufficient Funds");
            }
        }
Example #41
0
 // TODO: This function should be expanded, there should be an options class that can be created and validated against
 public void WriteOptions(string header, OptionsList options, bool optionToContinue = true)
 {
     HorizontalString();
     WriteAHeaderString(header, BoldColor);
     HorizontalString();
     for (var x = 0; x <= options.Count - 1; x++)
     {
         Write(RuleChar + " ", RuleOnColor);
         WriteBold((x + 1) + " ");
         Write(RuleChar + " ", RuleOffColor);
         WriteBold("\t" + options[x] + "\n");
     }
     if (optionToContinue)
     {
         Write(RuleChar + " ", RuleOnColor);
         WriteBold(options.ContinueOption + " ");
         Write(RuleChar + " ", RuleOffColor);
         Write("\t" + "To Continue" + "\n", SuccessColor);
     }
     HorizontalLine();
 }
                /// -----------------------------------------------------------------------------
                /// <summary>
                /// Method loads a file into memory and parses the directives
                /// </summary>
                /// <param name="file">File with full path containing configuration data</param>
                /// <returns>Method returns a fully parsed configuration</returns>
                /// <remarks>
                /// We still need to make sure that comment codes can appear escaped in strings, at
                /// the moment there is no support for escape sequences in config files. So the results
                /// of putting comments in strings are unpredictable (Bad)
                /// </remarks>
                /// <history>
                /// 	[Caleb]	12/1/2005	Created
                /// </history>
                /// -----------------------------------------------------------------------------
                public ConfigurationReturn Load(string file)
                {
                    try
                    {
                        string FileData = "";
                        System.IO.StreamReader tFileStream;
                        if (System.IO.File.Exists(file))
                        {
                            tFileStream = System.IO.File.OpenText(file);
                            FileData = tFileStream.ReadToEnd();
                        }
                        ConfigurationReturn ConfigData = new ConfigurationReturn();
                        if (FileData != null)
                        {
                            Regex multilinecomments = new Regex("/\\*[^*]*\\*+([^/*][^*]*\\*+)*/", RegexOptions.Multiline);
                            Regex linecomments = new Regex("//.+$", RegexOptions.Multiline);
                            Regex linecomments2 = new Regex("\\#.+$", RegexOptions.Multiline);
                            Match tMatch;
                            Match uMatch;
                            FileData = multilinecomments.Replace(FileData, "");
                            FileData = linecomments.Replace(FileData, "");
                            FileData = linecomments2.Replace(FileData, "");
                            OptionsList CurrentConfigGroup = new OptionsList();
                            Regex blocks = new Regex("(?<name>[\\w\\d-_]*)[\\s]*\\{(?<values>[^\\}]*)\\}\\;", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            string tMatchString;
                            Regex stringoptions = new Regex("(?<optionname>[\\w\\d-_]+)[\\s]*\"(?<optionvalue>[^\"]*)\"\\;", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            Regex numericoptions = new Regex("(?<optionname>[\\w\\d-_]*)[\\s]*(?<optionvalue>[\\d]+)\\;", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (FileData.IndexOf("/*") >= 0)
                            {
                                Configuration.Clear();
                                ConfigData.Loaded = false;

                                ConfigData.Data.Add("File contains comment which does not end");
                                return ConfigData;
                            }
                            while (blocks.Matches(FileData).Count > 0)
                            {
                                tMatch = blocks.Matches(FileData)[0];
                                tMatchString = tMatch.Groups["values"].Value;
                                // MsgBox(tMatch.Groups("name").Value & " " & tMatch.Groups("values").Value)
                                while (stringoptions.Matches(tMatchString).Count > 0)
                                {
                                    uMatch = stringoptions.Matches(tMatchString)[0];
                                    if (CurrentConfigGroup.ContainsKey(uMatch.Groups["optionname"].Value + "1"))
                                    {
                                        //ConfigData.Data.Add(String.Format("Option ""{1}"" already exists in block ""{0}""", tMatch.Groups("name").Value, uMatch.Groups("optionname").Value))
                                        int tInt = 2;
                                        bool tExists = false;
                                        while (tExists == false)
                                        {
                                            if (CurrentConfigGroup.ContainsKey(uMatch.Groups["optionname"].Value + tInt))
                                            {
                                                tInt += 1;
                                            }
                                            else
                                            {
                                                tExists = true;
                                            }
                                        }
                                        CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value + tInt, uMatch.Groups["optionvalue"].Value);
                                    }
                                    else
                                    {
                                        CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value + "1", uMatch.Groups["optionvalue"].Value);
                                    }
                                    tMatchString = stringoptions.Replace(tMatchString, "", 1);
                                }
                                while (numericoptions.Matches(tMatchString).Count > 0)
                                {
                                    uMatch = numericoptions.Matches(tMatchString)[0];
                                    if (CurrentConfigGroup.ContainsKey(uMatch.Groups["optionname"].Value + "1"))
                                    {
                                        //ConfigData.Data.Add(String.Format("Option ""{1}"" already exists in block ""{0}""", tMatch.Groups("name").Value, uMatch.Groups("optionname").Value))
                                        int tInt = 2;
                                        bool tExists = false;
                                        while (tExists == false)
                                        {
                                            if (CurrentConfigGroup.ContainsKey(uMatch.Groups["optionname"].Value + tInt))
                                            {
                                                tInt += 1;
                                            }
                                            else
                                            {
                                                tExists = true;
                                            }
                                        }
                                        CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value + tInt, uMatch.Groups["optionvalue"].Value);
                                    }
                                    else
                                    {
                                        CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value + "1", uMatch.Groups["optionvalue"].Value);
                                    }
                                    tMatchString = numericoptions.Replace(tMatchString, "", 1);
                                }
                                tMatchString = tMatchString.Replace(Core.IRC.CRLF, "");
                                tMatchString = tMatchString.Replace(Core.IRC.LF, "");
                                tMatchString = tMatchString.Replace(Core.IRC.CR, "");
                                tMatchString = tMatchString.Trim();
                                if (tMatchString.Length > 0)
                                {
                                    Configuration.Clear();
                                    ConfigData.Loaded = false;
                                    ConfigData.Data.Add("Block contains erronous text \"" + tMatch.Groups["name"].Value + "\"");
                                    return ConfigData;
                                }
                                else
                                {
                                    if (Configuration.ContainsKey(tMatch.Groups["name"].Value + "1"))
                                    {
                                        int tInt = 2;
                                        bool tExists = false;
                                        while (tExists == false)
                                        {
                                            if (Configuration.ContainsKey(tMatch.Groups["name"].Value + tInt))
                                            {
                                                tInt += 1;
                                            }
                                            else
                                            {
                                                tExists = true;
                                            }
                                        }
                                        // ConfigData.Data.Add(String.Format("Block ""{0}"" already exists", tMatch.Groups("name").Value))
                                        Configuration.Add(tMatch.Groups["name"].Value + tInt, CurrentConfigGroup);
                                    }
                                    else
                                    {
                                        Configuration.Add(tMatch.Groups["name"].Value + "1", CurrentConfigGroup);
                                    }
                                    CurrentConfigGroup = new OptionsList();
                                }
                                FileData = blocks.Replace(FileData, "", 1);
                                // MsgBox(FileData)
                            }
                            while (stringoptions.Matches(FileData).Count > 0)
                            {
                                uMatch = stringoptions.Matches(FileData)[0];
                                CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value, uMatch.Groups["optionvalue"].Value);
                                FileData = stringoptions.Replace(FileData, "", 1);
                            }
                            while (numericoptions.Matches(FileData).Count > 0)
                            {
                                uMatch = numericoptions.Matches(FileData)[0];
                                CurrentConfigGroup.Add(uMatch.Groups["optionname"].Value, uMatch.Groups["optionvalue"].Value);
                                FileData = numericoptions.Replace(FileData, "", 1);
                            }
                            Configuration.Add("global1", CurrentConfigGroup);
                            FileData = FileData.Replace(Core.IRC.CRLF, "");
                            FileData = FileData.Replace(Core.IRC.LF, "");
                            FileData = FileData.Replace(Core.IRC.CR, "");
                            FileData = FileData.Trim();
                            if (FileData.Length > 0)
                            {
                                Configuration.Clear();
                                ConfigData.Loaded = false;
                                ConfigData.Data.Add("Configuration contains erronous text");
                                return ConfigData;
                            }
                            else
                            {
                                ConfigData.Loaded = true;
                                return ConfigData;
                            }
                        }
                        else
                        {
                            Configuration.Clear();
                            ConfigData.Loaded = false;
                            ConfigData.Data.Add("Unable to find configuration file");
                            return ConfigData;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                        //MessageBox.Show("Caught Error: " + ex.Message + " " + ex.StackTrace);
                        // Base.SendLogMessage("Config", "Load", Errors.LOG_ERROR, "Problem loading config", "", ex.Message, ex.StackTrace);
                    }
                }