public void UserService_Get_User_Permissions_For_Unassigned_Permission_Nodes()
        {
            // Arrange
            var userService = ServiceContext.UserService;
            var userType = userService.GetUserTypeByAlias("admin");
            //we know this actually is an IUser so we'll just cast
            var user = (IUser)ServiceContext.UserService.CreateMembershipUser("test1", "test1", "test1", userType, "test1@test.com");
            var contentType = MockedContentTypes.CreateSimpleContentType();
            ServiceContext.ContentTypeService.Save(contentType);
            var content = new []
                {
                    MockedContent.CreateSimpleContent(contentType),
                    MockedContent.CreateSimpleContent(contentType),
                    MockedContent.CreateSimpleContent(contentType)
                };
            ServiceContext.ContentService.Save(content);

            // Act
            var permissions = userService.GetPermissions(user, content.ElementAt(0).Id, content.ElementAt(1).Id, content.ElementAt(2).Id);

            //assert
            Assert.AreEqual(3, permissions.Count());
            Assert.AreEqual(17, permissions.ElementAt(0).AssignedPermissions.Count());
            Assert.AreEqual(17, permissions.ElementAt(1).AssignedPermissions.Count());
            Assert.AreEqual(17, permissions.ElementAt(2).AssignedPermissions.Count());
        }
Example #2
0
        public void Execute()
        {
            //
            // ElementAt拡張メソッドは、指定した位置の要素を取得するメソッド。
            //
            // 範囲外のインデックスを指定した場合は例外が発生する.
            //
            var languages = new[] {"csharp", "visualbasic", "java", "python", "ruby", "php", "c++"};
            Output.WriteLine(languages.ElementAt(1));

            try
            {
                languages.ElementAt(100);
            }
            catch (ArgumentOutOfRangeException)
            {
                Output.WriteLine("要素の範囲外のインデックスを指定している。");
            }

            //
            // ElementAtOrDefault拡張メソッドは、ElementAt拡張メソッドと同じ動作を
            // しながら、範囲外のインデックスを指定された場合に規定値を返すメソッド。
            //
            Output.WriteLine(languages.ElementAtOrDefault(-1) ?? "null");
            Output.WriteLine(languages.ElementAtOrDefault(100) ?? "null");
        }
 private static void CheckIsRightTriangle(double a, double b, double c)
 {
     var orderedSide = new[] {a, b, c}.OrderBy(x => x);
     var hypotenuse = orderedSide.First();
     var legs1 = orderedSide.ElementAt(1);
     var legs2 = orderedSide.ElementAt(2);
     if (hypotenuse*hypotenuse != legs1*legs1 + legs2*legs2)
     {
         throw new ArithmeticException("Треугольник не является прямоугольным");
     }
 }
