Пример #1
0
        public SocketSniffer(NetworkInterfaceInfo nic, Filters<IPPacket> filters, IOutput output)
        {
            this.outputQueue = new BlockingCollection<TimestampedData>();
            this.filters = filters;
            this.output = output;

            this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            this.receivePool = new ConcurrentStack<SocketAsyncEventArgs>();
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            // IPv4
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode
            try
            {
                this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
                throw;
            }
        }
Пример #2
0
        internal void FromFilters(Filters fs)
        {
            this.SetAllNull();

            if (fs.Blank != null && fs.Blank.Value) this.Blank = fs.Blank.Value;
            if (fs.CalendarType != null) this.CalendarType = fs.CalendarType.Value;

            if (fs.HasChildren)
            {
                SLFilter f;
                SLDateGroupItem dgi;
                using (OpenXmlReader oxr = OpenXmlReader.Create(fs))
                {
                    while (oxr.Read())
                    {
                        if (oxr.ElementType == typeof(Filter))
                        {
                            f = new SLFilter();
                            f.FromFilter((Filter)oxr.LoadCurrentElement());
                            this.Filters.Add(f);
                        }
                        else if (oxr.ElementType == typeof(DateGroupItem))
                        {
                            dgi = new SLDateGroupItem();
                            dgi.FromDateGroupItem((DateGroupItem)oxr.LoadCurrentElement());
                            this.DateGroupItems.Add(dgi);
                        }
                    }
                }
            }
        }
Пример #3
0
 public static FieldFilterExpression AddFieldExpression(Filters Filters, IFilter Filter, TableField Field, string FieldTableAlias)
 {
     FieldFilterExpression FieldFilterExpression = Filter.CreateFieldFilterExpression();
     FieldFilterExpression.Code = GenNewKeyValueFromCollection(Filters, "FieldFilterExpression");
     FieldFilterExpression.Field = Field;
     FieldFilterExpression.TableAlias = FieldTableAlias;
     return FieldFilterExpression;
 }
Пример #4
0
        public Status DeclineOffer(OfferID offerId, Filters filters)
        {
            var offerIdBytes = ProtoBufHelper.Serialize(offerId);
            var filtersBytes = ProtoBufHelper.Serialize(filters);

            using (var pinnedOfferId = MarshalHelper.CreatePinnedObject(offerIdBytes))
            using (var pinnedFilters = MarshalHelper.CreatePinnedObject(filtersBytes))
                return (Status)NativeImports.SchedulerDriver.DeclineOffer(_nativeDriverPtr, pinnedOfferId.Ptr, pinnedFilters.Ptr);
        }
 private DateTime? GetDateFromFilter(Filters filters, string fieldName, string prefix) {
     var dateString = filters.Get(prefix + ".Date");
     try {
         return _dateLocalizationServices.ConvertFromLocalizedDateString(dateString);
     }
     catch (FormatException ex) {
         filters.UpdateModel.AddModelError(prefix, T(@"Error parsing '{0}' date string '{1}': {2}", fieldName, dateString, ex.Message));
         return null;
     }
 }
Пример #6
0
        /// <summary>
        /// Filters data according to the given filters.
        /// </summary>
        /// <param name="nodesFilter"></param>
        /// <param name="waysFilter"></param>
        /// <param name="relationsFilter"></param>
        public TagsDataProcessorFilter(Filters.Filter nodesFilter, Filters.Filter waysFilter,
                                       Filters.Filter relationsFilter)
        {
            _nodesFilter = nodesFilter;
            _waysFilter = waysFilter;
            _relationsFilter = relationsFilter;

            _wayKeepNodes = false;
            _relationKeepObjects = false;
        }
Пример #7
0
        public Status AcceptOffers(IEnumerable<OfferID> offerIds, IEnumerable<Offer.Operation> operations, Filters filters)
        {
            var offerIdsArrays = offerIds.Select(ProtoBufHelper.Serialize);
            var operationsArrays = operations.Select(ProtoBufHelper.Serialize);
            var filtersBytes = ProtoBufHelper.Serialize(filters);

            using (var pinnedOfferIdsArrays = MarshalHelper.CreatePinnedObject(offerIdsArrays))
            using (var pinnedOperationsArrays = MarshalHelper.CreatePinnedObject(operationsArrays))
            using (var pinnedFiltersBytes = MarshalHelper.CreatePinnedObject(filtersBytes))
                return (Status)NativeImports.SchedulerDriver.AcceptOffers(_nativeDriverPtr, pinnedOfferIdsArrays.Ptr, pinnedOperationsArrays.Ptr, pinnedFiltersBytes.Ptr);
        }
Пример #8
0
        public System.Collections.Generic.IEnumerable<IGrouping<int, EF.AccountListing>> Get(Filters.AccountListingFilter filter)
        {
            using (EF.BubisDEntities db = new EF.BubisDEntities())
            {
                var collAccounts = from l in db.Accounts_Versions
                               where l.VERS_IsCurrent && l.VERS_Active && l.ACT_Date.Year == filter.Year
                               select new EF.AccountListing()
                               {
                                   ACT_Date = l.ACT_Date,
                                   ACT_Amount = filter.IsPesosMoney ? l.ACT_Amount : l.ACT_Amount_U__.Value,
                                   ACT_TYPE_Color = l.AccountsConcepts.AccountsConcepts_Versions.FirstOrDefault(v => v.VERS_IsCurrent && v.VERS_Active).Accounts_Types.ACT_TYPE_Color,
                                   ACT_GROUP_Id = l.AccountsConcepts.AccountsConcepts_Versions.FirstOrDefault(v => v.VERS_IsCurrent && v.VERS_Active).ACT_GROUP_Id,
                                   ACT_CPT_Description = l.AccountsConcepts.AccountsConcepts_Versions.FirstOrDefault(v => v.VERS_IsCurrent && v.VERS_Active).ACT_CPT_Description
                               };

                if (filter.Month.HasValue)
                    collAccounts = collAccounts.Where(l => l.ACT_Date.Month == filter.Month.Value);

                switch (filter.ACT_GROUP_Id)
                {
                    case "GCEE_GCEI":
                        collAccounts = collAccounts.Where(l => l.ACT_GROUP_Id == "GCEE" || l.ACT_GROUP_Id == "GCEI");
                        break;
                    case "IE":
                    case "IE  ":
                        collAccounts = collAccounts.Where(l => l.ACT_GROUP_Id == "IE" || l.ACT_GROUP_Id == "IE  ");
                        break;
                    case "EPC":
                    case "EPC ":
                        collAccounts = collAccounts.Where(l => l.ACT_GROUP_Id == "EPC" || l.ACT_GROUP_Id == "EPC ");
                        break;
                    case "ALL":
                    default:
                        break;
                }

                var a = collAccounts.ToList();
                foreach (var account in a)
                    switch (account.ACT_GROUP_Id)
                    {
                        case "EPC":
                        case "EPC ":
                        case "GCEE":
                            account.ACT_Amount = -account.ACT_Amount;
                            break;
                        default:
                            break;
                    }

                return a.GroupBy(l => l.ACT_Date.Month);
            }
        }
Пример #9
0
        /// <inheritdoc />
        public async Task OnAuthorizationAsync(Filters.AuthorizationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // If this filter is not closest to the action, it is not applicable.
            if (!IsClosestToAction(context.Filters))
            {
                return;
            }

            var httpContext = context.HttpContext;
            var request = httpContext.Request;
            if (request.Headers.ContainsKey(CorsConstants.Origin))
            {
                var policy = await _corsPolicyProvider.GetPolicyAsync(httpContext, PolicyName);
                var result = _corsService.EvaluatePolicy(context.HttpContext, policy);
                _corsService.ApplyResult(result, context.HttpContext.Response);

                var accessControlRequestMethod =
                        httpContext.Request.Headers[CorsConstants.AccessControlRequestMethod];
                if (string.Equals(
                        request.Method,
                        CorsConstants.PreflightHttpMethod,
                        StringComparison.Ordinal) &&
                    !StringValues.IsNullOrEmpty(accessControlRequestMethod))
                {
                    // If this was a preflight, there is no need to run anything else.
                    // Also the response is always 200 so that anyone after mvc can handle the pre flight request.
                    context.Result = new HttpStatusCodeResult(StatusCodes.Status200OK);
                }

                // Continue with other filters and action.
            }
        }
