Esempio n. 1
0
        public void TestWhereExtension_IQueryable_MultipleIFilters()
        {
            var list = new List <LinqFilterTestClass>();

            list.Add(new LinqFilterTestClass
            {
                Id         = 1,
                NullableId = 1,
                S          = "hello"
            });

            var filter1 = new SimpleFilter
            {
                Comparison = ComparisonType.Like.Value,
                Property   = "S",
                Value      = "h"
            };
            var filter2 = new SimpleFilter
            {
                Comparison = ComparisonType.Like.Value,
                Property   = "S",
                Value      = "o"
            };
            var results = list.AsQueryable().Where(new List <IFilter> {
                filter1, filter2
            }).ToList();

            Assert.AreEqual(1, results.Count);
        }
Esempio n. 2
0
        private void UpdateFilter()
        {
            if (ShowAdvancedView)
            {
                advanced_filter.AttachTo(view);
                advanced_filter.Clear();

                if (AdvancedFilterViewModels.Count > 0)
                {
                    foreach (var fvm in AdvancedFilterViewModels)
                    {
                        advanced_filter.Add(fvm.Filter);
                    }
                }
                else
                {
                    var filter = new TextFilter();
                    if (!string.IsNullOrWhiteSpace(SimpleFilter.Input1))
                    {
                        filter.Input1 = SimpleFilter.Input1;
                    }
                    AddAdvancedFilter(filter);
                }
            }
            else
            {
                SimpleFilter.AttachTo(view);
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> VolumesReport([FromQuery, BindRequired] SimpleFilter filter)
        {
            Log.LogInformation($"VolumesReport Filter: {filter}");
            // Ground to design only
            // SummaryVolumesRequest

            // Returns SummaryVolumesResult
            var filterUid = await ConvertSimpleFilter(filter);

            // Base UID needs to be filter
            // Top UID needs to be design
            var route  = $"/volumes/summary?projectUid={filter.ProjectUid}&baseUid={filterUid}&topUid={filter.DesignFileUid}";
            var result = await _productivity3dV2ProxyCompaction.ExecuteGenericV2Request <CompactionVolumesSummaryResult>(route, HttpMethod.Get, null, CustomHeaders);

            if (result != null)
            {
                return(Json(result));
            }

            ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest,
                                                          (int)Now3DExecutionStates.ErrorCodes.GeneralError,
                                                          null,
                                                          "No Data");
            return(null);
        }
Esempio n. 4
0
 private void AddSimpleFilter_Click(object sender, RoutedEventArgs e)
 {
     if (selectedLine?.Line != null)
     {
         var effect = new SimpleFilter();
         selectedLine.Line.AddEffect(effect);
     }
 }
Esempio n. 5
0
        public IFilter ToFilter()
        {
            var type = Enum.Parse <FilterType>(Type);

            if (type == FilterType.Composite)
            {
                var compositeFilter = new CompositeFilter
                {
                    And     = And,
                    Type    = FilterType.Composite,
                    Filters = Filters?.Select(t => t.ToFilter())?.ToList() ?? new List <IFilter>()
                };
                return(compositeFilter);
            }

            object value = Value;

            if (Value is JsonElement jsonElement)
            {
                if (jsonElement.ValueKind == JsonValueKind.String)
                {
                    value = jsonElement.ToString();
                }
                else if (jsonElement.ValueKind == JsonValueKind.Number && jsonElement.TryGetInt64(out var l))
                {
                    value = l;
                }
                else if (jsonElement.ValueKind == JsonValueKind.True)
                {
                    value = true;
                }
                else if (jsonElement.ValueKind == JsonValueKind.False)
                {
                    value = false;
                }
                else if (jsonElement.ValueKind == JsonValueKind.Array)
                {
                    throw new System.Exception("TODO");
                }
                else
                {
                    value = null;
                }
            }

            var simpleFilter = new SimpleFilter
            {
                And             = And,
                Type            = type,
                Not             = Not,
                Path            = Path,
                Value           = value,
                CaseInsensitive = CaseInsensitive,
            };

            return(simpleFilter);
        }
Esempio n. 6
0
        public SimpleFilterUI(SimpleFilter simpleFilter)
        {
            this.simpleFilter = simpleFilter;
            InitializeComponent();

            Frequency.Value    = simpleFilter.Frequency;
            Resonation.Value   = simpleFilter.Resonation;
            lowpass.IsChecked  = simpleFilter.Type == SimpleFilter.FilterType.Lowpass;
            highpass.IsChecked = simpleFilter.Type == SimpleFilter.FilterType.Highpass;
        }
Esempio n. 7
0
        public void ValidCases(string filter, object value, bool result)
        {
            var entity = new DynamicTableEntity("", "");

            entity.Properties.Add(PropertyName, EntityProperty.CreateEntityPropertyFromObject(value));
            var simpleFilter = new SimpleFilter(filter);

            Assert.True(simpleFilter.HasValidExpression);
            Assert.Equal(result, simpleFilter.Satisfies(entity));
        }
Esempio n. 8
0
        public void TestToString()
        {
            var simpleFilter = new SimpleFilter
            {
                Comparison = ComparisonType.Equal.Value,
                Property   = "Hello",
                Value      = "World"
            };

            Assert.IsNotNull(simpleFilter.ToString());
        }
Esempio n. 9
0
        public WebView(IRenderer renderer, IAssetLoader assetLoader, SpriteBatch spriteBatch, int width, int height, string homePage)
        {
            _rn          = renderer;
            _spriteBatch = spriteBatch;
            _filter      = new SimpleFilter(renderer, spriteBatch, assetLoader.Get <Effect>("shaders/bgra_to_rgba.fx"));

            InitialiseUltralight();

            Resize(width, height);
            Navigate(homePage);
        }
Esempio n. 10
0
        public async Task <IActionResult> MdpReport([FromQuery, BindRequired] SimpleFilter filter)
        {
            // Request: projectUid and filterUid (optional)
            // Url api/v2/mdp/summary
            // Returns CompactionMdpSummaryResult
            Log.LogInformation($"MdpReport Filter: {filter}");

            var filterUid = await ConvertSimpleFilter(filter);

            var result = await ExecuteRequest <CompactionMdpSummaryResult>("/mdp/summary", Guid.Parse(filter.ProjectUid), filterUid);

            return(Json(result));
        }
Esempio n. 11
0
        public async Task <IActionResult> CmvReport([FromQuery, BindRequired] SimpleFilter filter)
        {
            // Request: projectUid, filterUid (optional)
            // Default filter to project extents, no design
            // URL api/v2/cmv/summary
            // Response CompactionCmvSummaryResult
            Log.LogInformation($"CmvReport Filter: {filter}");
            var filterUid = await ConvertSimpleFilter(filter);

            var result = await ExecuteRequest <CompactionCmvSummaryResult>("/cmv/summary", Guid.Parse(filter.ProjectUid), filterUid);

            return(Json(result));
        }
Esempio n. 12
0
        /// <summary>
        /// Create a new payment request.
        /// </summary>
        /// <param name="amount">Amount of vouchers that are required to confirm the payment.</param>
        /// <param name="pocketAckUrl">Confirmation URL invoked by the Pocket.</param>
        /// <param name="posAckUrl">Confirmation URL used by the Registry.</param>
        /// <param name="filter">Filter used to determine which vouchers satisfy the payment.</param>
        /// <param name="isPersistent"></param>
        /// <param name="nonce">Unique nonce of the payment request, is auto-generated if null.</param>
        /// <param name="password">User password required to confirm the payment, is auto-generated if null.</param>
        public async Task <PaymentRequest> RequestPayment(int amount,
                                                          string pocketAckUrl, string posAckUrl = null,
                                                          SimpleFilter filter = null, bool isPersistent = false,
                                                          string nonce        = null, string password   = null)
        {
            if (amount <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(amount));
            }
            if (string.IsNullOrWhiteSpace(pocketAckUrl))
            {
                throw new ArgumentNullException(nameof(pocketAckUrl));
            }

            _client.Logger.LogInformation(LoggingEvents.PointOfSale,
                                          "Creating payment request for {0} vouchers", amount);

            var effectiveNonce = nonce ?? Guid.NewGuid().ToString("N");

            _client.Logger.LogDebug(LoggingEvents.PointOfSale,
                                    "Performing payment creation request");

            var response = await _client.PerformOperation <PaymentRegisterResponse>("v1/payment/register", new PaymentRegisterPayload {
                PosId   = _id,
                Nonce   = effectiveNonce,
                Payload = _client.Crypto.Encrypt(new PaymentRegisterPayload.Content {
                    PosId        = _id,
                    Nonce        = effectiveNonce,
                    Password     = password,
                    Amount       = amount,
                    SimpleFilter = filter,
                    PocketAckUrl = pocketAckUrl,
                    PosAckUrl    = posAckUrl
                }, await _client.GetRegistryPublicKey())
            });

            var responseContent = _client.Crypto.Decrypt <PaymentRegisterResponse.Content>(response.Payload, _privateKey);

            _client.Logger.LogDebug(LoggingEvents.PointOfSale, "Performing payment verification request");

            await _client.PerformOperation("v1/payment/verify", new PaymentVerifyPayload {
                Payload = _client.Crypto.Encrypt(new PaymentVerifyPayload.Content {
                    Otc = responseContent.Otc
                }, await _client.GetRegistryPublicKey())
            });

            _client.Logger.LogDebug(LoggingEvents.PointOfSale, "Voucher creation succeeded");

            return(new PaymentRequest(_client, responseContent.Otc, responseContent.Password));
        }