Example #4
0
        public void Enumerations_should_sort_by_Value_by_default()
        {
            var states = new [] { State.Stopping, State.Off, State.Starting, State.Busy, State.Waiting };

            Array.Sort(states);

            states.ElementAt(0).ShouldBe(State.Off);
            states.ElementAt(1).ShouldBe(State.Starting);
            states.ElementAt(2).ShouldBe(State.Waiting);
            states.ElementAt(3).ShouldBe(State.Busy);
            states.ElementAt(4).ShouldBe(State.Stopping);
        }
    public static void Main () {
        var ints = new[] { 1, 2, 3, 4 };

        Console.WriteLine(ints.ElementAt(0));
        Console.WriteLine(ints.ElementAt(1));
        Console.WriteLine(ints.ElementAt(3));

        Console.WriteLine(ints.ElementAtOrDefault(0));
        Console.WriteLine(ints.ElementAtOrDefault(1));
        Console.WriteLine(ints.ElementAtOrDefault(3));
        Console.WriteLine(ints.ElementAtOrDefault(-1));
        Console.WriteLine(ints.ElementAtOrDefault(5));
    }
        public void WhenQueryingForQuestionnareTemplates_ThenProvidesQuestionnaireTemplateResult()
        {
            AsyncResult<IEnumerable<QuestionnaireTemplate>> ar = null;
            QuestionnaireTemplate[] suppliedQuestionnaire = new[] { new QuestionnaireTemplate() };

            var serviceMock = new MockQuestionnaireService();

            serviceMock.HandleBeginGetQuestionnaireTemplates = (r) => ar = r;


            var repository = new QuestionnaireRepository(serviceMock);

            IOperationResult<IEnumerable<QuestionnaireTemplate>> getResult = null;
            repository.GetQuestionnaireTemplatesAsync((result) => getResult = result);

            serviceMock.ProceedGetQuestionnaireTemplates(ar, suppliedQuestionnaire);

            EnqueueConditional(() => getResult != null);
            EnqueueCallback(() =>
            {
                Assert.AreSame(suppliedQuestionnaire.ElementAt(0), getResult.Result.ElementAt(0));
            });

            EnqueueTestComplete();
        }
        internal static IEnumerable<Dokument> GetVedlegg(int antall = 5)
        {

            var vedleggTxt0 = new Dokument("Vedlegg", ResourceUtility.ReadAllBytes(true, "vedlegg", "Vedlegg.txt"), "text/plain");
            var vedleggDocx = new Dokument("Vedleggsgris", ResourceUtility.ReadAllBytes(true, "vedlegg", "VedleggsGris.docx"), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            var vedleggPdf = new Dokument("Vedleggshjelm", ResourceUtility.ReadAllBytes(true, "vedlegg", "VedleggsHjelm.pdf"), "application/pdf");
            var vedleggTxt1 = new Dokument("Vedlegg", ResourceUtility.ReadAllBytes(true, "vedlegg", "Vedlegg.txt"), "text/plain");
            var vedleggTxt2 = new Dokument("Vedlegg", ResourceUtility.ReadAllBytes(true, "vedlegg", "Vedlegg.txt"), "text/plain");

            var vedlegg = new[] {vedleggTxt0, vedleggDocx, vedleggPdf, vedleggTxt1, vedleggTxt2};

            if (antall <= 5)
            {
                return vedlegg.Take(antall);
            }
            else
            {
                var vedleggbatch = new List<Dokument>();
                for (var i = 0; i < antall; i++)
                {
                    var element = vedlegg.ElementAt(i % vedlegg.Length);
                    vedleggbatch.Add(new Dokument(element.Tittel, element.Bytes, element.MimeType, "NO", $"{i}-{element.Filnavn}"));
                }
                return vedleggbatch;
            }
        }
 public void Criar_EncontroPresencial_Com_Nome_ListaPresenca_QtdeBrindes_Data()
 {
     // Assert
     string nomeEvento = "1o Evento DevRs.Net 2013";
     var listaPresenca = new []{ "Participante1", "Participante2" };
     DateTime data = new DateTime(2013, 03, 26);
     int qtdeBrindes = 6;
     // Act
     EncontroPresencialTDD encontroPresencial = new EncontroPresencialTDD(nomeEvento, listaPresenca, qtdeBrindes, data);
     // Arrange
     Assert.AreEqual(nomeEvento, encontroPresencial.Nome);
     Assert.AreEqual(listaPresenca.ElementAt(0), encontroPresencial.ListaPresenca.ElementAt(0));
     Assert.AreEqual(listaPresenca.ElementAt(1), encontroPresencial.ListaPresenca.ElementAt(1));
     Assert.AreEqual(qtdeBrindes, encontroPresencial.QtdeBrindes);
     Assert.AreEqual(data, encontroPresencial.Data);
 }
        public void Intersperse_should_intersperse_an_item_between_each_element_of_a_list()
        {
            var items = new[] {1, 2, 3, 4, 5}.Intersperse(0);

            var expectedItems = new[] {1, 0, 2, 0, 3, 0, 4, 0, 5};

            for (int i = 0; i < 9; i++)
            {
                items.ElementAt(i).ShouldEqual(expectedItems[i]);
            }
        }
 public void TestEnumerableStringsConvert()
 {
     string input = "Mike,Jessy,Louis";
     IEnumerable<string> expected = new[] { "Mike", "Jessy", "Louis" };
     IEnumerable<string> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<string>)) as IEnumerable<string>;
     Assert.IsNotNull(result);
     Assert.AreEqual(expected.Count(), result.Count());
     for (int i = 0; i < expected.Count(); i++)
     {
         Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i));
     }
 }
 public void TestEnumerableIntConvert()
 {
     string input = "10,20,30";
     IEnumerable<int> expected = new[] { 10, 20, 30 };
     IEnumerable<int> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<int>)) as IEnumerable<int>;
     Assert.IsNotNull(result);
     Assert.AreEqual(expected.Count(), result.Count());
     for (int i = 0; i < expected.Count(); i++)
     {
         Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i));
     }
 }
        public void DifferenceTest()
        {
            var a = new[] { 1, 2, 3, 4, 5, 6, 7 };
            var b = new[] { 4, 5, 6, 7, 8, 9, 10 };

            IEnumerable<int> expected = new[] { 1, 2, 3, 8, 9, 10 };
            var result = a.Difference(b);

            Assert.AreEqual(expected.Count(), result.Count());
            for (int x = 0; x < expected.Count(); ++x)
                Assert.AreEqual(expected.ElementAt(x), result.ElementAt(x));
        }
 public void TestEnumerableDateConvert()
 {
     string input = "2010-09-08,2009-08-07,2008-07-06";
     IEnumerable<DateTime> expected = new[] { new DateTime(2010, 09, 08), new DateTime(2009, 08, 07), new DateTime(2008, 07, 06) };
     IEnumerable<DateTime> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<DateTime>)) as IEnumerable<DateTime>;
     Assert.IsNotNull(result);
     Assert.AreEqual(expected.Count(), result.Count());
     for (int i = 0; i < expected.Count(); i++)
     {
         Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i));
     }
 }
        public void Filter_string_not_equal_caseinsensitive()
        {
            IEnumerable<Person> people = new[] { new Person { Name = "A" }, new Person { Name = "B" } };

            var quearyablePeople = QueryableFactory.CreateQueryable(people);

            var filteredPeople = quearyablePeople.Where(new[] { new FilterDescriptor
            {
                Member = "Name",
                Operator = FilterOperator.IsNotEqualTo,
                Value = "a"
            }}).Cast<Person>();

            Assert.Same(people.ElementAt(1), filteredPeople.FirstOrDefault());
        }
Example #15
0
 public void ElementAt()
 {
     var items = new[] { 0, 1, 2 };
     AssertEquals(items.ElementAt(0), 0);
     AssertEquals(items.ElementAt(1), 1);
     AssertEquals(items.ElementAt(2), 2);
 }
Example #16
0
        public void UserRoleStoreInterface_AddToRoleAsync_AddsInstancesToCollectionProperties_ForBothSidesOfEntityRelationship()
        {
            var entities = new Mock<IWriteEntities>(MockBehavior.Strict);
            var instance = new SecurityStore(entities.Object) as IUserRoleStore<User, int>;
            const string roleName = "test";
            var user = new User();
            var data = new[]
            {
                new Permission { Name = Guid.NewGuid().ToString() },
                new Permission { Name = roleName },
                new Permission { Name = Guid.NewGuid().ToString() },
            }.AsQueryable();
            var dbSet = new Mock<DbSet<Permission>>(MockBehavior.Strict).SetupDataAsync(data);
            entities.Setup(x => x.Get<Permission>()).Returns(dbSet.Object);

            instance.AddToRoleAsync(user, roleName).Wait();

            user.Permissions.ShouldContain(data.ElementAt(1));
            data.ElementAt(1).Users.ShouldContain(user);
        }
