public async static Task GetDirectoryObjects(List<string> objectIds, List<Group> groups, List<DirectoryRole> roles, List<User> users)
        {
            string userObjectId = ClaimsPrincipal.Current.FindFirst(Globals.ObjectIdClaimType).Value;

            // MULTITENANT - need to formulate GraphServiceRoot from user's tenant instead of app's tenant
            Uri graphServiceRoot = new Uri(ConfigHelper.GraphResourceId + "/" + ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value);

            ActiveDirectoryClient graphClient = new ActiveDirectoryClient(graphServiceRoot, async () => { return GraphHelper.AcquireToken(userObjectId); });

            int batchCount = 0;
            List<Task<IBatchElementResult[]>> requests = new List<Task<IBatchElementResult[]>>();
            List<IReadOnlyQueryableSetBase<IDirectoryObject>> batch = new List<IReadOnlyQueryableSetBase<IDirectoryObject>>();
            IEnumerator<string> idIndex = objectIds.GetEnumerator();
            IEnumerator<string> nextId = objectIds.GetEnumerator();
            nextId.MoveNext();
            while (idIndex.MoveNext())
            {
                string thisId = idIndex.Current; // for delegate capture
                batch.Add(graphClient.DirectoryObjects.Where(o => o.ObjectId.Equals(thisId)));
                batchCount++;
                if (!nextId.MoveNext() || batchCount == 5)
                {
                    requests.Add(graphClient.Context.ExecuteBatchAsync(batch.ToArray()));
                    batchCount = 0;
                    batch.Clear();
                }
            }

            IBatchElementResult[][] responses = await Task.WhenAll<IBatchElementResult[]>(requests);
            foreach (IBatchElementResult[] batchResult in responses)
            {
                foreach (IBatchElementResult query in batchResult)
                {
                    if (query.SuccessResult != null && query.FailureResult == null)
                    {
                        if (query.SuccessResult.CurrentPage.First() is Group)
                        {
                            Group group = query.SuccessResult.CurrentPage.First() as Group;
                            groups.Add(group);
                        }
                        if (query.SuccessResult.CurrentPage.First() is DirectoryRole)
                        {
                            DirectoryRole role = query.SuccessResult.CurrentPage.First() as DirectoryRole;
                            roles.Add(role);
                        }
                        if (query.SuccessResult.CurrentPage.First() is User)
                        {
                            User user = query.SuccessResult.CurrentPage.First() as User;
                            users.Add(user);
                        }
                    }
                    else
                    {
                        throw new Exception("Directory Object Not Found.");
                    }
                }
            }

            return;
        }