Esempio n. 13
0
        public Simulator(Parameters parameters, bool do_not_start)
        {
            _parameters         = parameters;
            StartingNetworkSize = parameters.Size;
            CurrentNetworkSize  = 0;
            Nodes               = new SortedList <Address, NodeMapping>();
            TakenIDs            = new SortedList <int, NodeMapping>();
            SimBroadcastHandler = new SimpleFilter();

            if (parameters.Seed != -1)
            {
                _rand = new Random(parameters.Seed);
            }
            else
            {
                _rand = new Random();
            }

            BrunetNamespace = "testing" + _rand.Next();
            _broken         = parameters.Broken;
            _secure_edges   = parameters.SecureEdges;
            _secure_senders = parameters.SecureSenders;
            _pathing        = parameters.Pathing;
            _dtls           = parameters.Dtls;
            if (_secure_edges || _secure_senders)
            {
                _se_key = new RSACryptoServiceProvider();
                byte[] blob = _se_key.ExportCspBlob(false);
                RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();
                rsa_pub.ImportCspBlob(blob);
                CertificateMaker cm = new CertificateMaker("United States", "UFL",
                                                           "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
                                                           "brunet:node:abcdefghijklmnopqrs");
                Certificate cert = cm.Sign(cm, _se_key);
                _ca_cert = cert;
            }

            if (parameters.LatencyMap != null)
            {
                SimulationEdgeListener.LatencyMap = parameters.LatencyMap;
            }

            _start = parameters.Evaluation;
            if (!do_not_start)
            {
                Start();
            }
            _start = false;
        }
