Example #1
0
        public IEnumerable<Product> GetAllProducts()
        {
            string sqlExecute = string.Empty;
            List<Product> ProductList = new List<Product>();
            try
            {
                #region SQL 語法

                sqlExecute = @"select * from Product ";

                #endregion SQL 語法

                #region SQL 執行
                using (var conn = SQLFunc.OpenConnection(DBList.Test))
                {
                   ProductList= conn.Query<Product>(sqlExecute).ToList();
                }
                var builder = new ODataConventionModelBuilder() { Namespace = "Default" };
                builder.EntitySet<Product>("Products");
                var model = builder.GetEdmModel();
                return ProductList.AsQueryable();

                #endregion
            }
            catch (Exception ex)
            {

            }
            return ProductList.AsQueryable();
        }
        public static IRepository<WorkLog> Create()
        {
            var logsList = new List<WorkLog>();

            for (int i = 1; i < 20; i++)
            {
                logsList.Add(new WorkLog
                {
                    Id = i,
                    ShortDescription = "Log short Description " + i,
                    StartTime = DateTime.Now
                });
            }

            logsList.Add(new WorkLog
            {
                Id = 25,
                ShortDescription = "Log short Description " + 25,
                StartTime = DateTime.Now,
                EndTime = DateTime.Now.AddHours(2)
            });

            var repo = new Mock<IRepository<WorkLog>>();
            repo.Setup(x => x.All()).Returns(logsList.AsQueryable());
            repo.Setup(x => x.Find(It.IsAny<Expression<Func<WorkLog, bool>>>()))
                .Returns<Expression<Func<WorkLog, bool>>>(id => logsList.AsQueryable().Where(id));
            repo.Setup(x => x.Update(It.IsAny<WorkLog>())).Verifiable();

            return repo.Object;
        }
        public static IPostsService GetPostsService()
        {
            var post = new Post
            {
                Content = "test post",
                Id = 1,
                PostDate = new DateTime(2015, 11, 1),
                ThreadId = 1,
                UserId = "id1",
                User = new User { Nickname = "testuser" },
                Thread = new Thread { Title = "testTitle" },
                Comments = new List<Comment>(),
                Votes = new List<Vote>()
            };
            var posts = new List<Post>()
            {
                post
            };

            var postsService = new Mock<IPostsService>();
            postsService.Setup(p => p.Add(It.IsAny<string>(), It.Is<int>(t => t > 100), It.IsAny<string>())).Throws<ArgumentException>();
            postsService.Setup(p => p.Add(It.IsAny<string>(), It.Is<int>(t => t < 100), It.IsAny<string>())).Returns(1);
            postsService.Setup(p => p.GetById(It.IsAny<int>())).Returns(post);
            postsService.Setup(p => p.GetByThread(It.IsAny<int>())).Returns(posts.AsQueryable());
            postsService.Setup(p => p.GetByUser(It.Is<string>(s => s != "not exist"))).Returns(posts.AsQueryable());
            postsService.Setup(p => p.GetByUser(It.Is<string>(s => s == "not exist"))).Throws<ArgumentException>();
            postsService.Setup(p => p.Update(It.IsAny<int>(), It.IsAny<string>())).Verifiable();

            return postsService.Object;
        }
        public async Task<IHttpActionResult> Waypoints(int id)
        {
            Mission mission = await db.Missions.FindAsync(id);
            if (mission == null)
            {
                return BadRequest();
            }
            var wps = mission.Waypoints;
            List<Waypoint> wpsInOrder = new List<Waypoint>();
            if (wps.Count == 0)
            {
                return Ok(wpsInOrder.AsQueryable());
            }
            var activeWps = from wp in mission.Waypoints
                            where wp.IsActive
                            select wp;
            var tail = activeWps.First(wp => wp.NextWaypoint == null && wp.IsActive);
            wpsInOrder.Add(tail);
            foreach (var wp in activeWps)
            {
                if (wp.Id == tail.Id)
                {
                    //This is already in the list we don't want to insert it.
                    continue;
                }
                var next = wp.NextWaypoint;
                int index = next != null ? wpsInOrder.FindIndex(n => n.Id == next.Id) : -1;
                if (index == -1)
                {
                    //The next waypoint of this waypoint is not in this list, just insert it behind the last waypoint.
                    int len = wpsInOrder.Count;
                    wpsInOrder.Insert(len - 1, wp);
                }
                else
                {
                    //Insert the waypoint behind its next waypoint.
                    wpsInOrder.Insert(index, wp);
                }

            }

            var diffType = from wp in wpsInOrder.AsQueryable()
                           select new
                           {
                               MissionId = wp.MissionId,
                               NextWaypointId = wp.NextWaypointId,
                               Latitude = wp.Latitude,
                               Longitude = wp.Longitude,
                               Altitude = wp.Altitude,
                               IsActive = wp.IsActive,
                               Id = wp.Id,
                               TimeCompleted = wp.TimeCompleted,
                               WaypointName = wp.WaypointName,
                               Action = wp.Action,
                               GeneratedBy = wp.GeneratedBy,
                           };


            return Ok(diffType);
        }
