Example #1
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;
        }
Example #2
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 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);
        }
        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 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 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;
		}
        /// <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<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();
        }
		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();

		}
Example #12
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 #13
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);
            });
        }
        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 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();
        }
        //[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());
        }
        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);
        }
Example #18
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();
        }
 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 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 #21
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 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 #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();
        }
        /// <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 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 #26
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;
        }
Example #27
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;
        }
        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 = "******", 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 = "******", 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)));
        }
        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();
        }
Example #30
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;
        }
Example #31
0
        public static AutoMock SetUserRepository <T>(this AutoMock mock, List <T> data = null)
            where T : IModel
        {
            var m = mock.Mock <IDataRepository>();

            m.Setup(a => a.GetSet <T>())
            .Returns(data?.AsQueryable());
            return(mock);
        }
Example #32
0
        private void BuildBody(FundingClaimReportModel model, List <FM25Learner> fm25Learners, IEnumerable <ILearner> applicableLearners, DateTime?referenceDateFilter)
        {
            var learnersArray = applicableLearners.Select(x => x.LearnRefNumber);

            var fm25LearnersQueryable = fm25Learners?.AsQueryable() ?? Enumerable.Empty <FM25Learner>().AsQueryable();

            fm25LearnersQueryable = ApplyFm25LearnersFilter(fm25LearnersQueryable, learnersArray);
            fm25LearnersQueryable = ApplyUserFilters(fm25LearnersQueryable, referenceDateFilter);

            var filteredFm25Learners = fm25LearnersQueryable?.ToList();

            if (filteredFm25Learners != null && filteredFm25Learners.Any())
            {
                var fm25Learner = filteredFm25Learners.First();

                model.FundingFactor = new FundingFactorModel
                {
                    AreaCostFact1618Hist     = fm25Learner.AreaCostFact1618Hist.GetValueOrDefault(0).ToString("N5"),
                    ProgWeightHist           = fm25Learner.ProgWeightHist.GetValueOrDefault(0).ToString("N5"),
                    PrvDisadvPropnHist       = fm25Learner.PrvDisadvPropnHist.GetValueOrDefault(0).ToString("N5"),
                    PrvHistLrgProgPropn      = fm25Learner.PrvHistLrgProgPropn.GetValueOrDefault(0).ToString("N5"),
                    PrvRetentFactHist        = fm25Learner.PrvRetentFactHist.GetValueOrDefault(0).ToString("N5"),
                    PrvHistL3ProgMathEngProp = fm25Learner.PrvHistL3ProgMathEngProp.GetValueOrDefault(0).ToString("N5")
                };

                var validProgrammeLearnersForFundlineA = filteredFm25Learners?.Where(x => StudyProgrammePredicate(x) && x.FundLine == FundLineConstants.DirectFundedStudents1416).ToList();
                var validTLevelLearnersForFundlineA    = filteredFm25Learners?.Where(x => TLevelPredicate(x) && x.FundLine == FundLineConstants.DirectFundedStudents1416).ToList();
                model.DirectFundingStudents = BuildFundlineReprtingBandModelForProgrammes(validProgrammeLearnersForFundlineA, validTLevelLearnersForFundlineA);

                var validProgrammeLearnersForFundlineB = filteredFm25Learners?.Where(x => StudyProgrammePredicate(x) && (x.FundLine == FundLineConstants.StudentsExcludingHighNeeds1619 ||
                                                                                                                         x.FundLine == FundLineConstants.HighNeedsStudents1619)).ToList();
                var validTLevelLearnersForFundlineB = filteredFm25Learners?.Where(x => TLevelPredicate(x) && (x.FundLine == FundLineConstants.StudentsExcludingHighNeeds1619 ||
                                                                                                              x.FundLine == FundLineConstants.HighNeedsStudents1619)).ToList();
                model.StudentsIncludingHNS = BuildFundlineReprtingBandModelForProgrammes(validProgrammeLearnersForFundlineB, validTLevelLearnersForFundlineB);

                var validProgrammeLearnersForFundlineC = filteredFm25Learners?.Where(x => StudyProgrammePredicate(x) && x.FundLine == FundLineConstants.StudentsWithEHCP1924).ToList();
                var validTLevelLearnersForFundlineC    = filteredFm25Learners?.Where(x => TLevelPredicate(x) && x.FundLine == FundLineConstants.StudentsWithEHCP1924).ToList();
                model.StudentsWithEHCPlan = BuildFundlineReprtingBandModelForProgrammes(validProgrammeLearnersForFundlineC, validTLevelLearnersForFundlineC);

                var validProgrammeLearnersForFundlineD = filteredFm25Learners?.Where(x => StudyProgrammePredicate(x) && x.FundLine == FundLineConstants.ContinuingStudents19Plus).ToList();
                var validTLevelLearnersForFundlineD    = filteredFm25Learners?.Where(x => TLevelPredicate(x) && x.FundLine == FundLineConstants.ContinuingStudents19Plus).ToList();
                model.ContinuingStudentsExcludingEHCPlan = BuildFundlineReprtingBandModelForProgrammes(validProgrammeLearnersForFundlineD, validTLevelLearnersForFundlineD);
            }
        }
Example #33
0
 public IQueryable <Product> Collection()
 {
     return(products.AsQueryable());
 }
Example #34
0
 public IQueryable <T> Collection()
 {
     return(items.AsQueryable());
 }
        public IEnumerable <MonitoringUnitReceiptAll> GetReportQuery(string no, string refNo, string roNo, string doNo, string unit, string supplier, DateTime?dateFrom, DateTime?dateTo, int offset)
        {
            DateTime d1 = dateFrom == null ? new DateTime(1970, 1, 1) : (DateTime)dateFrom;
            DateTime d2 = dateTo == null ? DateTime.Now : (DateTime)dateTo;

            List <MonitoringUnitReceiptAll> list = new List <MonitoringUnitReceiptAll>();
            var Data = (from a in dbContext.GarmentUnitReceiptNotes
                        join b in dbContext.GarmentUnitReceiptNoteItems on a.Id equals b.URNId
                        join c in dbContext.GarmentDeliveryOrders on a.DOId equals c.Id
                        join d in dbContext.GarmentExternalPurchaseOrderItems on b.EPOItemId equals d.Id
                        join e in dbContext.GarmentExternalPurchaseOrders on d.GarmentEPOId equals e.Id
                        where a.IsDeleted == false &&
                        ((d1 != new DateTime(1970, 1, 1)) ? (a.CreatedUtc.Date >= d1 && a.CreatedUtc.Date <= d2) : true) &&
                        ((supplier != null) ? (a.SupplierCode == supplier) : true) &&
                        ((unit != null) ? (a.UnitCode == unit) : true) &&
                        ((no != null) ? (a.URNNo == no) : true) &&
                        ((doNo != null) ? (a.DONo == doNo) : true) &&
                        ((roNo != null) ? (b.RONo == roNo) : true) &&
                        ((refNo != null) ? (b.POSerialNumber == refNo) : true)
                        select  new { id = a.Id, no = a.URNNo, dateBon = a.ReceiptDate, unit = a.UnitName, supplier = a.SupplierName, doNo = a.DONo, poEksternalNo = e.EPONo, poRefPR = b.POSerialNumber, design = b.DesignColor,
                                      roNo = b.RONo, article = d.Article, productCode = b.ProductCode, productName = b.ProductName, qty = b.ReceiptQuantity, uom = b.UomUnit, remark = b.ProductRemark, user = a.CreatedBy, internNo = c.InternNo }
                        )
                       .Distinct()
                       .ToList();

            var Query = (from data in Data
                         select new MonitoringUnitReceiptAll
            {
                no = data.no,
                dateBon = (data.dateBon.AddHours(offset)).ToString("dd MMMM yyyy", CultureInfo.InvariantCulture),
                unit = data.unit,
                supplier = data.supplier,
                doNo = data.doNo,
                poEksternalNo = data.poEksternalNo,
                poRefPR = data.poRefPR,
                roNo = data.roNo,
                article = data.article,
                productCode = data.productCode,
                productName = data.productName,
                qty = data.qty,
                uom = data.uom,
                remark = data.remark,
                user = data.user,
                design = data.design,
                internNote = data.internNo
            }).OrderByDescending(s => s.dateBon);
            int i = 1;

            foreach (var item in Query)
            {
                list.Add(
                    new MonitoringUnitReceiptAll
                {
                    id            = i,
                    no            = item.no,
                    dateBon       = item.dateBon,
                    unit          = item.unit,
                    supplier      = item.supplier,
                    doNo          = item.doNo,
                    poEksternalNo = item.poEksternalNo,
                    poRefPR       = item.poRefPR,
                    roNo          = item.roNo,
                    article       = item.article,
                    productCode   = item.productCode,
                    productName   = item.productName,
                    qty           = item.qty,
                    uom           = item.uom,
                    remark        = item.remark,
                    user          = item.user,
                    design        = item.design,
                    internNote    = item.internNote
                });
                i++;
            }

            return(list.AsQueryable());
        }