Esempio n. 14
0
        public static List <People> ApplyFilterInPeople(List <People> peoples, SimpleFilter customFilter)
        {
            List <People> newPeoples = new List <People> {
            };

            foreach (People people in peoples)
            {
                if (customFilter(people))
                {
                    newPeoples.Add(people);
                }
            }

            return(newPeoples);
        }
Esempio n. 15
0
        public async Task <IActionResult> CutFillReport([FromQuery, BindRequired] SimpleFilter filter)
        {
            // Request orojectUid, filterUid (optional), cutfillDesignUid
            // Url api/v2/cutfill/details"
            // Returns CompactionCutFillDetailedResult
            Log.LogInformation($"CutFillReport Filter: {filter}");
            var filterUid = await ConvertSimpleFilter(filter);

            var additionalParams = new Dictionary <string, string>
            {
                { "cutfillDesignUid", filter.DesignFileUid }
            };

            var result = await ExecuteRequest <CompactionCutFillDetailedResult>("/cutfill/details", Guid.Parse(filter.ProjectUid), filterUid, additionalParams);

            return(Json(result));
        }
Esempio n. 16
0
        public static ISimpleFilter ReplaceByOn(this IFilter filter, string path)
        {
            var simpleFilter = filter as ISimpleFilter;

            if (simpleFilter == null)
            {
                throw new Exception("Must be a simple filter");
            }

            var ret = new SimpleFilter();

            ret.And   = filter.And;
            ret.Type  = filter.Type;
            ret.Value = simpleFilter.Value;
            ret.Path  = path;
            return(ret);
        }