Example #5
0
        public static List<Key> BuildKeyList(List<String[]> ParsedPrefix, List<String[]> ParsedSuffix, List<Family> FamilyList)
        {
            List<Key> ret = new List<Key>();

            foreach(String[] thisKeyPrefix in ParsedPrefix)
            {
                if (thisKeyPrefix.Length != 2)
                    throw new Exception();
                foreach(String[] thisKeySuffix in ParsedSuffix)
                {
                    if (thisKeySuffix.Length < 2 || thisKeySuffix.Length > 3)
                        throw new Exception();

                    Family Family2 = null;
                    if (thisKeySuffix.Length == 3)
                        Family2 = FamilyList.AsQueryable().Where(x => x.Name == thisKeySuffix[2]).First();

                    ret.Add
                    (
                        new Key
                        (
                            String.Format("{0}{1}", thisKeyPrefix[0], thisKeySuffix[0]),
                            Int32.Parse(thisKeyPrefix[1]),
                            FamilyList.AsQueryable().Where(x => x.Name == thisKeySuffix[1]).First(),
                            Family2
                        )
                    );
                }
            }

            return ret;
        }
        public IQueryable<Course> GetAllCoursesForUser(string id)
        {
            var specialty = this.specialtiesRepository
                .All()
                .Where(s => s.Students.Any(std => std.Id == id))
                .Include(s => s.Semesters)
                .FirstOrDefault();

            var courses = new List<Course>();

            if (specialty == null)
            {
                return courses.AsQueryable();
            }

            foreach (var item in specialty.Semesters)
            {
                foreach (var e in item.Courses)
                {
                    courses.Add(e);
                }
            }

            return courses.AsQueryable();
        }