Example #36
0
        public async Task CreateDealershipShouldThrowForPictureExtension()
        {
            var dealerships = new List <Dealership>();

            this.mockDealershipRepository.Setup(r => r.AllAsNoTracking()).Returns(() => dealerships.AsQueryable());
            this.mockDealershipRepository.Setup(r => r.AddAsync(It.IsAny <Dealership>())).Callback((Dealership dealership) => dealerships.Add(dealership));

            var fileMock = new Mock <IFormFile>();
            var content  = "Hello World from a Fake File";
            var fileName = "test.xd";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var file = fileMock.Object;

            var model = new CreateDealershipInputModel
            {
                DealershipName = "autoa",
                Location       = "sofiq",
                PhoneNumber    = "088",
                Description    = "desc",
                LogoPicture    = file,
            };

            var appUser = new ApplicationUser
            {
                Email = "*****@*****.**",
            };

            var ex = await Assert.ThrowsAsync <Exception>(async() => await this.mockService.CreateDealershipAsync(model, appUser, "wwwroot/images/dealerships/"));

            Assert.Equal("Invalid picture extension xd", ex.Message);
        }
        public IActionResult LoadInsurance()
        {
            var draw          = Request.Form["draw"].FirstOrDefault();
            var start         = Request.Form["start"].FirstOrDefault();
            var length        = Request.Form["length"].FirstOrDefault();
            var sortColumn    = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
            var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
            var searchValue   = Request.Form["search[value]"].FirstOrDefault();

            int pageSize = length != null?Convert.ToInt32(length) : 0;

            int skip = start != null?Convert.ToInt32(start) : 0;

            int recordsTotal = 0;

            List <Insurance> insurance = db.Insurance.GetAll().Where(d => d.IsActive == true && d.IsDeleted == false).ToList();


            var insuranceList = new List <vmInsurance>();

            //Sorting
            if (!string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortColumnDir))
            {
                insurance = insurance.AsQueryable().OrderBy(sortColumn + " " + sortColumnDir).ToList();
            }
            else
            {
                insurance = insurance.OrderByDescending(x => x.Id).ToList();
            }

            //Search
            if (!string.IsNullOrEmpty(searchValue))
            {
                insurance = insurance.Where(x => x.Name.Contains(searchValue)).ToList();
            }

            foreach (var item in insurance)
            {
                insuranceList.Add(new vmInsurance
                {
                    Id               = item.Id,
                    Name             = item.Name,
                    EligibleEmployee = item.EligibleEmployee,
                    EffectiveFrom    = item.EffectiveFrom.ToString("dd MMMM, yyyy"),
                    Expiry           = item.Expiry?.ToString("dd MMMM, yyyy"),
                    Description      = item.Description,
                    CreatedDate      = item.CreatedDate
                });
            }

            insuranceList = insuranceList.OrderByDescending(i => i.CreatedDate.Date)
                            .ThenByDescending(i => i.CreatedDate.TimeOfDay).ToList();
            //total number of rows count
            recordsTotal = insuranceList.Count();

            //Paging
            var data = insuranceList.Skip(skip).Take(pageSize).ToList();

            //Returning Json Data
            return(Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }));
        }
Example #38
0
 public IQueryable <Board> GetAll()
 {
     return(boards.AsQueryable());
 }
Example #39
0
        private IList <IReportInvoiceLine> ReportInvoiceLines(int year)
        {
            if (HttpContext.Current.Cache[CacheKey] == null)
            {
                List <IReportInvoiceLine> items = new List <IReportInvoiceLine>();
                int contactId = 0;
                for (int i = 1; i < 88; i++)
                {
                    int thisyear = _rng.Next(2010, 2016);
                    var j        = new ReportInvoiceLine()
                    {
                        Year = thisyear, InvoiceNumber = i, City = RandomString(8)
                    };

                    items.Add(j);
                }
                HttpContext.Current.Cache.Insert(CacheKey, items);
            }

            List <IReportInvoiceLine> data = (List <IReportInvoiceLine>)HttpContext.Current.Cache[CacheKey];


            var q = data.AsQueryable();

            //if (!String.IsNullOrWhiteSpace(globalSearch))
            {
                q = q.Where(p => p.Year == year);
            }

            //totalRecords = q.Count();

            //if (!String.IsNullOrWhiteSpace(orderBy))
            //{
            //    switch (orderBy.ToLower())
            //    {
            //        case "id":
            //            if (!desc)
            //                q = q.OrderBy(p => p.JobId);
            //            else
            //                q = q.OrderByDescending(p => p.JobId);
            //            break;
            //        case "name":
            //            if (!desc)
            //                q = q.OrderBy(p => p.Name);
            //            else
            //                q = q.OrderByDescending(p => p.Name);
            //            break;
            //        case "contact":
            //            if (!desc)
            //                q = q.OrderBy(p => p.Contact.FullName);
            //            else
            //                q = q.OrderByDescending(p => p.Contact.FullName);
            //            break;
            //    }
            //}

            //if (limitOffset.HasValue)
            //{
            //    q = q.Skip(limitOffset.Value).Take(limitRowCount.Value);
            //}

            return(q.ToList());
        }
Example #40
0
        public IQueryable <Product> SearchProduct(string term)
        {
            List <Product> res = db.Products.Where(x => x.ProductName.Contains(term)).ToList();

            return(res.AsQueryable());
        }
        public IQueryable <PlayList> Read()
        {
            IList <PlayList> lista = new List <PlayList>(ApplicationDbContext.applicationDbContext.PlayList);

            return(lista.AsQueryable());
        }