Esempio n. 17
0
        public void TestToClientFilter_NotEqualComparison()
        {
            var filter = new SimpleFilter
            {
                Comparison = ComparisonType.NotEqual.Value,
                Property   = "S",
                Value      = "hello"
            };

            var linqFilter = filter.ToLinqFilter <SimpleFilterTestClass>();

            Assert.IsInstanceOfType(linqFilter, typeof(NotEqualFilter <SimpleFilterTestClass>));

            var typedLinqFilter = (NotEqualFilter <SimpleFilterTestClass>)linqFilter;

            Assert.AreEqual(filter.Value, typedLinqFilter.Value);
            Assert.AreEqual(filter.Property, typedLinqFilter.PropertyInfo.Name);
        }
Esempio n. 18
0
        public void TestToClientFilter_LessThanComparison()
        {
            var filter = new SimpleFilter
            {
                Comparison = ComparisonType.LessThan.Value,
                Property   = "I",
                Value      = 1
            };

            var linqFilter = filter.ToLinqFilter <SimpleFilterTestClass>();

            Assert.IsInstanceOfType(linqFilter, typeof(LessThanFilter <SimpleFilterTestClass>));

            var typedLinqFilter = (LessThanFilter <SimpleFilterTestClass>)linqFilter;

            Assert.AreEqual(filter.Value, typedLinqFilter.Value);
            Assert.AreEqual(filter.Property, typedLinqFilter.PropertyInfo.Name);
        }
Esempio n. 19
0
        public void TestToClientFilter_ContainsAnyComparison()
        {
            var filter = new SimpleFilter
            {
                Comparison = ComparisonType.ContainsAny.Value,
                Property   = "Ids",
                Value      = new List <int> {
                    1
                }
            };

            var linqFilter = filter.ToLinqFilter <SimpleFilterTestClass>();

            Assert.IsInstanceOfType(linqFilter, typeof(ContainsAnyFilter <SimpleFilterTestClass>));

            var typedLinqFilter = (ContainsAnyFilter <SimpleFilterTestClass>)linqFilter;

            Assert.AreEqual(filter.Value, typedLinqFilter.Value);
            Assert.AreEqual(filter.Property, typedLinqFilter.PropertyInfo.Name);
        }
        public void Should_Correctly_Apply_Equal_Filter_On_String_Type()
        {
            //Act

            //var filter = new SimpleFilter(nameof(Car.Make), FilteringOperator.Equal, bmw.Make)
            //    .Or(new ScopedFilter(new SimpleFilter(nameof(Car.Make), FilteringOperator.Equal, toyota.Make).And(new SimpleFilter(nameof(Car.Price), FilteringOperator.Equal, 20001))))
            //    .Or(new SimpleFilter(nameof(Car.Make), FilteringOperator.Equal, renault.Make));
            var filter = new SimpleFilter($"{nameof(Car.Engine)}.{nameof(Car.Engine.ProductionDate)}", FilteringOperator.Equal, new DateTime(2019, 09, 16))
                         .Or(new SimpleFilter(nameof(Car.Make), FilteringOperator.Equal, renault.Make));
            var result = cars.FilterBy(filter).ToList();

            //    var result = cars.FilterBy(new Filter(nameof(Car.Make), FilteringOperator.Equal, bmw.Make, LogicalConnection.Or),
            //new Filter(nameof(Car.Make), FilteringOperator.Equal, toyota.Make, LogicalConnection.And),
            //new Filter(nameof(Car.Price), FilteringOperator.Equal, 20000, LogicalConnection.Or),
            //new Filter(nameof(Car.Make), FilteringOperator.Equal, "Renault", LogicalConnection.Or)).ToList();

            //    Assert.IsNotNull(result);
            //Assert.AreEqual(result.Count(), 1);
            //Assert.AreEqual(result.Count(c => c.Equals(bmw)), 1);
        }