Example #17
0
        static void Main(string[] args)
        {
            List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6 };
            List<int> list2 = new List<int>() { 6, 4, 2, 7, 9, 0 };

            // select many with list2.
            var query = list1.SelectMany(o => list2);

            foreach (var q in query)
                Console.Write("{0} ", q);

            // LINQ statement of SelectMany
            var query1 = from item1 in list1
                         from item2 in list2
                         select new { a = item1, b = item2 };

            foreach (var q in query1)
                Console.WriteLine("{0} ", q);

            // select many with list2
            var query2 = list1.SelectMany(o => list2, (a, b) => new { a, b });

            foreach (var q in query2)
                Console.WriteLine("{0} ", q);

            // join is equivalent to LINQ statement.
            //var query = from item1 in list1
            //            join item2 in list2 on item1 equals item2
            //            select item2;

            var query3 = list1.Join(
                list2,
                item1 => item1,
                item2 => item2,
                (item1, item2) => item2);

            foreach (var q in query3)
                Console.WriteLine("{0} ", q);

            // LINQ statement with group join
            var query4 = from item1 in list1
                         join item2 in list2 on item1 equals item2 into g
                         from item in g
                         select new { v = item1, c = item };

            foreach (var q in query4)
                Console.WriteLine("{0} count: {1} ", q.v, q.c);

            // LINQ method call equivalent to LINQ statement.            
            var query5 = list1.GroupJoin(
                list2,
                item1 => item1,
                item2 => item2,
                (item1, item2) => new { v = item1, c = item2.Count() });

            foreach (var q in query5)
                Console.WriteLine("{0} count: {1} ", q.v, q.c);

            //List<int> sequences = new List<int>() { 1, 2, 4, 3, 2, 4, 6, 4, 2, 4, 5, 6, 5, 2, 2, 6, 3, 5, 7, 5 };

            //var group = sequences.GroupBy(o => o);

            //foreach (var g in group)
            //    Console.WriteLine("{0} count: {1}", g.Key, g.Count());

            //var group2 = sequences.GroupBy(
            //    o => (o % 2 == 0) ? "Odd Number" : "Even Numbder",
            //    o2 => (o2 % 2 == 0) ? "Odd" : "Even");

            //foreach (var g in group2)
            //    Console.WriteLine(g.ToString());

            // ToLookup() demo
            var nameValuesGroup = new[]
            {
                new { name = "Allen", value = 65, group = "A" },
                new { name = "Abbey", value = 120, group = "A" },
                new { name = "Slong", value = 330, group = "B" },
                new { name = "George", value = 213, group = "C" },
                new { name = "Meller", value = 329, group = "C" },
                new { name = "Mary", value = 192, group = "B" },
                new { name = "Sue", value = 200, group = "C" }
            };
            var lookupValues = nameValuesGroup.ToLookup(c => c.group);
            foreach (var g in lookupValues)
            {
                Console.WriteLine("=== Group : {0} ===", g.Key);
                foreach (var item in g)
                    Console.WriteLine("name: {0}, value: {1}", item.name, item.value);
            }

            // order list.
            var nameValues = new[]
            {
                new { name = "Allen", value = 65 },
                new { name = "Abbey", value = 120 },
                new { name = "Slong", value = 330 },
                new { name = "George", value = 213 },
                new { name = "Meller", value = 329 },
                new { name = "Mary", value = 192 },
                new { name = "Sue", value = 200 }
            };

            // single sort
            var sortedNames = nameValues.OrderBy(c => c.name);
            var sortedValues = nameValues.OrderBy(c => c.value);
            Console.WriteLine("== OrderBy() demo: sortedNames ==");
            foreach (var q in sortedNames)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);
            Console.WriteLine("== OrderBy() demo: sortedValues ==");
            foreach (var q in sortedValues)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);

            // multiple sort conditions.
            var sortedByNameValues = nameValues.OrderBy(c => c.name).ThenBy(c =>
            c.value);
            var sortedByValueNames = nameValues.OrderBy(c => c.value).ThenBy(c => c.name);
            Console.WriteLine("== OrderBy() + ThenBy() demo: sortedByNameValues ==");
            foreach (var q in sortedByNameValues)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);
            Console.WriteLine("== OrderBy() + ThenBy() demo: sortedByValueNames ==");
            foreach (var q in sortedByValueNames)
                Console.WriteLine("name: {0} value: {1} ", q.name, q.value);

            // Union/Intersect/Except
            int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
            int[] numbersB = { 1, 3, 5, 7, 8 };

            var unionResults = numbersA.Union(numbersB);
            var intersectResults = numbersA.Intersect(numbersB);
            var exceptResults = numbersA.Except(numbersB);

            Console.WriteLine("== Union ==");

            foreach (var q in unionResults)
                Console.Write(q + " ");

            Console.WriteLine();
            Console.WriteLine("== Intersect ==");

            foreach (var q in intersectResults)
                Console.Write(q + " ");

            Console.WriteLine();
            Console.WriteLine("== Except ==");

            foreach (var q in exceptResults)
                Console.Write(q + " ");

            Console.WriteLine();

            // distinct
            int[] numberSeries = { 2, 2, 3, 5, 5 };

            var distinctValues = numberSeries.Distinct();

            Console.WriteLine("Distinct values from numberSeries");

            foreach (var q in distinctValues)
                Console.Write(q + " ");

            Console.WriteLine();

            var firstLastItems = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            // First()/Last()
            string firstContainsO = firstLastItems.First(s => s.Contains('o'));
            string lastContainsO = firstLastItems.Last(s => s.Contains('o'));

            Console.WriteLine("First string starting with 'o': {0}", firstContainsO);
            Console.WriteLine("Last string starting with 'o': {0}", lastContainsO);
            
            // ElementAt()
            string itemAtThree = firstLastItems.ElementAt(2);
            string itemAtSix = firstLastItems.ElementAt(5);

            Console.WriteLine("3rd string in list : {0}", itemAtThree);
            Console.WriteLine("6th string in list : {0}", itemAtSix);

            // 存款
            double myBalance = 100.0;
            // 提款的額度
            int[] withdrawItems = { 20, 10, 40, 50, 10, 70, 30 };
            double balance = withdrawItems.Aggregate(myBalance,
            (originbalance, nextWithdrawal) =>
            {
                Console.WriteLine("originbalance: {0}, nextWithdrawal: {1}",
                originbalance, nextWithdrawal);
                Console.WriteLine("Withdrawal status: {0}", (nextWithdrawal <=
                originbalance) ? "OK" : "FAILED");
                // 若存款餘額不夠時,不會扣除,否則扣除提款額度。
                return ((nextWithdrawal <= originbalance) ? (originbalance -
                nextWithdrawal) : originbalance);
            });
            // 顯示最終的存款數
            Console.WriteLine("Ending balance: {0}", balance);

            var balanceStatus = withdrawItems.Aggregate(myBalance,
                (originbalance, nextWithdrawal) =>
                {
                    return ((nextWithdrawal <= originbalance) ? (originbalance -
                    nextWithdrawal) : originbalance);
                },
                (finalbalance) =>
                {
                    return (finalbalance >= 1000) ? "Normal" : "Lower";
                });

            Console.WriteLine("Balance status: {0}", balanceStatus);


            Console.ReadLine();
        }
