Exemplo n.º 1
0
        public async Task Create(SharedFolder item)
        {
            var propertyList = new List <string>()
            {
                "UserId", "FolderId"
            };
            var valueList = new List <object>()
            {
                new ObjectId(item.UserId), item.FolderId
            };
            var filter = FilterService <SharedFolder> .GetFilterByTwoParam(propertyList, valueList);

            var sharedFolder = await DatabaseData.SharedFolders.Find(filter).FirstOrDefaultAsync();

            if (sharedFolder != null && sharedFolder.Role == item.Role)
            {
                throw new Exception("The user have access to this folder");
            }
            else if (sharedFolder != null && sharedFolder.Role != item.Role)
            {
                sharedFolder.Role = item.Role;
                await Update(sharedFolder.Id, sharedFolder);
            }
            else
            {
                await DatabaseData.SharedFolders.InsertOneAsync(item);
            }

            await ShareNotesFromFolder(item);
        }
Exemplo n.º 2
0
		  public void execute(ProcessEngine engine, string scenarioName)
		  {
			FilterService filterService = engine.FilterService;

			Filter filterOne = filterService.newTaskFilter("taskFilterOne");

			IDictionary<string, object> primitivesMap = new Dictionary<string, object>();
			primitivesMap["string"] = "aStringValue";
			primitivesMap["int"] = 47;
			primitivesMap["intOutOfRange"] = int.MaxValue + 1L;
			primitivesMap["long"] = long.MaxValue;
			primitivesMap["double"] = 3.14159265359D;
			primitivesMap["boolean"] = true;
			primitivesMap["null"] = null;

			filterOne.Properties = Collections.singletonMap<string, object>("foo", Collections.singletonList(primitivesMap));
			filterService.saveFilter(filterOne);

			Filter filterTwo = engine.FilterService.newTaskFilter("taskFilterTwo");

			IList<object> primitivesList = new List<object>();
			primitivesList.Add("aStringValue");
			primitivesList.Add(47);
			primitivesList.Add(int.MaxValue + 1L);
			primitivesList.Add(long.MaxValue);
			primitivesList.Add(3.14159265359D);
			primitivesList.Add(true);
			primitivesList.Add(null);

			filterTwo.Properties = Collections.singletonMap<string, object>("foo", Collections.singletonMap("bar", primitivesList));
			filterService.saveFilter(filterTwo);
		  }
 public ChirperExtension()
 {
     logger          = UserMod.Services.GetService <ILogger>();
     filterService   = UserMod.Services.GetService <FilterService>();
     inputService    = UserMod.Services.GetService <InputService>();
     positionService = UserMod.Services.GetService <PositionService>();
 }
Exemplo n.º 4
0
        public SampleTestRunner()
        {
            var list = new List<Student>();
            var rand = new Random();
            const int total = 10000000;
            Console.WriteLine("Creating list ...");
            for(var i = 0; i < total; i++)
            {
                var student = new Student
                    {
                        FirstName = rand.Next().ToString(),
                        Id = i,
                        LastName = rand.Next().ToString(),
                        IsInternational = rand.Next(2) != 0,
                        Gender = rand.Next(2) == 0 ? "Male" : "Female",
                    };
                list.Add(student);
            }

            Console.WriteLine("Filtering ...");
            var st = DateTime.Now;
            var service = new FilterService<Student>();
            service.AddBinaryFilter(e => e.Id < total);
            service.AddBinaryFilter(e => e.FirstName.Contains("1"));
            service.AddBinaryFilter(e => e.LastName.Contains("2"));
            service.AddBinaryFilter(e => !e.IsInternational);
            service.AddBinaryFilter(e => e.Gender.Equals("Female"));
            var filtered = service.Filter(list);
            var et = DateTime.Now;
            Console.WriteLine("Done filtering...");
            Console.WriteLine("Filtering time (in ms): {0}", et.Subtract(st).TotalMilliseconds);

            Console.WriteLine("Total Count: {0}", list.Count);
            Console.WriteLine("Filtered Count: {0}", filtered.Count());
        }
        public void Destroy(FilterService filterService)
        {
            filterService.Remove(_filterHandle, _filterServiceEntry);
            long filtersVersion = _agentInstanceContextCreateContext.StatementContext.FilterService.FiltersVersion;

            _agentInstanceContextCreateContext.EpStatementAgentInstanceHandle.StatementFilterVersion.StmtFilterVersion = filtersVersion;
        }