Example #7
0
        public static List<Breed> BuildBreedList(List<String[]> ParsedCSV, List<Monster> MonsterList, List<Family> FamilyList)
        {
            List<Breed> ret = new List<Breed>();

            foreach(String[] thisBreed in ParsedCSV)
            {
                if (thisBreed.Length < 3 || thisBreed.Length > 4)
                    throw new Exception();

                //check if there is a required depth (+x) for this breed to succeed
                int? thisRequiredDepth = null;
                if (thisBreed.Length == 4)
                    thisRequiredDepth = Int32.Parse(thisBreed[3]);

                IBreedable thisParent1;
                //create first parent (either family or monster)
                if(thisBreed[1].StartsWith("*") && thisBreed[1].EndsWith("*"))
                {
                    //this parent is any member of the specified family
                    thisParent1 = FamilyList.AsQueryable().Where(x => x.Name.ToUpper() == thisBreed[1].TrimStart('*').TrimEnd('*')).First();
                }
                else
                {
                    thisParent1 = MonsterList.AsQueryable().Where(x => x.Name.ToUpper() == thisBreed[1].ToUpper()).First();
                }

                IBreedable thisParent2;
                //create second parent (either family or monster)
                if(thisBreed[2].StartsWith("*") && thisBreed[2].EndsWith("*"))
                {
                    //this parent is any member of the specified family
                    thisParent2 = FamilyList.AsQueryable().Where(x => x.Name.ToUpper() == thisBreed[2].TrimStart('*').TrimEnd('*')).First();
                }
                else
                {
                    thisParent2 = MonsterList.AsQueryable().Where(x => x.Name.ToUpper() == thisBreed[2].ToUpper()).First();
                }

                ret.Add
                (
                    new Breed
                    (
                        MonsterList.AsQueryable().Where(x => x.Name.ToUpper() == thisBreed[0]).First(),
                        thisParent1,
                        thisParent2,
                        thisRequiredDepth
                    )
                );
            }

            return ret;
        }
		protected static List<BaseComparer>  GenericSorter (List<BaseComparer> list)
		{
			BaseComparer bc = list[0];
			SortColumn  scc = bc.ColumnCollection[0] as SortColumn;
			ListSortDirection sd = scc.SortDirection;
			List<BaseComparer> lbc = null;
			if (sd == ListSortDirection.Ascending) {
				lbc = list.AsQueryable().AscendingOrder().ToList();
			} else {

				lbc = list.AsQueryable().DescendingOrder().ToList();
			}
			return lbc;
		}
        private IQueryable<ComposablePartDefinition> LoadParts()
        {
            if (!Directory.Exists(_dir))
            {
                return (new ComposablePartDefinition[0]).AsQueryable();
            }

            var parts = new List<ComposablePartDefinition>();

            foreach(var file in Directory.GetFiles(this._dir, "*.dll"))
            {
                try
                {
                    var assembly = Assembly.LoadFrom(file);

                    using(var catalog = new AssemblyDiscoveryCatalog(assembly))
                    {
                        parts.AddRange(catalog.Parts);
                    }
                }
                catch (Exception)
                {
                    // TODO: we should log or trace
                }
            }

            return parts.AsQueryable();
        }
        public virtual void Configure(IEngine engine, ContainerManager containerManager, EventBroker broker, SmartStoreConfig configuration)
        {
            //other dependencies
            containerManager.AddComponentInstance<SmartStoreConfig>(configuration, "sm.configuration");
            containerManager.AddComponentInstance<IEngine>(engine, "sm.engine");
            containerManager.AddComponentInstance<ContainerConfigurer>(this, "sm.containerConfigurer");

            //type finder
            containerManager.AddComponent<ITypeFinder, WebAppTypeFinder>("sm.typeFinder");

            //register dependencies provided by other assemblies
            var typeFinder = containerManager.Resolve<ITypeFinder>();
            containerManager.UpdateContainer(x =>
            {
                var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>();
                var drInstances = new List<IDependencyRegistrar>();
                foreach (var drType in drTypes)
                    drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
                //sort
                drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
                foreach (var dependencyRegistrar in drInstances)
                    dependencyRegistrar.Register(x, typeFinder);
            });

            // event broker
            containerManager.AddComponentInstance(broker);

			// AutofacDependencyResolver
			var scopeProvider = new AutofacLifetimeScopeProvider(containerManager.Container);
			var dependencyResolver = new AutofacDependencyResolver(containerManager.Container, scopeProvider);
			DependencyResolver.SetResolver(dependencyResolver);
        }
        /// <summary>
        /// Fakes the ceremony.
        /// </summary>
        /// <param name="count">The count.</param>
        /// <param name="ceremonyRepository">The ceremony repository.</param>
        /// <param name="specificCeremonies">The specific ceremonies.</param>
        public static void FakeCeremony(int count, IRepository<Ceremony> ceremonyRepository, List<Ceremony> specificCeremonies)
        {
            var ceremonies = new List<Ceremony>();
            var specificTransactionsCount = 0;
            if (specificCeremonies != null)
            {
                specificTransactionsCount = specificCeremonies.Count;
                for (int i = 0; i < specificTransactionsCount; i++)
                {
                    ceremonies.Add(specificCeremonies[i]);
                }
            }

            for (int i = 0; i < count; i++)
            {
                ceremonies.Add(CreateValidEntities.Ceremony(i + specificTransactionsCount + 1));
            }

            var totalCount = ceremonies.Count;
            for (int i = 0; i < totalCount; i++)
            {
                ceremonies[i].SetIdTo(i + 1);
                int i1 = i;
                ceremonyRepository
                    .Expect(a => a.GetNullableById(i1 + 1))
                    .Return(ceremonies[i])
                    .Repeat
                    .Any();
            }
            ceremonyRepository.Expect(a => a.GetNullableById(totalCount + 1)).Return(null).Repeat.Any();
            ceremonyRepository.Expect(a => a.Queryable).Return(ceremonies.AsQueryable()).Repeat.Any();
            ceremonyRepository.Expect(a => a.GetAll()).Return(ceremonies).Repeat.Any();
        }
 public JsonResult EmptyDataSource()
 {
     var people = new List<Person>();
     people.Add(new Person { LastName = "Alone", FirstName = "All" });
     var dataSource = KendoUiHelper.ParseGridData<Person>(people.AsQueryable());
     return Json(dataSource, JsonRequestBehavior.AllowGet);
 }