Esempio n. 21
0
        public async Task <IActionResult> CreatePayment(
            string ackUrl,
            int amount = 10,
            [FromBody] SimpleFilter filter = null
            )
        {
            if (!Hosting.IsDevelopment())
            {
                return(Unauthorized());
            }

            if (amount <= 0)
            {
                throw new ArgumentOutOfRangeException("Amount cannot be zero or negative", nameof(amount));
            }
            if (string.IsNullOrWhiteSpace(ackUrl))
            {
                throw new ArgumentException("Acknowledgment URL cannot be void", nameof(ackUrl));
            }

            Logger.LogInformation("Creating payment for {0} vouchers", amount);

            var testPos = await Mongo.GetPosById(_testPosId);

            Logger.LogTrace("Test POS: {0}", testPos.Id);

            (var otcPay, var pwd) = await Operator.CreatePaymentRequest(testPos, new PaymentRegisterPayload.Content {
                Amount       = amount,
                Nonce        = Guid.NewGuid().ToString("N"),
                SimpleFilter = filter,
                PosId        = testPos.Id.ToString(),
                PocketAckUrl = ackUrl
            }, isPreVerified : true);

            Logger.LogDebug("New payment request created with code {0}", otcPay);

            return(Ok(new {
                OtcPay = UrlGenerator.GeneratePaymentUrl(otcPay),
                Pin = pwd
            }));
        }
Esempio n. 22
0
        public void TestWhereExtension_IEnumerable_SingleIFilter()
        {
            var list = new List <LinqFilterTestClass>();

            list.Add(new LinqFilterTestClass
            {
                Id         = 1,
                NullableId = 1,
                S          = "hello"
            });

            var filter = new SimpleFilter
            {
                Comparison = ComparisonType.Like.Value,
                Property   = "S",
                Value      = "hello"
            };
            var results = list.Where(filter).ToList();

            Assert.AreEqual(1, results.Count);
        }
Esempio n. 23
0
        static void Main()
        {
            var simple       = new Simple();
            var simpleFilter = new SimpleFilter();

            Expression <Func <Simple, bool> > result;

            try
            {
                result = simpleFilter.GeneratorEqualityTest(x => x.SimpleProperty, 1);
                Console.WriteLine("First case worked.");
            }
            catch (Exception exc)
            {
                Console.WriteLine("First case failed: " + exc.Message);
            }

            try
            {
                result = simpleFilter.GeneratorEqualityTest(x => x.Complex.ComplexProperty, 2);
                Console.WriteLine("Second case worked.");
            }
            catch (Exception exc)
            {
                Console.WriteLine("Second case failed: " + exc.Message);
            }

            try
            {
                result = simpleFilter.GeneratorEqualityTest(x => x.Complex.MoreComplex.MoreComplexProperty, 3);
                Console.WriteLine("Third case worked.");
            }
            catch (Exception exc)
            {
                Console.WriteLine("Third case failed: " + exc.Message);
            }

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
 private void Write75_SimpleFilterOfVersion(string n, string ns, SimpleFilter<Version> o, bool isNullable, bool needType)
 {
     if (o == null)
     {
         if (isNullable)
         {
             base.WriteNullTagLiteral(n, ns);
         }
     }
     else
     {
         if (!needType && (o.GetType() != typeof(SimpleFilter<Version>)))
         {
             throw base.CreateUnknownTypeException(o);
         }
         base.WriteStartElement(n, ns, o, false, null);
         if (needType)
         {
             base.WriteXsiType("SimpleFilterOfVersion", "");
         }
         base.WriteElementString("ValueComparision", "", this.Write73_SimpleComparision(o.ValueComparision));
         this.Write74_Version("FromValue", "", o.FromValue, false, false);
         this.Write74_Version("ToValue", "", o.ToValue, false, false);
         base.WriteEndElement(o);
     }
 }
 private void Write82_SimpleFilterOfByte(string n, string ns, SimpleFilter<byte> o, bool isNullable, bool needType)
 {
     if (o == null)
     {
         if (isNullable)
         {
             base.WriteNullTagLiteral(n, ns);
         }
     }
     else
     {
         if (!needType)
         {
             System.Type type = o.GetType();
             if (type != typeof(SimpleFilter<byte>))
             {
                 if (type != typeof(IntegralFilter<byte>))
                 {
                     throw base.CreateUnknownTypeException(o);
                 }
                 this.Write83_IntegralFilterOfByte(n, ns, (IntegralFilter<byte>) o, isNullable, true);
                 return;
             }
         }
         base.WriteStartElement(n, ns, o, false, null);
         if (needType)
         {
             base.WriteXsiType("SimpleFilterOfByte", "");
         }
         base.WriteElementString("ValueComparision", "", this.Write73_SimpleComparision(o.ValueComparision));
         base.WriteElementStringRaw("FromValue", "", XmlConvert.ToString(o.FromValue));
         base.WriteElementStringRaw("ToValue", "", XmlConvert.ToString(o.ToValue));
         base.WriteEndElement(o);
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Convert a simple filter into a Real Filter via the Filter service
        /// </summary>
        /// <returns>Filter UID</returns>
        private async Task <Guid> ConvertSimpleFilter(SimpleFilter simpleFilter)
        {
            if (simpleFilter == null)
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest,
                                                              (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure,
                                                              null,
                                                              "No Simple Filter found");
            }

            var project = await _projectProxy.GetProjectForCustomer(CustomerUid, simpleFilter.ProjectUid, CustomHeaders);

            if (project == null)
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest,
                                                              (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure,
                                                              null,
                                                              $"Cannot find project {simpleFilter.ProjectUid} for Customer {CustomerUid}");
            }

            var file = await _fileImportProxy.GetFileForProject(simpleFilter.ProjectUid, UserId, simpleFilter.DesignFileUid,
                                                                CustomHeaders);

            if (file == null)
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest,
                                                              (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure,
                                                              null,
                                                              $"Cannot find file {simpleFilter.DesignFileUid} for project {simpleFilter.ProjectUid}");
            }

            var filterModel = new Filter.Abstractions.Models.Filter(simpleFilter.StartDateUtc,
                                                                    simpleFilter.EndDateUtc,
                                                                    simpleFilter.DesignFileUid,
                                                                    file.Name,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    simpleFilter.LiftNumber);

            var filterRequest = FilterRequest.Create(filterModel);

            var result = await _filterServiceProxy.CreateFilter(simpleFilter.ProjectUid, filterRequest, CustomHeaders);

            if (result.Code != 0)
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest,
                                                              (int)Now3DExecutionStates.ErrorCodes.DataError,
                                                              result.Code.ToString(),
                                                              result.Message);
            }

            var guid = Guid.Parse(result.FilterDescriptor.FilterUid);

            Log.LogInformation($"Converted Simple filter '{JsonConvert.SerializeObject(simpleFilter)}' to a " +
                               $"{nameof(FilterRequest)}: '{JsonConvert.SerializeObject(filterRequest)}'. FilterUID: {guid}");

            return(guid);
        }