Exemplo n.º 6
0
        public AjaxResult ReadFunctions(PageRequest request)
        {
            var emptyPage = new PageData <FunctionOutputDto2>();

            if (request.FilterGroup.Rules.Count == 0)
            {
                return(new AjaxResult(emptyPage));
            }
            Expression <Func <Module, bool> > moduleExp = FilterService.GetExpression <Module>(request.FilterGroup);

            int[]  moduleIds   = _functionAuthManager.Modules.Where(moduleExp).Select(m => m.Id).ToArray();
            Guid[] functionIds = _functionAuthManager.ModuleFunctions.Where(m => moduleIds.Contains(m.ModuleId))
                                 .Select(m => m.FunctionId).Distinct().ToArray();
            if (functionIds.Length == 0)
            {
                return(new AjaxResult(emptyPage));
            }
            if (request.PageCondition.SortConditions.Length == 0)
            {
                request.PageCondition.SortConditions = new[] { new SortCondition("Area"), new SortCondition("Controller") };
            }
            var page = _functionAuthManager.Functions.ToPage(m => functionIds.Contains(m.Id),
                                                             request.PageCondition,
                                                             m => new FunctionOutputDto2()
            {
                Id = m.Id, Name = m.Name, AccessType = m.AccessType, Area = m.Area, Controller = m.Controller
            });

            return(new AjaxResult(page.ToPageData()));
        }
        public Dictionary <string, object> GetStateOfJurisdiction(bool isAll)
        {
            FilterService  filterService  = new FilterService();
            FilterComboObj filterComboObj = filterService.GetStateOfJurisdiction(isAll ? null : UserContext.AssociationNumber);

            return(returnFilterResult(filterComboObj, filterComboObj.StateOfJurisdictionsList));
        }
Exemplo n.º 8
0
        private void RunAssertionAddRemoveFilter(FilterService service)
        {
            var eventType    = SupportEventTypeFactory.CreateBeanType(typeof(SupportBean));
            var spec         = SupportFilterSpecBuilder.Build(eventType, new Object[] { "TheString", FilterOperator.EQUAL, "HELLO" });
            var filterValues = spec.GetValueSet(null, null, null);

            var callables = new Func <bool> [5];

            for (int ii = 0; ii < callables.Length; ii++)
            {
                callables[ii] =
                    () =>
                {
                    var handle = new SupportFilterHandle();
                    for (int jj = 0; jj < 10000; jj++)
                    {
                        var entry = service.Add(filterValues, handle);
                        service.Remove(handle, entry);
                    }
                    return(true);
                };
            }

            Object[] result = TryMT(callables);
            EPAssertionUtil.AssertAllBooleanTrue(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// See the method of the same name in <seealso cref="com.espertech.esper.view.stream.StreamFactoryService"/>.
        /// </summary>
        /// <param name="filterSpec">is the filter definition</param>
        /// <param name="filterService">to be used to deactivate filter when the last event stream is dropped</param>
        /// <param name="isJoin">is indicatng whether the stream will participate in a join statement, informationnecessary for stream reuse and multithreading concerns</param>
        /// <param name="hasOrderBy">if the consumer has an order-by clause</param>
        /// <param name="filterWithSameTypeSubselect"></param>
        /// <param name="stateless"></param>
        public void DropStream(
            FilterSpecCompiled filterSpec,
            FilterService filterService,
            bool isJoin,
            bool hasOrderBy,
            bool filterWithSameTypeSubselect,
            bool stateless)
        {
            StreamEntry entry;
            var         forceNewStream = isJoin || (!_isReuseViews) || hasOrderBy || filterWithSameTypeSubselect || stateless;

            if (forceNewStream)
            {
                entry = _eventStreamsIdentity.Get(filterSpec);
                if (entry == null)
                {
                    throw new IllegalStateException("Filter spec object not in collection");
                }
                _eventStreamsIdentity.Remove(filterSpec);
                filterService.Remove(entry.Callback, entry.FilterServiceEntry);
            }
            else
            {
                entry = _eventStreamsRefCounted[filterSpec];
                var isLast = _eventStreamsRefCounted.Dereference(filterSpec);
                if (isLast)
                {
                    filterService.Remove(entry.Callback, entry.FilterServiceEntry);
                }
            }
        }
Exemplo n.º 10
0
        public void FilterService_FilterExpiringAnnualCheckUp_ShouldReturnIEnumerableCollection_WhenPassedParametersAreCorrect()
        {
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = 1, Manufacturer = "VW", Model = "Golf", ValidUntilAnnualCheckUp = DateTime.Now
                },
                new Car()
                {
                    Id = 2, Manufacturer = "BMW", Model = "e40", ValidUntilAnnualCheckUp = DateTime.Now
                },
                new Car()
                {
                    Id = 3, Manufacturer = "Lada", Model = "2105", ValidUntilAnnualCheckUp = DateTime.Now
                }
            };
            var mockedRepo = new Mock <IRepository <Car> >();

            mockedRepo.Setup(s => s.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            var result = service.FilterExpiringAnnualCheckUp().ToList();

            Assert.AreEqual(collectionOfCars.Count, result.Count);
        }
Exemplo n.º 11
0
        public void FilterService_GetMailsForCarsInsuranceExpiration_VerifysThatMethodAllIsCalledExactlyOneTime()
        {
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = 1, Manufacturer = "VW", Model = "Golf", ValidUntilVignette = DateTime.Now,
                },
                new Car()
                {
                    Id = 2, Manufacturer = "BMW", Model = "e40", ValidUntilVignette = DateTime.Now,
                },
                new Car()
                {
                    Id = 3, Manufacturer = "Lada", Model = "2105", ValidUntilVignette = DateTime.Now,
                }
            };

            var mockedRepo = new Mock <IRepository <Car> >();

            mockedRepo.Setup(m => m.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            service.GetMailsForCarsInsuranceExpiration();

            mockedRepo.Verify(m => m.All(), Times.Exactly(1));
        }
        public Dictionary <string, object> GetLocations(string filterValue, string selectedValue, string memberNumber)
        {
            FilterService  filterService  = new FilterService();
            FilterComboObj filterComboObj = filterService.GetLocations(UserContext.UserID, UserContext.AssociationNumber, memberNumber, filterValue, selectedValue);

            return(returnFilterResult(filterComboObj, filterComboObj.LocationList));
        }