Example #13
0
        public static IQueryable<RequestorType> getSampleCallerTypes()
        {
            var requestor0 = new RequestorType {
                RequestorTypeID = 0,
                Code = "ADMIN",
                Value = "Administrator",
                Active = true
            };

            var requestor1 = new RequestorType {
                RequestorTypeID = 1,
                Code = "DRUG CO",
                Value = "Drug Company",
                Active = false
            };

            var requestor2 = new RequestorType {
                RequestorTypeID = 2,
                Code = "FAMILY",
                Value = "Family Members",
                Active = false
            };

            var sampleCallers = new List<RequestorType> {
                requestor0,
                requestor1,
                requestor2
            };

            return sampleCallers.AsQueryable();
        }
Example #14
0
        public static IEnumerable<Type> FindTypes(TypeIncludes flags, Type baseType)
        {
            if (baseType == null) throw new ArgumentNullException("baseType", "Must be set to a type");

            Func<Type, bool> predicate = BuildPredicate(flags);
            var foundTypes = from containedType in FindTypes(baseType)
                             where predicate(containedType)
                             select containedType;

            if (!(IsSet(flags, TypeIncludes.ConcreteTypes) && IsConcreteType(baseType)))
            {
                if(foundTypes.Contains(baseType))
                {
                    IList<Type> b = new List<Type>();
                    b.Add(baseType);
                    foundTypes = foundTypes.Except(b.AsQueryable());
                }
            }
            
            if (IsSet(flags, TypeIncludes.PrimitiveTypes))
            {
                foundTypes = foundTypes.Concat(FindPrimitiveTypes());
            }
            return foundTypes;
        }
        //[Route("~/")]
        //[Route("")]
        public ActionResult Index()
        {
            List<ArticleModel> articles = new List<ArticleModel>();
            user = (Users)Session["User"];
            // if (ModelState.IsValid)
            // {
            ConnManager connManager = new ConnManager();
            if(user!= null && user.UserId == 1)
                articles = connManager.GetArticles("Select * from VwArticles order by articleId desc");
            else
                articles = connManager.GetArticles("Select * from VwArticles where IsDisplay =1 order by articleId desc");

            // }

            PagingInfo info = new PagingInfo();
            info.SortField = " ";
            info.SortDirection = " ";
            info.PageSize = 7;
            info.PageCount = Convert.ToInt32(Math.Ceiling((double)(articles.Count/info.PageSize)));
            info.CurrentPageIndex = 0;

            // var query = articles.OrderByDescending(c => c.ArticleID).Take(info.PageSize);

            var query = articles.AsQueryable();
            query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
            ViewBag.PagingInfo = info;

            return View(query.ToList());
        }
Example #16
0
        public IQueryable<Contact> Filter(List<Contact> contacts, int id, string name)
        {

            var result = contacts.AsQueryable().Where(c => c.ContactId == id || c.Name == name);

            return result;
        }
 public override void EstablishContext()
 {
     repository = new Mock<IRepository>();
       users = new List<User>();
       repository.Setup(r => r.All<User>()).Returns(users.AsQueryable());
       service = new ClubPoolMembershipService(repository.Object);
 }
        public IQueryable<PageRemarkViewModel> Read() {
            List<PageRemarkViewModel> ret = new List<PageRemarkViewModel>();
            var qry = db.PageRemark.Where(x=>x.isOpen != "F");
            foreach (PageRemark o in qry)
            {
                PageRemarkViewModel v = new PageRemarkViewModel();

                v.ID = o.ID;
                //v.Content = o.Content;
                if (o.ModifyUserID != null)
                    v.ModifyUserName = o.UserData.UserName;
                v.PageCName = o.PageCName;
                v.PageName = o.PageName;
                v.ModifyDT = o.ModifyDateTime;
                if(o.ModifyDateTime!=null)
                    v.ModifyDTStr = o.ModifyDateTime.Value.ToString("yyyy/MM/dd");
                v.isOpen = o.isOpen;
                v.ModifyUserID = o.ModifyUserID;
                v.OrderSeq = o.OrderSeq.Value;
                v.HasActtachment = "";

                if (db.PageFiles.Where(x => x.PageID == o.ID).Count() > 0)
                    v.HasActtachment = "@";
                ret.Add(v);
            }
            return ret.AsQueryable();
        }