Esempio n. 27
0
        private async Task <(string AckUrl, Guid Otc, string Password)> Pay(Pocket p, int amount, string pocketAckUrl, SimpleFilter filter = null)
        {
            int beforeCount = p.VoucherCount;

            (var otcPay, var pwd) = await _pos.RequestPayment(amount, pocketAckUrl, "https://example.org", filter, false);

            var ret = await p.PayWithRandomVouchers(otcPay, pwd);

            Assert.AreEqual(beforeCount - amount, p.VoucherCount);
            return(ret, otcPay, pwd);
        }
Esempio n. 28
0
        public async Task <TResult> ShowDialog <TResult>(Form owner, params string[] route)
            where TResult : AngularAction
        {
            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner));
            }

            var tcs = new TaskCompletionSource <TResult>();

            var subscriptions = new List <IDisposable>();

            try
            {
                subscriptions.Add(_pipe.Messages
                                  .OfType <WindowShownMessage>()
                                  .Subscribe(p => { _hwnd = p.Body?.ToIntPtr() ?? IntPtr.Zero; }));

                subscriptions.Add(_pipe.Messages
                                  .OfActions()
                                  .OfType <TResult>()
                                  .Subscribe(p => { tcs.TrySetResult(p); }));

                RegisterHandlers(owner);
                try
                {
                    await _pipe.SendMessage(new ActionsMessage
                    {
                        Body = new ActionsMessageBody
                        {
                            Actions = new List <AngularAction>
                            {
                                new NavigateToAction {
                                    Route = route
                                }
                            }
                        }
                    }, CancellationToken.None);

                    await _pipe.SendMessage(new ShowMessage(), CancellationToken.None);

                    var filter = new SimpleFilter(owner.Handle);
                    Application.AddMessageFilter(filter);
                    try
                    {
                        var result = await tcs.Task;

                        await _pipe.SendMessage(new HideMessage(), CancellationToken.None);

                        return(result);
                    }
                    finally
                    {
                        _hwnd = IntPtr.Zero;
                        Application.RemoveMessageFilter(filter);
                    }
                }
                finally
                {
                    UnregisterHandlers(owner);
                }
            }
            finally
            {
                foreach (var subscription in subscriptions)
                {
                    subscription.Dispose();
                }
            }
        }
 private SimpleFilter<byte> Read82_SimpleFilterOfByte(bool isNullable, bool checkType)
 {
     XmlQualifiedName type = checkType ? base.GetXsiType() : null;
     bool flag = false;
     if (isNullable)
     {
         flag = base.ReadNull();
     }
     if ((checkType && (type != null)) && ((type.Name != this.id269_SimpleFilterOfByte) || (type.Namespace != this.id2_Item)))
     {
         if ((type.Name != this.id222_IntegralFilterOfByte) || (type.Namespace != this.id2_Item))
         {
             throw base.CreateUnknownTypeException(type);
         }
         return this.Read83_IntegralFilterOfByte(isNullable, false);
     }
     if (flag)
     {
         return null;
     }
     SimpleFilter<byte> o = new SimpleFilter<byte>();
     bool[] flagArray = new bool[3];
     while (base.Reader.MoveToNextAttribute())
     {
         if (!base.IsXmlnsAttribute(base.Reader.Name))
         {
             base.UnknownNode(o);
         }
     }
     base.Reader.MoveToElement();
     if (base.Reader.IsEmptyElement)
     {
         base.Reader.Skip();
         return o;
     }
     base.Reader.ReadStartElement();
     base.Reader.MoveToContent();
     int whileIterations = 0;
     int readerCount = base.ReaderCount;
     while ((base.Reader.NodeType != XmlNodeType.EndElement) && (base.Reader.NodeType != XmlNodeType.None))
     {
         if (base.Reader.NodeType == XmlNodeType.Element)
         {
             if ((!flagArray[0] && (base.Reader.LocalName == this.id200_ValueComparision)) && (base.Reader.NamespaceURI == this.id2_Item))
             {
                 o.ValueComparision = this.Read73_SimpleComparision(base.Reader.ReadElementString());
                 flagArray[0] = true;
             }
             else if ((!flagArray[1] && (base.Reader.LocalName == this.id201_FromValue)) && (base.Reader.NamespaceURI == this.id2_Item))
             {
                 o.FromValue = XmlConvert.ToByte(base.Reader.ReadElementString());
                 flagArray[1] = true;
             }
             else if ((!flagArray[2] && (base.Reader.LocalName == this.id202_ToValue)) && (base.Reader.NamespaceURI == this.id2_Item))
             {
                 o.ToValue = XmlConvert.ToByte(base.Reader.ReadElementString());
                 flagArray[2] = true;
             }
             else
             {
                 base.UnknownNode(o, ":ValueComparision, :FromValue, :ToValue");
             }
         }
         else
         {
             base.UnknownNode(o, ":ValueComparision, :FromValue, :ToValue");
         }
         base.Reader.MoveToContent();
         base.CheckReaderCount(ref whileIterations, ref readerCount);
     }
     base.ReadEndElement();
     return o;
 }