Пример #10
0
        public void LengthFilterTests(Filters.LengthFilterFactory sut, Interface.IResourceLoader resourceLoader)
        {
            List<string> result = null;

            "Given a Length Filter".Given(() => { });
            "when a sample text 'turn right at Albuquerque' is analyzed with min:3 and max:7".When(
                () =>
                {
                    ((Interface.IFlexFilterFactory)sut).Initialize(new Dictionary<string, string> { { "min", "3" }, { "max", "7" } }, resourceLoader);
                    var filters = new List<Interface.IFlexFilterFactory> { sut };
                    var analyzer = new CustomAnalyzer(new Tokenizers.StandardTokenizerFactory(), filters.ToArray());
                    result = SearchDsl.ParseTextUsingAnalyzer(analyzer, "test", "turn right at Albuquerque");
                });

            "it should produce 2 tokens".Observation(() => result.Count.Should().Be(2));
            "it should be 'turn','right'".Observation(
                () => result.Should().Equal(new List<string> { "turn", "right" }));
        }
Пример #11
0
        public void LowerCaseFilterTests(Filters.LowerCaseFilterFactory sut, Interface.IResourceLoader resourceLoader)
        {
            List<string> result = null;

            "Given a LowerCase filter".Given(() => { });
            "when a sample text 'Bob's I.O.U.' is analyzed".When(
                () =>
                {
                    ((Interface.IFlexFilterFactory)sut).Initialize(new Dictionary<string, string>(), resourceLoader);
                    var filters = new List<Interface.IFlexFilterFactory> { sut };
                    var analyzer = new CustomAnalyzer(new Tokenizers.StandardTokenizerFactory(), filters.ToArray());
                    result = SearchDsl.ParseTextUsingAnalyzer(analyzer, "test", "Bob's I.O.U.");
                });

            "it should produce 2 tokens".Observation(() => result.Count.Should().Be(2));
            "it should be 'bob's','i.o.u'".Observation(
                () => result.Should().Equal(new List<string> { "bob's", "i.o.u" }));
        }
Пример #12
0
        public void PatternReplaceTests(Filters.PatternReplaceFilterFactory sut, Interface.IResourceLoader resourceLoader)
        {
            List<string> result = null;

            "Given a PatternReplace Filter".Given(() => { });
            "when a sample text 'cat concatenate catycat' is analyzed with pattern:cat and replacementtext:dog".When(
                () =>
                {
                    ((Interface.IFlexFilterFactory)sut).Initialize(new Dictionary<string, string> { { "pattern", "cat" }, { "replacementtext", "dog" } }, resourceLoader);
                    var filters = new List<Interface.IFlexFilterFactory> { sut };
                    var analyzer = new CustomAnalyzer(new Tokenizers.StandardTokenizerFactory(), filters.ToArray());
                    result = SearchDsl.ParseTextUsingAnalyzer(analyzer, "test", "cat concatenate catycat");
                });

            "it should produce 3 tokens".Observation(() => result.Count.Should().Be(3));
            "it should be 'turn','right'".Observation(
                () => result.Should().Equal(new List<string> { "dog", "condogenate", "dogydog" }));
        }
Пример #13
0
        internal Filters ToFilters()
        {
            Filters fs = new Filters();
            if (this.Blank != null && this.Blank.Value) fs.Blank = this.Blank.Value;
            if (HasCalendarType) fs.CalendarType = this.CalendarType;

            foreach (SLFilter f in this.Filters)
            {
                fs.Append(f.ToFilter());
            }

            foreach (SLDateGroupItem dgi in this.DateGroupItems)
            {
                fs.Append(dgi.ToDateGroupItem());
            }

            return fs;
        }
Пример #14
0
        /// <inheritdoc />
        public virtual async Task OnAuthorizationAsync(Filters.AuthorizationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Build a ClaimsPrincipal with the Policy's required authentication types
            if (Policy.AuthenticationSchemes != null && Policy.AuthenticationSchemes.Any())
            {
                ClaimsPrincipal newPrincipal = null;
                foreach (var scheme in Policy.AuthenticationSchemes)
                {
                    var result = await context.HttpContext.Authentication.AuthenticateAsync(scheme);
                    if (result != null)
                    {
                        newPrincipal = SecurityHelper.MergeUserPrincipal(newPrincipal, result);
                    }
                }
                // If all schemes failed authentication, provide a default identity anyways
                if (newPrincipal == null)
                {
                    newPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
                }
                context.HttpContext.User = newPrincipal;
            }

            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            var httpContext = context.HttpContext;
            var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();

            // Note: Default Anonymous User is new ClaimsPrincipal(new ClaimsIdentity())
            if (httpContext.User == null ||
                !httpContext.User.Identities.Any(i => i.IsAuthenticated) ||
                !await authService.AuthorizeAsync(httpContext.User, context, Policy))
            {
                context.Result = new ChallengeResult(Policy.AuthenticationSchemes.ToArray());
            }
        }
Пример #15
0
 public Receive(RichTextBox richTextBox1_receive, RichTextBox richTextBox2_receive, PacketDevice device1_receive, int d1_index_receive, PacketDevice device2_receive, int d2_index_receive, DataGridView dataGridView1_receive, DataGridView dataGridView2_receive, Filters filters_class_receive)
 {
     richTextBox1 = richTextBox1_receive;
     richTextBox2 = richTextBox2_receive;
     device1 = device1_receive;
     device2 = device2_receive;
     d1_index = d1_index_receive;
     d2_index = d2_index_receive;
     communicator1 = device1.Open(65536, PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.Promiscuous, 1000);
     communicator2 = device2.Open(65536, PacketDeviceOpenAttributes.NoCaptureLocal | PacketDeviceOpenAttributes.Promiscuous, 1000);
     mac_table = new MAC_table();
     dataGridView1 = dataGridView1_receive;
     dataGridView2 = dataGridView2_receive;
     filters_class = filters_class_receive;
     get_Info.prefill_statistics(statistics_d1_I);
     get_Info.prefill_statistics(statistics_d1_O);
     get_Info.prefill_statistics(statistics_d2_I);
     get_Info.prefill_statistics(statistics_d2_O);
 }
Пример #16
0
        public void KeepWordFilterShouldOnlyKeepKeepwords(
            Filters.KeepWordsFilterFactory sut,
            Interface.IResourceLoader resourceLoader)
        {
            List<string> result = null;

            "Given a keepword filter".Given(() => { });
            "when a wordlist of keepwords is passed and a sample text 'hello world test' is analyzed".When(
                () =>
                {
                    ((Interface.IFlexFilterFactory)sut).Initialize(
                        new Dictionary<string, string> { { "filename", "wordlist.txt" } },
                        resourceLoader);
                    var filters = new List<Interface.IFlexFilterFactory> { sut };
                    var analyzer = new CustomAnalyzer(new Tokenizers.StandardTokenizerFactory(), filters.ToArray());
                    result = SearchDsl.ParseTextUsingAnalyzer(analyzer, "test", "hello world test");
                });

            "it should produce 2 tokens".Observation(() => result.Count.Should().Be(2));
            "it should remove all non keep words from the input".Then(
                () => result.Should().Equal(new List<string> { "hello", "world" }));
        }
Пример #17
0
 public S3StorageProviderSettingsPartHandler(IRepository <JGS3StorageProviderSettingsRecord> repository)
 {
     T = NullLocalizer.Instance;
     Filters.Add(new ActivatingFilter <S3StorageProviderSettingsPart>("Site"));
     Filters.Add(StorageFilter.For(repository));
 }
 public LambdaPartHandler(IRepository <LambdaRecord> repository)
 {
     Filters.Add(new ActivatingFilter <LambdaPart>("lambda"));
     Filters.Add(StorageFilter.For(repository));
 }
Пример #19
0
 public ShippingProductHandler(IRepository <ShippingProductRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
 }
Пример #20
0
 public static IServer StartWith(Stage stage, Resources resources, int port, Configuration.SizingConf sizing, Configuration.TimingConf timing)
 => StartWith(stage, resources, Filters.None(), port, sizing, timing);