Example #18
0
        private List<string> GetParts(string zenSyntax, char[] symbols)
        {
            List<string> parts = new List<string>();
            int index = 0;

            for (int i = 0; i < zenSyntax.Length; i++)
            {
                char c = zenSyntax[i];

                if (i > 0 && symbols.Contains(c))
                {
                    parts.Add(zenSyntax.Substring(index, i - index));
                    index = i;
                }
            }

            IEnumerable<string> final = new[] { zenSyntax.Substring(index) };

            if (final.ElementAt(0) == "+")
            {
                final = HandleTrailingPlus(parts.Last());
            }

            parts.AddRange(final);

            // Adjust for multiple ^ characters
            for (int i = parts.Count - 2; i >= 0; i--)
            {
                if (parts[i] == "^")
                {
                    parts[i] = '^' + parts[i + 1];
                    parts.RemoveAt(i + 1);
                }
            }

            return parts;
        }
        public void TestWhenAll2_Completed1_Canceled1()
        {
            Task[] tasks =
                new[]
                {
                    DelayedTask.Delay(TimeSpan.FromMilliseconds(1 * TimingGranularity.TotalMilliseconds)).Select(_ => string.Empty),
                    DelayedTask.Delay(TimeSpan.FromMilliseconds(3 * TimingGranularity.TotalMilliseconds)).Then(_ => CompletedTask.Canceled())
                };
            Task delayed = DelayedTask.WhenAll(tasks);
            Assert.IsFalse(delayed.IsCompleted);

            try
            {
                delayed.Wait();
                Assert.Fail("Expected an exception");
            }
            catch (AggregateException ex)
            {
                Assert.AreEqual(TaskStatus.Canceled, delayed.Status);
                Assert.AreEqual(1, ex.InnerExceptions.Count);
                Assert.IsInstanceOfType(ex.InnerExceptions[0], typeof(TaskCanceledException));
            }

            Assert.IsTrue(delayed.IsCompleted);
            Assert.IsTrue(delayed.IsCanceled);
            Assert.AreEqual(TaskStatus.Canceled, delayed.Status);

            Task firstTask = tasks.ElementAt(0);
            Assert.IsTrue(firstTask.IsCompleted);
            Assert.AreEqual(TaskStatus.RanToCompletion, firstTask.Status);

            Task secondTask = tasks.ElementAt(1);
            Assert.IsTrue(secondTask.IsCompleted);
            Assert.IsTrue(secondTask.IsCanceled);
            Assert.AreEqual(TaskStatus.Canceled, secondTask.Status);
        }
Example #20
0
        void checkNaviMode(System.Windows.Media.PointCollection jointPositions, List<int> depthList)
        {
            //extract lefhand info
            System.Windows.Point leftHandPoint = jointPositions.ElementAt(0);
            int leftHandDepth = depthList.ElementAt(0);

            //handle unlock action (sliding)
            if (!isNaviModeOn && isFirstTouch)
            {
                if (leftHandPoint.X > lockButtonPosition.X - lockButtonWidth / 2 &&
                leftHandPoint.X < lockButtonPosition.X + lockButtonWidth / 2 &&
                leftHandPoint.Y > lockButtonPosition.Y - lockButtonHeight / 2 &&
                leftHandPoint.Y < lockButtonPosition.Y + lockButtonHeight / 2)
                {
                    isFirstTouch = false;

                    //update button x axis
                    lockButtonPosition.X = (float)leftHandPoint.X;
                }

            }
            else if (!isNaviModeOn && !isFirstTouch){
                if (leftHandPoint.Y > lockButtonPosition.Y - (lockButtonHeight / 2  + 20)&&
                leftHandPoint.Y < lockButtonPosition.Y + (lockButtonHeight / 2 + 20))
                {
                    //update button x axis
                    lockButtonPosition.X = (float)leftHandPoint.X;
                    if (lockButtonPosition.X > 320)
                    { //swipe to center and unlock
                        isNaviModeOn = true;
                        isFirstTouch = true;
                        lockButtonPosition.X = 40;
                    }
                }
                else { //back to original position
                    isFirstTouch = true;
                    lockButtonPosition.X = 40;
                }
            }

            if(isNaviModeOn){
                if (leftHandPoint.X > lockButtonPosition.X - lockButtonWidth / 2 &&
                    leftHandPoint.X < lockButtonPosition.X + lockButtonWidth / 2 &&
                    leftHandPoint.Y > lockButtonPosition.Y - lockButtonHeight / 2 &&
                    leftHandPoint.Y < lockButtonPosition.Y + lockButtonHeight / 2)
                {
                    naviModeCounter++;
                    if (naviModeCounter > naviModeThreshold)
                    {
                        isNaviModeOn = false;
                        naviModeCounter = 0;
                    }
                }
                else {
                    naviModeCounter = 0;
                }
            }
        }