Example #42
0
 public IQueryable <Part> GetAllParts()
 {
     return(_parts.AsQueryable());
 }
 internal CloudInfoQuery(string accessToken)
 {
     _accessToken = accessToken;
     Provider     = new CloudInfoProvider(accessToken, _cloudContents);
     Expression   = _cloudContents.AsQueryable().Expression;
 }
        public IEnumerable <OfflineTestStudentMarksGridModel> GetOfflineNotificationData(out int totalRecords, int userId,
                                                                                         int?limitOffset, int?limitRowCount, string orderBy, bool desc)
        {
            int BranchId = userId;
            IQueryable <OfflineTestStudentMarksGridModel> finalList = null;
            List <OfflineTestStudentMarksGridModel>       list      = new List <OfflineTestStudentMarksGridModel>();
            var query = _repository.Project <OfflineTestStudentMarks, IQueryable <OfflineTestStudentMarksGridModel> >(offlineTestPaperMarks => (
                                                                                                                          from offlineTest in offlineTestPaperMarks
                                                                                                                          orderby offlineTest.CreatedOn descending
                                                                                                                          group offlineTest by new
            {
                offlineTest.OfflineTestPaperId,
                offlineTest.OfflineTestPaper.Title,
                offlineTest.OfflineTestPaper.TotalMarks,
                offlineTest.OfflineTestPaper.Class.Name,
                offlineTest.OfflineTestPaper.TestDate,
                subjectName = offlineTest.OfflineTestPaper.Subject.Name,
                selectedBranches = offlineTest.OfflineTestPaper.SelectedBranches
            } into offlineTestPaper
                                                                                                                          select new OfflineTestStudentMarksGridModel
            {
                OfflineTestPaperId = offlineTestPaper.Key.OfflineTestPaperId,
                Title = offlineTestPaper.Key.Title,
                TotalMarks = offlineTestPaper.Key.TotalMarks,
                Class = offlineTestPaper.Key.Name,
                Date = offlineTestPaper.Key.TestDate,
                CreatedOn = offlineTestPaper.Select(x => x.CreatedOn).FirstOrDefault(),
                Subject = offlineTestPaper.Key.subjectName,
                SelectedBranches = offlineTestPaper.Key.selectedBranches
            }));

            if (BranchId != 0)
            {
                foreach (var offlineTestPaperMarks in query)
                {
                    var selectedBranchList = offlineTestPaperMarks.SelectedBranches.Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToList();
                    if (selectedBranchList.Contains(BranchId))
                    {
                        list.Add(offlineTestPaperMarks);
                    }
                }
                finalList = list.AsQueryable();
            }
            else
            {
                finalList = query;
            }

            totalRecords = finalList.Count();
            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                switch (orderBy)
                {
                case nameof(OfflineTestStudentMarksGridModel.Class):
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.Class);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.Class);
                    }
                    break;

                case nameof(OfflineTestStudentMarksGridModel.Subject):
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.Subject);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.Subject);
                    }
                    break;

                case nameof(OfflineTestStudentMarksGridModel.Title):
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.Title);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.Title);
                    }
                    break;

                case nameof(OfflineTestStudentMarksGridModel.TotalMarks):
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.TotalMarks);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.TotalMarks);
                    }
                    break;

                case nameof(OfflineTestStudentMarksGridModel.Date):
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.Date);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.Date);
                    }
                    break;

                default:
                    if (!desc)
                    {
                        finalList = finalList.OrderBy(p => p.CreatedOn);
                    }
                    else
                    {
                        finalList = finalList.OrderByDescending(p => p.CreatedOn);
                    }
                    break;
                }
            }
            if (limitOffset.HasValue)
            {
                finalList = finalList.Skip(limitOffset.Value).Take(limitRowCount.Value);
            }
            return(finalList.ToList());
        }
Example #45
0
        public IQueryable <Prestamo> Get()
        {
            IList <Prestamo> lista = new List <Prestamo>(ApplicationDbContext.applicationDbContext.Prestamos);

            return(lista.AsQueryable());
        }
Example #46
0
 public IQueryable <MetadataViewModel> GetMetadata()
 {
     return(database.AsQueryable());
 }
Example #47
0
 public IQueryable <T> GetItems()
 {
     return(items.AsQueryable());
 }
Example #48
0
        public void Equal()
        {
            // test simple
            var q1  = Persons.AsQueryable().Query(t => t.Equal("FirstName", "David"));
            var q1b = Persons.AsQueryable().Where(t => t.FirstName == "David");

            QueryableAssert.AreEqual(q1, q1b);

            // test and
            var q2  = Persons.AsQueryable().Query(t => t.Equal("FirstName", "David").AndEqual("LastName", "Lebee"));
            var q2b = Persons.AsQueryable().Where(t => t.FirstName == "David" && t.LastName == "Lebee");

            QueryableAssert.AreEqual(q2, q2b);


            // test or
            var q3  = Persons.AsQueryable().Query(t => t.Equal("FirstName", "David").OrEqual("FirstName", "Michaela"));
            var q3b = Persons.AsQueryable().Where(t => t.FirstName == "David" || t.FirstName == "Michaela");

            QueryableAssert.AreEqual(q3, q3b);
        }
        private void SetupGamesForPlayer(int playerId, int numberofUniqueGamesToSetup)
        {
            var playerGameResults = new List <PlayerGameResult>();

            for (int j = 0; j < numberofUniqueGamesToSetup; j++)
            {
                for (int i = 0; i < 5; i++)
                {
                    playerGameResults.Add(
                        new PlayerGameResult
                    {
                        PlayerId   = playerId,
                        PlayedGame = new PlayedGame
                        {
                            GameDefinitionId = j + 1
                        }
                    });
                }
            }

            _autoMocker.Get <IDataContext>().Expect(mock => mock.GetQueryable <PlayerGameResult>()).Return(playerGameResults.AsQueryable());
        }