Exemplo n.º 13
0
        public void FilterService_FilterExpiringAnnualCheckUp_VerifyThatTheMethodIsCalledExactOneTime_WhenPassedParametersAreCorrect()
        {
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = 1, Manufacturer = "VW", Model = "Golf", ValidUntilAnnualCheckUp = DateTime.Now
                },
                new Car()
                {
                    Id = 2, Manufacturer = "BMW", Model = "e40", ValidUntilAnnualCheckUp = DateTime.Now
                },
                new Car()
                {
                    Id = 3, Manufacturer = "Lada", Model = "2105", ValidUntilAnnualCheckUp = DateTime.Now
                }
            };
            var mockedRepo = new Mock <IRepository <Car> >();

            mockedRepo.Setup(m => m.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            service.FilterExpiringAnnualCheckUp();

            mockedRepo.Verify(m => m.All(), Times.Exactly(1));
        }
        public Dictionary <string, object> GetCoverages()
        {
            FilterService  filterService  = new FilterService();
            FilterComboObj filterComboObj = filterService.GetCoverages(UserContext.UserID);

            return(returnFilterResult(filterComboObj, filterComboObj.CoverageList));
        }
Exemplo n.º 15
0
        public static Filter CreateFilterForUserAndLogon(string userName, string userPassword, int userId)
        {
            var name     = DataHelper.RandomString(20);
            var password = DataHelper.RandomString(20);

            BusinessHelper.CreateUserWithFullControl(name, password);

            BusinessPrincipal.Login(name, password);

            var filter = FilterService.FilterNew();

            var task = BusinessHelper.CreateTask();

            filter.Name   = DataHelper.RandomString(20);
            filter.Target = DataHelper.RandomString(20);
            filter.Query  = DataHelper.RandomString(20);

            filter = FilterService.FilterSave(filter);

            BusinessPrincipal.Logout();

            BusinessPrincipal.Login(userName, userPassword);

            return(filter);
        }
