Extensions for IConsole.
예제 #1
0
        private static void AddPriceBook()
        {
            Console.WriteLine("Begin AddPriceBookUX");

            var view = Proxy.GetValue(ShopsContainer.GetEntityView(string.Empty, "Details", "AddPriceBook", string.Empty));

            view.Should().NotBeNull();
            view.Policies.Should().BeEmpty();
            view.Properties.Should().NotBeEmpty();
            view.ChildViews.Should().BeEmpty();

            view.Properties = new ObservableCollection <ViewProperty>
            {
                new ViewProperty {
                    Name = "Name", Value = "InvalidPriceBook{"
                },
            };
            var result = Proxy.DoCommand(ShopsContainer.DoAction(view));

            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            view.Properties = new ObservableCollection <ViewProperty>
            {
                new ViewProperty {
                    Name = "Name", Value = "ConsoleUxPriceBook"
                },
                new ViewProperty {
                    Name = "DisplayName", Value = "displayname"
                },
                new ViewProperty {
                    Name = "Description", Value = "description"
                },
                new ViewProperty
                {
                    Name  = "CurrencySetId",
                    Value = "{0F65742E-317F-44B0-A4DE-EBF06209E8EE}"
                }
            };
            result = Proxy.DoCommand(ShopsContainer.DoAction(view));
            result.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
        }
        private static void RemoveListPrices_Variation()
        {
            Console.WriteLine("Begin RemoveListPrices_Variation");

            var price1 = Money.CreateMoney(10M);

            price1.CurrencyCode = "USD";
            var price2 = Money.CreateMoney(12M);

            price2.CurrencyCode = "CAD";

            var result = Proxy.DoCommand(Container.UpdateListPrices("Adventure Works Catalog|AW140 13|41", new List <Money> {
                price1, price2
            }));

            result.Should().NotBeNull();

            result = Proxy.DoCommand(Container.RemoveListPrices("Adventure Works Catalog|AW140 13|41", new List <Money> {
                price1
            }));
            result.Should().NotBeNull();
            result.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();

            var sellableItem = Proxy.GetValue(Container.SellableItems.ByKey("Adventure Works Catalog,AW140 13,41").Expand("Components($expand=ChildComponents($expand=ChildComponents($expand=ChildComponents)))"));

            sellableItem.Should().NotBeNull();
            var variation = sellableItem.Components.OfType <ItemVariationsComponent>()
                            .FirstOrDefault()?
                            .ChildComponents.OfType <ItemVariationComponent>()
                            .FirstOrDefault();

            variation.Should().NotBeNull();
            variation?.Policies.OfType <ListPricingPolicy>().FirstOrDefault()?.Prices.Should().NotBeNullOrEmpty();
            variation?.Policies.OfType <ListPricingPolicy>().FirstOrDefault()?.Prices.Any(p => p.CurrencyCode.Equals(price1.CurrencyCode)).Should().BeFalse();
            variation?.Policies.OfType <ListPricingPolicy>().FirstOrDefault()?.Prices.Any(p => p.CurrencyCode.Equals(price2.CurrencyCode)).Should().BeTrue();

            result = Proxy.DoCommand(Container.RemoveListPrices("Adventure Works Catalog|AW140 13|41", new List <Money> {
                Money.CreateMoney(10)
            }));
            result.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");
        }