Example #2
0
        public static void listIteration()
        {
            Console.WriteLine("# List Iteration Sample");

            List<String> list = new List<String>();
            list.Add("Hello");
            list.Add("Lorem");
            list.Add("Ipsum");

            List<String>.Enumerator iterator = list.GetEnumerator();
            while (iterator.MoveNext())
            {
                String current = iterator.Current;
                Console.WriteLine(current);
            }

            IEnumerator<String> iterator2 = list.GetEnumerator();
            while (iterator2.MoveNext())
            {
                String current = iterator2.Current;
                Console.WriteLine(current);
            }

            foreach (String current in list)
            {
                Console.WriteLine(current);
            }
        }
        static void Main(string[] args)
        {
            var list = new List<int> { 1, 2, 3 };
            //var x1 = new { Items = ((IEnumerable<int>)list).GetEnumerator() };
           /* while (x1.Items.MoveNext())
            {
                Console.WriteLine(x1.Items.Current);
            }*/

            //Console.ReadLine();

            var x2 = new { Items = list.GetEnumerator() };
            var en = list.GetEnumerator();
            while (en.MoveNext())
            {
                Console.WriteLine(en.Current);
            }
            Console.ReadLine();
            return;
            
            Program pr = new Program();
            pr.Test();
            return;
            ReadLastDates();
            string mongoUrl = File.ReadAllText("settings\\mongoConnection");
            CountersDatabase.InitConnection(mongoUrl);
            List<CounterCategoryInfo> categories = CountersDatabase.Instance.GetCounterCategories().ToList();
            foreach (CounterCategoryInfo counterCategoryInfo in categories)
            {
                List<CounterNameInfo> counterNames =
                    CountersDatabase.Instance.GetCounterNamesInCategory(counterCategoryInfo.Id).ToList();
                foreach (CounterNameInfo counterNameInfo in counterNames)
                {
                    Console.WriteLine("Чистим " + counterCategoryInfo.Name + "." + counterNameInfo.Name);
                    DateTime left, right;
                    left = right = GetLastProcessedDateForCounter(counterCategoryInfo, counterNameInfo);
                    while (right < DateTime.Now.AddMinutes(-20))
                    {
                        var possibleLeftDate = CountersDatabase.Instance.GetFreshestAfterDate(counterCategoryInfo.Name, counterNameInfo.Name, left);
                        if(!possibleLeftDate.HasValue) break;
                        left = possibleLeftDate.Value;
                        right = left.AddMinutes(5).AddSeconds(-1);
                        CountersDatabase.Instance.RemoveCountersValuesBetweenDates(counterCategoryInfo.Name, counterNameInfo.Name, left, right);
                        //left = right.AddSeconds(1);
                    }
                    Console.WriteLine("Почистили " + counterCategoryInfo.Name + "." + counterNameInfo.Name);
                    File.AppendAllText("lastDates", counterCategoryInfo.Name + "\t" + counterNameInfo.Name + "\t" + left+"\r\n");
                }
            }
        }
Example #4
0
 public static Mock<EnvDTE.Commands> CreateCommands(List<EnvDTE.Command> commands)
 {
     var mock = new Mock<EnvDTE.Commands>(MockBehavior.Strict);
     var enumMock = mock.As<IEnumerable>();
     mock.Setup(x => x.GetEnumerator()).Returns(() =>
         {
             return commands.GetEnumerator();
         });
     mock.SetupGet(x => x.Count).Returns(commands.Count);
     enumMock.Setup(x => x.GetEnumerator()).Returns(() =>
         {
             return commands.GetEnumerator();
         });
     return mock;
 }
 public void Constructor_with_enumerator_argument_should_initialize_instance()
 {
     var items = new List<int> { 1, 2 };
     var subject = new BatchableSource<int>(items.GetEnumerator());
     subject.Batch.Should().BeNull();
     subject.HasMore.Should().BeTrue();
 }