Пример #21
0
        private static void Main(string[] args)
        {
            SetUpConsole();

            var files = args.ToList();

            if (files.Count == 0)
            {
                PrintUsage();
                return;
            }

            // config options are handled in Misc.Settings
            Utilities.RemoveConfigOptions(ref files);

            if (!Utilities.GetFiles(ref files))
            {
                EndPrompt();
                return;
            }

            Thread.CurrentThread.CurrentCulture     = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

            // Disable DB when we don't need its data (dumping to a binary file)
            if (!Settings.DumpFormatWithSQL())
            {
                SQLConnector.Enabled = false;
                SSHTunnel.Enabled    = false;
            }
            else
            {
                Filters.Initialize();
            }

            SQLConnector.ReadDB();

            var count = 0;

            foreach (var file in files)
            {
                SessionHandler.ZStreams.Clear();
                ClientVersion.SetVersion(Settings.ClientBuild);
                try
                {
                    var sf = new SniffFile(file, Settings.DumpFormat, Tuple.Create(++count, files.Count));
                    sf.ProcessFile();
                }
                catch (IOException ex)
                {
                    Console.WriteLine($"Can't process {file}. Skipping. Message: {ex.Message}");
                }
            }

            if (!string.IsNullOrWhiteSpace(Settings.SQLFileName) && Settings.DumpFormatWithSQL())
            {
                Builder.DumpSQL("Dumping global sql", Settings.SQLFileName, SniffFile.GetHeader("multi"));
            }

            SQLConnector.Disconnect();
            SSHTunnel.Disconnect();

            if (Settings.LogErrors)
            {
                Logger.WriteErrors();
            }

            Trace.Listeners.Remove("ConsoleMirror");

            EndPrompt();
        }
Пример #22
0
        public override bool Execute()
        {
            var msg = new BuildMessageEventArgs("Templator Syntax checking", "", "TemplatorSyntaxChecker", MessageImportance.Normal);

            BuildEngine.LogMessageEvent(msg);
            if (ConfigFilePath.IsNullOrWhiteSpace())
            {
                var proj       = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(ProjectPath).FirstOrDefault() ?? new Project(ProjectPath);
                var configFile = proj.GetItemsByEvaluatedInclude(TemplatorConfig.DefaultConfigFileName).FirstOrDefault();

                if (configFile != null)
                {
                    ConfigFilePath = configFile.EvaluatedInclude;
                }
            }

            TemplatorConfig config;

            if (ConfigFilePath.IsNullOrWhiteSpace())
            {
                config = TemplatorConfig.DefaultInstance;
                const string url = "https://github.com/djsxp/Templator/blob/master/project/Templator/TemplatorConfig.xml";
                msg = new BuildMessageEventArgs("Unable to find '{0}', using defaults, for a config file, please find; '{1}'".FormatInvariantCulture(TemplatorConfig.DefaultConfigFileName, url), "", "TemplatorSyntaxChecker", MessageImportance.Normal);
                BuildEngine.LogMessageEvent(msg);
            }
            else
            {
                try
                {
                    config = TemplatorConfig.FromXml(ConfigFilePath);
                    var path = config.CustomOptions.EmptyIfNull().PropertyOfFirstOrDefault(c => c.Category == ConfigCategory && c.Key == "Path", pr => pr.Value);
                    Path = path ?? Path;
                    var filter = config.CustomOptions.EmptyIfNull().PropertyOfFirstOrDefault(c => c.Category == ConfigCategory && c.Key == "Filters", pr => pr.Value);
                    Filters = filter ?? Filters;
                    var depth = config.CustomOptions.EmptyIfNull().PropertyOfFirstOrDefault(c => c.Category == ConfigCategory && c.Key == "Depth", pr => pr.Value);
                    int d;
                    Depth = int.TryParse(depth, out d) ? d : Depth;
                }
                catch (Exception e)
                {
                    var message = new BuildErrorEventArgs("TemplatorSyntaxConfig", "TemplatorConfigLoadError", ConfigFilePath, 0, 0, 0, 0, e.Message, "TemplatorBuildTask", "TemplatorBuildTask");
                    BuildEngine.LogErrorEvent(message);
                    return(false);
                }
            }
            if (Path.IsHtmlNullOrWhiteSpace() || !Directory.Exists(Path))
            {
                var message = new BuildErrorEventArgs("TemplatorSyntaxConfig", "Unable to find the template path: '{0}'".FormatInvariantCulture(Path), "project", 0, 0, 0, 0, "", "TemplatorBuildTask", "TemplatorBuildTask");
                BuildEngine.LogErrorEvent(message);
                return(false);
            }
            string[] filters = null;
            if (!Filters.IsNullOrWhiteSpace())
            {
                filters = Filters.Split(',');
            }
            var logger = new TemplatorLogger();

            config.Logger = logger;
            var p = new TemplatorParser(config);

            p.GrammarCheckDirectory(Path, filters, Depth);
            if (p.ErrorCount > 0)
            {
                foreach (var m in logger.Errors)
                {
                    var message = new BuildErrorEventArgs("TemplatorSyntaxChecker", "TemplatorSyntaxError", m.FileName, m.Line + 1, m.Column + 1, m.EndLineNumber + 1, m.EndColumnNumber + 1, m.Message, "TemplatorBuildTask", "TemplatorBuildTask");
                    BuildEngine.LogErrorEvent(message);
                }
            }
            return(p.ErrorCount == 0);
        }
Пример #23
0
 public IEnumerable <WeatherInfo> Filter([FromBody] Filters filters)
 {
     return(weatherObj.GetFilteredWeatherInfo(filters));
 }