Exemplo n.º 16
0
        // settable for view-sharing

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="stmtEngineServices">is the engine services for the statement</param>
        /// <param name="schedulingService">implementation for schedule registration</param>
        /// <param name="scheduleBucket">is for ordering scheduled callbacks within the view statements</param>
        /// <param name="epStatementHandle">is the statements-own handle for use in registering callbacks with services</param>
        /// <param name="viewResultionService">is a service for resolving view namespace and name to a view factory</param>
        /// <param name="patternResolutionService">is the service that resolves pattern objects for the statement</param>
        /// <param name="statementExtensionSvcContext">provide extension points for custom statement resources</param>
        /// <param name="statementStopService">for registering a callback invoked when a statement is stopped</param>
        /// <param name="methodResolutionService">is a service for resolving static methods and aggregation functions</param>
        /// <param name="patternContextFactory">is the pattern-level services and context information factory</param>
        /// <param name="filterService">is the filtering service</param>
        /// <param name="statementResultService">handles awareness of listeners/subscriptions for a statement customizing output produced</param>
        /// <param name="internalEventEngineRouteDest">routing destination</param>
        /// <param name="annotations">The annotations.</param>
        /// <param name="statementAgentInstanceRegistry">The statement agent instance registry.</param>
        /// <param name="defaultAgentInstanceLock">The default agent instance lock.</param>
        /// <param name="contextDescriptor">The context descriptor.</param>
        /// <param name="patternSubexpressionPoolSvc">The pattern subexpression pool SVC.</param>
        /// <param name="matchRecognizeStatePoolStmtSvc">The match recognize state pool statement SVC.</param>
        /// <param name="statelessSelect">if set to <c>true</c> [stateless select].</param>
        /// <param name="contextControllerFactoryService">The context controller factory service.</param>
        /// <param name="defaultAgentInstanceScriptContext">The default agent instance script context.</param>
        /// <param name="aggregationServiceFactoryService">The aggregation service factory service.</param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="writesToTables">if set to <c>true</c> [writes to tables].</param>
        /// <param name="statementUserObject">The statement user object.</param>
        /// <param name="statementSemiAnonymousTypeRegistry">The statement semi anonymous type registry.</param>
        /// <param name="priority">The priority.</param>
        public StatementContext(
            StatementContextEngineServices stmtEngineServices,
            SchedulingService schedulingService,
            ScheduleBucket scheduleBucket,
            EPStatementHandle epStatementHandle,
            ViewResolutionService viewResultionService,
            PatternObjectResolutionService patternResolutionService,
            StatementExtensionSvcContext statementExtensionSvcContext,
            StatementStopService statementStopService,
            MethodResolutionService methodResolutionService,
            PatternContextFactory patternContextFactory,
            FilterService filterService,
            StatementResultService statementResultService,
            InternalEventRouteDest internalEventEngineRouteDest,
            Attribute[] annotations,
            StatementAIResourceRegistry statementAgentInstanceRegistry,
            IReaderWriterLock defaultAgentInstanceLock,
            ContextDescriptor contextDescriptor,
            PatternSubexpressionPoolStmtSvc patternSubexpressionPoolSvc,
            MatchRecognizeStatePoolStmtSvc matchRecognizeStatePoolStmtSvc,
            bool statelessSelect,
            ContextControllerFactoryService contextControllerFactoryService,
            AgentInstanceScriptContext defaultAgentInstanceScriptContext,
            AggregationServiceFactoryService aggregationServiceFactoryService,
            ScriptingService scriptingService,
            bool writesToTables,
            object statementUserObject,
            StatementSemiAnonymousTypeRegistry statementSemiAnonymousTypeRegistry,
            int priority)
        {
            _stmtEngineServices               = stmtEngineServices;
            SchedulingService                 = schedulingService;
            ScheduleBucket                    = scheduleBucket;
            EpStatementHandle                 = epStatementHandle;
            ViewResolutionService             = viewResultionService;
            PatternResolutionService          = patternResolutionService;
            StatementExtensionServicesContext = statementExtensionSvcContext;
            StatementStopService              = statementStopService;
            MethodResolutionService           = methodResolutionService;
            PatternContextFactory             = patternContextFactory;
            FilterService                = filterService;
            _statementResultService      = statementResultService;
            InternalEventEngineRouteDest = internalEventEngineRouteDest;
            ScheduleAdjustmentService    = stmtEngineServices.ConfigSnapshot.EngineDefaults.ExecutionConfig.IsAllowIsolatedService ? new ScheduleAdjustmentService() : null;
            Annotations = annotations;
            StatementAgentInstanceRegistry = statementAgentInstanceRegistry;
            DefaultAgentInstanceLock       = defaultAgentInstanceLock;
            ContextDescriptor                 = contextDescriptor;
            PatternSubexpressionPoolSvc       = patternSubexpressionPoolSvc;
            MatchRecognizeStatePoolStmtSvc    = matchRecognizeStatePoolStmtSvc;
            IsStatelessSelect                 = statelessSelect;
            ContextControllerFactoryService   = contextControllerFactoryService;
            DefaultAgentInstanceScriptContext = defaultAgentInstanceScriptContext;
            AggregationServiceFactoryService  = aggregationServiceFactoryService;
            ScriptingService    = scriptingService;
            IsWritesToTables    = writesToTables;
            StatementUserObject = statementUserObject;
            StatementSemiAnonymousTypeRegistry = statementSemiAnonymousTypeRegistry;
            Priority = priority;
        }
        static async Task Main(string[] args)
        {
            Log.Info("Building services...");
            var config   = BuildConfig();
            var links    = config.GetSection("links").Get <IEnumerable <Link> >();
            var services = new List <LinkerService>();

            foreach (var link in links)
            {
                if (link.Filters == null || !link.Filters.Any())
                {
                    Log.Info("Setting 'include all' default filter");
                    var defaultFilter = new Filter(FilterType.Stream, "*", FilterOperation.Include);
                    link.Filters = new List <Filter> {
                        defaultFilter
                    };
                }
                var filters = link.Filters.Select(linkFilter => new Filter
                {
                    FilterOperation = linkFilter.FilterOperation, FilterType = linkFilter.FilterType,
                    Value           = linkFilter.Value
                }).ToList();
                var filterService = new FilterService(filters);
                var service       = new LinkerService(new LinkerConnectionBuilder(new Uri(link.Origin.ConnectionString),
                                                                                  ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials(link.Origin.User, link.Origin.Pass)),
                                                                                  link.Origin.ConnectionName), new LinkerConnectionBuilder(new Uri(link.Destination.ConnectionString),
                                                                                                                                           ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials(link.Destination.User, link.Destination.Pass)),
                                                                                                                                           link.Destination.ConnectionName), filterService, Settings.Default(), new NLogger());
                services.Add(service);
            }
            await StartServices(services);

            Log.Info("Press enter to exit the program");
            Console.ReadLine();
        }
Exemplo n.º 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp()
        public virtual void setUp()
        {
            filterService   = engineRule.FilterService;
            historyService  = engineRule.HistoryService;
            taskService     = engineRule.TaskService;
            identityService = engineRule.IdentityService;
        }
Exemplo n.º 19
0
        public static IApplicationBuilder UseTomatoLog(this IApplicationBuilder app,
                                                       IConfiguration configuration,
                                                       IDistributedCache cache,
                                                       SysConfigManager sysManager,
                                                       ProConfigManager proManager,
                                                       IApplicationLifetime lifetime)
        {
            lifeTime         = lifetime;
            sysConfigManager = sysManager;
            filterService    = new FilterService(configuration, cache, sysManager, proManager, logger);
            var flowType = configuration.GetSection("TomatoLog:Flow:Type").Get <FlowType>();

            switch (flowType)
            {
            default:
                UseRedis(configuration, cache);
                break;

            case FlowType.RabbitMQ:
                UseRabbitMQ(configuration);
                break;

            case FlowType.Kafka:
                UseKafka(configuration);
                break;
            }
            return(app);
        }