Example #6
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");

        try
        {
            string[] strArray = { "apple", "banana", "chocolate", "dog", "food" };
            List<string> listObject = new List<string>(strArray);
            List<string>.Enumerator enumerator = listObject.GetEnumerator();
            int i = 0;
            while (enumerator.MoveNext())
            {
                if (enumerator.Current != strArray[i])
                {
                    TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,The i is: " + i);
                    retVal = false;
                }
                i++;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
 private static List<MemoryElement> GenerateObjectTypeGroups(ObjectInfo[] memory, MemoryElementDataManager.ObjectTypeFilter filter)
 {
   List<MemoryElement> memoryElementList = new List<MemoryElement>();
   MemoryElement memoryElement = (MemoryElement) null;
   foreach (ObjectInfo objectInfo in memory)
   {
     if (MemoryElementDataManager.GetObjectTypeFilter(objectInfo) == filter)
     {
       if (memoryElement == null || objectInfo.className != memoryElement.name)
       {
         memoryElement = new MemoryElement(objectInfo.className);
         memoryElementList.Add(memoryElement);
       }
       memoryElement.AddChild(new MemoryElement(objectInfo, true));
     }
   }
   memoryElementList.Sort(new Comparison<MemoryElement>(MemoryElementDataManager.SortByMemorySize));
   using (List<MemoryElement>.Enumerator enumerator = memoryElementList.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       MemoryElement current = enumerator.Current;
       current.children.Sort(new Comparison<MemoryElement>(MemoryElementDataManager.SortByMemorySize));
       if (filter == MemoryElementDataManager.ObjectTypeFilter.Other && !MemoryElementDataManager.HasValidNames(current.children))
         current.children.Clear();
     }
   }
   return memoryElementList;
 }
Example #8
0
        private static void CannotChangeForeachIterationVariable()
        {
            var people = new List<Person>
            {
                new Person() { FirstName = "John", LastName = "Doe"},
                new Person() { FirstName = "Jane", LastName = "Doe"},
            };
            foreach (Person p in people)
            {
                p.LastName = "Changed"; // This is allowed
                // p = new Person(); // This gives a compile error
            }

            // Compiler generated code
            List<Person>.Enumerator e = people.GetEnumerator();
            try
            {
                Person v;
                while (e.MoveNext())
                {
                    v = e.Current;
                }
            }
            finally
            {
                System.IDisposable d = e as System.IDisposable;
                if (d != null) d.Dispose();
            }
        }
Example #9
0
 public WorldModel(List<Action> actions)
 {
     this.ResourceEnabled = new Dictionary<string, bool>();
     this.GoalValues = new Dictionary<string, float>();
     this.Actions = actions;
     this.ActionEnumerator = actions.GetEnumerator();
 }
        public IEnumerable<Tuple<float, string>> CalculateRatios(float length)
        {
            var ratios = new List<float>();
            var names = new List<string>();
            float last = 0.0f;
            foreach (var shaderKeyframe in keyframes)
            {
                ratios.Add((shaderKeyframe.Key - last) / length);
                last = shaderKeyframe.Key;
                names.Add(shaderKeyframe.Value);
            }
            ratios.Add((length - last) / length);
            ratios.RemoveAt(0);
            var result = new List<Tuple<float, string>>();
            if (0 == ratios.Count) return result;

            var enumRatios = ratios.GetEnumerator();
            var enumNames = names.GetEnumerator();
            enumRatios.MoveNext();
            enumNames.MoveNext();
            do
            {
                result.Add(new Tuple<float, string>(enumRatios.Current, enumNames.Current));
            } while (enumRatios.MoveNext() && enumNames.MoveNext());
            return result;
        }
Example #11
0
		protected virtual void initWithArray(List<CCMenuItem> arrayOfItems){
			this.touchPriority = kCCMenuHandlerPriority;
			this.touchMode = kCCTouchesMode.OneByOne;
			this.isTouchEnabled = true;
			_enabled = true;
			
			// by default, menu in the center of the screen
			Vector2 s = CCDirector.sharedDirector.winSize;
			
			this.ignoreAnchorPointForPosition = true;
			_anchorPoint = new Vector2(0.5f, 0.5f);
			this.contentSize = s;


			this.position = s / 2;
			
			int z=0;

			if(arrayOfItems!=null){
				var enumerator = arrayOfItems.GetEnumerator();
				while (enumerator.MoveNext()) {
					CCMenuItem item = enumerator.Current;
					addChild(item, z);
					z++;
				}
			}
			_selectedItem = null;
			_state = kCCMenuState.Waiting;
			
			// enable cascade color and opacity on menus
			this.cascadeColorEnabled = true;
			this.cascadeOpacityEnabled = true;
		}
Example #12
0
        public byte[] GetHeadlockFileFingerprintOld(string path)
        {
            var fileContents = new List<string>(File.ReadAllLines(path));
            var result = new List<string>();

            var e = fileContents.GetEnumerator();
            while (e.MoveNext())
            {
                if (e.Current.Equals(BEGIN))
                {
                    e.MoveNext();
                    while(!e.Current.Equals(END))
                    {
                        result.Add(e.Current);
                        e.MoveNext();
                    }

                    var sb = new StringBuilder();
                    foreach (var line in result)
                        sb.Append(line+"\r");

                    sb.Length = sb.Length - 1;

                    return _encoding.CurrentEncoding.GetBytes(sb.ToString());
                }
            }

            throw new Exception("didn't find fingerprint");
        }
        public void Animal_needs_an_enclosure()
        {
            var mockContext = new Mock<IZooDbContext>();

            var animals = new List<Animal>
            {
                new Animal
                {
                    Id = 1,
                    Name = "Pumba",
                    Enclosure = new Enclosure
                    {
                        Id = 1, Name = "Kenya Room",
                        Location = "Center",
                        Environment = "Africa"
                    }
                }
            }.AsQueryable();

            var mockSet = new Mock<DbSet<Animal>>();
            mockSet.As<IQueryable<Animal>>().Setup(m => m.Provider).Returns(animals.Provider);
            mockSet.As<IQueryable<Animal>>().Setup(m => m.Expression).Returns(animals.Expression);
            mockSet.As<IQueryable<Animal>>().Setup(m => m.ElementType).Returns(animals.ElementType);
            mockSet.As<IQueryable<Animal>>().Setup(m => m.GetEnumerator()).Returns(animals.GetEnumerator());

            mockContext.Setup(x => x.Animals)
                .Returns(mockSet.Object);

            var db = mockContext.Object;
            var controller = new HomeController() { Database = db };

            var result = controller.Index();

            Assert.IsType<ViewResult>(result);
        }
Example #14
0
 private IEnumerator LoadAsync(List<string> list)
 {
     using (List<string>.Enumerator erator = list.GetEnumerator())
     {
         while (erator.MoveNext())
         {
             string key = erator.Current;
             if (key.EndsWith(".cb"))
             {
                 if (ResHost.UseCsv)
                 {
                     OnCsvHandle(key, File.ReadAllBytes(UrlUtil.Combine(Settings.CSV_FOLDER, Path.GetFileNameWithoutExtension(key) + ".csv")));
                 }
                 else
                 {
                     // AssetManager.Load(key, false, OnDataHandle, OnLoadCallback);
                     OnDataHandle(key, File.ReadAllBytes(UrlUtil.Combine(Settings.UNITY_RAW_FOLDER, key)));
                     OnLoadCallback(key);
                 }
                 yield return 1;
             }
             else
             {
                 AssetManager.Load(key, false, null, OnLoadCallback);
             }
         }
     }
 }
 public void CleanupUntouchedEditors()
 {
   List<UnityEngine.Object> objectList = new List<UnityEngine.Object>();
   using (Dictionary<UnityEngine.Object, EditorWrapper>.KeyCollection.Enumerator enumerator = this.m_EditorCache.Keys.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       UnityEngine.Object current = enumerator.Current;
       if (!this.m_UsedEditors.ContainsKey(current))
         objectList.Add(current);
     }
   }
   if (this.m_EditorCache != null)
   {
     using (List<UnityEngine.Object>.Enumerator enumerator = objectList.GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         UnityEngine.Object current = enumerator.Current;
         EditorWrapper editorWrapper = this.m_EditorCache[current];
         this.m_EditorCache.Remove(current);
         if (editorWrapper != null)
           editorWrapper.Dispose();
       }
     }
   }
   this.m_UsedEditors.Clear();
 }