Пример #24
0
        /// <summary>
        /// The create filter.
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        /// <returns>
        /// The <see cref="Filters"/>.
        /// </returns>
        private static Filters CreateFilters(EncodeTask job)
        {
            Filters filter = new Filters
            {
                FilterList = new List <Filter>(),
            };

            // Note, order is important.

            // Detelecine
            if (job.Detelecine != Detelecine.Off)
            {
                IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_DETELECINE, null, null, job.CustomDetelecine);
                string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);
                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken settings = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)hb_filter_ids.HB_FILTER_DETELECINE, Settings = settings
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            // Deinterlace
            if (job.DeinterlaceFilter == DeinterlaceFilter.Yadif)
            {
                IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_DEINTERLACE, EnumHelper <Deinterlace> .GetShortName(job.Deinterlace), null, job.CustomDeinterlace);
                string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);
                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken root = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)hb_filter_ids.HB_FILTER_DEINTERLACE, Settings = root
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            // Decomb
            if (job.DeinterlaceFilter == DeinterlaceFilter.Decomb)
            {
                IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_DECOMB, EnumHelper <Decomb> .GetShortName(job.Decomb), null, job.CustomDecomb);
                string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);
                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken settings = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)hb_filter_ids.HB_FILTER_DECOMB, Settings = settings
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            if (job.DeinterlaceFilter == DeinterlaceFilter.Decomb || job.DeinterlaceFilter == DeinterlaceFilter.Yadif)
            {
                if (job.CombDetect != CombDetect.Off)
                {
                    IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_COMB_DETECT, EnumHelper <CombDetect> .GetShortName(job.CombDetect), null, job.CustomCombDetect);
                    string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);
                    if (!string.IsNullOrEmpty(unparsedJson))
                    {
                        JToken settings = JObject.Parse(unparsedJson);

                        Filter filterItem = new Filter
                        {
                            ID       = (int)hb_filter_ids.HB_FILTER_COMB_DETECT,
                            Settings = settings
                        };
                        filter.FilterList.Add(filterItem);
                    }
                }
            }

            // Denoise
            if (job.Denoise != Denoise.Off)
            {
                hb_filter_ids id = job.Denoise == Denoise.hqdn3d
                    ? hb_filter_ids.HB_FILTER_HQDN3D
                    : hb_filter_ids.HB_FILTER_NLMEANS;

                IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)id, job.DenoisePreset.ToString().ToLower().Replace(" ", string.Empty), job.DenoiseTune.ToString().ToLower().Replace(" ", string.Empty), job.CustomDenoise);
                string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);

                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken settings = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)id, Settings = settings
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            // Deblock
            if (job.Deblock >= 5)
            {
                IntPtr settingsPtr  = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_DEBLOCK, null, null, string.Format("qp={0}", job.Deblock));
                string unparsedJson = Marshal.PtrToStringAnsi(settingsPtr);
                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken settings = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)hb_filter_ids.HB_FILTER_DEBLOCK, Settings = settings
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            // CropScale Filter
            string cropSettings             = string.Format("width={0}:height={1}:crop-top={2}:crop-bottom={3}:crop-left={4}:crop-right={5}", job.Width, job.Height, job.Cropping.Top, job.Cropping.Bottom, job.Cropping.Left, job.Cropping.Right);
            IntPtr cropSettingsPtr          = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_CROP_SCALE, null, null, cropSettings);
            string unparsedCropSettingsJson = Marshal.PtrToStringAnsi(cropSettingsPtr);

            if (!string.IsNullOrEmpty(unparsedCropSettingsJson))
            {
                JToken cropSettingsJson = JObject.Parse(unparsedCropSettingsJson);

                Filter cropScale = new Filter
                {
                    ID       = (int)hb_filter_ids.HB_FILTER_CROP_SCALE,
                    Settings = cropSettingsJson
                };
                filter.FilterList.Add(cropScale);
            }

            // Grayscale
            if (job.Grayscale)
            {
                Filter filterItem = new Filter {
                    ID = (int)hb_filter_ids.HB_FILTER_GRAYSCALE, Settings = null
                };
                filter.FilterList.Add(filterItem);
            }

            // Rotate
            if (job.Rotation != 0 || job.FlipVideo)
            {
                string rotateSettings = string.Format("angle={0}:hflip={1}", job.Rotation, job.FlipVideo ? "1" : "0");
                IntPtr settingsPtr    = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_ROTATE, null, null, rotateSettings);
                string unparsedJson   = Marshal.PtrToStringAnsi(settingsPtr);
                if (!string.IsNullOrEmpty(unparsedJson))
                {
                    JToken settings = JObject.Parse(unparsedJson);

                    Filter filterItem = new Filter {
                        ID = (int)hb_filter_ids.HB_FILTER_ROTATE, Settings = settings
                    };
                    filter.FilterList.Add(filterItem);
                }
            }

            // Framerate shaping filter
            int fm = job.FramerateMode == FramerateMode.CFR ? 1 : job.FramerateMode == FramerateMode.PFR ? 2 : 0;
            int?num = null, den = null;

            if (job.Framerate != null)
            {
                IntPtr frameratePrt = Marshal.StringToHGlobalAnsi(job.Framerate.Value.ToString(CultureInfo.InvariantCulture));
                int    vrate        = HBFunctions.hb_video_framerate_get_from_name(frameratePrt);

                if (vrate > 0)
                {
                    num = 27000000;
                    den = vrate;
                }
            }

            string framerateString = num.HasValue ? string.Format("mode={0}:rate={1}/{2}", fm, num, den) : string.Format("mode={0}", fm); // filter_cfr, filter_vrate.num, filter_vrate.den
            IntPtr framerateSettingsPtr = HBFunctions.hb_generate_filter_settings_json((int)hb_filter_ids.HB_FILTER_VFR, null, null, framerateString);
            string unparsedFramerateJson = Marshal.PtrToStringAnsi(framerateSettingsPtr);

            if (!string.IsNullOrEmpty(unparsedFramerateJson))
            {
                JToken framerateSettings = JObject.Parse(unparsedFramerateJson);

                Filter framerateShaper = new Filter
                {
                    ID       = (int)hb_filter_ids.HB_FILTER_VFR,
                    Settings = framerateSettings
                };
                filter.FilterList.Add(framerateShaper);
            }

            return(filter);
        }
Пример #25
0
        public static void ImportPriFile(EnvDTE.Project project, string fileName)
        {
            VCProject vcproj;

            if (!HelperFunctions.IsQtProject(project))
            {
                return;
            }

            vcproj = project.Object as VCProject;
            if (vcproj == null)
            {
                return;
            }

            QtVersionManager vm    = QtVersionManager.The();
            string           qtDir = vm.GetInstallPath(vm.GetDefaultVersion());

            if (qtDir == null)
            {
                Messages.DisplayErrorMessage(SR.GetString("CannotFindQMake"));
                return;
            }

            FileInfo priFileInfo = new FileInfo(fileName);

            QMakeWrapper qmake = new QMakeWrapper();

            qmake.setQtDir(qtDir);
            if (qmake.readFile(priFileInfo.FullName))
            {
                bool          flat      = qmake.isFlat();
                List <string> priFiles  = ResolveFilesFromQMake(qmake.sourceFiles(), project, priFileInfo.DirectoryName);
                List <string> projFiles = HelperFunctions.GetProjectFiles(project, FilesToList.FL_CppFiles);
                projFiles = ProjectExporter.ConvertFilesToFullPath(projFiles, vcproj.ProjectDirectory);
                ProjectExporter.SyncIncludeFiles(vcproj, priFiles, projFiles, project.DTE, flat, Filters.SourceFiles());

                priFiles  = ResolveFilesFromQMake(qmake.headerFiles(), project, priFileInfo.DirectoryName);
                projFiles = HelperFunctions.GetProjectFiles(project, FilesToList.FL_HFiles);
                projFiles = ProjectExporter.ConvertFilesToFullPath(projFiles, vcproj.ProjectDirectory);
                ProjectExporter.SyncIncludeFiles(vcproj, priFiles, projFiles, project.DTE, flat, Filters.HeaderFiles());

                priFiles  = ResolveFilesFromQMake(qmake.formFiles(), project, priFileInfo.DirectoryName);
                projFiles = HelperFunctions.GetProjectFiles(project, FilesToList.FL_UiFiles);
                projFiles = ProjectExporter.ConvertFilesToFullPath(projFiles, vcproj.ProjectDirectory);
                ProjectExporter.SyncIncludeFiles(vcproj, priFiles, projFiles, project.DTE, flat, Filters.FormFiles());

                priFiles  = ResolveFilesFromQMake(qmake.resourceFiles(), project, priFileInfo.DirectoryName);
                projFiles = HelperFunctions.GetProjectFiles(project, FilesToList.FL_Resources);
                projFiles = ProjectExporter.ConvertFilesToFullPath(projFiles, vcproj.ProjectDirectory);
                ProjectExporter.SyncIncludeFiles(vcproj, priFiles, projFiles, project.DTE, flat, Filters.ResourceFiles());
            }
            else
            {
                Messages.PaneMessage(project.DTE, "--- (Importing .pri file) file: "
                                     + priFileInfo + " could not be read.");
            }
        }
Пример #26
0
 public TwitterWidgetRecordHandler(IRepository <TwitterWidgetRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
 }
Пример #27
0
 public FeedSyncProfileItemPartHandler(IRepository <FeedSyncProfileItemPartRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
 }
Пример #28
0
        public MenuWidgetPartHandler(IRepository <MenuWidgetPartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));

            OnInitializing <MenuWidgetPart>((context, part) => { part.StartLevel = 1; });
        }
Пример #29
0
 public void Enqueue(IFilter <T> filter, int bufferSize)
 {
     Filters.Enqueue(new Pipe <T>(filter, new BlockingCollection <T>(bufferSize)));
 }
Пример #30
0
        private static void Main(string[] args)
        {
            SetUpConsole();

            var files = args.ToList();

            if (files.Count == 0)
            {
                PrintUsage();
                return;
            }

            // config options are handled in Misc.Settings
            Utilities.RemoveConfigOptions(ref files);

            if (!Utilities.GetFiles(ref files))
            {
                EndPrompt();
                return;
            }

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            if (Settings.FilterPacketNumLow < 0)
            {
                throw new ConstraintException("FilterPacketNumLow must be positive");
            }

            if (Settings.FilterPacketNumHigh < 0)
            {
                throw new ConstraintException("FilterPacketNumHigh must be positive");
            }

            if (Settings.FilterPacketNumLow > 0 && Settings.FilterPacketNumHigh > 0 &&
                Settings.FilterPacketNumLow > Settings.FilterPacketNumHigh)
            {
                throw new ConstraintException("FilterPacketNumLow must be less or equal than FilterPacketNumHigh");
            }

            // Disable DB when we don't need its data (dumping to a binary file)
            if (Settings.DumpFormat == DumpFormatType.None || Settings.DumpFormat == DumpFormatType.Pkt ||
                Settings.DumpFormat == DumpFormatType.PktSplit || Settings.DumpFormat == DumpFormatType.SniffDataOnly)
            {
                SQLConnector.Enabled = false;
                SSHTunnel.Enabled    = false;
            }
            else
            {
                Filters.Initialize();
            }

            SQLConnector.ReadDB();

            var count = 0;

            foreach (var file in files)
            {
                SessionHandler.z_streams.Clear();
                ClientVersion.SetVersion(Settings.ClientBuild);
                new SniffFile(file, Settings.DumpFormat, Tuple.Create(++count, files.Count)).ProcessFile();
            }

            if (!String.IsNullOrWhiteSpace(Settings.SQLFileName))
            {
                Builder.DumpSQL("Dumping global sql", Settings.SQLFileName, "# multiple files\n");
            }

            SQLConnector.Disconnect();
            SSHTunnel.Disconnect();
            Logger.WriteErrors();

            EndPrompt();
        }
 public AdminThemeSiteSettingsPartHandler()
 {
     T = NullLocalizer.Instance;
     Filters.Add(new ActivatingFilter <AdminThemeSettingsPart>("Site"));
     Filters.Add(new TemplateFilterForPart <AdminThemeSettingsPart>("AdminThemeSettings", "Parts/AdminTheme.ThemeSettings", "Admin Theme"));
 }