Example #50
0
 public IQueryable <User> GetAll()
 {
     return(Users.AsQueryable());
 }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var htmlContentService = new HtmlContentService(rockContext);
            var htmlContent        = htmlContentService.Queryable();

            string pageName = "";
            string siteName = "";
            var    htmlList = new List <HtmlApproval>();

            foreach (var content in htmlContent)
            {
                content.Block.LoadAttributes();
                var blah = content.Block.GetAttributeValue("RequireApproval");
                if (!string.IsNullOrEmpty(blah) && blah.ToLower() == "true")
                {
                    var pageService = new PageService(rockContext);
                    if (content.Block.PageId != null)
                    {
                        var page = pageService.Get((int)content.Block.PageId);
                        if (page != null)
                        {
                            pageName = page.InternalName;
                            while (page.ParentPageId != null)
                            {
                                page = pageService.Get((int)page.ParentPageId);
                            }
                            var siteService = new SiteService(rockContext);
                            siteName = siteService.GetByDefaultPageId(page.Id).Select(s => s.Name).FirstOrDefault();
                        }
                    }

                    var htmlApprovalClass = new HtmlApproval();
                    htmlApprovalClass.SiteName           = siteName;
                    htmlApprovalClass.PageName           = pageName;
                    htmlApprovalClass.Block              = content.Block;
                    htmlApprovalClass.BlockId            = content.BlockId;
                    htmlApprovalClass.Content            = content.Content;
                    htmlApprovalClass.Id                 = content.Id;
                    htmlApprovalClass.IsApproved         = content.IsApproved;
                    htmlApprovalClass.ApprovedByPerson   = content.ApprovedByPerson;
                    htmlApprovalClass.ApprovedByPersonId = content.ApprovedByPersonId;
                    htmlApprovalClass.ApprovedDateTime   = content.ApprovedDateTime;

                    htmlList.Add(htmlApprovalClass);
                }
            }

            // Filter by Site
            if (ddlSiteFilter.SelectedIndex > 0)
            {
                if (ddlSiteFilter.SelectedValue.ToLower() != "all")
                {
                    htmlList = htmlList.Where(h => h.SiteName == ddlSiteFilter.SelectedValue).ToList();
                }
            }

            // Filter by approved/unapproved
            if (ddlApprovedFilter.SelectedIndex > -1)
            {
                if (ddlApprovedFilter.SelectedValue.ToLower() == "unapproved")
                {
                    htmlList = htmlList.Where(a => a.IsApproved == false).ToList();
                }
                else if (ddlApprovedFilter.SelectedValue.ToLower() == "approved")
                {
                    htmlList = htmlList.Where(a => a.IsApproved == true).ToList();
                }
            }

            // Filter by the person that approved the content
            if (_canApprove)
            {
                int personId = 0;
                if (int.TryParse(gContentListFilter.GetUserPreference("Approved By"), out personId) && personId != 0)
                {
                    htmlList = htmlList.Where(a => a.ApprovedByPersonId.HasValue && a.ApprovedByPersonId.Value == personId).ToList();
                }
            }

            SortProperty sortProperty = gContentList.SortProperty;

            if (sortProperty != null)
            {
                gContentList.DataSource = htmlList.AsQueryable().Sort(sortProperty).ToList();
            }
            else
            {
                gContentList.DataSource = htmlList.OrderBy(h => h.Id).ToList();
            }

            gContentList.DataBind();
        }
Example #52
0
        /// <summary>
        /// Get trash list
        /// </summary>
        /// <param name="trashType">Type (post, page, comment)</param>
        /// <param name="take">Take for a page</param>
        /// <param name="skip">Items to sckip</param>
        /// <param name="filter">Filter expression</param>
        /// <param name="order">Sort order</param>
        /// <returns></returns>
        public TrashVM GetTrash(TrashType trashType, int take = 10, int skip = 0, string filter = "1 == 1", string order = "DateCreated descending")
        {
            if (!Security.IsAuthorizedTo(Rights.AccessAdminPages))
            {
                throw new UnauthorizedAccessException();
            }

            var trash     = new TrashVM();
            var comments  = new List <Comment>();
            var posts     = new List <Post>();
            var pages     = new List <Page>();
            var trashList = new List <TrashItem>();
            var trashPage = new List <TrashItem>();
            var query     = trashList.AsQueryable().Where(filter);

            // comments
            if (trashType == TrashType.All || trashType == TrashType.Comment)
            {
                foreach (var p in Post.Posts)
                {
                    if (!Security.IsAuthorizedTo(Rights.EditOtherUsersPosts))
                    {
                        if (p.Author.ToLower() != Security.CurrentUser.Identity.Name.ToLower())
                        {
                            continue;
                        }
                    }

                    comments.AddRange(p.DeletedComments);
                }
            }

            if (comments.Count > 0)
            {
                foreach (var c in comments)
                {
                    TrashItem t1 = new TrashItem
                    {
                        Id          = c.Id,
                        Title       = c.Author + ": " + c.Teaser,
                        RelativeUrl = c.RelativeLink,
                        ObjectType  = "Comment",
                        DateCreated = c.DateCreated.ToString("MM/dd/yyyy HH:mm")
                    };

                    trashList.Add(t1);
                }
            }

            // posts
            if (trashType == TrashType.All || trashType == TrashType.Post)
            {
                posts = (from x in Post.DeletedPosts orderby x.DateCreated descending select x).ToList();
            }

            if (posts.Count > 0)
            {
                foreach (var p in posts)
                {
                    if (!Security.IsAuthorizedTo(Rights.EditOtherUsersPosts))
                    {
                        if (p.Author.ToLower() != Security.CurrentUser.Identity.Name.ToLower())
                        {
                            continue;
                        }
                    }

                    TrashItem t2 = new TrashItem
                    {
                        Id          = p.Id,
                        Title       = System.Web.HttpContext.Current.Server.HtmlEncode(p.Title),
                        RelativeUrl = p.RelativeLink,
                        ObjectType  = "Post",
                        DateCreated = p.DateCreated.ToString("MM/dd/yyyy HH:mm")
                    };

                    trashList.Add(t2);
                }
            }

            // pages
            if (trashType == TrashType.All || trashType == TrashType.Page)
            {
                pages = (from x in Page.DeletedPages orderby x.DateCreated descending select x).ToList();
            }

            if (pages.Count > 0)
            {
                foreach (var p in pages)
                {
                    TrashItem t3 = new TrashItem
                    {
                        Id          = p.Id,
                        Title       = System.Web.HttpContext.Current.Server.HtmlEncode(p.Title),
                        RelativeUrl = p.RelativeLink,
                        ObjectType  = "Page",
                        DateCreated = p.DateCreated.ToString("MM/dd/yyyy HH:mm")
                    };

                    trashList.Add(t3);
                }
            }

            trash.TotalCount = trashList.Count;

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

            foreach (var item in query.OrderBy(order).Skip(skip).Take(take))
            {
                trashPage.Add(item);
            }

            trash.Items = trashPage;

            return(trash);
        }
Example #53
0
 public IQueryable <ProductCategory> Collection()
 {
     return(productCategories.AsQueryable());
 }
Example #54
0
 protected List <Business> AsBusinessObjects(List <Data> data)
 {
     return(data.AsQueryable().ProjectTo <Business>(mappingConfig).ToList());
 }
        public void TestInitialize()
        {
            _signins = new List <WorkerSignin>();
            _signins.Add(new WorkerSignin()
            {
                ID = 111, dwccardnum = 12345, dateforsignin = DateTime.Today
            });
            _signins.Add(new WorkerSignin()
            {
                ID = 112, dwccardnum = 12346, dateforsignin = DateTime.Today
            });
            _signins.Add(new WorkerSignin()
            {
                ID = 113, dwccardnum = 12347, dateforsignin = DateTime.Today
            });
            _signins.Add(new WorkerSignin()
            {
                ID = 114, dwccardnum = 12348, dateforsignin = DateTime.Today
            });
            _signins.Add(new WorkerSignin()
            {
                ID = 115, dwccardnum = 12349, dateforsignin = DateTime.Today
            });

            _workers = new List <Worker>();
            _workers.Add(new Worker()
            {
                ID = 1, dwccardnum = 12345
            });
            _workers.Add(new Worker()
            {
                ID = 2, dwccardnum = 12347
            });
            _workers.Add(new Worker()
            {
                ID = 3, dwccardnum = 12349
            });
            _workers.Add(new Worker()
            {
                ID = 3, dwccardnum = 66666
            });

            _persons = new List <Person>();
            _persons.Add(new Person()
            {
                ID = 1, firstname1 = "UnitTest"
            });
            _persons.Add(new Person()
            {
                ID = 3, firstname1 = "UnitTest"
            });

            _requests = new List <WorkerRequest>();
            //_requests.Add(new WorkerRequest() {ID = 1, WorkOrderID = }
            //
            // Arrange WorkerSignin
            _wsiRepo = new Mock <IWorkerSigninRepository>();
            _wsiRepo.Setup(s => s.GetAllQ()).Returns(_signins.AsQueryable());
            // Arrange Worker
            _wServ = new Mock <IWorkerService>();
            _wServ.Setup(w => w.GetAll()).Returns(_workers);
            //
            _wrServ = new Mock <IWorkerRequestService>();
            _wrServ.Setup(w => w.GetAll()).Returns(_requests);
            // Arrange Person
            _pServ = new Mock <IPersonService>();
            _pServ.Setup(s => s.GetAll()).Returns(_persons);

            _iServ = new Mock <IImageService>();
            _uow   = new Mock <IUnitOfWork>();
            _map   = new Mock <IMapper>();
        }