Example #21
0
        void interpretCommand(System.Windows.Media.PointCollection jointPositions, List<int> depthList)
        {
            //only take care of right hand first
            System.Windows.Point rightHandPoint = jointPositions.ElementAt(1);
            int rightHandDepth = depthList.ElementAt(1);

            System.Windows.Point leftHandPoint = jointPositions.ElementAt(0);
            int leftHandDepth = depthList.ElementAt(0);

            string textInString = "";
            MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_DUPLEX, 0.8, 0.8);

            double x_ratio = rightHandPoint.X / (double)currentColorFrame.Width;
            double y_ratio = rightHandPoint.Y / (double)currentColorFrame.Height;

            //distance range
            int zoom_min = 1000;
            int zoom_max = 1700;
            int zoom_buffer_count = 25;
            float radius = 25.0f;

            int click_buffer_count = 25;

            if (rightHandDepth > zoom_min && rightHandDepth < zoom_max) //airmouse
            {
                zoom_in_counter = 0;
                zoom_out_counter = 0;

                //textInString = "AirMouse";
                //commandMode = "AirMouse";

                //check if click action is activated (i.e., left-hand position is close to right-hand)
                if (Math.Abs(rightHandPoint.X - leftHandPoint.X) < 20 && Math.Abs(rightHandPoint.Y - leftHandPoint.Y) < 20) {
                    click_counter++;

                    if (click_counter > click_buffer_count)
                    {
                        textInString = "Click";
                        commandMode = "MOUSE_CLICK";
                        socket.kinectClick();
                        click_counter = 0;
                    }
                }
                else{
                    click_counter = 0;
                    textInString = "AirMouse";
                    commandMode = "AirMouse";
                    socket.kinectMove(x_ratio, y_ratio);
                }
                /*
                double x = rightHandPoint.X - center_width;
                double y = rightHandPoint.Y - center_height;
                double distance = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
                double radians = Math.Atan(y / x);
                double degree = (radians / Math.PI) * 180;
                degree = -degree;

                if (x < 0)
                {
                    degree = degree + 180;
                }
                else if (x > 0 && y > 0)
                {
                    degree = degree + 360;
                }

                textInString = "dist:" + Math.Round(distance).ToString() + " deg:" + Math.Round(degree).ToString() + " depth:" + rightHandDepth.ToString();

                socket.airMouse(degree, distance);
                */
                //socket.kinectMove(x_ratio, y_ratio);

            }
            else if (rightHandDepth < zoom_min) //zoom_in
            {
                radius = 40.0f;
                socket.stopAirmouse();
                zoom_out_counter = 0;
                zoom_in_counter++;
                commandMode = "ZoomIn";
                textInString = "ZoomIn";

                if (zoom_in_counter > zoom_buffer_count)
                {
                    socket.zoomIn();
                    zoom_in_counter = 0;
                }

            }
            else if (rightHandDepth > zoom_max){ //zoom_out
                radius = 15.0f;
                socket.stopAirmouse();
                zoom_in_counter = 0;
                zoom_out_counter++;
                commandMode = "ZoomOut";
                textInString = "ZoomOut";

                if (zoom_out_counter > zoom_buffer_count)
                {
                    socket.zoomOut();
                    zoom_out_counter = 0;

                }
            }

            /*
            //check if it is in green zone for ZOOM_IN/ZOOM_OUT
            if (rightHandPoint.X < center_width + margin_right &&
                rightHandPoint.X > center_width - margin_left &&
                rightHandPoint.Y < center_height + margin_down &&
                rightHandPoint.Y > center_height - margin_up)
            {
                socket.stopAirmouse();

                //zoom-in/zoom-out mode
                if (rightHandDepth < zoom_in_max && rightHandDepth > zoom_in_min) {
                    textInString = "ZOOM_IN:" + rightHandDepth.ToString();
                    zoom_out_counter = 0;
                    zoom_in_counter++;
                    if (zoom_in_counter > zoom_buffer_count)
                    {
                        socket.zoomIn();
                        zoom_in_counter = 0;
                    }

                }
                else if (rightHandDepth < zoom_out_min && rightHandDepth > zoom_in_max) {
                    textInString = "NONE:" + rightHandDepth.ToString();
                }
                else if (rightHandDepth < zoom_out_max && rightHandDepth > zoom_out_min)
                {
                    textInString = "ZOOM_OUT:" + rightHandDepth.ToString();
                    zoom_in_counter = 0;
                    zoom_out_counter++;
                    if (zoom_out_counter > zoom_buffer_count)
                    {
                        socket.zoomOut();
                        zoom_out_counter = 0;
                    }
                }
                else {
                    textInString = "NONE:" + rightHandDepth.ToString();
                }

            }
            else {
                //calcuate the distance between center and angle degree

                double x = rightHandPoint.X - center_width;
                double y = rightHandPoint.Y - center_height;
                double distance = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
                double radians = Math.Atan(y/x);
                double degree = (radians / Math.PI) * 180;
                degree = -degree;

                if (x < 0) {
                    degree = degree + 180;
                }
                else if (x > 0 && y > 0) {
                    degree = degree + 360;
                }

                textInString = "dist:" + Math.Round(distance).ToString() + " deg:" + Math.Round(degree).ToString() + " depth:" + rightHandDepth.ToString();

                socket.airMouse(degree, distance);
            }
            */
            //overaly right hand
            Bgr bgr;
            /*
            if(commandMode == "AirMouse")
                bgr = new Bgr(200, 200, 200); //Red for hands
            else if(commandMode == "ZoomIn")
                bgr = new Bgr(100, 0, 100); //Red for hands
            else if(commandMode == "ZoomOut")
                bgr = new Bgr(0, 200, 0); //Red for hands
            else
                bgr = new Bgr(0, 0, 255); //Red for hands
            */
            bgr = new Bgr(100, 0, 100);

            //convert point type
            System.Drawing.PointF point = new System.Drawing.PointF((float)rightHandPoint.X, (float)rightHandPoint.Y);
            CircleF circle = new CircleF();
            circle.Center = point;

            //set radius/stroke according to the depth
            float ratio = (float)(max_depth_range - rightHandDepth) / (float)(max_depth_range - min_depth_range);
            if (ratio < 0)
                ratio = 0;

            //float radius = 40.0f * ratio;

            int stroke = (int)(40.0f * ratio);
            circle.Radius = radius;
            currentColorFrame.Draw(circle, bgr, -1);

            //System.Drawing.Point textLoc = new System.Drawing.Point((int)rightHandPoint.X, (int)rightHandPoint.Y);
            System.Drawing.Point textLoc = new System.Drawing.Point(300, 30);
            currentColorFrame.Draw(textInString, ref font, textLoc, new Bgr(0, 0, 0));
        }
        public void ElementAt_returns_the_element_at_the_specified_index()
        {
            IEnumerable data = new[] { 1 };

            Assert.Equal(1, data.ElementAt(0));
        }