Example #16
0
        static void Main(string[] args)
        {
            //PullExample.Run();
            Console.WriteLine("enumerables: foreach (array)");
            IEnumerable<int> xs = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            foreach (var x in xs) Console.Write(x + " "); Console.WriteLine();

            Console.WriteLine("enumerables: foreach (list)");
            xs = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
            foreach (var x in xs) Console.Write(x + " "); Console.WriteLine();

            Console.WriteLine("enumerables: behind the scenes");
            var e = xs.GetEnumerator();
            while (e.MoveNext()) Console.Write(e.Current + " "); Console.WriteLine();

            Console.WriteLine("enumerables: queries (filter) - Where(x => x % 2 == 0)");
            var ys = xs.Where(x => x % 2 == 0);
            foreach (var y in ys) Console.Write(y + " "); Console.WriteLine();

            Console.WriteLine("enumerables: queries (map) - Select(x => x * x)");
            ys = xs.Select(x => x * x);
            foreach (var y in ys) Console.Write(y + " "); Console.WriteLine();
            Console.ReadLine();
              	//  PushExample.Run();

               // TasksExample.Run();
        }
Example #17
0
        public static void ParallelTask(List<Action> actionList, int taskCountPerTime)
        {
            if (actionList == null || actionList.Count == 0) return;
            if (taskCountPerTime <= 1 || actionList.Count == 1)
            {
                SerialTask(actionList);
                return;
            }

            var enumer = actionList.GetEnumerator();

            int taskCount = Math.Min(actionList.Count, taskCountPerTime);

            Task[] tasks = new Task[taskCount];

            for (int i = 0; i < taskCount; i++)
            {
                enumer.MoveNext();
                tasks[i] = Task.Factory.StartNew(enumer.Current);
            }

            while (enumer.MoveNext())
            {
                int idx = Task.WaitAny(tasks);
                tasks[idx] = Task.Factory.StartNew(enumer.Current);
            }
            Task.WaitAll(tasks);
        }
        public void Execute(ActionExecutionContext context)
        {
            try {
                var taskList = new List<IResult>();
                using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) {
                    if (storage.DirectoryExists(G.FolderName)) {
                        var fileNames = storage.GetFileNames(G.FolderName + "\\*").OrderByDescending(s => s).ToList();
                        int counter = 0;
                        foreach (var fileName in fileNames) {
                            if (string.IsNullOrEmpty(fileName))
                                continue;
                            string filePath = Path.Combine(G.FolderName, fileName);
                            //If there are more exceptions in the pool we just delete them.
                            if (counter < G.MaxExceptions)
                                taskList.Add(new SendErrorTask(filePath));
                            else
                                storage.DeleteFile(filePath);
                            counter++;
                            //
                        }
                    }
                }
                Coroutine.BeginExecute(taskList.GetEnumerator());
            }
            //If this fails it probably due to an issue with the Isolated Storage.
            catch (Exception e) { /* Swallow like a fish - Not much that we can do here */}
            finally {
                TaskCompleted();

            }
        }