Example #19
0
        public IEnumerable<Models.HtmlBlock> All(Models.Site site)
        {
            List<HtmlBlock> results = new List<HtmlBlock>();

            while (site != null)
            {
                var tempResults = QueryBySite(site);
                if (results.Count == 0)
                {
                    results.AddRange(tempResults);
                }
                else
                {
                    foreach (var item in tempResults)
                    {
                        if (!results.Any(it => it.Name.Equals(item.Name, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            results.Add(item);
                        }
                    }
                }
                site = site.Parent;
            }
            return results.AsQueryable();
        }
		public async Task<IEnumerable<Reference>> GetReferencesFiltered(string filter)
		{
			List<Reference> references = new List<Reference>();

			StringBuilder requestUri = new StringBuilder()
					.Append(this.SiteUrl)
					.Append("/_api/web/lists/getbyTitle('")
					.Append(this.ReferencesListName)
					.Append("')/items?$select=ID,Title,URL,Comments,Project");

			if (!String.IsNullOrEmpty(filter))
			{
				requestUri.Append("&$filter=" + filter);
			}

			HttpResponseMessage response = await this.Get(requestUri.ToString());
			string responseString = await response.Content.ReadAsStringAsync();
			XElement root = XElement.Parse(responseString);

			foreach (XElement entryElem in root.Elements().Where(e => e.Name.LocalName == "entry"))
			{
				references.Add(entryElem.ToReference());
			}

			return references.AsQueryable();

		}
        public void InMemory_Request_Retrieve_Mock_Test()
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule<ProcessingConsumerModule>();
            builder.RegisterModule<BillingConsumerModule>();
            builder.RegisterModule<UserManagementConsumerModule>();

            var itemList = new List<Item>();
            itemList.Add(new Item { Info = "mockResponse" });
            var mockItemRepository = new Mock<IRepository<Item>>();

            mockItemRepository.Setup(rep =>
                rep.Query(It.IsAny<Expression<Func<Item, bool>>>()))
                   .Returns(itemList.AsQueryable());
            builder.Register(c =>
                mockItemRepository.Object).As<IRepository<Item>>();

            using (var service = Service.InMemory(builder).Start())
            {
                var msg = new RequestItemMessage("mockSelection");
                var client = service.CreateRequestClient<RequestItem, ItemResponse>();
                var response = client.Request(msg).Result;
                Assert.AreEqual("mockResponse", response.ItemInfo);
            }
        }
Example #22
0
        public virtual void Configure(IEngine engine, ContainerManager containerManager)
        {
            //other dependencies
            //containerManager.AddComponentInstance<NopConfig>(configuration, "nop.configuration");
            //containerManager.AddComponentInstance<IEngine>(engine, "nop.engine");
            //containerManager.AddComponentInstance<ContainerConfigurer>(this, "nop.containerConfigurer");

            //type finder
            containerManager.AddComponent<ITypeFinder, WebAppTypeFinder>("nop.typeFinder");
            //ContainerBuilder builder = new ContainerBuilder();
            //builder.RegisterType<WebAppTypeFinder>().As<ITypeFinder>();
            //IContainer container=builder.Build();

            //register dependencies provided by other assemblies
            var typeFinder = containerManager.Resolve<ITypeFinder>();
            containerManager.UpdateContainer(x =>
            {
                var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>();
                var drInstances = new List<IDependencyRegistrar>();
                foreach (var drType in drTypes)
                    drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
                //sort
                drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
                foreach (var dependencyRegistrar in drInstances)
                    dependencyRegistrar.Register(x, typeFinder);
            });
        }
Example #23
0
        public IQueryable<MonthlyAttendanceSummary> GetFamilyAttendance(int personId, int monthCount)
        {
            List<MonthlyAttendanceSummary> attendanceSummary = new List<MonthlyAttendanceSummary>();

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("PersonId", personId);
            parameters.Add("MonthCount", monthCount);

            var table = DbService.GetDataTable( "spCheckin_BadgeAttendance", System.Data.CommandType.StoredProcedure, parameters );

            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    MonthlyAttendanceSummary item = new MonthlyAttendanceSummary();
                    item.AttendanceCount = row["AttendanceCount"].ToString().AsInteger();
                    item.SundaysInMonth = row["SundaysInMonth"].ToString().AsInteger();
                    item.Month = row["Month"].ToString().AsInteger();
                    item.Year = row["Year"].ToString().AsInteger();

                    attendanceSummary.Add(item);
                }
            }

            return attendanceSummary.AsQueryable();
        }