Exemplo n.º 20
0
        public void CheckingMovieWithoutShowsForTodayReturnsFalse()
        {
            FilterService serviceUnderTest = new FilterService();

            _movie = new SimpleMovie
            {
                Name  = "Just another day",
                Genre = new List <string>
                {
                    "Action"
                },
                Shows = new List <SimpleShow>
                {
                    new SimpleShow
                    {
                        ShowDate = DateTime.Today.Date.AddDays(1.0),
                        Start    = "10:00"
                    }
                }
            };

            var actual = _serviceUnderTest.Check(_movie);

            Assert.False(actual);
        }
Exemplo n.º 21
0
        public AjaxResult ReadFunctions(int userId, [FromBody] PageRequest request)
        {
            var empty = new PageData <FunctionOutputDto2>();

            if (userId == 0)
            {
                return(new AjaxResult(empty));
            }

            FunctionAuthManager functionAuthManager = _provider.GetRequiredService <FunctionAuthManager>();

            int[]  moduleIds   = functionAuthManager.GetUserWithRoleModuleIds(userId);
            Guid[] functionIds = functionAuthManager.ModuleFunctions.Where(m => moduleIds.Contains(m.ModuleId)).Select(m => m.FunctionId).Distinct()
                                 .ToArray();
            if (functionIds.Length == 0)
            {
                return(new AjaxResult(empty));
            }

            Expression <Func <Function, bool> > funcExp = FilterService.GetExpression <Function>(request.FilterGroup);

            funcExp = funcExp.And(m => functionIds.Contains(m.Id));
            if (request.PageCondition.SortConditions.Length == 0)
            {
                request.PageCondition.SortConditions = new[] { new SortCondition("Area"), new SortCondition("Controller") };
            }

            PageResult <FunctionOutputDto2> page = functionAuthManager.Functions.ToPage <Function, FunctionOutputDto2>(funcExp, request.PageCondition);

            return(new AjaxResult(page.ToPageData()));
        }
Exemplo n.º 22
0
        public AjaxResult Read(PageRequest request)
        {
            request.AddDefaultSortCondition(
                new SortCondition("Level"),
                new SortCondition("Order")
                );
            IFunction function = this.GetExecuteFunction();
            Expression <Func <PackOutputDto, bool> > exp = FilterService.GetExpression <PackOutputDto>(request.FilterGroup);
            IServiceProvider           provider          = HttpContext.RequestServices;
            IQueryable <PackOutputDto> query             = provider.GetAllPacks().Select(m => new PackOutputDto()
            {
                Name      = m.GetType().Name,
                Display   = m.GetType().GetDescription(true),
                Class     = m.GetType().FullName,
                Level     = m.Level,
                Order     = m.Order,
                IsEnabled = m.IsEnabled
            }).AsQueryable();

            var page = CacheService.ToPageCache(query,
                                                exp,
                                                request.PageCondition,
                                                m => m,
                                                function);

            return(new AjaxResult("数据读取成功", AjaxResultType.Success, page.ToPageData()));
        }
Exemplo n.º 23
0
 public ProductCatalogStructurePackage(BaseProductService baseProductService, ProductListService productListService,
                                       RelationshipTypeService relationshipTypeService, CategoryService categoryService,
                                       UnitOfMeasurementService unitOfMeasurementService, DataService dataService,
                                       FieldTemplateService fieldTemplateService,
                                       LanguageService languageService, VariantService variantService,
                                       InventoryService inventoryService,
                                       PriceListService priceListService,
                                       StructureInfoService structureInfoService,
                                       CurrencyService currencyService,
                                       FilterService filterService,
                                       InventoryItemService inventoryItemService,
                                       PriceListItemService priceListItemService,
                                       ProductListItemService productListItemService)
 {
     _baseProductService        = baseProductService;
     _categoryService           = categoryService;
     _dataService               = dataService;
     _fieldTemplateService      = fieldTemplateService;
     _languageService           = languageService;
     _variantService            = variantService;
     _inventoryService          = inventoryService;
     _priceListService          = priceListService;
     _structureInfoService      = structureInfoService;
     _currencyService           = currencyService;
     _filterService             = filterService;
     _productListService        = productListService;
     _relationshipTypeService   = relationshipTypeService;
     _unitOfMeasurementService  = unitOfMeasurementService;
     _bidirectionalRelationList = new List <ImportBidirectionalRelation>();
     _inventoryItemService      = inventoryItemService;
     _priceListItemService      = priceListItemService;
     _productListItemService    = productListItemService;
 }
        public void CarsAnnualCheckUpExpiration_VerifysThatMethodAllIsCalledExactlyOneTime()
        {
            // Arrange
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "VW", Model = "Golf", ValidUntilVignette = DateTime.Now,
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "BMW", Model = "e40", ValidUntilVignette = DateTime.Now,
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "Lada", Model = "2105", ValidUntilVignette = DateTime.Now,
                }
            };

            var mockedRepo = new Mock <IEfGenericRepository <Car> >();

            mockedRepo.Setup(m => m.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            // Act
            service.GetMailsForCarsAnnualCheckUpExpiration();

            // Assert
            mockedRepo.Verify(m => m.All(), Times.Exactly(1));
        }
        public void ShouldReturnIEnumerableCollection_WhenPassedParametersAreCorrect()
        {
            // Arrange
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "VW", Model = "Golf", ValidUntilVignette = DateTime.Now
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "BMW", Model = "e40", ValidUntilVignette = DateTime.Now
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "Lada", Model = "2105", ValidUntilVignette = DateTime.Now
                }
            };
            var mockedRepo = new Mock <IEfGenericRepository <Car> >();

            mockedRepo.Setup(m => m.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            // Act
            var result = service.FilterExpiringVignetteCars().ToList();

            // Assert
            Assert.AreEqual(collectionOfCars.Count, result.Count);
        }
        public Dictionary <string, object> GetClientAnalysis5(string filterValue)
        {
            FilterService  filterService  = new FilterService();
            FilterComboObj filterComboObj = filterService.GetClientAnalysis5(UserContext.UserID, UserContext.AssociationNumber, filterValue);

            return(returnFilterResult(filterComboObj, filterComboObj.ClientAnalysesList));
        }
        public void VerifyThatTheMethodIsCalledExactOneTime_WhenPassedParametersAreCorrect()
        {
            // Arrange
            var collectionOfCars = new List <Car>
            {
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "VW", Model = "Golf", ValidUntilVignette = DateTime.Now
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "BMW", Model = "e40", ValidUntilVignette = DateTime.Now
                },
                new Car()
                {
                    Id = Guid.NewGuid(), Manufacturer = "Lada", Model = "2105", ValidUntilVignette = DateTime.Now
                }
            };
            var mockedRepo = new Mock <IEfGenericRepository <Car> >();

            mockedRepo.Setup(m => m.All()).Returns(collectionOfCars);
            var service = new FilterService(mockedRepo.Object);

            // Act
            service.FilterExpiringVignetteCars();

            // Assert
            mockedRepo.Verify(m => m.All(), Times.Exactly(1));
        }