Example #19
0
        /** Reads the stream, consuming a format that is a tab-separated values of 3 columns:
         * an "id", a "name" and the "shape".  Empty lines and lines starting with a '#' are skipped.
         * The stream is closed.
         */
        public static IEnumerator<SpatialTestData> GetTestData(Stream @in, SpatialContext ctx)
        {
            List<SpatialTestData> results = new List<SpatialTestData>();
            TextReader bufInput = new StreamReader(@in, Encoding.UTF8);
            try
            {
                String line;
                while ((line = bufInput.ReadLine()) != null)
                {
                    if (line.Length == 0 || line[0] == '#')
                        continue;

                    SpatialTestData data = new SpatialTestData();
                    String[] vals = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (vals.Length != 3)
                        throw new ArgumentException("bad format; expecting 3 tab-separated values for line: " + line);
                    data.id = vals[0];
                    data.name = vals[1];
                    try
                    {
                        data.shape = ctx.ReadShapeFromWkt(vals[2]);
                    }
                    catch (ParseException e)
                    {
                        throw new ApplicationException(e.Message, e);
                    }
                    results.Add(data);
                }
            }
            finally
            {
                bufInput.Dispose();
            }
            return results.GetEnumerator();
        }
        public async void LoadLatestDeviceTelemetryAsyncTest()
        {
            var year = 2016;
            var month = 7;
            var date = 5;
            var minTime = new DateTime(year, month, date);

            var blobReader = new Mock<IBlobStorageReader>();
            var blobData = "deviceid,temperature,humidity,externaltemperature,eventprocessedutctime,partitionid,eventenqueuedutctime,IoTHub" +
                Environment.NewLine +
                "test1,34.200411299709423,32.2233033525866,,2016-08-04T23:07:14.2549606Z,3," + minTime.ToString("o") + ",Record";
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(blobData));
            var blobContents = new BlobContents {Data = stream, LastModifiedTime = DateTime.UtcNow};
            var blobContentIterable = new List<BlobContents>();
            blobContentIterable.Add(blobContents);

            blobReader.Setup(x => x.GetEnumerator()).Returns(blobContentIterable.GetEnumerator());
            _blobStorageClientMock.Setup(x => x.GetReader(It.IsNotNull<string>(), It.IsAny<DateTime?>()))
                .ReturnsAsync(blobReader.Object);
            var telemetryList = await deviceTelemetryRepository.LoadLatestDeviceTelemetryAsync("test1", null, minTime);
            Assert.NotNull(telemetryList);
            Assert.NotEmpty(telemetryList);
            Assert.Equal(telemetryList.First().DeviceId, "test1");
            Assert.Equal(telemetryList.First().Timestamp, minTime);
        }