Пример #32
0
        public Filters<IPPacket> BuildFilters()
        {
            var filters = new Filters<IPPacket>(this.FilterOperator);

            if (this.FilterProtocol.HasValue)
            {
                filters.PropertyFilters.Add(new PropertyFilter<IPPacket>(x => x.Protocol, this.FilterProtocol.Value));
            }

            if (this.FilterSourceAddress != null)
            {
                filters.PropertyFilters.Add(new PropertyFilter<IPPacket>(x => x.SourceAddress, this.FilterSourceAddress));
            }

            if (this.FilterDestAddress != null)
            {
                filters.PropertyFilters.Add(new PropertyFilter<IPPacket>(x => x.DestAddress, this.FilterDestAddress));
            }

            if (this.FilterSourcePort.HasValue)
            {
                filters.PropertyFilters.Add(new PropertyFilter<IPPacket>(x => x.SourcePort, this.FilterSourcePort.Value));
            }

            if (this.FilterDestPort.HasValue)
            {
                filters.PropertyFilters.Add(new PropertyFilter<IPPacket>(x => x.DestPort, this.FilterDestPort.Value));
            }

            return filters;
        }
Пример #33
0
 public ProductPartHandler(IRepository <ProductPartRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
 }
Пример #34
0
 public DiscountPartHandler(IRepository <DiscountPartRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
 }
 public CategoryPartHandler(IRepository <CategoryPartRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
     //Filters.Add(new ActivatingFilter<CategoryPart>("Site"));
 }
Пример #36
0
		public void SetFilter(Filters whichFilter)
		{
			SetPropertyLocking(ref _whichFilter, whichFilter, _filterLocker);
		}
Пример #37
0
 public static IServer StartWith(Stage stage, Resources resources, Filters filters, int port, Configuration.SizingConf sizing, Configuration.TimingConf timing)
 => StartWith(stage, resources, filters, port, sizing, timing, "queueMailbox", "queueMailbox");
Пример #38
0
    attachRemoteLogger(Ice.RemoteLoggerPrx prx, Ice.LogMessageType[] messageTypes, string[] categories, 
                       int messageMax, Ice.Current current)
    {
        if(prx == null)
        {
            return; // can't send this null RemoteLogger anything!
        }
        
        Ice.RemoteLoggerPrx remoteLogger = Ice.RemoteLoggerPrxHelper.uncheckedCast(prx.ice_twoway());
       
        Filters filters = new Filters(messageTypes, categories);
        LinkedList<Ice.LogMessage> initLogMessages = null;
       
        lock(this)
        {
            if(_sendLogCommunicator == null)
            {
                if(_destroyed)
                {
                    throw new Ice.ObjectNotExistException();
                }

                _sendLogCommunicator = 
                    createSendLogCommunicator(current.adapter.getCommunicator(), _logger.getLocalLogger());
            }
            
            Ice.Identity remoteLoggerId = remoteLogger.ice_getIdentity();
            
            if(_remoteLoggerMap.ContainsKey(remoteLoggerId))
            {
                if(_traceLevel > 0)
                {
                    _logger.trace(_traceCategory, "rejecting `" + remoteLogger.ToString() +
                                 "' with RemoteLoggerAlreadyAttachedException");
                }
                
                throw new Ice.RemoteLoggerAlreadyAttachedException();
            }

            _remoteLoggerMap.Add(remoteLoggerId, 
                                 new RemoteLoggerData(changeCommunicator(remoteLogger, _sendLogCommunicator), filters));
            
            if(messageMax != 0)
            {
                initLogMessages = new LinkedList<Ice.LogMessage>(_queue); // copy
            }
            else
            {
                initLogMessages = new LinkedList<Ice.LogMessage>();
            }
        }
        
        if(_traceLevel > 0)
        {
            _logger.trace(_traceCategory, "attached `" + remoteLogger.ToString() + "'");
        }

        if(initLogMessages.Count > 0)
        {
            filterLogMessages(initLogMessages, filters.messageTypes, filters.traceCategories, messageMax);
        }
        
        try
        {
            remoteLogger.begin_init(_logger.getPrefix(), initLogMessages.ToArray(), initCompleted, null);
        }
        catch(Ice.LocalException ex)
        {
            deadRemoteLogger(remoteLogger, _logger, ex, "init");
            throw ex;
        }    
    }
Пример #39
0
 public static IServer StartWithAgent(
     Stage stage,
     Resources resources,
     int port,
     int dispatcherPoolSize) =>
 StartWithAgent(stage, resources, Filters.None(), port, dispatcherPoolSize);
Пример #40
0
		void AppendRetroShaderChain(FilterProgram program, string name, Filters.RetroShaderChain retroChain, Dictionary<string, object> properties)
		{
			for (int i = 0; i < retroChain.Passes.Length; i++)
			{
				var pass = retroChain.Passes[i];
				var rsp = new Filters.RetroShaderPass(retroChain, i);
				string fname = string.Format("{0}[{1}]", name, i);
				program.AddFilter(rsp, fname);
				rsp.Parameters = properties;
			}
		}
Пример #41
0
 /// <summary>Apply a filter to the current Image.</summary>
 /// <param name="filter">Any filter that supports the <see cref="Filters.IFilter">IFilter</see> interface</param>
 /// <seealso cref="Kaliko.ImageLibrary.Filters"></seealso>
 public void ApplyFilter(Filters.IFilter filter) {
     filter.Run(this);
 }
		public void ProcessImage (int image_num, Filters.FilterSet filter_set)
		{
			IBrowsableItem photo = collection [image_num];
			string photo_path = photo.DefaultVersionUri.LocalPath;
			string path;
			ScaleRequest req;

			req = requests [0];
			
			MakeDir (SubdirPath (req.Name));
			path = SubdirPath (req.Name, ImageName (image_num));
			
			using (Filters.FilterRequest request = new Filters.FilterRequest (photo.DefaultVersionUri)) {
				filter_set.Convert (request);
				if (request.Current.LocalPath == path)
					request.Preserve(request.Current);
				else
					File.Copy (request.Current.LocalPath, path, true); 

				if (photo != null && photo is Photo && Core.Database != null) {
					Core.Database.Exports.Create ((photo as Photo).Id, (photo as Photo).DefaultVersionId,
								      ExportStore.FolderExportType,
								      // FIXME this is wrong, the final path is the one
								      // after the Xfer.
								      UriList.PathToFileUriEscaped (path).ToString ());
				}

				using (Exif.ExifData data = new Exif.ExifData (photo_path)) {
					for (int i = 1; i < requests.Length; i++) {
						
						req = requests [i];
						if (scale && req.AvoidScale (size))
							continue;
				
						Filters.FilterSet req_set = new Filters.FilterSet ();
						req_set.Add (new Filters.ResizeFilter ((uint)Math.Max (req.Width, req.Height)));
						if ((bool)Preferences.Get (Preferences.EXPORT_FOLDER_SHARPEN)) {
							if (req.Name == "lq")
								req_set.Add (new Filters.SharpFilter (0.1, 2, 4));
							if (req.Name == "thumbs")
								req_set.Add (new Filters.SharpFilter (0.1, 2, 5));
						}
						using (Filters.FilterRequest tmp_req = new Filters.FilterRequest (photo.DefaultVersionUri)) {
							req_set.Convert (tmp_req);
							MakeDir (SubdirPath (req.Name));
							path = SubdirPath (req.Name, ImageName (image_num));
							System.IO.File.Copy (tmp_req.Current.LocalPath, path, true);
						}
						
					}
				}
			}
		}
        public void ResetFields()
        {
            Filters = new Filters(255);
            filters.ValueChanged += OnFilterChanged;
            Noise.Reset();
            Inpainting = new Inpainting();

            HistogramLeft = 0;
            HistogramRight = 255;

            // show initial image
        }