예제 #3
0
        public List <int> RecurentWalk(Node root, string nodeType = "root")
        {
            List <int> result = new List <int>();

            if (Level == 1)
            {
                Description.AppendLine($@"
=================================================
| We show recurent walking through binary tree  |
| At first we look at left side and if we have  |
| left node we move there. Then we look at rght |
| and if we have right node - move there. Then  |
| we look at current node to take it value and  |
| move to the root                              |
=================================================
");
            }

            if (root.Left != null)
            {
                Level++;
                Description.Append($"|({nodeType}) -> Left |");
                var left = RecurentWalk(root.Left, "left");
                result.AddRange(left);
            }

            if (root.Right != null)
            {
                Level++;
                Description.Append($"|({nodeType}) -> Right |");
                var right = RecurentWalk(root.Right, "right");
                result.AddRange(right);
            }

            result.Add(root.Data);
            Description.AppendLine($"|({nodeType}) = Got: {root.Data}|");
            Description.AppendLine($@"{ConsoleExtensions.MakeLeftPadding(Level)} | Recurent level: {Level} | All values: {result.Represent()}
-------------------------------------------------------------------------------------------------------------------");
            Level--;

            return(result);
        }
        private static void RemovePriceSnapshotTag()
        {
            Console.WriteLine("Begin RemovePriceSnapshotTag");

            var result = Proxy.DoCommand(Container.RemovePriceSnapshotTag("InvalidCard", _priceSnapshotId, "ThisIsATag"));

            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            result = Proxy.DoCommand(Container.RemovePriceSnapshotTag(_priceCardFriendlyId, "InvalidSnapshot", "ThisIsATag"));
            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            result = Proxy.DoCommand(Container.RemovePriceSnapshotTag(_priceCardFriendlyId, _priceSnapshotId, "InvalidTag"));
            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            result = Proxy.DoCommand(Container.RemovePriceSnapshotTag(_priceCardFriendlyId, _priceSnapshotId, "ThisIsATag"));
            result.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
        }
        private static void AddPriceCard()
        {
            Console.WriteLine("Begin AddPriceCard");

            var result = Proxy.DoCommand(Container.AddPriceCard(_priceBookFriendlyId, "ConsolePriceCard", "displayname", "description"));

            result.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
            result.Models.OfType <PriceCardAdded>().FirstOrDefault().Should().NotBeNull();
            _priceCardFriendlyId = result.Models.OfType <PriceCardAdded>().FirstOrDefault()?.PriceCardFriendlyId;

            result = Proxy.DoCommand(Container.AddPriceCard(_priceBookFriendlyId, "ConsolePriceCard", "displayname", "description"));
            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            result = Proxy.DoCommand(Container.AddPriceCard(_priceBookFriendlyId, "ConsolePriceCard1", string.Empty, "description"));
            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();

            result = Proxy.DoCommand(Container.AddPriceCard(_priceBookFriendlyId, "ConsolePriceCard2", "displayname", string.Empty));
            result.Messages.Any(m => m.Code.Equals("validationerror", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
        }
            public unsafe void trace60(
                string message = "",
                [CallerFilePath] string sourceFilePath  = "",
                [CallerLineNumber] int sourceLineNumber = 0
                )
            {
                //if (this.FrameIndex > 300)
                //    return;

                if (this.FrameIndex % 60 == 1)
                {
                    ConsoleExtensions.trace(
                        message,
                        //value,
                        sourceFilePath,
                        sourceLineNumber

                        );
                }
            }
예제 #7
0
        /// <summary>
        /// Write the response of all asserted test via Console.IO
        /// </summary>
        /// <returns></returns>
        public ResponseContext WriteAssertions()
        {
            "assertions".WriteHeader();
            foreach (var assertion in _assertions)
            {
                assertion.WriteTest();
            }

            "schema validation".WriteHeader();
            if (_isSchemaValid)
            {
                ConsoleExtensions.WritePassedTest();
            }
            else
            {
                ConsoleExtensions.WriteFailedTest();
            }

            return(this);
        }
예제 #8
0
        public static string Run(ShopperContext context)
        {
            using (new SampleBuyScenarioScope())
            {
                try
                {
                    var container = context.ShopsContainer();

                    var orderId = BuySplitShipment.Run(context);
                    if (!string.IsNullOrEmpty(orderId))
                    {
                        OrdersUX.HoldOrder(orderId);
                    }

                    var order = Orders.GetOrder(container, orderId);
                    if (order.Totals.GrandTotal.Amount != 180.40M)
                    {
                        ConsoleExtensions.WriteColoredLine(
                            ConsoleColor.Red,
                            $"GrandTotal Incorrect - Expecting:{180.40M} Actual:{order.Totals.GrandTotal.Amount}");
                    }

                    var lineToDelete = order.Lines.First();
                    var action       = new EntityView
                    {
                        Action   = "DeleteLineItem",
                        EntityId = orderId,
                        ItemId   = lineToDelete.Id
                    };
                    container.DoAction(action).GetValue();
                    return(orderId);
                }
                catch (Exception ex)
                {
                    ConsoleExtensions.WriteColoredLine(
                        ConsoleColor.Red,
                        $"Exception in Scenario {ScenarioName} (${ex.Message}) : Stack={ex.StackTrace}");
                    return(null);
                }
            }
        }
예제 #9
0
        private static void AddAddress()
        {
            Console.WriteLine("Begin AddressDetails for Add");

            var view = Proxy.GetValue(ShopsContainer.GetEntityView(_customerId, "AddressDetails", "SelectAddressCountry", string.Empty));

            view.Should().NotBeNull();
            view.Properties.Should().NotBeEmpty();
            view?.Policies.Should().BeEmpty();
            view.Action.Should().Be("GetCountryRegionsForCustomers");

            view.Properties.FirstOrDefault(p => p.Name.Equals("Country")).Value = "CA";
            var action = Proxy.DoCommand(ShopsContainer.DoAction(view));

            action.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();

            view = action.Models.OfType <EntityView>().FirstOrDefault(v => v.Name.Equals(view.Name));
            view.Should().NotBeNull();
            view?.Policies.Should().BeEmpty();
            view?.Properties.Should().NotBeEmpty();
            view?.Action.Should().Be("AddAddress");
            view.Properties.FirstOrDefault(p => p.Name.Equals("AddressName")).Value = "Home";
            view.Properties.FirstOrDefault(p => p.Name.Equals("State")).Value       = "ON";

            action = Proxy.DoCommand(ShopsContainer.DoAction(view));
            action.Messages.Any(m => m.Code.EndsWith("error", StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            ConsoleExtensions.WriteColoredLine(ConsoleColor.Yellow, "Expected error");

            view.Properties.FirstOrDefault(p => p.Name.Equals("FirstName")).Value     = "first name";
            view.Properties.FirstOrDefault(p => p.Name.Equals("LastName")).Value      = "last name";
            view.Properties.FirstOrDefault(p => p.Name.Equals("Address1")).Value      = "123 street";
            view.Properties.FirstOrDefault(p => p.Name.Equals("Address2")).Value      = string.Empty;
            view.Properties.FirstOrDefault(p => p.Name.Equals("City")).Value          = "city";
            view.Properties.FirstOrDefault(p => p.Name.Equals("ZipPostalCode")).Value = "postalCode";
            view.Properties.FirstOrDefault(p => p.Name.Equals("PhoneNumber")).Value   = "phoneNumber";
            view.Properties.FirstOrDefault(p => p.Name.Equals("IsPrimary")).Value     = "true";
            action = Proxy.DoCommand(ShopsContainer.DoAction(view));
            action.Messages.Any(m => m.Code.EndsWith("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
            action.Models.OfType <CustomerAddressAdded>().FirstOrDefault().Should().NotBeNull();
            _addressId = action.Models.OfType <CustomerAddressAdded>().FirstOrDefault()?.AddressId;
        }
예제 #10
0
            void Perform <TColor>() where TColor : IColor
            {
                Console.WriteLine(typeof(TColor).FullName);

                double accuracy = 0;
                double length   = 0;

                var stopwatch = new Stopwatch();

                stopwatch.Start();
                for (double r = 0; r < 255; r++)
                {
                    ConsoleExtensions.ClearLine();
                    Console.Write("Step {0}/255 ({1})".F(r.ToString().PadLeft(3, '0'), stopwatch.Elapsed.GetRemaining(255, r.ToInt64()).ToShortTime()));
                    for (double g = 0; g < 255; g++)
                    {
                        for (double b = 0; b < 255; b++)
                        {
                            //The first color
                            var color_a = new RGB(r / 255.0, g / 255.0, b / 255.0);
                            //The first color, converted
                            var color_b = color_a.To <TColor>(_converter);
                            //The converted color, converted back
                            var color_c = color_b.To <RGB>(_converter);

                            //The accuracy of the conversion
                            var _accuracy = GetAccuracy(color_a, color_c);
                            _accuracy = double.IsNaN(_accuracy) ? 100 : _accuracy;

                            accuracy += _accuracy;
                            length++;
                        }
                    }
                }
                stopwatch.Stop();
                accuracy /= length;

                ConsoleExtensions.ClearLine();
                Console.WriteLine("Accuracy: {0}%".F(accuracy));
                Console.WriteLine(string.Empty);
            }
예제 #11
0
        internal int RenderMenu(string header = "")
        {
            bool   isDone     = false;
            int    response   = 0;
            string menuChoice = "";

            do
            {
                if (header != "")
                {
                    Console.WriteLine(header);
                }
                for (int i = 0; i < options.Length; i++)
                {
                    Console.WriteLine($"{i + 1}) {options[i]}");
                }

                Console.Write("> ");
                menuChoice = Console.ReadLine();

                if (menuChoice.Trim().ToLower() == ":q")
                {
                    return(-1);
                }

                isDone = int.TryParse(menuChoice, out response);

                if (response != 0)
                {
                    if (response > options.Length)
                    {
                        Console.WriteLine("You have chosen a bad menu option. Try again!");
                        isDone = false;
                        Console.Read();
                        ConsoleExtensions.ClearLines(1 + options.Length);
                    }
                }
            }while (!isDone);

            return(response);
        }
예제 #12
0
        private void ReceivedData()
        {
            while (_continue)
            {
                try
                {
                    var message = serialPort.ReadLine();
                    ConsoleExtensions.WriteInfo($"Received message: {message}");

                    var splittedMessage = message.Split(' ');

                    if (stringComparer.Equals("hlp", splittedMessage[0]))
                    {
                        serialPort.WriteLine(GetHelp());
                    }
                    else
                    {
                        if (splittedMessage.Length != 3)
                        {
                            throw new NotSupportedOperation(splittedMessage[0]);
                        }

                        var first  = double.Parse(splittedMessage[1]);
                        var second = double.Parse(splittedMessage[2]);

                        controller.Execute(splittedMessage[0], first, second);
                    }
                }
                catch (NotSupportedOperation)
                {
                    ConsoleExtensions.WriteError("Not supported operation. Type HLP to get help");
                    serialPort.WriteLine("Not supported operation. Type HLP to get help");
                }
                catch (Exception ex)
                {
                    ConsoleExtensions.WriteError($"Error: {ex.Message}");
                    serialPort.WriteLine($"Error: {ex.Message}");
                    _continue = false;
                }
            }
        }
예제 #13
0
        /// <inheritdoc/>
        public void Run(CancellationToken cancellationToken)
        {
            ConsoleExtensions.WriteColoredLine(Resources.StrategyExampleRunning, ConsoleColor.Cyan);
            var list = new List <string>
            {
                "furthest",
                "Hello",
                "Speak",
                "Correctness",
                "Inexperience",
                "Furthest",
                "Correctness",
                "speak"
            };
            var bubbleSortStrategy = this.strategyResolver.Resolve(SortType.BubbleSort);
            var quicksortStrategy  = this.strategyResolver.Resolve(SortType.Quicksort);

            Console.WriteLine(Resources.StrategyExampleOriginalList);
            ConsoleExtensions.WriteColoredLine(
                string.Join(Environment.NewLine, list),
                ConsoleColor.DarkGray);
            Console.WriteLine();

            Console.WriteLine(Resources.StrategyExampleApplyingBubbleSort);
            var bubbleSortList = new List <string>(list);

            bubbleSortStrategy.Sort(bubbleSortList, StringComparer.OrdinalIgnoreCase);
            ConsoleExtensions.WriteColoredLine(
                string.Join(Environment.NewLine, bubbleSortList),
                ConsoleColor.DarkGray);
            Console.WriteLine();

            Console.WriteLine(Resources.StrategyExampleApplyingQuicksort);
            var quicksortList = new List <string>(list);

            quicksortStrategy.Sort(quicksortList, StringComparer.OrdinalIgnoreCase);
            ConsoleExtensions.WriteColoredLine(
                string.Join(Environment.NewLine, quicksortList),
                ConsoleColor.DarkGray);
            Console.WriteLine();
        }
        private List <CardOperation> AskUserToChoseOperationsFromSet(List <CardOperation> operations)
        {
            Console.WriteLine("Перечислите операции к обработке:");

            var chosenOperationsNumbers = ConsoleExtensions
                                          .ReadIntRangeListOrRetry()
                                          .SelectUnique();

            var chosenOperations = new List <CardOperation>();

            foreach (var operationNumber in chosenOperationsNumbers)
            {
                if (operationNumber > 0 && operationNumber <= operations.Count)
                {
                    var operation = operations[operationNumber - 1];
                    chosenOperations.Add(operation);
                }
            }

            return(chosenOperations);
        }
예제 #15
0
        // JVM load the .so and calls this native function
        static jstring Java_AndroidBrowserVR_Activities_xMarshal_stringFromJNI(
            // what would we be able to do inspecting the runtime?
            JNIEnv env,
            jobject thiz,
            jobject args
            )
        {
            ConsoleExtensions.trace("enter Java_AndroidBrowserVR_Activities_xMarshal_stringFromJNI");

            // do we have a console yet?
            //Console.WriteLine("enter Java_AndroidBrowserVRNDK_Activities_xMarshal_stringFromJNI");


            var n = env.NewStringUTF;

            //// if we change our NDK code, will nuget packaing work on the background, and also upgrade running apps?
            var v = n(env, "hello from Java_AndroidBrowserVR_Activities_xMarshal_stringFromJNI. yay");

            return(v);
            // ConfigurationCreateNuGetPackage.cs
        }
예제 #16
0
파일: Monster.cs 프로젝트: Bia10/ArcNET
        private static ObjFNpcFlags ParseObjFNpcFlags(string paramValue)
        {
            var flag        = (ObjFNpcFlags)0;
            var trimmedFlag = paramValue.TrimStart().TrimEnd();

            if (!((IList)Enum.GetNames(typeof(ObjFNpcFlags))).Contains(trimmedFlag))
            {
                ConsoleExtensions.Log($"Unrecognized ObjFNpcFlags param:|{trimmedFlag}|", "warn");
            }

            foreach (var npcFlag in (ObjFNpcFlags[])Enum.GetValues(typeof(ObjFNpcFlags)))
            {
                if (!Enum.GetName(typeof(ObjFNpcFlags), npcFlag).Equals(trimmedFlag))
                {
                    continue;
                }
                //ConsoleExtensions.Log($"Recognized ObjFNpcFlags param:|{trimmedFlag}|", "success");
                flag = npcFlag;
            }
            return(flag);
        }
예제 #17
0
        private static void EditPriceSnapshot()
        {
            using (new SampleMethodScope())
            {
                var beginDate = DateTimeOffset.Now;

                var result = Proxy.DoCommand(Container.EditPriceSnapshot("InvalidCard", _priceSnapshotId, beginDate));
                result.Messages.Should().ContainMessageCode("validationerror");
                ConsoleExtensions.WriteExpectedError();

                result = Proxy.DoCommand(Container.EditPriceSnapshot(_cardFriendlyId, "InvalidSnapshot", beginDate));
                result.Messages.Should().ContainMessageCode("validationerror");
                ConsoleExtensions.WriteExpectedError();

                result = Proxy.DoCommand(Container.EditPriceSnapshot(_cardFriendlyId, _priceSnapshotId, beginDate));
                result.Messages.Should().NotContainErrors();
                var card     = GetPriceCard(_cardFriendlyId);
                var snapshot = card?.Snapshots.FirstOrDefault(s => s.Id.EndsWith(_priceSnapshotId));
                snapshot?.BeginDate.Should().BeCloseTo(beginDate, 1000);
            }
        }
예제 #18
0
파일: Monster.cs 프로젝트: Bia10/ArcNET
        private static ObjFCritterFlags2 ParseObjFCritterFlags2(string paramValue)
        {
            var flag        = (ObjFCritterFlags2)0;
            var trimmedFlag = paramValue.TrimStart().TrimEnd();

            if (!((IList)Enum.GetNames(typeof(ObjFCritterFlags2))).Contains(trimmedFlag))
            {
                ConsoleExtensions.Log($"Unrecognized ObjFCritterFlags2 param:|{trimmedFlag}|", "warn");
            }

            foreach (var critterFlag2 in (ObjFCritterFlags2[])Enum.GetValues(typeof(ObjFCritterFlags2)))
            {
                if (!Enum.GetName(typeof(ObjFCritterFlags2), critterFlag2).Equals(trimmedFlag))
                {
                    continue;
                }
                //ConsoleExtensions.Log($"Recognized ObjFCritterFlags2 param:|{trimmedFlag}|", "success");
                flag = critterFlag2;
            }
            return(flag);
        }
예제 #19
0
        private void CovarianceExample()
        {
            ConsoleExtensions
            .WriteColoredLine(Resources.CovarianceExampleRunning, ConsoleColor.Cyan);

            // A covariant type in an interface or delegate can be converted to a more GENERAL type.

            // Interface: ICovariant<Banana> to ICovariant<Fruit>
            ICovariant <Fruit> fruitCovariantInterface = this.bananaCovariantInterface;

            // Delegate: Covariant<Lemon> to Covariant<object>
            Covariant <object> objectCovariantDelegate = this.lemonCovariantDelegate;

            const int FruitQuality = 85;
            var       fruit        = fruitCovariantInterface.Create(FruitQuality);
            var       obj          = objectCovariantDelegate();

            Console.WriteLine(Resources.CovarianceExampleFruitColor, fruit.Name, fruit.Color);
            Console.WriteLine(Resources.CovarianceExampleObjString, nameof(obj), obj.ToString());
            Console.WriteLine();
        }
        public static string Run(ShopperContext context)
        {
            using (new SampleBuyScenarioScope())
            {
                try
                {
                    var container = context.ShopsContainer();

                    var cartId = Carts.GenerateCartId();

                    Proxy.DoCommand(container.AddCartLine(cartId, "Adventure Works Catalog|AW210 12|4", 1));

                    var commandResult = Proxy.DoCommand(
                        container.SetCartFulfillment(
                            cartId,
                            context.Components.OfType <PhysicalFulfillmentComponent>().First()));

                    var totals = commandResult.Models.OfType <Totals>().First();

                    var paymentComponent = context.Components.OfType <FederatedPaymentComponent>().First();
                    paymentComponent.Amount = Money.CreateMoney(totals.GrandTotal.Amount);
                    commandResult           = Proxy.DoCommand(container.AddFederatedPayment(cartId, paymentComponent));
                    totals = commandResult.Models.OfType <Totals>().First();

                    totals.PaymentsTotal.Amount.Should().Be(totals.GrandTotal.Amount);

                    var order = Orders.CreateAndValidateOrder(container, cartId, context);

                    order.Totals.GrandTotal.Amount.Should().Be(233.20M);
                    return(order.Id);
                }
                catch (Exception ex)
                {
                    ConsoleExtensions.WriteColoredLine(
                        ConsoleColor.Red,
                        $"Exception in Scenario {ScenarioName} (${ex.Message}) : Stack={ex.StackTrace}");
                    return(null);
                }
            }
        }
예제 #21
0
        public static string Run(ShopperContext context)
        {
            using (new SampleBuyScenarioScope())
            {
                try
                {
                    var container = context.ShopsContainer();

                    var orderId = BuySplitShipment.Run(context);
                    if (!string.IsNullOrEmpty(orderId))
                    {
                        OrdersUX.HoldOrder(orderId);
                    }

                    var journalizedOrdersMetadata =
                        container.GetListMetadata($"JournalEntries-ByEntity-{orderId}").GetValue();
                    System.Console.WriteLine(
                        $"List:{journalizedOrdersMetadata.ListName} Count:{journalizedOrdersMetadata.Count}");

                    var journalizedOrdersList = container.GetList(
                        $"JournalEntries-ByEntity-{orderId}",
                        "Sitecore.Commerce.Plugin.Journaling.JournalEntry, Sitecore.Commerce.Plugin.Journaling",
                        0,
                        10)
                                                .Expand("Items")
                                                .GetValue();

                    journalizedOrdersList.TotalItemCount.Should().Be(2);

                    return(orderId);
                }
                catch (Exception ex)
                {
                    ConsoleExtensions.WriteColoredLine(
                        ConsoleColor.Red,
                        $"Exception in Scenario {ScenarioName} (${ex.Message}) : Stack={ex.StackTrace}");
                    return(null);
                }
            }
        }
예제 #22
0
        private Currency GetCurrency()
        {
            bool     rightAnswer      = false;
            int      selectedCurrency = -1;
            Currency c = null;

            do
            {
                Console.WriteLine("Select currency to send your payment in:");

                for (int i = 0; i < currencies.Length; i++)
                {
                    Console.WriteLine($"{i + 1}) {currencies[i].CurrencyLongName}");
                }

                Console.Write("Select your currency: ");
                if (int.TryParse(Console.ReadLine(), out selectedCurrency))
                {
                    if (selectedCurrency - 1 < 0 || selectedCurrency - 1 > currencies.Length)
                    {
                        Console.WriteLine("Bad answer! Try again! ");
                        Console.ReadKey();
                        ConsoleExtensions.ClearLines(currencies.Length + 3);
                    }
                    else
                    {
                        c           = currencies[selectedCurrency - 1];
                        rightAnswer = true;
                    }
                }
                else
                {
                    Console.WriteLine("Bad answer! Try again! ");
                    Console.ReadKey();
                    ConsoleExtensions.ClearLines(currencies.Length + 3);
                }
            } while (!rightAnswer);

            return(c);
        }
예제 #23
0
        private static string[] Parse(string input)
        {
            //failures to conform to pattern:
            input = input switch
            {
                "2028 door light wood" => "{2028}{door-light-wood}",
                "2029 door heavy wood" => "{2029}{door-heavy-wood}",
                "2030 door metal gate" => "{2030}{door-metal-gate}",
                "2031 door metal" => "{2031}{door-metal}",
                "2032 door glass" => "{2032}{door-glass}",
                "2033 door stone" => "{2033}{door-stone}",
                "2034 door rock cave in" => "{2034}{door-rock-cave-in}",
                "2035 window house standard" => "{2035}{window-house-standard}",
                "2036 window store front" => "{2036}{window-store-front}",
                "2037 window curtains only" => "{2037}{window-curtains-only}",
                "2038 window jail bars" => "{2038}{window-jail-bars}",
                "2039 window wooden shutters" => "{2039}{window-wooden-shutters}",
                "2040 window metal shutters" => "{2040}{window-metal-shutters}",
                "2041 window stained glass" => "{2041}{window-stained-glass}",
                "2042 window boarded up" => "{2042}{window-boarded-up}",
                _ => input
            };

            var regex = new Regex(Pattern);

            if (Regex.Matches(input, Pattern).Count == 0)
            {
                ConsoleExtensions.Log($"Input: |{input}| failed to match pattern: {Pattern}!", "error");
            }
            var matches = Regex.Matches(input, Pattern);

            var output = new string[matches.Count];

            for (var i = 0; i < matches.Count; i++)
            {
                output[i] = regex.Replace(matches[i].Value, Substitution);
            }

            return(output);
        }
예제 #24
0
            public void Output_Should_Honor_Current_State_When_Switching_Between_States()
            {
                // Enable color output

                ColorOutputEnabledTest();


                // Disable color output

                /////////////////
                // ARRANGE
                /////////

                ConsoleExtensions.Disable();


                /////////////////
                // ACT
                /////////

                var outputAnsiColorString1 = _input.Pastel(Color.FromArgb(1, 1, 1));
                var outputAnsiColorString2 = _input.Pastel("#010101");
                var outputAnsiColorString3 = _input.PastelBg(Color.FromArgb(1, 1, 1));
                var outputAnsiColorString4 = _input.PastelBg("#010101");


                /////////////////
                // ASSERT
                /////////

                Assert.Equal(_input, outputAnsiColorString1);
                Assert.Equal(_input, outputAnsiColorString2);
                Assert.Equal(_input, outputAnsiColorString3);
                Assert.Equal(_input, outputAnsiColorString4);


                // Re-enable color output

                ColorOutputEnabledTest();
            }
예제 #25
0
        private static void NewAllocation()
        {
            using (new SampleMethodScope())
            {
                var view = Proxy.GetValue(
                    ShopsContainer.GetEntityView(
                        _privateCouponGroupId,
                        "AllocationDetails",
                        "NewAllocation",
                        string.Empty));
                view.Should().NotBeNull();
                view.Policies.Should().BeEmpty();
                view.Properties.Should().NotBeEmpty();
                view.Properties.Count.Should().Be(2); // Version & Count
                view.ChildViews.Should().BeEmpty();
                var version = view.Properties.FirstOrDefault(p => p.Name.Equals("Version"));
                view.Properties = new ObservableCollection <ViewProperty>
                {
                    new ViewProperty {
                        Name = "Count", Value = "15"
                    },
                    version
                };

                var newAllocationAction = Proxy.DoCommand(ShopsContainer.DoAction(view));
                newAllocationAction.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase))
                .Should()
                .BeFalse();
                newAllocationAction.Models.OfType <PrivateCouponList>().FirstOrDefault().Should().NotBeNull();
                var privateCouponList = newAllocationAction.Models.OfType <PrivateCouponList>().FirstOrDefault();
                privateCouponList.Should().NotBeNull();
                privateCouponList.GroupFriendlyId.Should().NotBeNullOrEmpty();

                ConsoleExtensions.WriteColoredLine(ConsoleColor.Green, "Allocated the following coupon codes");
                foreach (var code in privateCouponList.CouponCodes)
                {
                    Console.WriteLine(code);
                }
            }
        }
예제 #26
0
        public static void Represent(ISort sorter)
        {
            string _sortRuleName = string.Empty;
            int    length        = ConsoleExtensions.GetIntNumber(30, 5);

            int[] source = RandomGenerator.GetRandomIntArray(100, 0, length);

            Console.WriteLine($@"
=========================================
| Alhorithm: {sorter.Title}
| Initial array: {source.Represent()}
=========================================
| Available Actions:                    |
| 1. Sort generated array by descending |
| 2. Sort generated array by ascending  |
=========================================
");
            switch (ConsoleExtensions.GetIntNumber(2, 1))
            {
            case 1:
                _sortRuleName = "DESCENDING";
                sorter.Descending(source);
                break;

            case 2:
                _sortRuleName = "ASCENDING";
                sorter.Ascending(source);
                break;

            default:
                break;
            }

            Console.WriteLine($@"
========================================
|  {_sortRuleName,10} sort with description    |
========================================
|     Result is: {source.Represent()}
========================================");
        }
예제 #27
0
        private decimal GetAmount(string currency)
        {
            decimal amount;
            bool    rightAnswer = false;

            do
            {
                Console.Write($"\nEnter Amount: {currency}");
                if (decimal.TryParse(Console.ReadLine(), out amount))
                {
                    rightAnswer = true;
                }
                else
                {
                    Console.WriteLine("Bad answer! Try again! ");
                    Console.ReadKey();
                    ConsoleExtensions.ClearLines(2);
                }
            } while (!rightAnswer);

            return(amount);
        }
예제 #28
0
            // called by Java_com_oculus_gles3jni_GLES3JNILib_onTouchEvent
            // uithread
            public void ovrMessageQueue_PostMessage(ref ovrMessage message)
            {
                // 1674
                //ConsoleExtensions.tracei("enter ovrMessageQueue_PostMessage", (int)message.Id);

                // enabled by?
                if (!this.Enabled)
                {
                    ConsoleExtensions.trace("exit ovrMessageQueue_PostMessage, disabled!");
                    return;
                }
                while (this.Tail - this.Head >= MAX_MESSAGES)
                {
                    // block for a second until messages are processed in the worker?
                    // usleep(microseconds)
                    unistd.usleep(1000);
                }

                // lock(?)
                pthread.pthread_mutex_lock(ref this.Mutex);
                Messages[Tail & (MAX_MESSAGES - 1)] = message;
                Tail++;

                pthread.pthread_cond_broadcast(ref Posted);
                if (message.Wait == ovrMQWait.MQ_WAIT_RECEIVED)
                {
                    //ConsoleExtensions.tracei("ovrMessageQueue_PostMessage MQ_WAIT_RECEIVED, pthread_cond_wait");
                    pthread.pthread_cond_wait(ref Received, ref Mutex);
                }
                else if (message.Wait == ovrMQWait.MQ_WAIT_PROCESSED)
                {
                    //ConsoleExtensions.tracei("ovrMessageQueue_PostMessage MQ_WAIT_PROCESSED, pthread_cond_wait");
                    pthread.pthread_cond_wait(ref Processed, ref Mutex);
                    //ConsoleExtensions.tracei("ovrMessageQueue_PostMessage MQ_WAIT_PROCESSED, pthread_cond_wait done");
                }
                pthread.pthread_mutex_unlock(ref Mutex);

                //ConsoleExtensions.tracei("exit ovrMessageQueue_PostMessage");
            }
예제 #29
0
        private static void EditPriceTier()
        {
            using (new SampleMethodScope())
            {
                var result = Proxy.DoCommand(
                    Container.EditPriceTier("InvalidCard", _priceSnapshotId, _priceTierId, 13));
                result.Messages.Should().ContainMessageCode("validationerror");
                ConsoleExtensions.WriteExpectedError();

                result = Proxy.DoCommand(Container.EditPriceTier(_cardFriendlyId, "InvalidSnapshot", _priceTierId, 13));
                result.Messages.Should().ContainMessageCode("validationerror");
                ConsoleExtensions.WriteExpectedError();

                result = Proxy.DoCommand(
                    Container.EditPriceTier(_cardFriendlyId, _priceSnapshotId, "InvalidTiers", 13));
                result.Messages.Should().ContainMessageCode("validationerror");
                ConsoleExtensions.WriteExpectedError();

                result = Proxy.DoCommand(Container.EditPriceTier(_cardFriendlyId, _priceSnapshotId, _priceTierId, 13));
                result.Messages.Should().NotContainErrors();
            }
        }
        private static void AddPrivateCoupon()
        {
            Console.WriteLine("Begin AddPrivateCoupon");

            var addView = Proxy.GetValue(ShopsContainer.GetEntityView(_promotionId, "CouponDetails", "AddPrivateCoupon", string.Empty));

            addView.Should().NotBeNull();
            addView.Policies.Should().BeEmpty();
            addView.Properties.Should().NotBeEmpty();
            addView.Properties.Count.Should().Be(4); // Version, Prefix, Suffix & Total
            addView.ChildViews.Should().BeEmpty();
            var version = addView.Properties.FirstOrDefault(p => p.Name.Equals("Version"));

            addView.Properties = new ObservableCollection <ViewProperty>
            {
                new ViewProperty {
                    Name = "Prefix", Value = "before_"
                },
                new ViewProperty {
                    Name = "Suffix", Value = "_after"
                },
                new ViewProperty {
                    Name = "Total", Value = "20"
                },
                version
            };

            var addAction = Proxy.DoCommand(ShopsContainer.DoAction(addView));

            addAction.Messages.Any(m => m.Code.Equals("error", StringComparison.OrdinalIgnoreCase)).Should().BeFalse();
            addAction.Models.OfType <PrivateCouponGroupAdded>().FirstOrDefault().Should().NotBeNull();
            _privateCouponGroupId = addAction.Models.OfType <PrivateCouponGroupAdded>().FirstOrDefault()?.GroupFriendlyId;
            _privateCouponGroupId.Should().NotBeNullOrEmpty();
            var message = addAction.Messages.FirstOrDefault(m => m.Code.Equals("information", StringComparison.OrdinalIgnoreCase));

            message.Should().NotBeNull();

            ConsoleExtensions.WriteColoredLine(ConsoleColor.Green, message.Text);
        }