Example #23
0
        // Q61: Find the sum of the only set of six 4-digit
        // figurate numbers with a cyclic property.
        public static int Q77()
        {
            Func<int, int> triangle = n => n * (n + 1) / 2;
              Func<int, int> square = n => n * n;
              Func<int, int> pentagonal = n => n * (3 * n - 1) / 2;
              Func<int, int> hexagonal = n => n * (2 * n - 1);
              Func<int, int> heptagonal = n => n * (5 * n - 3) / 2;
              Func<int, int> octagonal = n => n * (3 * n - 2);

              Func<Func<int, int>, string[]> get4digs = func => {
            int i = 0;
            IList<string> fourdigs = new List<string>();
            while (true) {
              var res = func(++i);
              if (res > 9999) return fourdigs.ToArray();
              if (res > 999 && Int32.Parse(res.ToString().Substring(2)) > 9) fourdigs.Add(res.ToString());
            }
              };

              var triangle4digits = get4digs(triangle);
              var square4digits = get4digs(square);
              var pentagonal4digits = get4digs(pentagonal);
              var hexagonal4digits = get4digs(hexagonal);
              var heptagonal4digits = get4digs(heptagonal);
              var octagonal4digits = get4digs(octagonal);

              Func<List<string>, bool> isCyclicUniqueSet = set => {
            if (set.Distinct().Count() != set.Count) return false;

            return set.All(n => set.Any(m => m != n && n.Substring(2) == m.Substring(0, 2)));
              };
              var all = new [] {
            triangle4digits,
            square4digits,
            pentagonal4digits,
            hexagonal4digits,
            heptagonal4digits,
            octagonal4digits}.
              OrderBy(s => s.Length).
              ToArray();

              Func<string, string, bool> isCyclic = (m, n) => m != n &&
            (m.Substring(2) == n.Substring(0, 2) ||
              n.Substring(2) == m.Substring(0, 2));

              foreach (var str1 in all.ElementAt(0)) {
            foreach (var str2 in all.ElementAt(1)) {
              if (!isCyclic(str1, str2)) continue;
              foreach (var str3 in all.ElementAt(2)) {
            if (!isCyclic(str3, str2) && !isCyclic(str3, str1)) continue;
            foreach (var str4 in all.ElementAt(3)) {
              if (!isCyclic(str4, str3) && !isCyclic(str4, str2) && !isCyclic(str4, str1)) continue;
              foreach (var str5 in all.ElementAt(4)) {
                if (!isCyclic(str5, str4) && !isCyclic(str5, str3) && !isCyclic(str5, str2) && !isCyclic(str5, str1)) continue;
                foreach (var str6 in all.ElementAt(5)) {
                  var set = new List<string> {str1, str2, str3, str4, str5, str6};
                  if (isCyclicUniqueSet(set)) return set.Select(Int32.Parse).Sum();
                }
              }
            }
              }
            }
              }
              return Int32.MinValue;
        }