Пример #44
0
        /// <summary>
        /// Runs the filters.
        /// </summary>
        /// <returns><c>true</c>, if filters was run, <c>false</c> otherwise.</returns>
        public bool RunFilters()
        {
            bool success = true;

            if (!Filters.Any())
            {
                LogManager.Info("No filter operations configured.", this);
                return(success);
            }

            if (Filters?.Count > 0 && InputData?.Keys?.Count >= 1)
            {
                var filteredData = new Dictionary <string, IEnumerable <SensorReading> >();
                foreach (var filterCommand in Filters)
                {
                    var filter = FilterManager.GetFilter(filterCommand.Name);
                    if (filter == null)
                    {
                        success = false;
                        continue;
                    }

                    // Sanity checking ...
                    LogManager.Info($"Running filter operation:\n\t{filter}", this);

                    // Processing the data for the phase...
                    if (filterCommand.Parameters != null)
                    {
                        // retrieving the input for the phase
                        var phaseData = new List <PhaseData <SensorReading> >();
                        foreach (var key in InputData.Keys)
                        {
                            phaseData.Add(new PhaseData <SensorReading>
                            {
                                Name = key,
                                Data = InputData[key].ToList()
                            });
                        }

                        // INPUT = COMMANDS, SET OF FILE NAMES AND DATA VALUES
                        // OUTPUT = SET OF FILE NAMES AND NEW DATA VALUES

                        var filteredResultSets = filter.Filter(new PhaseInput <SensorReading>
                        {
                            Input      = phaseData,
                            Parameters = filterCommand.Parameters
                        });

                        // list of calibrated thresholds for various fields
                        // ONLY APPLICABLE TO THIS INDIVIDUAL INPUT DATA SET!!

                        /*if (filter is ThresholdCalibrationFilter calibFilter)
                         * {
                         * var thresholdValues = calibFilter.CalibratedThresholds;
                         * CalibrationData.Add(phaseInput.Name, thresholdValues);
                         * }*/

                        if (filteredResultSets != null && filteredResultSets.Any())
                        {
                            foreach (var filterResult in filteredResultSets)
                            {
                                filteredData[filterResult.Name] = filterResult.Data;
                                if (WriteOutputFile)
                                {
                                    CsvFileWriter.WriteResultsToFile
                                        (new string[] { OutputDirs.Filters, filterCommand.Name },
                                        filterResult.Name, filter.HeaderCsv, filterResult.Data);
                                }
                            }
                        }
                        else
                        {
                            success = false;
                        }
                    }
                    else
                    {
                        success = false;
                    }
                }

                InputData = filteredData;
            }
            else
            {
                LogManager.Error("No input data to run filters on.", this);
            }

            return(success);
        }
Пример #45
0
 /// <summary>
 /// Set the Where condition.
 /// </summary>
 /// <param name="filter"></param>
 /// <returns></returns>
 public Specification <TType> Where(Expression <Func <TType, bool> > filter)
 {
     Filters.Add(filter);
     return(this);
 }
Пример #46
0
        protected override void OnInitialized()
        {
            base.OnInitialized();

            Sortable = Sortable || SorterMultiple != default || SorterCompare != default || DefaultSortOrder != default || SortDirections?.Any() == true;

            if (IsHeader)
            {
                if (FieldExpression != null)
                {
                    var paramExp = Expression.Parameter(ItemType);
                    var member   = ColumnExpressionHelper.GetReturnMemberInfo(FieldExpression);
                    var bodyExp  = Expression.MakeMemberAccess(paramExp, member);
                    GetFieldExpression = Expression.Lambda(bodyExp, paramExp);
                }
                else if (DataIndex != null)
                {
                    (_, GetFieldExpression) = ColumnDataIndexHelper <TData> .GetDataIndexConfig(this);
                }

                if (GetFieldExpression != null)
                {
                    var member = ColumnExpressionHelper.GetReturnMemberInfo(GetFieldExpression);
                    DisplayName = member.GetCustomAttribute <DisplayNameAttribute>(true)?.DisplayName ?? member.GetCustomAttribute <DisplayAttribute>(true)?.GetName() ?? member.Name;
                    FieldName   = DataIndex ?? member.Name;
                }

                if (Sortable && GetFieldExpression != null)
                {
                    SortModel = new SortModel <TData>(GetFieldExpression, FieldName, SorterMultiple, DefaultSortOrder, SorterCompare);
                }
            }
            else if (IsBody)
            {
                SortModel = Context.HeaderColumns[ColIndex] is IFieldColumn fieldColumn ? fieldColumn.SortModel : null;

                (GetValue, _) = ColumnDataIndexHelper <TData> .GetDataIndexConfig(this);
            }

            SortDirections ??= Table.SortDirections;

            Sortable       = Sortable || SortModel != null;
            _sortDirection = SortModel?.SortDirection ?? DefaultSortOrder ?? SortDirection.None;

            if (Filters?.Any() == true)
            {
                Filterable        = true;
                _columnFilterType = TableFilterType.List;
            }
            else if (Filterable)
            {
                _columnDataType = THelper.GetUnderlyingType <TData>();
                if (_columnDataType == typeof(bool))
                {
                    _columnFilterType = TableFilterType.List;

                    Filters = new List <TableFilter <TData> >();

                    var trueFilterOption = GetNewFilter();
                    trueFilterOption.Text  = Table.Locale.FilterOptions.True;
                    trueFilterOption.Value = THelper.ChangeType <TData>(true);
                    ((List <TableFilter <TData> >)Filters).Add(trueFilterOption);
                    var falseFilterOption = GetNewFilter();
                    falseFilterOption.Text  = Table.Locale.FilterOptions.False;
                    falseFilterOption.Value = THelper.ChangeType <TData>(false);
                    ((List <TableFilter <TData> >)Filters).Add(falseFilterOption);
                }
                else
                {
                    _columnFilterType = TableFilterType.FeildType;
                    InitFilters();
                }
            }

            ClassMapper
            .If("ant-table-column-has-sorters", () => Sortable)
            .If($"ant-table-column-sort", () => Sortable && SortModel != null && SortModel.SortDirection.IsIn(SortDirection.Ascending, SortDirection.Descending));
        }
        private async Task<int> Filter(Filters filters)
        {
            int filtered = 0;

            //Filter children
            foreach (var child in _children)
                filtered += await child.Filter(filters);

            if (filters == null)
            {
                IsFiltered = true;
            }
            else
            {
                //Filter self (skip entirely if a child is visible)
                IsFiltered = Children.Any(a => a.IsFiltered)
                             || filters.Strings.Any(s => TypeName.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0)
                             || filters.Strings.Any(s => Metadata.Any(a => a.Key.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))
                             || filters.Strings.Any(s => HierarchicalProperties.Any(a => a.Key.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0));
            }

            OnPropertyChanged("Children");

            return filtered + (IsFiltered ? 1 : 0);
        }
 private void SearchScientists(object obj)
 {
     Scientists = new ObservableCollection <Scientist>(SelectedXmlSearcher.GetScientists(Filters.ToList()).ToList());
 }