Example #21
0
		static void Main(string[] args)
		{
			List<Duck> ducks = new List<Duck>()
			{
				new Duck() {Kind = KindOfDuck.Mallard, Size = 17},
				new Duck() {Kind = KindOfDuck.Muscovy, Size = 18},
				new Duck() {Kind = KindOfDuck.Decoy, Size = 14},
				new Duck() {Kind = KindOfDuck.Muscovy, Size = 11},
				new Duck() {Kind = KindOfDuck.Mallard , Size = 14},
				new Duck() {Kind = KindOfDuck.Decoy, Size = 13},
			};

			DuckComparer duckComparer = new DuckComparer(SortCriteria.KindThenSize);

			//Duck[] duckArray = new Duck[6];
			//duckArray.GetEnumerator();
			//ducks[0].CompareTo(ducks[1]);
			//ducks.OrderBy(x => x.Size);
			//DuckComparerBySize sizeComparer = new DuckComparerBySize();
			//DuckComparerByKInd kindComparer = new DuckComparerByKInd();
			////ducks.Sort(sizeComparer);
			//ducks.Sort(kindComparer);
			ducks.Sort(duckComparer);
			ducks.GetEnumerator();
			PrintDucks(ducks);
			Console.ReadKey();


		}
        public async void LoadLatestDeviceTelemetrySummaryAsyncTest()
        {
            var year = 2016;
            var month = 7;
            var date = 5;
            var minTime = new DateTime(year, month, date);

            var blobReader = new Mock<IBlobStorageReader>();
            var blobData = "deviceid,averagehumidity,minimumhumidity,maxhumidity,timeframeminutes" + Environment.NewLine +
                           "test2,37.806204872115607,37.806204872115607,37.806204872115607,5";
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(blobData));
            var blobContents = new BlobContents {Data = stream, LastModifiedTime = DateTime.UtcNow};
            var blobContentIterable = new List<BlobContents>();
            blobContentIterable.Add(blobContents);

            blobReader.Setup(x => x.GetEnumerator()).Returns(blobContentIterable.GetEnumerator());
            _blobStorageClientMock.Setup(x => x.GetReader(It.IsNotNull<string>(), It.IsAny<DateTime?>()))
                .ReturnsAsync(blobReader.Object);
            var telemetrySummaryList =
                await deviceTelemetryRepository.LoadLatestDeviceTelemetrySummaryAsync("test2", minTime);
            Assert.NotNull(telemetrySummaryList);
            Assert.Equal(telemetrySummaryList.DeviceId, "test2");
            Assert.Equal(telemetrySummaryList.AverageHumidity, 37.806204872115607);
            Assert.Equal(telemetrySummaryList.MinimumHumidity, 37.806204872115607);
            Assert.Equal(telemetrySummaryList.MaximumHumidity, 37.806204872115607);
            Assert.Equal(telemetrySummaryList.TimeFrameMinutes, 5);
        }