Example #24
0
        public virtual void Configure(IEngine engine, ContainerManager containerManager, EventBroker broker, SiteConfig configuration)
        {
            //other dependencies
            containerManager.AddComponentInstance<SiteConfig>(configuration, "site.configuration");
            containerManager.AddComponentInstance<IEngine>(engine, "site.engine");
            containerManager.AddComponentInstance<ContainerConfigurer>(this, "site.containerConfigurer");

            //type finder
            containerManager.AddComponent<ITypeFinder, WebAppTypeFinder>("site.typeFinder");

            //register dependencies provided by other assemblies
            var typeFinder = containerManager.Resolve<ITypeFinder>();
            containerManager.UpdateContainer(x =>
            {
                var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>();
                var drInstances = new List<IDependencyRegistrar>();
                foreach (var drType in drTypes)
                    drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
                //sort
                drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
                foreach (var dependencyRegistrar in drInstances)
                    dependencyRegistrar.Register(x, typeFinder);
            });

            //event broker
            containerManager.AddComponentInstance(broker);

            //service registration
            containerManager.AddComponent<DependencyAttributeRegistrator>("site.serviceRegistrator");
            var registrator = containerManager.Resolve<DependencyAttributeRegistrator>();
            var services = registrator.FindServices();
            var configurations = GetComponentConfigurations(configuration);
            services = registrator.FilterServices(services, configurations);
            registrator.RegisterServices(services);
        }