Пример #49
0
		public virtual bool Open(Filters.Abstract recipe)
		{
			this.graph = new DirectShowLib.FilterGraph() as DirectShowLib.IFilterGraph2;
			DirectShowLib.IMediaEventEx mediaEvent = this.graph as DirectShowLib.IMediaEventEx;
			if (mediaEvent.NotNull())
			{
				if (this.eventPoller.NotNull())
					this.eventPoller.Dispose();
				this.eventPoller = Parallel.RepeatThread.Start("DS Event Poller", () =>
				{
					DirectShowLib.EventCode code;
					IntPtr parameter1, parameter2;
					if (mediaEvent.GetEvent(out code, out parameter1, out parameter2, 960) == 0)
					{
						switch (code)
						{
							default:
								Error.Log.Append(Error.Level.Debug, "DirectShow Event: " + code, "DirectShow event " + code + " occured. (paramenter1: " + parameter1 + ", paramenter2: " + parameter2 + ")");
								break;
							case DirectShowLib.EventCode.GraphChanged:
								Error.Log.Append(Error.Level.Debug, "DirectShow Event: Graph Changed", "The DirectShow graph has changed.");
								break;
							case DirectShowLib.EventCode.Paused:
								Error.Log.Append(Error.Level.Debug, "DirectShow Event: Paused", "The DirectShow graph has completed a pause request.");
								break;
							case DirectShowLib.EventCode.ClockChanged:
								Error.Log.Append(Error.Level.Debug, "DirectShow Event: Clock Changed", "The DirectShow graph has changed the reference clock.");
								break;
							case DirectShowLib.EventCode.StErrStPlaying:
								Error.Log.Append(Error.Level.Debug, "DirectShow Event: Stream Error, Still Playing", "A stream error occured, trying to recover by issuing stop followed by play. (paramenter: " + parameter1 + ")");
								this.Stop();
								this.Play();
								break;
						}
					}
				});
			}
			return recipe.Build(this);
		}
Пример #50
0
 public ShopRunnerSettingsPartHandler(IRepository <ShopRunnerSettingsPartRecord> repository)
 {
     Filters.Add(StorageFilter.For(repository));
     Filters.Add(new ActivatingFilter <ShopRunnerSettingsPart>("Site"));
 }
Пример #51
0
 getLog(Ice.LogMessageType[] messageTypes, string[] categories, int messageMax, out string prefix, 
        Ice.Current current)
 {
     LinkedList<Ice.LogMessage> logMessages = null;
     lock(this)
     {
         if(messageMax != 0)
         {
             logMessages = new LinkedList<Ice.LogMessage>(_queue);
         }
         else
         {
             logMessages = new LinkedList<Ice.LogMessage>();
         }
     }
     
     prefix = _logger.getPrefix();
 
     if(logMessages.Count > 0)
     {
         Filters filters = new Filters(messageTypes, categories);
         filterLogMessages(logMessages, filters.messageTypes, filters.traceCategories, messageMax);
     }
     return logMessages.ToArray();
 }
Пример #52
0
        AttachRemoteLogger(IRemoteLoggerPrx prx, LogMessageType[] messageTypes, string[] categories,
                           int messageMax, Current current)
        {
            if (prx == null)
            {
                return; // can't send this null RemoteLogger anything!
            }

            var remoteLogger = prx.Clone(oneway: false);

            Filters filters = new Filters(messageTypes, categories);
            LinkedList <LogMessage> initLogMessages = null;

            lock (this)
            {
                if (_sendLogCommunicator == null)
                {
                    if (_destroyed)
                    {
                        throw new ObjectNotExistException();
                    }

                    _sendLogCommunicator =
                        createSendLogCommunicator(current.Adapter.Communicator, _logger.getLocalLogger());
                }

                Ice.Identity remoteLoggerId = remoteLogger.Identity;

                if (_remoteLoggerMap.ContainsKey(remoteLoggerId))
                {
                    if (_traceLevel > 0)
                    {
                        _logger.trace(_traceCategory, "rejecting `" + remoteLogger.ToString() +
                                      "' with RemoteLoggerAlreadyAttachedException");
                    }

                    throw new Ice.RemoteLoggerAlreadyAttachedException();
                }

                _remoteLoggerMap.Add(remoteLoggerId,
                                     new RemoteLoggerData(changeCommunicator(remoteLogger, _sendLogCommunicator), filters));

                if (messageMax != 0)
                {
                    initLogMessages = new LinkedList <Ice.LogMessage>(_queue); // copy
                }
                else
                {
                    initLogMessages = new LinkedList <Ice.LogMessage>();
                }
            }

            if (_traceLevel > 0)
            {
                _logger.trace(_traceCategory, "attached `" + remoteLogger.ToString() + "'");
            }

            if (initLogMessages.Count > 0)
            {
                filterLogMessages(initLogMessages, filters.messageTypes, filters.traceCategories, messageMax);
            }

            try
            {
                remoteLogger.InitAsync(_logger.getPrefix(), initLogMessages.ToArray()).ContinueWith(
                    (t) =>
                {
                    try
                    {
                        t.Wait();
                        if (_traceLevel > 1)
                        {
                            _logger.trace(_traceCategory, "init on `" + remoteLogger.ToString()
                                          + "' completed successfully");
                        }
                    }
                    catch (System.AggregateException ae)
                    {
                        Debug.Assert(ae.InnerException is Ice.LocalException);
                        deadRemoteLogger(remoteLogger, _logger, (Ice.LocalException)ae.InnerException, "init");
                    }
                },
                    System.Threading.Tasks.TaskScheduler.Current);
            }
            catch (Ice.LocalException ex)
            {
                deadRemoteLogger(remoteLogger, _logger, ex, "init");
                throw;
            }
        }
Пример #53
0
 internal RemoteLoggerData(Ice.RemoteLoggerPrx prx, Filters f)
 {
     remoteLogger = prx;
     filters = f;
 }
Пример #54
0
        internal List <IRemoteLoggerPrx> log(LogMessage logMessage)
        {
            lock (this)
            {
                List <IRemoteLoggerPrx> remoteLoggers = null;

                //
                // Put message in _queue
                //
                if ((logMessage.type != Ice.LogMessageType.TraceMessage && _maxLogCount > 0) ||
                    (logMessage.type == Ice.LogMessageType.TraceMessage && _maxTraceCount > 0))
                {
                    _queue.AddLast(logMessage);

                    if (logMessage.type != Ice.LogMessageType.TraceMessage)
                    {
                        Debug.Assert(_maxLogCount > 0);
                        if (_logCount == _maxLogCount)
                        {
                            //
                            // Need to remove the oldest log from the queue
                            //
                            Debug.Assert(_oldestLog != null);
                            var next = _oldestLog.Next;
                            _queue.Remove(_oldestLog);
                            _oldestLog = next;

                            while (_oldestLog != null && _oldestLog.Value.type == Ice.LogMessageType.TraceMessage)
                            {
                                _oldestLog = _oldestLog.Next;
                            }
                            Debug.Assert(_oldestLog != null); // remember: we just added a Log at the end
                        }
                        else
                        {
                            Debug.Assert(_logCount < _maxLogCount);
                            _logCount++;
                            if (_oldestLog == null)
                            {
                                _oldestLog = _queue.Last;
                            }
                        }
                    }
                    else
                    {
                        Debug.Assert(_maxTraceCount > 0);
                        if (_traceCount == _maxTraceCount)
                        {
                            //
                            // Need to remove the oldest trace from the queue
                            //
                            Debug.Assert(_oldestTrace != null);
                            var next = _oldestTrace.Next;
                            _queue.Remove(_oldestTrace);
                            _oldestTrace = next;

                            while (_oldestTrace != null && _oldestTrace.Value.type != Ice.LogMessageType.TraceMessage)
                            {
                                _oldestTrace = _oldestTrace.Next;
                            }
                            Debug.Assert(_oldestTrace != null);  // remember: we just added a Log at the end
                        }
                        else
                        {
                            Debug.Assert(_traceCount < _maxTraceCount);
                            _traceCount++;
                            if (_oldestTrace == null)
                            {
                                _oldestTrace = _queue.Last;
                            }
                        }
                    }
                }

                //
                // Queue updated, now find which remote loggers want this message
                //
                foreach (RemoteLoggerData p in _remoteLoggerMap.Values)
                {
                    Filters filters = p.filters;

                    if (filters.messageTypes.Count == 0 || filters.messageTypes.Contains(logMessage.type))
                    {
                        if (logMessage.type != Ice.LogMessageType.TraceMessage || filters.traceCategories.Count == 0 ||
                            filters.traceCategories.Contains(logMessage.traceCategory))
                        {
                            if (remoteLoggers == null)
                            {
                                remoteLoggers = new List <IRemoteLoggerPrx>();
                            }
                            remoteLoggers.Add(p.remoteLogger);
                        }
                    }
                }

                return(remoteLoggers);
            }
        }
        private static void PopulateAutoFilter(XLAutoFilter xlAutoFilter, AutoFilter autoFilter)
        {
            var filterRange = xlAutoFilter.Range;
            autoFilter.Reference = filterRange.RangeAddress.ToString();

            foreach (var kp in xlAutoFilter.Filters)
            {
                var filterColumn = new FilterColumn {ColumnId = (UInt32)kp.Key - 1};
                var xlFilterColumn = xlAutoFilter.Column(kp.Key);
                var filterType = xlFilterColumn.FilterType;
                if (filterType == XLFilterType.Custom)
                {
                    var customFilters = new CustomFilters();
                    foreach (var filter in kp.Value)
                    {
                        var customFilter = new CustomFilter {Val = filter.Value.ToString()};

                        if (filter.Operator != XLFilterOperator.Equal)
                            customFilter.Operator = filter.Operator.ToOpenXml();

                        if (filter.Connector == XLConnector.And)
                            customFilters.And = true;

                        customFilters.Append(customFilter);
                    }
                    filterColumn.Append(customFilters);
                }
                else if (filterType == XLFilterType.TopBottom)
                {
                    var top101 = new Top10 {Val = (double)xlFilterColumn.TopBottomValue};
                    if (xlFilterColumn.TopBottomType == XLTopBottomType.Percent)
                        top101.Percent = true;
                    if (xlFilterColumn.TopBottomPart == XLTopBottomPart.Bottom)
                        top101.Top = false;

                    filterColumn.Append(top101);
                }
                else if (filterType == XLFilterType.Dynamic)
                {
                    var dynamicFilter = new DynamicFilter
                    {Type = xlFilterColumn.DynamicType.ToOpenXml(), Val = xlFilterColumn.DynamicValue};
                    filterColumn.Append(dynamicFilter);
                }
                else
                {
                    var filters = new Filters();
                    foreach (var filter in kp.Value)
                    {
                        filters.Append(new Filter {Val = filter.Value.ToString()});
                    }

                    filterColumn.Append(filters);
                }
                autoFilter.Append(filterColumn);
            }


            if (xlAutoFilter.Sorted)
            {
                var sortState = new SortState
                {
                    Reference =
                        filterRange.Range(filterRange.FirstCell().CellBelow(), filterRange.LastCell()).RangeAddress.
                            ToString()
                };
                var sortCondition = new SortCondition
                {
                    Reference =
                        filterRange.Range(1, xlAutoFilter.SortColumn, filterRange.RowCount(),
                            xlAutoFilter.SortColumn).RangeAddress.ToString()
                };
                if (xlAutoFilter.SortOrder == XLSortOrder.Descending)
                    sortCondition.Descending = true;

                sortState.Append(sortCondition);
                autoFilter.Append(sortState);
            }
        }