Example #23
0
 public WorldModel(List<Action> actions)
 {
     this.Properties = new Dictionary<string, object>();
     this.GoalValues = new Dictionary<string, float>();
     this.Actions = actions;
     this.ActionEnumerator = actions.GetEnumerator();
 }
            public void ReturnsPostsThatHavePublishedSetToTrue_AndPostedDateDesc()
            {
                var posts = new List<Post>
                {
                    new Post {Id = 1, PostedOn = DateTime.Now.AddDays(-2), Published = true},
                    new Post {Id = 2, PostedOn = DateTime.Now.AddDays(-1), Published = false},
                    new Post {Id = 3, PostedOn = DateTime.Now, Published = true},
                }.AsQueryable();

                var mockPosts = new Mock<DbSet<Post>>();
                mockPosts.As<IQueryable<Post>>().Setup(m => m.Provider).Returns(posts.Provider);
                mockPosts.As<IQueryable<Post>>().Setup(m => m.Expression).Returns(posts.Expression);
                mockPosts.As<IQueryable<Post>>().Setup(m => m.ElementType).Returns(posts.ElementType);
                mockPosts.As<IQueryable<Post>>().Setup(m => m.GetEnumerator()).Returns(posts.GetEnumerator());

                var expected = mockPosts.Object.Where(x => x.Published).OrderByDescending(x => x.PostedOn).ToList();

                _slapdashContext
                    .Setup(x => x.Posts)
                    .Returns(mockPosts.Object);

                var actual = _classUnderTest.Posts(1, 1);

                Assert.Equal(expected, actual);
            }
Example #25
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");

        try
        {
            int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 };
            List<int> listObject = new List<int>(iArray);
            List<int>.Enumerator enumerator = listObject.GetEnumerator();
            for (int i = 0; i < 10; i++)
            {
                enumerator.MoveNext();
                if (enumerator.Current != iArray[i])
                {
                    TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is: " + i);
                    retVal = false;
                }
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public async void LoadLatestAlertHistoryAsyncTest()
        {
            var year = 2016;
            var month = 7;
            var date = 5;
            var value = "10.0";
            var minTime = new DateTime(year, month, date);

            await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await alertsRepository.LoadLatestAlertHistoryAsync(minTime, 0));

            var blobReader = new Mock<IBlobStorageReader>();
             var blobData = $"deviceid,reading,ruleoutput,time,{Environment.NewLine}Device123,{value},RuleOutput123,{minTime.ToString("o")}";
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(blobData));
            var blobContents = new BlobContents {Data = stream, LastModifiedTime = DateTime.UtcNow};
            var blobContentIterable = new List<BlobContents>();
            blobContentIterable.Add(blobContents);

            blobReader.Setup(x => x.GetEnumerator()).Returns(blobContentIterable.GetEnumerator());

            _blobStorageClientMock
                .Setup(x => x.GetReader(It.IsNotNull<string>(), It.IsAny<DateTime?>()))
                .ReturnsAsync(blobReader.Object);

            var alertsList = await alertsRepository.LoadLatestAlertHistoryAsync(minTime, 5);
            Assert.NotNull(alertsList);
            Assert.NotEmpty(alertsList);
            Assert.Equal(alertsList.First().Value, value);
            Assert.Equal(alertsList.First().Timestamp, minTime);
        }