Example #24
0
        SharedSettings(
            System.Collections.Generic.IEnumerable<Bam.Core.Module> objectFiles,
            System.Type convertExtensionClassType,
            System.Type conversionInterfaceType,
            Bam.Core.TypeArray convertParameterTypes)
        {
            var sharedInterfaces = SharedInterfaces(objectFiles);
            var implementedInterfaces = new Bam.Core.TypeArray(sharedInterfaces);
            implementedInterfaces.Add(conversionInterfaceType);

            // define a new type, that contains just the shared interfaces between all object files
            // (any interface not shared, must be cloned later)
            var typeSignature = "IDESharedSettings";
            var assemblyName = new System.Reflection.AssemblyName(typeSignature);
            var assemblyBuilder = System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule", true);
            var sharedSettingsTypeDefn = moduleBuilder.DefineType(typeSignature,
                System.Reflection.TypeAttributes.Public |
                System.Reflection.TypeAttributes.Class |
                System.Reflection.TypeAttributes.AutoClass |
                System.Reflection.TypeAttributes.AnsiClass |
                System.Reflection.TypeAttributes.BeforeFieldInit |
                System.Reflection.TypeAttributes.AutoLayout,
                typeof(C.SettingsBase),
                implementedInterfaces.ToArray());

                // TODO: is this necessary?
#if false
            sharedSettingsTypeDefn.DefineDefaultConstructor(
                System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName);
#endif

            // implement 'automatic property' setter and getters for each property in each interface
            foreach (var i in sharedInterfaces)
            {
                var properties = i.GetProperties();
                foreach (var prop in properties)
                {
                    var dynamicProperty = sharedSettingsTypeDefn.DefineProperty(prop.Name,
                        System.Reflection.PropertyAttributes.None,
                        prop.PropertyType,
                        System.Type.EmptyTypes);
                    var field = sharedSettingsTypeDefn.DefineField("m" + prop.Name,
                        prop.PropertyType,
                        System.Reflection.FieldAttributes.Private);
                    var methodAttrs = System.Reflection.MethodAttributes.Public |
                        System.Reflection.MethodAttributes.HideBySig |
                        System.Reflection.MethodAttributes.Virtual;
                    if (prop.IsSpecialName)
                    {
                        methodAttrs |= System.Reflection.MethodAttributes.SpecialName;
                    }
                    var getter = sharedSettingsTypeDefn.DefineMethod("get_" + prop.Name,
                        methodAttrs,
                        prop.PropertyType,
                        System.Type.EmptyTypes);
                    var setter = sharedSettingsTypeDefn.DefineMethod("set_" + prop.Name,
                        methodAttrs,
                        null,
                        new[] { prop.PropertyType });
                    var getIL = getter.GetILGenerator();
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ret);
                    dynamicProperty.SetGetMethod(getter);
                    var setIL = setter.GetILGenerator();
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ret);
                    dynamicProperty.SetSetMethod(setter);
                }
            }

            var projectSettingsConvertMethod = sharedSettingsTypeDefn.DefineMethod("Convert",
                System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Final | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.NewSlot | System.Reflection.MethodAttributes.Virtual,
                null,
                convertParameterTypes.ToArray());
            var convertIL = projectSettingsConvertMethod.GetILGenerator();
            foreach (var i in sharedInterfaces)
            {
                var extConvertParameterTypes = new Bam.Core.TypeArray(i);
                extConvertParameterTypes.AddRange(convertParameterTypes);
                var methInfo = convertExtensionClassType.GetMethod("Convert", extConvertParameterTypes.ToArray());
                if (null == methInfo)
                {
                        throw new Bam.Core.Exception("Unable to locate the function {0}.{1}(this {2})", convertExtensionClassType.FullName, "Convert", i.Name);
                }
                // TODO: can this be simplified, using the ldarg opcode? a simple loop would suffice
                convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                if (extConvertParameterTypes.Count > 1)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                }
                if (extConvertParameterTypes.Count > 2)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                }
                if (extConvertParameterTypes.Count > 3)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_3);
                }
                convertIL.Emit(System.Reflection.Emit.OpCodes.Call, methInfo);
            }
            convertIL.Emit(System.Reflection.Emit.OpCodes.Ret);

            var sharedSettingsType = sharedSettingsTypeDefn.CreateType();
            var attributeType = typeof(Bam.Core.SettingsExtensionsAttribute);

            // now that we have an instance of the shared settings type, calculate the values of the individual settings across all object files
            // for all shared interfaces
            var commonSettings = System.Activator.CreateInstance(sharedSettingsType) as SettingsBase;
            commonSettings.InitializeAllInterfaces(objectFiles.First(), true, false);
            foreach (var i in sharedInterfaces)
            {
                var attributeArray = i.GetCustomAttributes(attributeType, false);
                if (0 == attributeArray.Length)
                {
                    throw new Bam.Core.Exception("Settings interface {0} is missing attribute {1}", i.ToString(), attributeType.ToString());
                }

                var attribute = attributeArray[0] as Bam.Core.SettingsExtensionsAttribute;

                var cloneSettingsMethod = attribute.GetMethod("Clone", new[] { i, i });
                if (null == cloneSettingsMethod)
                {
                    throw new Bam.Core.Exception("Unable to find extension method {0}.SharedSettings(this {1}, {1}, {1}, {1})",
                        attribute.ExtensionsClassName,
                        i.ToString());
                }

                var intersectSettingsMethod = attribute.GetMethod("Intersect", new[] { i, i });
                if (null == intersectSettingsMethod)
                {
                    throw new Bam.Core.Exception("Unable to find extension method {0}.Intersect(this {1}, {1})",
                        attribute.ExtensionsClassName,
                        i.ToString());
                }

                var objectFileCount = objectFiles.Count();
                cloneSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.First().Settings });
                for (int objIndex = 1; objIndex < objectFileCount; ++objIndex)
                {
                    intersectSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.ElementAt(objIndex).Settings });
                }
            }
            return commonSettings;
        }
        private static void CheckForContradictionTestCase1()
        {
            List<DTElement> elements = new List<DTElement>();
            for (int i = 0; i < 3; i++)
                elements.Add(new DTElement { Name = string.Format("Condition {0}", i), Kind = DTElementKind.Condition });
            for (int i = 0; i < 2; i++)
                elements.Add(new DTElement { Name = string.Format("Action {0}", i), Kind = DTElementKind.Action });

            var f = DTState.No;
            var t = DTState.Yes;
            var e = DTState.Empty;
            var a = DTState.ActionYes;

            var states = new List<List<DTState>>
                                {   //contradicted: 0,1 / 2,4 / 3,6,7
                                    new DTState[] { t, t, t, t, t, f, t, t, f, f }.ToList(),
                                    new DTState[] { t, t, t, f, t, t, f, f, f, f }.ToList(),
                                    new DTState[] { t, t, f, t, f, t, t, t, t, f }.ToList(),
                                    new DTState[] { a, e, e, e, a, e, a, e, e, e }.ToList(),
                                    new DTState[] { a, a, a, e, a, a, e, a, a, e }.ToList()
                                };
            for (int i = 0; i < elements.Count; i++)
                elements[i].SetStates(states[i]);

            var expectedContradictedRules = new[]
                {
                    new[]
                    {
                        new DTRule(0, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[0] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[0] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[0] },
                        },
                        new[]
                        {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[0] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[0] },
                        }),
                        new DTRule(1, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[1] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[1] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[1] },
                        },
                        new[] {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[1] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[1] },
                        })
                    },
                    new[]
                    {
                        new DTRule(2, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[2] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[2] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[2] },
                        },
                        new[]
                        {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[2] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[2] },
                        }),
                        new DTRule(4, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[4] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[4] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[4] },
                        },
                        new[] {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[4] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[4] },
                        })
                    },
                    new[]
                    {
                        new DTRule(3, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[3] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[3] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[3] },
                        },
                        new[]
                        {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[3] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[3] },
                        }),
                        new DTRule(6, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[6] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[6] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[6] },
                        },
                        new[] {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[6] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[6] },
                        }),
                        new DTRule(7, new[]
                        {
                            new DTRuleElement{ ElementId = elements[0].Id, State = elements[0].States[7] },
                            new DTRuleElement{ ElementId = elements[1].Id, State = elements[1].States[7] },
                            new DTRuleElement{ ElementId = elements[2].Id, State = elements[2].States[7] },
                        },
                        new[] {
                            new DTRuleElement{ ElementId = elements[3].Id, State = elements[3].States[7] },
                            new DTRuleElement{ ElementId = elements[4].Id, State = elements[4].States[7] },
                        })
                    }
                };

            var ruleSet = DTRuleSet_Accessor.FromElements(elements);

            IEnumerable<IEnumerable<DTRule>> contradictedRules;
            bool hasContradictedRules = ruleSet.CheckForContradiction(out contradictedRules);
            contradictedRules = contradictedRules.OrderBy(cur => cur.Count());

            Assert.IsTrue(hasContradictedRules);
            Assert.IsTrue(expectedContradictedRules.Count() == contradictedRules.Count(), "Wrong contradicted rules count.");
            for (int i = 0; i < contradictedRules.Count(); i++)
            {
                var curActualList = contradictedRules.ElementAt(i);
                var curExpectedList = expectedContradictedRules.ElementAt(i);

                Assert.AreEqual(curExpectedList.Count(), curExpectedList.Count());
                for (int j = 0; j < curActualList.Count(); j++)
                {
                    var curActualRule = curActualList.ElementAt(j);
                    Assert.IsTrue(curExpectedList.Any(curExpectedRule => AreEqual(curExpectedRule, curActualRule)));
                }
            }
        }
        public virtual void Ensure_Correct_Timestamps_On_Revisions_Multiple_Units_Of_Work()
        {
            var e = new[]
                {
                    HiveModelCreationHelper.MockTypedEntity(), 
                    HiveModelCreationHelper.MockTypedEntity()
                };

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x)));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //create revisions with same status twice
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x)));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //new revision with new draft status
                e.ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x) { MetaData = new RevisionData(FixedStatusTypes.Draft) }));
                writer.Complete();
            }
            PostWriteCallback.Invoke();
            Thread.Sleep(TimeSpan.FromSeconds(0.7));

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                //dont' create a saved rev for the last one
                e.Where(x => x != e.Last()).ForEach(x => writer.EntityRepository.Revisions.AddOrUpdate(new Revision<TypedEntity>(x) { MetaData = new RevisionData(FixedStatusTypes.Saved) }));
                writer.Complete();
            }
            PostWriteCallback.Invoke();

            using (var reader = ReadonlyProviderSetup.ReadonlyUnitFactory.CreateReadonly())
            {
                var result = reader.EntityRepository.Revisions.GetAll<TypedEntity>().ToArray();
                Assert.AreEqual(7, result.Count());
                //ensure entity status changed dates are correct
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcStatusChanged).Distinct().Count());
                Assert.AreEqual(2, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcStatusChanged).Distinct().Count());

                //ensure rev created dates are correct
                Assert.AreEqual(4, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.MetaData.UtcCreated).Distinct().Count());
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.MetaData.UtcCreated).Distinct().Count());

                //ensure entity modifieid dates are correct
                Assert.AreEqual(4, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcModified).Distinct().Count());
                Assert.AreEqual(3, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcModified).Distinct().Count());

                //ensure entity created dates are correct
                Assert.AreEqual(1, result.Where(x => x.Item.Id == e.ElementAt(0).Id).Select(x => x.Item.UtcCreated).Distinct().Count());
                Assert.AreEqual(1, result.Where(x => x.Item.Id == e.ElementAt(1).Id).Select(x => x.Item.UtcCreated).Distinct().Count());
            }

        }