Example #25
0
        //Generate test data
        private IQueryable<Attendee> GenerateAttendees()
        {
            //Check cache first before regenerating test data
            string cacheKey="attendees";
            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                return (IQueryable<Attendee>)HttpContext.Current.Cache[cacheKey];
            }

            var attendees = new List<Attendee>();
            for (int i = 0; i < 1000; i++)
            {
                attendees.Add(
                    new Attendee()
                    {
                        AttendeeId = i,
                        FirstName = "First " + i.ToString(),
                        LastName = "Last " + i.ToString()
                    }
                    );
            }

            var result = attendees.AsQueryable();

            //Cache results
            HttpContext.Current.Cache[cacheKey] = result;

            return result;
        }
        public async Task<IEnumerable<Project>> GetProjects(string accessToken)
        {
            List<Project> projects = new List<Project>();
            
            StringBuilder requestUri = new StringBuilder()
                .Append(SiteUrl)
                .Append("/_api/web/lists/getbyTitle('")
                .Append(ProjectsListName)
                .Append("')/items?$select=ID,Title");

            HttpResponseMessage response = await Get(requestUri.ToString(), accessToken);
            string responseString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(responseString);
            }
            XElement root = XElement.Parse(responseString);
            
            foreach (XElement entryElem in root.Elements().Where(e => e.Name.LocalName == "entry"))
            {
                projects.Add(entryElem.ToProject());
            }

            return projects.AsQueryable();
        }
        /// <summary>
        /// Post list
        /// </summary>
        /// <param name="filter">Filter expression</param>
        /// <param name="order">Order expression</param>
        /// <param name="skip">Records to skip</param>
        /// <param name="take">Records to take</param>
        /// <returns>List of users</returns>
        public IEnumerable<BlogUser> Find(int take = 10, int skip = 0, string filter = "", string order = "")
        {
            if (!Security.IsAuthorizedTo(BlogEngine.Core.Rights.AccessAdminPages))
                throw new System.UnauthorizedAccessException();

            var users = new List<BlogUser>();
            int count;
            var userCollection = Membership.Provider.GetAllUsers(0, 999, out count);
            var members = userCollection.Cast<MembershipUser>().ToList();

            foreach (var m in members)
            {
                users.Add(new BlogUser { 
                    IsChecked = false, 
                    UserName = m.UserName, 
                    Email = m.Email,
                    Profile = GetProfile(m.UserName),
                    Roles = GetRoles(m.UserName)
                });
            }

            var query = users.AsQueryable().Where(filter);

            // if take passed in as 0, return all
            if (take == 0) take = users.Count;

            return query.OrderBy(order).Skip(skip).Take(take);
        }
        public IQueryable<HalonModels.Class> GetClasses()
        {
            IQueryable<WebApplication1.HalonModels.Firefighter> ffquery = _db.Firefighters;
            string firefighter_UName = Page.User.Identity.Name;
            ffquery = ffquery.Where(f => f.Firefighter_Account_Username.Equals(firefighter_UName));

            IQueryable<HalonModels.Firefighter> fireFighterHolder = _db.Firefighters;
            firefighters = fireFighterHolder.ToList();

            IQueryable<HalonModels.Course> courseHolder = _db.Courses;
            courses = courseHolder.ToList();

            IQueryable<HalonModels.Enrollment> enrollmentHolder = _db.Enrollments;
            enrollmentHolder = enrollmentHolder.Where(e => e.Firefighter_ID == ffquery.FirstOrDefault().Firefighter_ID);

            IQueryable<HalonModels.Class> query = _db.Classes;
            List<HalonModels.Class> returnList = new List<HalonModels.Class>();

            List<HalonModels.Enrollment> enrollList = enrollmentHolder.ToList();
            List<HalonModels.Class> classList = query.ToList();

            for (int i = 0; i < enrollList.Count(); i++)
            {
                for (int j = 0; j < classList.Count(); j++)
                {
                    if (enrollList[i].Class_ID == classList[j].Class_ID)
                    {
                        returnList.Add(classList[j]);
                    }
                }
            }
            query = returnList.AsQueryable<HalonModels.Class>();
            query = query.OrderByDescending(c => c.Class_Date);
            return query;
        }
        public IQueryable<Person> ReadSorted()
        {
            var nameList = new List<Person>
            {
                new Person
                {
                    FirstName = "THEODORE",
                    LastName = "BAKER"
                },
                new Person
                {
                    FirstName = "MADISON",
                    LastName = "KENT"
                },
                new Person
                {
                    FirstName = "ANDREW",
                    LastName = "SMITH"
                },

                new Person
                {
                    FirstName = "FREDRICK",
                    LastName = "SMITH"
                }
            };
            return nameList.AsQueryable();
        }
        private void SetupFakeAds()
        {

            var fakeAds = new List<Ad>()
            {
                new Ad()
                {
                    Id = 1,
                    Name = "Audi A6",
                    Type = new AdType() {Name = "Normal", Index = 101},
                    PostedOn = DateTime.Now.AddDays(-6),
                    Owner = new ApplicationUser() {UserName = "gosho", Id = "123"},
                    Price = 400
                },
                new Ad()
                {
                    Id = 2,
                    Name = "Audi A8",
                    Type = new AdType() {Name = "Premium", Index = 102},
                    PostedOn = DateTime.Now.AddDays(-3),
                    Owner = new ApplicationUser() {UserName = "Pesho", Id = "121"},
                    Price = 700
                },
            };

            this.AdRepositoryMock = new Mock<IRepository<Ad>>();
            this.AdRepositoryMock.Setup(r => r.All())
                .Returns(fakeAds.AsQueryable());

            this.AdRepositoryMock.Setup(r => r.Fing(It.IsAny<int>()))
                .Returns((int id) => (fakeAds.Find(ad => ad.Id == id)));
        }