Example #27
0
 //    
 //    void OnGUI()
 //    {
 //        Vector3 screen_pos = Camera.main.WorldToScreenPoint (transform.position);
 //        GUI.Label(new Rect(screen_pos.x - 100, Screen.height - screen_pos.y+30, 200, 15), current_hp + "/" + max_hp + " HP", enginePlayerS.hover_text);
 //        GUI.Label(new Rect(screen_pos.x - 100, Screen.height - screen_pos.y + 45, 200, 15), current_ap + "/" + max_ap + " AP", enginePlayerS.hover_text);
 //    }
 public static void moveToHexViaPath(Path _travel_path)
 {
     travel_path = _travel_path.getTraverseOrderList();
     travel_path_en = travel_path.GetEnumerator();
     travel_path_en.MoveNext();
     moving_on_path = true;
 }
Example #28
0
	public static Example exampleFromString(String data,
			DataSetSpecification dataSetSpec, Char separator) {
		Dictionary<String, LearningAttribute> attributes = new Dictionary<String, LearningAttribute>();
        List<String> attributeValues = new List<String>();

        string [] vals = data.Split(new char[] { ' ', '\t', ',' });
        foreach (string v in vals)
        {
            if (!String.IsNullOrWhiteSpace(v))
            {
                attributeValues.Add(v);
            }
        }
		if (dataSetSpec.isValid(attributeValues)) {
			List<String> names = dataSetSpec.getAttributeNames();
			List<String>.Enumerator nameiter = names.GetEnumerator();
            List<String>.Enumerator valueiter = attributeValues.GetEnumerator();
			while (nameiter.MoveNext() && valueiter.MoveNext()) {
                String name = nameiter.Current;
				AttributeSpecification attributeSpec = dataSetSpec
						.getAttributeSpecFor(name);
				LearningAttribute attribute = attributeSpec.createAttribute(valueiter.Current);
				attributes.Add(name, attribute);
			}
			String targetAttributeName = dataSetSpec.getTarget();
			return new Example(attributes, attributes[targetAttributeName]);
		} else {
			throw new ApplicationException("Unable to construct Example from "
					+ data);
		}
	}
Example #29
0
        public Foo()
        {
            _numbers = new List<int>();

            string s = _numbers[10].ToString(10);
            string s2 = _numbers.GetEnumerator().Current.ToString(10);
            string s3 = _numbers.Reduce<int>(delegate(int accumulated, int item) { return accumulated + item; }, 0).ToString(10);

            string s4 = _func(10).EncodeUriComponent();

            Func<int, string> f2 = _func;
            f2(11).Trim();

            Dictionary<string, int> d = new Dictionary<string, int>();
            string s5 = jQuery.ExtendDictionary<string, int>(d, d)["abc"].ToString(10);
            int keys = d.Count;
            bool b = d.ContainsKey("abc");
            d.Remove("abc");

            foreach (KeyValuePair<string, int> de in d) {
            }

            jQuery.AjaxRequest<string>("http://example.com").Success(delegate(string html) {
                Window.Alert(html);
            });

            string json = "";
            Foo f = Json.ParseData<Foo>(json).Setup().Run().Cleanup();

            string name = Document.GetElementById("nameTB").As<InputElement>().Value;
        }
Example #30
0
        public static void Main()
        {
            // Shopping list
            List<string> myList = new List<string>();
            myList.Add("Fruit");
            myList.Add("Vegetables");
            myList.Add("Sweets");
            myList.Add("Drinks");

            IEnumerator<string> myEnum = myList.GetEnumerator();
            // The IEnumerator is set to be BEFORE the first value in the list. Therefore, you must
            // moveNext at creation, or after Reset to obtain the first value. If you don't it will
            // be an undefined value and will return an error.
            myEnum.Reset();

            // Cast the List class directly into an IEnumerable
            IEnumerable<string> myEnumerable = (IEnumerable<string>)myList;

            Console.WriteLine("IEnumerator\n");
            outputValuesEnumerator(myEnum);
            Console.WriteLine("\nIEnumerable\n");
            outputValuesEnumerable(myEnumerable);

            foreach (int penum in GetPowersofTwo())
            {
                Console.WriteLine(penum);
            }
        }