Exemplo n.º 28
0
        public async Task FormatCodeAsync([Summary("ID of a message, or pasted code."), Remainder] string input)
        {
            if (FilterService.ContainsBlockedWord(input))
            {
                return;
            }

            var userMention = $"<@{Context.User.Id}>";
            var firstWord   = input.Split(" ")[0];

            // If a language is entered, remove it from input
            if (TryDetectLanguage(firstWord, out string language))
            {
                input     = input.Remove(0, language.Length + 1);               // Length + 1 for removing the whitespace as well, faster than calling .Trim();
                firstWord = input.Split(" ")[0];
            }

            // If an id is entered, try assigning the target message's content to input
            if (TryDetectMessageFromId(firstWord, out string content, out ulong messageId, out ulong messageAuthorId))
            {
                input = RemoveBacktics(content);
                var user = await Context.Guild.GetUserAsync(messageAuthorId);

                userMention = $"{user.Username}";
                if (CanDeleteOriginal(messageId))
                {
                    await Context.Channel.DeleteMessageAsync(messageId);
                }
            }
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="eventAdapterService">is the event wrapper and type service</param>
 /// <param name="eventTypeIdGenerator">The event type id generator.</param>
 /// <param name="engineImportService">for imported aggregation functions and static functions</param>
 /// <param name="variableService">provides access to variable values</param>
 /// <param name="engineSettingsService">some engine settings are writable</param>
 /// <param name="valueAddEventService">Update event handling</param>
 /// <param name="metricReportingService">for metric reporting</param>
 /// <param name="statementEventTypeRef">statement to event type reference holding</param>
 /// <param name="statementVariableRef">statement to variable reference holding</param>
 /// <param name="plugInViews">The plug in views.</param>
 /// <param name="filterService">The filter service.</param>
 /// <param name="patternSubexpressionPoolSvc">The pattern subexpression pool SVC.</param>
 /// <param name="tableService">The table service.</param>
 public ConfigurationOperationsImpl(
     EventAdapterService eventAdapterService,
     EventTypeIdGenerator eventTypeIdGenerator,
     EngineImportService engineImportService,
     VariableService variableService,
     EngineSettingsService engineSettingsService,
     ValueAddEventService valueAddEventService,
     MetricReportingService metricReportingService,
     StatementEventTypeRef statementEventTypeRef,
     StatementVariableRef statementVariableRef,
     PluggableObjectCollection plugInViews,
     FilterService filterService,
     PatternSubexpressionPoolEngineSvc patternSubexpressionPoolSvc,
     MatchRecognizeStatePoolEngineSvc matchRecognizeStatePoolEngineSvc,
     TableService tableService)
 {
     _eventAdapterService              = eventAdapterService;
     _eventTypeIdGenerator             = eventTypeIdGenerator;
     _engineImportService              = engineImportService;
     _variableService                  = variableService;
     _engineSettingsService            = engineSettingsService;
     _valueAddEventService             = valueAddEventService;
     _metricReportingService           = metricReportingService;
     _statementEventTypeRef            = statementEventTypeRef;
     _statementVariableRef             = statementVariableRef;
     _plugInViews                      = plugInViews;
     _filterService                    = filterService;
     _patternSubexpressionPoolSvc      = patternSubexpressionPoolSvc;
     _matchRecognizeStatePoolEngineSvc = matchRecognizeStatePoolEngineSvc;
     _tableService                     = tableService;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the IrcChannelViewModel class
        /// </summary>
        public IrcChannelViewModel(IrcChannel channel, string networkName, Settings settings)
        {
            this.Settings = settings;
              this.Message = string.Empty;
              this.Messages = new BindableCollection<Message>();
              this.Closable = true;
              this.DisplayName = channel.Name;
              this.networkName = networkName;
              this.personalHistory = new List<string>();
              this.events = IoC.Get<IEventAggregator>();
              this.filterService = IoC.Get<FilterService>();
              this.Channel = channel;
              this.Channel.ModesChanged += this.channelModesChanged;
              this.Channel.UsersListReceived += this.channelUsersListReceived;
              this.Channel.MessageReceived += this.channelMessageReceived;
              this.Channel.UserJoined += this.channelUserJoined;
              this.Channel.UserLeft += this.channelUserLeft;
              this.Channel.NoticeReceived += this.channelNoticeReceived;
              this.Channel.TopicChanged += this.channelTopicChanged;

              DirectoryInfo di = new DirectoryInfo(Settings.PATH + "\\logs\\");
              if (!di.Exists)
            di.Create();
              if (this.Settings.CanLog)
            this.logger = new Logger(String.Format("{0}\\logs\\{1}.{2}.txt",
                                 Settings.PATH,
                                 channel.Name,
                                 networkName));

              this.Channel.GetTopic();
              this.Users = new List<IrcChannelUser>();
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            var webApiUrl = ConfigurationManager.AppSettings["webApi"];

            IDataService   dataService   = new WebApiDataService(webApiUrl);
            IFilterService filterService = new FilterService();

            var owners = dataService.FetchOwnersAsync().Result;

            var maleOwnerCats   = filterService.FilterPets(owners, "Male", "Cat");
            var femaleOwnerCats = filterService.FilterPets(owners, "Female", "Cat");

            Console.WriteLine("Male:");
            foreach (var pet in maleOwnerCats)
            {
                Console.WriteLine($"\t{pet.Name}");
            }

            Console.WriteLine("Female:");
            foreach (var pet in femaleOwnerCats)
            {
                Console.WriteLine($"\t{pet.Name}");
            }

            Console.ReadLine();
        }
        public Dictionary <string, object> GetGroupCode4s(string filterValue, string selectedValue, string memberNumber, string location, string group1Code, string group2Code, string group3Code)
        {
            FilterService  filterService  = new FilterService();
            FilterComboObj filterComboObj = filterService.GetGroup4Codes(UserContext.UserID, UserContext.AssociationNumber, memberNumber, location, group1Code, group2Code, group3Code, filterValue, selectedValue);

            return(returnFilterResult(filterComboObj, filterComboObj.GroupCodeList));
        }
Exemplo n.º 33
0
 public void GenericContainTest()
 {
     var vm = new SortingFilterModel();
     var filterService = new FilterService(new ExpressionBuilder(), new SortingService(new ExpressionBuilder()));
     var query = Persons.AsQueryable();
     query = filterService.AppendQueryWithContains<Person>("PhoneNr", "12345", query, vm.AsSortingFilterModel);
     Assert.IsTrue(query.Count() == 4);
 }
Exemplo n.º 34
0
        public void getSales_shouldPass()
        {
            // Arrange
            FilterService service = new FilterService(aMockRepository.Object);
            aMockRepository.Setup(aService => aService.getSales(2,1,1,1,1)).Returns(saleList);

            // Act
            var result = service.getSales(2, 1, 1, 1, 1);

            // Assert
            Assert.IsTrue(result.Count == 2);
        }
Exemplo n.º 35
0
        private BaseFilter CreateBaseFilter(FilterDTO filterDTO, string locationID, string database)
        {
            var unit = LookUpUnit(filterDTO.Type);

            if (filterDTO.Type == "C" || filterDTO.Type == "V")
            {
                var dict = new FilterService().GetFilterOptions(locationID, database, filterDTO.CSelect, filterDTO.CTitle, filterDTO.CName);
                return new SelectFilter(filterDTO.Title, filterDTO.Name, unit, filterDTO.Type == "C", dict);
            }
            else if (filterDTO.Type  == "D" || filterDTO.Type == "X")
            {
                return new DateFilter(filterDTO.Title, filterDTO.Name, unit);
            }
            else
            {
                return new TextFilter(filterDTO.Title, filterDTO.Name, unit);
            }
        }
Exemplo n.º 36
0
        public FiltersModel CreateFiltersModel(string locationID, int headerID)
        {
            var filterDTOs = new FilterService().GetFilterDTOsByHeaderID(headerID);
            var headerDTO = new HeaderService().GetBaseHeaderDTO(headerID);

            var filterGroups = filterDTOs
                                    .GroupBy(f => f.GroupIndex)
                                    .OrderBy(g => g.Key)
                                    .Select(f => CreateFilterGroupModel(f, locationID, headerDTO.Database)).ToList()
                                    .ToList();

            return new FiltersModel()
            {
                Title = headerDTO.Title,
                Subtitle = headerDTO.Subtitle,
                LocationID = locationID,
                HeaderID = headerID,
                FilterGroups = filterGroups
            };
        }
Exemplo n.º 37
0
        public void GenericPagingSinglePageDatasCalculationTest()
        {
            //setup view model
            var filterSerivce = new FilterService(new ExpressionBuilder(), new SortingService(new ExpressionBuilder()));
            var vm = new SortingFilterModel();
            vm.PageSize = 20;

            //test senario 1, total as 900, index 1, should return 5 singlepagedata, with the page1 as selected
            vm.PageTotal = 900;
            vm.PageIndex = 1;
            filterSerivce.ReCaculateSinglePageDatas(vm);

            var singlePageDatas = vm.SinglePageDatas;

            Assert.IsTrue(singlePageDatas.FirstOrDefault() != null && singlePageDatas.FirstOrDefault().IsCurrentPageSelected == true, "the first page is not selected");

            Assert.IsTrue(singlePageDatas.Where(x => x.IsCurrentPageSelected == true).Count() == 1, "only one page is selected");
            Assert.IsTrue(singlePageDatas.Count() == 5, "total 5 pages as output");

            //test senario 2, set the pageindex to 6, then 4,5,6,7,8 should be presented
            vm.PageIndex = 6;
            filterSerivce.ReCaculateSinglePageDatas(vm);

            singlePageDatas = vm.SinglePageDatas;
            Assert.IsTrue(singlePageDatas.Count() == 5, "total 5 pages as output");
            Assert.IsTrue(singlePageDatas.IndexOf(singlePageDatas.FirstOrDefault(x => x.IsCurrentPageSelected)) == 2, "incorrect page is seleted");

            //test senario 3, move to last page, then 896, 897, 898, 899, 900 should be presented
            vm.PageIndex = 900;
            filterSerivce.ReCaculateSinglePageDatas(vm);

            singlePageDatas = vm.SinglePageDatas;
            Assert.IsTrue(singlePageDatas.Count() == 5, "total 5 pages as output");
            var index = singlePageDatas.IndexOf(singlePageDatas.FirstOrDefault(x => x.IsCurrentPageSelected));
            Assert.IsTrue(index == 4, "incorrect page is seleted");
        }
 public void GivenIAddAFilterForInternationalStudents()
 {
     var service = new FilterService<Student>();
     service.AddBinaryFilter(e => e.IsInternational);
     ScenarioContext.Current.Add("service", service);
 }
 public void GivenIAddAFilterWhereLastNameIsJackson()
 {
     var service = new FilterService<Student>();
     service.AddBinaryFilter(e => e.LastName == "Jackson");
     ScenarioContext.Current.Add("service", service);
 }
Exemplo n.º 40
0
        public void GenericPagingWhereMixTest()
        {
            //setup view model
            var vm = new SortingFilterModel();
            vm.SortingColumnCurrent = "BornDate";
            vm.SortingOrderCurrent = SortingOrder.Ascending;
            var filterService = new FilterService(new ExpressionBuilder(), new SortingService(new ExpressionBuilder()));
            var query = Persons.AsQueryable();
            //total 10, 4 pages, set index to 4
            vm.PageIndex = 4;
            query = query.Where(x => x.HasSupernaturalAbility == true);

            var resultSet = filterService.GenericPaging(query, vm.AsSortingFilterModel);
            //test1 the pageindex should have been resetted to 1
            Assert.IsTrue(vm.PageIndex == 1, "the where clause will make pagetotal 2, page index should be resetted to 1");
            //test2 navigate to page 2
            vm.PageIndex = 2;
            resultSet = filterService.GenericPaging(query, vm.AsSortingFilterModel);
            Assert.IsTrue(vm.PageIndex == 2);
        }
Exemplo n.º 41
0
        public void GenericPagingTest()
        {
            var query = Persons.AsQueryable();
            var vm = new SortingFilterModel { PageSize = 3 };
            var filterService = new FilterService(new ExpressionBuilder(), new SortingService(new ExpressionBuilder()));

            var resultSet = filterService.GenericPaging(query, vm.AsSortingFilterModel);

            //assert the page total
            Assert.IsTrue(vm.PageTotal == 4, "page totle calculation is incorrect");
            //assert the content within page 1, no need to default orderby since it only do take no skip
            Assert.IsTrue(resultSet.Select(x => x.Name).Contains("joe"), "the paging result contains incorrect elment");
            Assert.IsTrue(resultSet.Select(x => x.Name).Contains("kelly"), "the paging result contains incorrect elment");
            Assert.IsTrue(resultSet.Select(x => x.Name).Contains("nancy"), "the paging result contains incorrect elment");

            //set pageindex other than 1, run the function again, test if orderby + skip + take returns the correct resultset
            vm.PageIndex = 3;
            vm.SortingColumnCurrent = "BornDate";
            vm.SortingOrderCurrent = SortingOrder.Ascending;
            resultSet = filterService.GenericPaging(query, vm.AsSortingFilterModel);
            var compareList = Persons.OrderByDescending(x => x.BornDate).Skip(6).Take(3).ToList();
            Assert.IsTrue(resultSet.ToList()[0].PersonID == compareList[0].PersonID);
            Assert.IsTrue(resultSet.ToList()[1].PersonID == compareList[1].PersonID);
            Assert.IsTrue(resultSet.ToList()[2].PersonID == compareList[2].PersonID);
        }
Exemplo n.º 42
0
 public FilterController()
 {
     filterService = new FilterService();
 }
 public void GivenIAddAFilterWhereFirstNameIsJose()
 {
     var service = new FilterService<Student>();
     service.AddBinaryFilter(e => e.FirstName == "Jose");
     ScenarioContext.Current.Add("service", service);
 }