Пример #56
0
 internal RemoteLoggerData(IRemoteLoggerPrx prx, Filters f)
 {
     remoteLogger = prx;
     filters      = f;
 }
Пример #57
0
		public Share_DeleteShareBySearch(int operatorID, string operatorName, string operatorIP, Filters.ShareFilter filter, int totalDeleted)
			: base(operatorID, operatorName, operatorIP)
		{
			Filter = filter;
			TotalDeleted = totalDeleted;
		}
Пример #58
0
 public static int SelectCount(string searchText, string sortField, bool sortDirection, Filters filterList)
 {
     return(SelectCount());
 }
Пример #59
0
		public IPagedList<AppraiserUser> GetAppraiserUsersListByFilter(Filters.AppraiserFilter filter)
		{
			if (filter == null)
				throw new ArgumentNullException();

			Expression<Func<AppraiserUser, bool>> where = PredicateBuilder.True<AppraiserUser>();

			if (!string.IsNullOrEmpty(filter.UserName))
			{
				var userName = filter.UserName.Trim();
				where = where.AndAlso<AppraiserUser>(x => (x.User.FirstName + " " + x.User.LastName).Contains(userName) || (x.User.LastName + " " + x.User.FirstName).Contains(userName));
			}

			if (!string.IsNullOrEmpty(filter.Email))
			{
				where = where.AndAlso<AppraiserUser>(x => x.User.Email.Contains(filter.Email.Trim()));
			}

			if (!string.IsNullOrEmpty(filter.State))
			{
				var states = _refManager.GetStatesBySubstring(filter.State.Trim());
				var activeStatusString = LicenseStatus.Active.ToString();
				where = where.AndAlso<AppraiserUser>(x => x.Licenses.Any(l => states.Contains(l.State.ToLower()) && l.StatusValue == activeStatusString));
			}

			if (filter.Roles != null)
			{
				where = where.AndAlso<AppraiserUser>(x => filter.Roles.Any(r => x.User.Roles.Any(e => e.Id == r)));
			}

			if (!string.IsNullOrEmpty(filter.AppraisalCompany))
				where = where.AndAlso<AppraiserUser>(x => x.Company != null && x.Company.CompanyName.Contains(filter.AppraisalCompany.Trim()));
			if (filter.AppraisalCompanyId.HasValue)
				where = where.AndAlso<AppraiserUser>(x => x.Company.Id == filter.AppraisalCompanyId);
			if (filter.AppraiserBranchId.HasValue)
				where = where.AndAlso<AppraiserUser>(x => x.Branch.Id == filter.AppraiserBranchId);


			if (filter.Statuses != null)
			{
				var statuses = filter.Statuses.Select(s => s.ToString());
				where = where.AndAlso<AppraiserUser>(x => statuses.Contains(x.StatusId));
			}

			if (filter.ServiceAreaCenterPoint.HasValue)
			{
				where = where.AndAlso<AppraiserUser>(x => x.ServiceArea.ServiceAreaCenterpointId == filter.ServiceAreaCenterPoint.Value);
			}

			Func<IQueryable<AppraiserUser>, IOrderedQueryable<AppraiserUser>> orderBy = null;

			if (!string.IsNullOrEmpty(filter.NameOfSortColumn))
			{
				if (filter.IsAscending)
				{
					switch (filter.NameOfSortColumn)
					{
						case Constants.AppraisersSortColumns.Company:
							orderBy = i => i.OrderBy(x => x.Company.CompanyName);
							break;
						case Constants.AppraisersSortColumns.Email:
							orderBy = i => i.OrderBy(x => x.User.Email);
							break;
						case Constants.AppraisersSortColumns.Phone:
							orderBy = i => i.OrderBy(x => x.ContactInfo.Phones.FirstOrDefault().Number);
							break;
						case Constants.AppraisersSortColumns.Role:
							orderBy = i => i.OrderBy(x => x.User.Roles.FirstOrDefault().DisplayName);
							break;
						case Constants.AppraisersSortColumns.Status:
							orderBy = i => i.OrderBy(x => x.StatusId);
							break;
						case Constants.AppraisersSortColumns.UserName:
							orderBy = i => i.OrderBy(x => x.User.FirstName).ThenBy(x => x.User.LastName);
							break;
						default:
							throw new NotSupportedException("Unknow Column Name");
					}
				}
				else
				{
					switch (filter.NameOfSortColumn)
					{
						case Constants.AppraisersSortColumns.Company:
							orderBy = i => i.OrderByDescending(x => x.Company.CompanyName);
							break;
						case Constants.AppraisersSortColumns.Email:
							orderBy = i => i.OrderByDescending(x => x.User.Email);
							break;
						case Constants.AppraisersSortColumns.Phone:
							orderBy = i => i.OrderByDescending(x => x.ContactInfo.Phones.FirstOrDefault().Number);
							break;
						case Constants.AppraisersSortColumns.Role:
							orderBy = i => i.OrderByDescending(x => x.User.Roles.FirstOrDefault().DisplayName);
							break;
						case Constants.AppraisersSortColumns.Status:
							orderBy = i => i.OrderByDescending(x => x.StatusId);
							break;
						case Constants.AppraisersSortColumns.UserName:
							orderBy = i => i.OrderByDescending(x => x.User.FirstName).ThenByDescending(x => x.User.LastName);
							break;
						default:
							throw new NotSupportedException("Unknow Column Name");
					}
				}
			}

			var results = _appraiserUserRepository.GetPaged(where, orderBy, filter.ItemsOnPage ?? 10, filter.CurrentPage ?? 1);
			filter.PagesTotal = results.PageCount;

			return results;
		}
Пример #60
0
 public static int SelectCount(string searchText, string sortField, bool sortDirection, Filters filterList, IEnumerable <string> includeList)
 {
     return(SelectCount());
 }