Esempio n. 30
0
        static void Main(string[] args)
        {
            #region HelloWorld
            Console.WriteLine("Hello World");
            #endregion


            #region Conditional Structure
            bool thisIsTheMainContext = true;

            if (thisIsTheMainContext)
            {
                Console.WriteLine("Main Context");
            }

            #endregion


            #region Loops and Arrays
            int[] fundamentalNumbers =
            {
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9
            };

            for (int i = 0; i < fundamentalNumbers.Length; i++)
            {
                Console.WriteLine(fundamentalNumbers[i]);
            }

            foreach (int number in fundamentalNumbers)
            {
                Console.WriteLine(number);
            }
            #endregion


            #region Operation with 2 numbers using Delegate

            MathOperationWith2Numbers sum, mult, myCustomMathOperation;
            sum  = Sum;
            mult = Mult;

            myCustomMathOperation = sum + mult;

            Console.WriteLine(myCustomMathOperation(2, 3));

            #endregion


            #region List Declaration and Delegate Filter

            SimpleFilter callbackFilter = IsGreaterThanOrEqualsTo22Years;

            List <People> youngPeoples = new List <People> {
                new People {
                    name = "Fabricio",
                    age  = 22
                },
                new People {
                    name = "Kelvin",
                    age  = 22
                },
                new People {
                    name = "Caique",
                    age  = 21
                },
                new People {
                    name = "Larissa",
                    age  = 18
                },
                new People {
                    name = "Victor",
                    age  = 18
                },
            };

            List <People> newPeoplesFilteredByAge = ApplyFilterInPeople(youngPeoples, callbackFilter);

            foreach (People peopleFilteredByAge in newPeoplesFilteredByAge)
            {
                Console.WriteLine(peopleFilteredByAge);
            }

            #endregion


            #region using LINQ

            List <People> resultUsingLinq = (
                from APeople in youngPeoples
                where APeople.name[0] == 'F'
                select APeople
                ).ToList();

            Console.Write(resultUsingLinq[0]);

            #endregion
        }