Example #56
0
        public void testAddUser()
        {
            mockRepository.Expects.One.MethodWith(r => r.getAllEntities()).WillReturn(users.AsQueryable());

            mockRepository.Expects.One.MethodWith(r => r.addEntity(user1)).WillReturn(true);
            mockRepository.Expects.One.MethodWith(r => r.addEntity(user2)).WillReturn(false);
            Assert.IsTrue(userService.addUser(user1));
            Assert.IsFalse(userService.addUser(user2));
        }
Example #57
0
        public IQueryable <Species> FindAll()
        {
            const string   COMMAND_TEXT = "usp_GetSpeciesList";
            List <Species> speciesList  = new List <Species>();

            try
            {
                using (SqlConnection cn = DataContext.GetConnection(this.GetConnectionStringKey(_context)))
                {
                    using (SqlCommand cmd = new SqlCommand(COMMAND_TEXT, cn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Species species = new Species();
                                species.ID = GetInt(reader["taxonomy_species_id"].ToString());
                                species.CurrentTaxonomySpeciesID = GetInt(reader["current_taxonomy_species_id"].ToString());
                                species.NomenNumber          = GetInt(reader["nomen_number"].ToString());
                                species.IsSpecificHybrid     = (reader["is_specific_hybrid"].ToString() == "Y") ? true : false;
                                species.SpeciesName          = reader["species_name"].ToString();
                                species.Authority            = reader["species_authority"].ToString();
                                species.IsSubSpecificHybrid  = (reader["is_subspecific_hybrid"].ToString() == "Y") ? true : false;
                                species.SubSpeciesName       = reader["subspecies_name"].ToString();
                                species.SubSpeciesAuthority  = reader["subspecies_authority"].ToString();
                                species.IsVarietalHybrid     = (reader["is_varietal_hybrid"].ToString() == "Y") ? true : false;
                                species.VarietyName          = reader["variety_name"].ToString();
                                species.VarietyAuthority     = reader["variety_authority"].ToString();
                                species.IsSubVarietalHybrid  = (reader["is_subvarietal_hybrid"].ToString() == "Y") ? true : false;
                                species.SubVarietyName       = reader["subvariety_name"].ToString();
                                species.SubVarietyAuthority  = reader["subvariety_authority"].ToString();
                                species.IsFormaHybrid        = (reader["is_forma_hybrid"].ToString() == "Y") ? true : false;
                                species.FormaRankType        = reader["forma_rank_type"].ToString();
                                species.FormaName            = reader["forma_name"].ToString();
                                species.FormaAuthority       = reader["forma_authority"].ToString();
                                species.GenusID              = GetInt(reader["taxonomy_genus_id"].ToString());
                                species.GenusName            = reader["genus_name"].ToString();
                                species.IsNamePending        = (reader["is_name_pending"].ToString() == "Y") ? true : false;
                                species.SynonymCode          = reader["synonym_code"].ToString();
                                species.VerifierCooperatorID = GetInt(reader["verifier_cooperator_id"].ToString());
                                species.NameVerifiedDate     = GetDate(reader["name_verified_date"].ToString());
                                species.Name                   = reader["name"].ToString();
                                species.NameAuthority          = reader["name_authority"].ToString();
                                species.Protologue             = reader["protologue"].ToString();
                                species.ProtologueVirtualPath  = reader["protologue_virtual_path"].ToString();
                                species.Note                   = reader["note"].ToString();
                                species.AlternateName          = reader["alternate_name"].ToString();
                                species.CreatedDate            = GetDate(reader["created_date"].ToString());
                                species.CreatedByCooperatorID  = GetInt(reader["created_by"].ToString());
                                species.ModifiedDate           = GetDate(reader["modified_date"].ToString());
                                species.ModifiedByCooperatorID = GetInt(reader["modified_by"].ToString());
                                species.OwnedDate              = GetDate(reader["owned_date"].ToString());
                                species.OwnedByCooperatorID    = GetInt(reader["owned_by"].ToString());
                                speciesList.Add(species);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(speciesList.AsQueryable());
        }
Example #58
0
        public BaseSearchModel GetResults(SearchFilters filters, GridDescriptor request, IMaterialsContextUow context, string classificationIds, AdvSearchFiltersAll advFilters)
        {
            if (string.IsNullOrWhiteSpace(classificationIds) && HttpContext.Current.Session["ClassificationIds"] != "")
            {
                classificationIds = (string)HttpContext.Current.Session["ClassificationIds"];
            }

            BaseSearchModel model = new BaseSearchModel();

            if (filters.filter == null)
            {
                filters.filter = "";
            }

            IEnumerable <FullTextSearch>   results           = null;
            IEnumerable <MaterialTaxonomy> taxonomyResults   = new List <MaterialTaxonomy>();
            IEnumerable <MaterialTaxonomy> taxonomyResultsL1 = new List <MaterialTaxonomy>();
            IEnumerable <MaterialTaxonomy> taxonomyResultsL2 = new List <MaterialTaxonomy>();
            IEnumerable <MaterialTaxonomy> taxonomyResultsL3 = new List <MaterialTaxonomy>();
            IEnumerable <MaterialTaxonomy> taxonomyResultsL4 = new List <MaterialTaxonomy>();
            IEnumerable <int> taxonomyResultIds = new List <int>();
            IList <int>       typeIds           = new List <int>();
            IList <int>       classIds          = new List <int>();
            IList <int>       subclassIds       = new List <int>();
            IList <int>       groupIds          = new List <int>();


            IList <int> resultIds = null;

            if (filters.filter != "")
            {
                results   = context.FullTextSearch.GetMaterialsByFullTextSearch(false, filters.filter);
                resultIds = context.FullTextSearch.GetMaterialsIdsByFullTextSearch(filters.filter).ToList();
            }
            else
            {
                if ((filters.FromBrowse && filters.ClasificationId != 0))
                {
                    taxonomyResults = context.MaterialTaxonomyAll.AllAsNoTracking;
                    results         = context.FullTextSearch.AllAsNoTracking;
                    //resultIds = context.FullTextSearch.AllAsNoTracking.Select(c => c.Id).ToList();
                    resultIds = null;
                }
                else
                {
                    results   = new HashSet <FullTextSearch>();
                    resultIds = null;
                }
            }


            IList <string> allIds = new List <string>();
            IList <int>    classificationSelection = new List <int>();

            if (classificationIds != null && classificationIds.Length > 0)
            {
                allIds = classificationIds.Split(',').ToList();

                typeIds     = new List <int>();
                classIds    = new List <int>();
                subclassIds = new List <int>();
                groupIds    = new List <int>();
                IList <int> propIds = new List <int>();


                foreach (var item in allIds)
                {
                    if (item.Contains("TYPE"))
                    {
                        typeIds.Add(Int32.Parse(item.Replace("TYPE_", "")));
                    }
                    if (item.Contains("SUBCLASS"))
                    {
                        classIds.Add(Int32.Parse(item.Replace("SUBCLASS_", "")));
                    }
                    if (item.Contains("CLASS") && !item.Contains("SUBCLASS"))
                    {
                        groupIds.Add(Int32.Parse(item.Replace("CLASS_", "")));
                    }
                    if (item.Contains("GROUP"))
                    {
                        subclassIds.Add(Int32.Parse(item.Replace("GROUP_", "")));
                    }
                    if (item.Contains("PROPERTY"))
                    {
                        propIds.Add(Int32.Parse(item.Replace("PROPERTY_", "")));
                    }
                }

                /*
                 * Idem u bazu u MaterialTaxonomy i tamo za materijale koje imam u resultsu radim where po kriterijumima za classificationIds
                 * i to sto dobijem radim INTERSECT sa results od gore, a ovaj results ispod komentarisem
                 */
                taxonomyResults   = context.MaterialTaxonomyAll.AllAsNoTracking.Where(t => resultIds.Contains(t.ID));
                taxonomyResultsL1 = new List <MaterialTaxonomy>();
                taxonomyResultsL2 = new List <MaterialTaxonomy>();
                taxonomyResultsL3 = new List <MaterialTaxonomy>();
                taxonomyResultsL4 = new List <MaterialTaxonomy>();

                taxonomyResultIds = new List <int>();
                if (typeIds.Count > 0)
                {
                    taxonomyResultsL1 = taxonomyResults.Where(l1 => l1.Level1 != null && typeIds.Contains((int)l1.Level1));
                }

                if (groupIds.Count > 0)
                {
                    taxonomyResultsL2 = taxonomyResults.Where(l2 => l2.Level2 != null && groupIds.Contains((int)l2.Level2));
                }

                if (classIds.Count > 0)
                {
                    taxonomyResultsL3 = taxonomyResults.Where(l3 => l3.Level3 != null && classIds.Contains((int)l3.Level3));
                }

                if (subclassIds.Count > 0)
                {
                    taxonomyResultsL4 = taxonomyResults.Where(l4 => l4.Level4 != null && subclassIds.Contains((int)l4.Level4));
                }

                taxonomyResultIds = taxonomyResultsL1.Select(i1 => i1.ID).ToList()
                                    .Union(taxonomyResultsL2.Select(i2 => i2.ID).ToList())
                                    .Union(taxonomyResultsL3.Select(i3 => i3.ID).ToList())
                                    .Union(taxonomyResultsL4.Select(i4 => i4.ID).ToList());

                IList <int> intersectIds = resultIds.Intersect(taxonomyResultIds).Distinct().ToList();
                results = results.Where(r => intersectIds.Contains(r.Id));


                //results = results.Where(m => (typeIds.Count > 0 && m.type_ID != null && typeIds.Contains((int)m.type_ID))
                //    || (classIds.Count > 0 && m.class_ID != null && classIds.Contains((int)m.class_ID))
                //    || (groupIds.Count > 0 && m.group_ID != null && groupIds.Contains((int)m.group_ID))
                //    || (subclassIds.Count > 0 && m.subClass_ID != null && subclassIds.Contains((int)m.subClass_ID))
                //    );



                if (propIds.Count > 0)
                {
                    results = results.Where(r => r.prop_IDs != null && CheckIDs(r.prop_IDs, propIds));
                }

                classificationSelection = typeIds.Concat(classIds).Concat(groupIds).Concat(subclassIds).Concat(propIds).ToList();
                resultIds = null;
            }
            if (filters.FromBrowse)
            {
                if (filters.ClasificationId != 0)
                {
                    switch (filters.ClasificationTypeId)
                    {
                    case 1:
                        results         = results.Where(m => m.type_ID == filters.ClasificationId);
                        taxonomyResults = taxonomyResults.Where(m => m.Level1 == filters.ClasificationId);
                        break;

                    case 2:
                        results         = results.Where(m => m.group_ID == filters.ClasificationId);
                        taxonomyResults = taxonomyResults.Where(m => m.Level2 == filters.ClasificationId);
                        break;

                    case 3:
                        results         = results.Where(m => m.class_ID == filters.ClasificationId);
                        taxonomyResults = taxonomyResults.Where(m => m.Level3 == filters.ClasificationId);
                        break;

                    case 4:
                        results         = results.Where(m => m.subClass_ID == filters.ClasificationId);
                        taxonomyResults = taxonomyResults.Where(m => m.Level4 == filters.ClasificationId);
                        break;

                    default:
                        break;
                    }

                    resultIds = null;
                }
            }

            HttpContext.Current.Session["ClassificationSelection"] = classificationSelection;


            //  Inlude source filters
            if (filters.Source != null && filters.Source != "")
            {
                int sourceId;
                int?sourceDatabookId = null;

                if (filters.Source != "0")
                {
                    IList <string> allSourceIds = filters.Source.Split(',').ToList();
                    if (allSourceIds.Count > 1)
                    {
                        sourceId         = allSourceIds[0] != "" ? int.Parse(allSourceIds[0]) : 0;
                        sourceDatabookId = allSourceIds[1] != "" ? int.Parse(allSourceIds[1]) : 0;
                    }
                    else
                    {
                        sourceId = allSourceIds[0] != "" ? int.Parse(allSourceIds[0]) : 0;
                    }
                }
                else
                {
                    sourceId         = 0;
                    sourceDatabookId = null;
                }

                if (sourceId != 0)
                {
                    results   = results.Where(m => m.source_IDs != null && m.source_IDs.Contains(string.Concat(",", sourceId.ToString(), ",")));
                    resultIds = null;
                }

                if (sourceDatabookId != null && sourceDatabookId != 0)
                {
                    results   = results.Where(m => m.databook_IDs != null && m.databook_IDs.Contains(string.Concat(",", sourceDatabookId.ToString(), ",")));
                    resultIds = null;
                }
            }


            //// Inlude column filters
            SearchFilterColumnsAll columnFilters = (SearchFilterColumnsAll)System.Web.HttpContext.Current.Session["SearchFilterColumnsAll"];

            if (columnFilters != null)
            {
                foreach (SearchFilterColumns f in columnFilters.AllFilters.Where(c => c.Filter != null && c.Filter.Trim() != ""))
                {
                    string oneFilter = f.Filter.Trim().ToUpper();
                    if (f.Name == "Material Name")
                    {
                        results   = results.Where(m => m.material_designation != null && m.material_designation.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "Type")
                    {
                        results   = results.Where(m => m.material_type != null && m.material_type.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "Class")
                    {
                        results   = results.Where(m => m.material_group != null && m.material_group.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "Subclass")
                    {
                        results   = results.Where(m => m.material_class != null && m.material_class.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "Group")
                    {
                        results   = results.Where(m => m.material_subClass != null && m.material_subClass.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "UNS No.")
                    {
                        results   = results.Where(m => m.UNS != null && m.UNS.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                    else if (f.Name == "CAS RN")
                    {
                        results   = results.Where(m => m.CAS_RN != null && m.CAS_RN.ToUpper().Contains(oneFilter));
                        resultIds = null;
                    }
                }
            }

            /*adv search*/

            if (advFilters != null && advFilters.AllFilters != null && advFilters.AllFilters.Count > 0)
            {
                string sessionId = System.Web.HttpContext.Current.Session["TotalMateriaSession"].ToString();
                IQueryable <EquivalentProperty> propIds = context.EquivalentProperties.AllAsNoTracking;
                IQueryable <EquivalentMaterial> matIds  = context.EquivalentMaterials.AllAsNoTracking;

                IEnumerable <int> materialIds = context.AdvSearchResults.GetMaterialsByAdvancedSearch(false, advFilters, sessionId, propIds, matIds);

                IEnumerable <int> matVisibleIds = results.Select(n => n.Id);
                materialIds = materialIds.Where(n => matVisibleIds.Contains(n));
                IEnumerable <int> resTM = context.FullTextSearch.GetMaterialsByMaterialIds(materialIds).Select(n => n.Id);

                results   = results.Where(n => resTM.Contains(n.Id));
                resultIds = null;
            }

            // Eval query and prepare final results
            if (filters.FromBrowse)
            {
                // From taxonomy table
                IList <int> tmpList = null;

                if (resultIds == null)
                {
                    tmpList = taxonomyResults.Select(m => m.ID).Distinct().ToList();
                }
                else
                {
                    tmpList = resultIds.Distinct().ToList();
                }

                HttpContext.Current.Session["ClassificationRecordsCount"] = tmpList;

                if (request.Sort.PropertyName == "Name")
                {
                    IList <SampleMaterialModel> retListTemp = taxonomyResults
                                                              .OrderBy(l => l.ID)
                                                              .ThenBy(l1 => l1.Level1Name)
                                                              .ThenByDescending(l4 => l4.Level4Name)
                                                              .ThenByDescending(l3 => l3.Level3Name)
                                                              .ThenByDescending(l2 => l2.Level2Name)
                                                              .Select(m => new SampleMaterialModel()
                    {
                        Id           = m.ID,
                        Name         = m.MaterialName,
                        TypeName     = m.Level1Name,
                        GroupName    = m.Level2Name,
                        ClassName    = m.Level3Name,
                        SubClassName = m.Level4Name,
                        UNS          = null,
                        CAS_RN       = null
                    })
                                                              .ToList();

                    IList <SampleMaterialModel> retList = new List <SampleMaterialModel>();
                    foreach (int matId in tmpList)
                    {
                        SampleMaterialModel mResult = retListTemp.Where(r => r.Id == matId).FirstOrDefault();

                        if (mResult != null)
                        {
                            retList.Add(new SampleMaterialModel()
                            {
                                Id           = mResult.Id,
                                Name         = mResult.Name,
                                TypeName     = mResult.TypeName,
                                GroupName    = mResult.GroupName,
                                ClassName    = mResult.ClassName,
                                SubClassName = mResult.SubClassName
                            });
                        }
                    }

                    model.ListOfMaterials = PagerSearch <SampleMaterialModel>(request.Pager, retList.AsQueryable(), tmpList.Count).ToList();
                }
                else
                {
                    model.ListOfMaterials = taxonomyResults.AsQueryable().Slice(request).Select(m => new SampleMaterialModel()
                    {
                        Id           = m.ID,
                        Name         = m.MaterialName,
                        TypeName     = m.Level1Name,
                        GroupName    = m.Level2Name,
                        ClassName    = m.Level3Name,
                        SubClassName = m.Level4Name,
                        UNS          = null,
                        CAS_RN       = null
                    })
                                            .ToList();
                }
            }
            else
            {
                IList <int> tmpList = null;
                if (resultIds == null)
                {
                    tmpList = results.Select(m => m.Id).ToList();
                }
                else
                {
                    tmpList = resultIds;
                }
                HttpContext.Current.Session["ClassificationRecordsCount"] = tmpList;

                if (request.Sort.PropertyName == "Name")
                {
                    // If search is not "by taxonomy' use FullTextSearch, else use materialTaxonomy table
                    if (typeIds.Count() == 0 && groupIds.Count() == 0 && classIds.Count == 0 && subclassIds.Count() == 0)
                    {
                        IQueryable <SampleMaterialModel> retList = results.Select(m => new SampleMaterialModel()
                        {
                            Id           = m.Id,
                            Name         = m.material_designation,
                            TypeName     = m.material_type,
                            GroupName    = m.material_group,
                            ClassName    = m.material_class,
                            SubClassName = m.material_subClass,
                            UNS          = m.UNS,
                            CAS_RN       = m.CAS_RN
                        })
                                                                   .AsQueryable();

                        model.ListOfMaterials = PagerSearch <SampleMaterialModel>(request.Pager, retList, tmpList.Count).ToList();
                    }
                    else
                    {
                        IEnumerable <MaterialTaxonomy> tr  = context.MaterialTaxonomyAll.AllAsNoTracking;
                        IEnumerable <MaterialTaxonomy> tr1 = new List <MaterialTaxonomy>();
                        IEnumerable <MaterialTaxonomy> tr2 = new List <MaterialTaxonomy>();
                        IEnumerable <MaterialTaxonomy> tr3 = new List <MaterialTaxonomy>();
                        IEnumerable <MaterialTaxonomy> tr4 = new List <MaterialTaxonomy>();
                        if (typeIds.Count > 0)
                        {
                            tr1 = tr.Where(l1 => l1.Level1 != null && typeIds.Contains((int)l1.Level1));
                        }
                        if (groupIds.Count > 0)
                        {
                            tr2 = tr.Where(l2 => l2.Level2 != null && groupIds.Contains((int)l2.Level2));
                        }
                        if (classIds.Count > 0)
                        {
                            tr3 = tr.Where(l3 => l3.Level3 != null && classIds.Contains((int)l3.Level3));
                        }
                        if (subclassIds.Count > 0)
                        {
                            tr4 = tr.Where(l4 => l4.Level4 != null && subclassIds.Contains((int)l4.Level4));
                        }

                        IList <Tuple <int, string, string, string, string, string> > trs = tr1.Select(i1 => new Tuple <int, string, string, string, string, string>(i1.ID, i1.MaterialName, i1.Level1Name, i1.Level2Name, i1.Level3Name, i1.Level4Name))
                                                                                           .Union(tr2.Select(i2 => new Tuple <int, string, string, string, string, string>(i2.ID, i2.MaterialName, i2.Level1Name, i2.Level2Name, i2.Level3Name, i2.Level4Name)))
                                                                                           .Union(tr3.Select(i3 => new Tuple <int, string, string, string, string, string>(i3.ID, i3.MaterialName, i3.Level1Name, i3.Level2Name, i3.Level3Name, i3.Level4Name)))
                                                                                           .Union(tr4.Select(i4 => new Tuple <int, string, string, string, string, string>(i4.ID, i4.MaterialName, i4.Level1Name, i4.Level2Name, i4.Level3Name, i4.Level4Name)))
                                                                                           .ToList();

                        IList <SampleMaterialModel> retListTemp = trs
                                                                  .OrderBy(l => l.Item1)
                                                                  .ThenBy(l1 => l1.Item3)
                                                                  .ThenByDescending(l4 => l4.Item6)
                                                                  .ThenByDescending(l3 => l3.Item5)
                                                                  .ThenByDescending(l2 => l2.Item4)
                                                                  .Select(m => new SampleMaterialModel()
                        {
                            Id           = m.Item1,
                            Name         = m.Item2,
                            TypeName     = m.Item3,
                            GroupName    = m.Item4,
                            ClassName    = m.Item5,
                            SubClassName = m.Item6,
                            UNS          = null,
                            CAS_RN       = null
                        })
                                                                  .ToList();

                        IList <SampleMaterialModel> retList = new List <SampleMaterialModel>();
                        foreach (int matId in tmpList)
                        {
                            SampleMaterialModel mResult = retListTemp.Where(r => r.Id == matId).FirstOrDefault();

                            if (mResult != null)
                            {
                                retList.Add(new SampleMaterialModel()
                                {
                                    Id           = mResult.Id,
                                    Name         = mResult.Name,
                                    TypeName     = mResult.TypeName,
                                    GroupName    = mResult.GroupName,
                                    ClassName    = mResult.ClassName,
                                    SubClassName = mResult.SubClassName
                                });
                            }
                        }

                        model.ListOfMaterials = PagerSearch <SampleMaterialModel>(request.Pager, retList.AsQueryable(), tmpList.Count).ToList();
                    }
                }
                else
                {
                    model.ListOfMaterials = results.AsQueryable().Slice(request).Select(m => new SampleMaterialModel()
                    {
                        Id           = m.Id,
                        Name         = m.material_designation,
                        TypeName     = m.material_type,
                        GroupName    = m.material_group,
                        ClassName    = m.material_class,
                        SubClassName = m.material_subClass,
                        UNS          = m.UNS,
                        CAS_RN       = m.CAS_RN
                    })
                                            .ToList();
                }
            }


            model.Descriptor = request;

            model.Filter          = new SearchResultsCondition();
            model.Filter.FullText = filters.filter;
            if (classificationSelection.Count > 0)
            {
                HttpContext.Current.Session["NodeNames"] = context.Trees.GetTreeNodesNames(classificationSelection);
            }
            else
            {
                HttpContext.Current.Session["NodeNames"] = new Dictionary <int, string>();
            }
            return(model);
        }
        public static List <QueryEntity> FetchAllIntoMemory <TQueryableEntity>(this QueryClause <TQueryableEntity> query,
                                                                               IRepository repository,
                                                                               RepositoryEntityMetadata metadata,
                                                                               Func <Dictionary <string, IReadOnlyDictionary <string, object> > > getPrimaryEntities,
                                                                               Func <QueriedEntity, Dictionary <string, IReadOnlyDictionary <string, object> > > getJoinedEntities)
            where TQueryableEntity : IQueryableEntity
        {
            repository.GuardAgainstNull(nameof(repository));
            query.GuardAgainstNull(nameof(query));
            metadata.GuardAgainstNull(nameof(metadata));
            getPrimaryEntities.GuardAgainstNull(nameof(getPrimaryEntities));
            getJoinedEntities.GuardAgainstNull(nameof(getJoinedEntities));

            var take = query.GetDefaultTake(repository);

            if (take == 0)
            {
                return(new List <QueryEntity>());
            }

            var primaryEntities = getPrimaryEntities();

            if (!primaryEntities.HasAny())
            {
                return(new List <QueryEntity>());
            }

            var joinedContainers = query.JoinedEntities
                                   .Where(je => je.Join.Exists())
                                   .ToDictionary(je => je.EntityName, je => new
            {
                Collection   = getJoinedEntities(je),
                JoinedEntity = je
            });

            List <KeyValuePair <string, IReadOnlyDictionary <string, object> > > joinedEntities = null;

            if (!joinedContainers.Any())
            {
                joinedEntities = primaryEntities
                                 .Select(pe => new KeyValuePair <string, IReadOnlyDictionary <string, object> >(pe.Key, pe.Value))
                                 .ToList();
            }
            else
            {
                foreach (var joinedContainer in joinedContainers)
                {
                    var joinedEntity  = joinedContainer.Value.JoinedEntity;
                    var join          = joinedEntity.Join;
                    var rightEntities = joinedContainer.Value.Collection
                                        .ToDictionary(e => e.Key, e => e.Value);

                    joinedEntities = join
                                     .JoinResults(primaryEntities, rightEntities,
                                                  joinedEntity.Selects.ProjectSelectedJoinedProperties());
                }
            }

            var results = joinedEntities?.AsQueryable();
            var orderBy = query.ToDynamicLinqOrderByClause();
            var skip    = query.GetDefaultSkip();

            if (query.Wheres.Any())
            {
                var whereBy = query.Wheres.ToDynamicLinqWhereClause();
                results = results
                          .Where(whereBy);
            }
            return(results
                   .OrderBy(orderBy)
                   .Skip(skip)
                   .Take(take)
                   .Select(sel => new KeyValuePair <string, IReadOnlyDictionary <string, object> >(sel.Key, sel.Value))
                   .CherryPickSelectedProperties(query)
                   .Select(ped => QueryEntity.FromProperties(ped.Value, metadata))
                   .ToList());
        }
Example #60
0
        /// <summary>
        /// Gets all items list.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Media items list</returns>
        private Tuple <IEnumerable <MediaViewModel>, int> GetAllItemsList(MediaManagerViewModel request)
        {
            var query = Repository
                        .AsQueryable <Media>()
                        .Where(m => !m.IsDeleted &&
                               m.Original == null &&
                               m.Type == MediaType &&
                               (m is MediaFolder || m is TEntity && !((TEntity)m).IsTemporary));

            if (!request.IncludeArchivedItems)
            {
                query = query.Where(m => !m.IsArchived);
            }

            var removeEmptyFolders = false;

            if (request.Tags != null)
            {
                foreach (var tagKeyValue in request.Tags)
                {
                    var id = tagKeyValue.Key.ToGuidOrDefault();
                    query = query.Where(m => m is MediaFolder || m.MediaTags.Any(mt => mt.Tag.Id == id));
                    removeEmptyFolders = true;
                }
            }

            query = AttachDeniedMediasFilterIfEnabled(query, request);

            if (!string.IsNullOrWhiteSpace(request.SearchQuery))
            {
                var searchQuery = string.Format("%{0}%", request.SearchQuery);

                var predicate = PredicateBuilder.False <Media>();
                predicate = predicate.Or(m => m.Title.Contains(searchQuery));
                predicate = predicate.Or(m => m.Description.Contains(searchQuery));
                predicate = predicate.Or(m => m.MediaTags.Any(mt => mt.Tag.Name.Contains(searchQuery)));
                predicate = AppendSearchFilter(predicate, searchQuery);

                if (request.SearchInHistory)
                {
                    query = query.Where(m => m.History.AsQueryable().Any(predicate));
                }
                else
                {
                    query = query.Where(predicate);
                }

                query = query.Fetch(f => f.Folder);

                var mediaList = query.ToList();

                var result = new List <Media>();
                foreach (var media in mediaList)
                {
                    if (IsChild(media, request.CurrentFolderId, request.IncludeArchivedItems))
                    {
                        result.Add(media);
                    }
                }

                return(ToResponse(request, result.AsQueryable()));
            }

            if (!request.CurrentFolderId.HasDefaultValue())
            {
                query = query.Where(m => m.Folder.Id == request.CurrentFolderId);
            }
            else
            {
                query = query.Where(m => m.Folder == null);
            }


            return(removeEmptyFolders
                ? RemoveEmptyFolders(query, request)
                : ToResponse(request, query, true));
        }