Example #27
0
            public async Task OnPackageVersionHigherThanLatestSetsItToLatestVersion()
            {
                var packageRegistration = new PackageRegistration { Id = "theId" };
                var packages = new[]
                    {
                        new Package
                            {
                                Version = "1.0.1",
                                PackageRegistration = packageRegistration,
                                Listed = false,
                                IsLatest = false,
                                IsLatestStable = false
                            },
                        new Package
                            {
                                Version = "1.0.0",
                                PackageRegistration = packageRegistration,
                                Listed = true,
                                IsLatest = true,
                                IsLatestStable = true
                            }
                    }.ToList();
                packageRegistration.Packages = packages;
                var packageRepository = new Mock<IEntityRepository<Package>>();
                var service = CreateService(packageRepository: packageRepository);

                await service.MarkPackageListedAsync(packages[0]);

                Assert.True(packageRegistration.Packages.ElementAt(0).IsLatest);
                Assert.True(packageRegistration.Packages.ElementAt(0).IsLatestStable);
                Assert.False(packages.ElementAt(1).IsLatest);
                Assert.False(packages.ElementAt(1).IsLatestStable);
            }
        public void TestWhenAll3_Canceled1_Faulted1()
        {
            Exception expectedException = new FormatException();
            Func<Task, string> exceptionSelector =
                task =>
                {
                    throw expectedException;
                };
            IEnumerable<Task<string>> tasks =
                new[]
                {
                    DelayedTask.Delay(TimeSpan.FromMilliseconds(1 * TimingGranularity.TotalMilliseconds)).Then(_ => CompletedTask.Canceled<string>()),
                    DelayedTask.Delay(TimeSpan.FromMilliseconds(3 * TimingGranularity.TotalMilliseconds)).Select(exceptionSelector)
                };
            Task<string[]> delayed = DelayedTask.WhenAll(tasks);
            Assert.IsFalse(delayed.IsCompleted);

            try
            {
                delayed.Wait();
                Assert.Fail("Expected an exception");
            }
            catch (AggregateException ex)
            {
                Assert.AreEqual(TaskStatus.Faulted, delayed.Status);
                Assert.AreEqual(1, ex.InnerExceptions.Count);
                foreach (Exception innerException in ex.InnerExceptions)
                {
                    Assert.AreSame(expectedException, innerException);
                }
            }

            Assert.IsTrue(delayed.IsCompleted);
            Assert.IsTrue(delayed.IsFaulted);
            Assert.AreEqual(TaskStatus.Faulted, delayed.Status);

            Task firstTask = tasks.ElementAt(0);
            Assert.IsTrue(firstTask.IsCompleted);
            Assert.IsTrue(firstTask.IsCanceled);
            Assert.AreEqual(TaskStatus.Canceled, firstTask.Status);

            Task secondTask = tasks.ElementAt(1);
            Assert.IsTrue(secondTask.IsCompleted);
            Assert.IsTrue(secondTask.IsFaulted);
            Assert.AreEqual(TaskStatus.Faulted, secondTask.Status);
            Assert.IsNotNull(secondTask.Exception);
            Assert.AreEqual(1, secondTask.Exception.InnerExceptions.Count);
            Assert.AreSame(expectedException, secondTask.Exception.InnerExceptions[0]);
        }
            public void OnLatestPackageVersionSetsPreviousToLatestVersion()
            {
                var packageRegistration = new PackageRegistration { Id = "theId" };
                var packages = new[]
                    {
                        new Package
                            { Version = "1.0.1", PackageRegistration = packageRegistration, IsLatest = true, IsLatestStable = true },
                        new Package
                            { Version = "1.0.0", PackageRegistration = packageRegistration, IsLatest = false, IsLatestStable = false }
                    }.ToList();
                packageRegistration.Packages = packages;
                var packageRepository = new Mock<IEntityRepository<Package>>();
                var service = CreateService(packageRepository: packageRepository);

                service.MarkPackageUnlisted(packages[0]);

                Assert.False(packageRegistration.Packages.ElementAt(0).IsLatest);
                Assert.False(packageRegistration.Packages.ElementAt(0).IsLatestStable);
                Assert.True(packages.ElementAt(1).IsLatest);
                Assert.True(packages.ElementAt(1).IsLatestStable);
            }
 private WoopsaValue Calibrate(System.Collections.Generic.IEnumerable<IWoopsaValue> Arguments)
 {
     _minLevel = Arguments.ElementAt(0).ToDouble();
     _maxLevel = Arguments.ElementAt(1).ToDouble();
     return WoopsaValue.Null;
 }