Esempio n. 31
0
        static private Bitmap Simplefilter(Bitmap Source, int Range, SimpleFilter SF)
        {
            int         Width = Source.Width, Height = Source.Height;
            Bitmap      Result = new Bitmap(Width, Height);
            BitmapData  SourceData = Source.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            BitmapData  ResultData = Result.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            IntPtr      SourceScan = SourceData.Scan0;
            IntPtr      ResultScan = ResultData.Scan0;
            int         X, Y, T, A, B;
            List <byte> RGBList = new List <byte>();

            byte[,,] SourceImage = new byte[Height, Width, 3];
            byte[,,] ResultImage = new byte[Height, Width, 3];
            byte *SourcePointer = (byte *)SourceScan.ToPointer();
            byte *ResultPointer = (byte *)ResultScan.ToPointer();

            for (Y = 0; Y < Height; ++Y)
            {
                for (X = 0; X < Width; ++X)
                {
                    for (T = 0; T < 3; ++T)
                    {
                        SourceImage[Y, X, T] = SourcePointer[0];
                        ++SourcePointer;
                    }
                    ++SourcePointer;
                }
            }
            for (Y = 0; Y < Height; ++Y)
            {
                for (X = 0; X < Width; ++X)
                {
                    for (T = 0; T < 3; ++T)
                    {
                        RGBList.Clear();
                        for (A = Y - Range / 2; A <= Y + Range / 2; ++A)
                        {
                            if (A >= 0 && A < Height)
                            {
                                for (B = X - Range / 2; B <= X + Range / 2; ++B)
                                {
                                    if (B >= 0 && B < Width)
                                    {
                                        RGBList.Add(SourceImage[A, B, T]);
                                    }
                                }
                            }
                        }
                        if (SF == SimpleFilter.Median)
                        {
                            ResultImage[Y, X, T] = Median(RGBList.ToArray());
                        }
                        else if (SF == SimpleFilter.ArithmeticMean)
                        {
                            ResultImage[Y, X, T] = Arithmeticmean(RGBList.ToArray());
                        }
                        else if (SF == SimpleFilter.Max)
                        {
                            ResultImage[Y, X, T] = Max(RGBList.ToArray());
                        }
                        else if (SF == SimpleFilter.Min)
                        {
                            ResultImage[Y, X, T] = Min(RGBList.ToArray());
                        }
                        else if (SF == SimpleFilter.MidPoint)
                        {
                            ResultImage[Y, X, T] = MidPoint(RGBList.ToArray());
                        }
                    }
                }
            }
            for (Y = 0; Y < Height; ++Y)
            {
                for (X = 0; X < Width; ++X)
                {
                    for (T = 0; T < 3; ++T)
                    {
                        ResultPointer[0] = ResultImage[Y, X, T];
                        ++ResultPointer;
                    }
                    ResultPointer[0] = 255;
                    ++ResultPointer;
                }
            }
            Source.UnlockBits(SourceData);
            Result.UnlockBits(ResultData);
            return(Result);
        }
Esempio n. 32
0
 public HomeController()
 {
     filterer    = new SimpleFilter();
     pbefilterer = new FilterByPBE();
 }