コード例 #1
0
        private string CompileCondition(ComparisonCondition condition)
        {
            string left  = condition.left.compile(this.traits);
            string right = getName(condition.right);

            switch (condition.comparison)
            {
            case ComparisonType.EQUAL:
                return(left + " = " + right);

            case ComparisonType.GREATEROREQUAL:
                return(left + " >= " + right);

            case ComparisonType.GREATERTHAN:
                return(left + " > " + right);

            case ComparisonType.LESSOREQUAL:
                return(left + " <= " + right);

            case ComparisonType.LESSTHAN:
                return(left + " < " + right);

            case ComparisonType.NOTEQUAL:
                return(left + " != " + right);

            default:
                throw new NotSupportedException();
            }
        }
コード例 #2
0
        static bool EvaluateComparable(IComparable leftOperand, ComparisonCondition operatorType, IComparable rightOperand)
        {
            object convertedOperand = null;

            try
            {
                convertedOperand = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
            }
            catch (InvalidCastException)
            {
            }

            if (convertedOperand == null)
            {
                return(operatorType == ComparisonCondition.NotEqual);
            }

            int comparison = leftOperand.CompareTo((IComparable)convertedOperand);

            return(operatorType switch
            {
                ComparisonCondition.Equal => comparison == 0,
                ComparisonCondition.NotEqual => comparison != 0,
                ComparisonCondition.LessThan => comparison < 0,
                ComparisonCondition.LessThanOrEqual => comparison <= 0,
                ComparisonCondition.GreaterThan => comparison > 0,
                ComparisonCondition.GreaterThanOrEqual => comparison >= 0,
                _ => false,
            });
コード例 #3
0
ファイル: Parser.cs プロジェクト: bramhoven/Poseidon
 private void CreateNewMatchCondition()
 {
     // create a new empty ComparisonCondition instance ready to fill
     _currentComparisonCondition = new ComparisonCondition();
     _currentComparisonCondition.LogOpToNextCondition = DslLogicalOperator.None;
     _queryModel.ComparisonConditions.Add(_currentComparisonCondition);
 }
コード例 #4
0
        /// <inheritdoc />
        /// <summary>Reads the JSON representation of the object.</summary>
        /// <param name="reader">The <see cref="JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">
        /// The existing value of object being read. If there is no existing value then <c>null</c> will be used.
        /// </param>
        /// <param name="hasExistingValue">The existing value has a value.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The deserialized <see cref="ComparisonCondition{T}" />.</returns>
        public override ComparisonCondition <T> ReadJson(
            JsonReader reader,
            Type objectType,
            ComparisonCondition <T> existingValue,
            bool hasExistingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                throw new JsonSerializationException($"Cannot deserialize null value to {objectType}");
            }

            if (reader.TokenType != JsonToken.String)
            {
                throw new JsonSerializationException(
                          $"Unexpected token when deserializing ComparisonCondition. Expected String, got {reader.TokenType}");
            }

            var value       = (string)reader.Value;
            var operandType = typeof(T);

            string operandString;

            var op = ExtractOperator(value);

            if (op != null)
            {
                operandString = value.Substring(op.Length);
            }
            else
            {
                op            = "==";
                operandString = value;
            }

            T operand;

            try
            {
                operand = (T)Convert.ChangeType(operandString, operandType);
            }
            catch (FormatException)
            {
                throw new JsonSerializationException($"Failed to parse '{operandString}' as {operandType}");
            }

            return(new ComparisonCondition <T>(operand, op));
        }
コード例 #5
0
        public IncomingRequestsView(IncomingRequestsViewModel viewModel, IRegionManager regionManager, IEventAggregator eventAggregator, IFileManagerService fileManagerService)
            : base(regionManager, eventAggregator)
        {
            _fileManagerService = fileManagerService;
            InitializeComponent();
            DataContext = viewModel;
            if (GlobalAppProperties.User.RoleCurrent == Role.Admin || GlobalAppProperties.User.RoleCurrent == Role.Director)
            {
                var recordFilter = new RecordFilter {
                    FieldName = nameof(IncomingRequestLookup.HasAnyPerformer)
                };
                var condition = new ComparisonCondition(ComparisonOperator.Equals, false);
                recordFilter.Conditions.Add(condition);
                IncomingRequestsGrid.FieldLayouts.First().RecordFilters.Add(recordFilter);

                var recordFilter2 = new RecordFilter {
                    FieldName = nameof(IncomingRequest.IsActual)
                };
                var condition2 = new ComparisonCondition(ComparisonOperator.Equals, true);
                recordFilter2.Conditions.Add(condition2);
                IncomingRequestsGrid.FieldLayouts.First().RecordFilters.Add(recordFilter2);
            }

            if (GlobalAppProperties.User.RoleCurrent == Role.SalesManager)
            {
                var recordFilter = new RecordFilter {
                    FieldName = nameof(IncomingRequest.IsDone)
                };
                var condition = new ComparisonCondition(ComparisonOperator.Equals, false);
                recordFilter.Conditions.Add(condition);
                IncomingRequestsGrid.FieldLayouts.First().RecordFilters.Add(recordFilter);

                //скрываем колонки
                IncomingRequestsGrid.FieldLayouts.First().Fields
                .Single(x => x.Name == nameof(IncomingRequestLookup.HasAnyPerformer)).Visibility = Visibility.Collapsed;
            }

            viewModel.SelectedIncomingRequestChanged += request =>
            {
                if (request != null)
                {
                    _currentUri         = new Uri(_fileManagerService.GetPath(request.Document));
                    this.Browser.Source = _currentUri;
                }
            };
        }
コード例 #6
0
        static bool Compare(object leftOperand, ComparisonCondition operatorType, object rightOperand)
        {
            if (leftOperand != null && rightOperand != null)
            {
                rightOperand = TypeConverterHelper.Convert(rightOperand.ToString(), leftOperand.GetType().FullName);
            }

            IComparable leftComparableOperand  = leftOperand as IComparable;
            IComparable rightComparableOperand = rightOperand as IComparable;

            if ((leftComparableOperand != null) && (rightComparableOperand != null))
            {
                return(EvaluateComparable(leftComparableOperand, operatorType, rightComparableOperand));
            }

            switch (operatorType)
            {
            case ComparisonCondition.Equal:
                return(object.Equals(leftOperand, rightOperand));

            case ComparisonCondition.NotEqual:
                return(!object.Equals(leftOperand, rightOperand));

            case ComparisonCondition.LessThan:
            case ComparisonCondition.LessThanOrEqual:
            case ComparisonCondition.GreaterThan:
            case ComparisonCondition.GreaterThanOrEqual:
            {
                if (leftComparableOperand == null && rightComparableOperand == null)
                {
                    throw new ArgumentException("Invalid operands");
                }
                else if (leftComparableOperand == null)
                {
                    throw new ArgumentException("Invalid left operand");
                }
                else
                {
                    throw new ArgumentException("Invalid right operand");
                }
            }
            }

            return(false);
        }
コード例 #7
0
        private static void OnFilterValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataPresenterBase presenter   = (DataPresenterBase)d;
            string            filterValue = (string)e.NewValue;

            string[] filterByFields = ReadCsvs((string)presenter.GetValue(XamDataPresenterBase.FilterByFieldsProperty));

            //If the field layout is not initialized or the FilterByFields property is not set return.
            if (presenter.FieldLayouts.Count <= 0 || filterByFields.Length == 0)
            {
                return;
            }

            //Clear any exisitng filters
            presenter.FieldLayouts[0].RecordFilters.Clear();

            //If the filter is empty return
            if (string.IsNullOrEmpty(filterValue))
            {
                return;
            }

            //Make sure the filter action is Hide
            presenter.FieldLayoutSettings.FilterAction = RecordFilterAction.Default;
            presenter.FieldLayoutSettings.RecordFiltersLogicalOperator = LogicalOperator.Or;

            //Create the filters
            foreach (var fieldName in filterByFields)
            {
                ComparisonCondition condition = new ComparisonCondition();
                condition.Operator = ComparisonOperator.Contains;
                condition.Value    = filterValue;

                RecordFilter rFilter = new RecordFilter();
                rFilter.FieldName = fieldName;

                rFilter.Conditions.Add(condition);

                presenter.FieldLayouts[0].RecordFilters.Add(rFilter);
            }
        }
コード例 #8
0
        public ComparisonAttribute(string otherProperty, ComparisonCondition comparisonCondition)
        {
            _otherProperty = otherProperty;
            _comparisonCondition = comparisonCondition;

            _comparisonFunctions = new Dictionary<ComparisonCondition, Func<object, object, bool>>
            {
                {ComparisonCondition.Equal, (x, y) => _comparer.Compare(x, y) == 0},
                {ComparisonCondition.Greater, (x, y) => _comparer.Compare(x, y) > 0},
                {ComparisonCondition.Less, (x, y) => _comparer.Compare(x, y) < 0}
            };

            _comparisonFunctions.Add(ComparisonCondition.GreaterOrEqual,
                (x, y) =>
                    _comparisonFunctions[ComparisonCondition.Greater](x, y) ||
                    _comparisonFunctions[ComparisonCondition.Equal](x, y));

            _comparisonFunctions.Add(ComparisonCondition.LessOrEqual,
                (x, y) =>
                    _comparisonFunctions[ComparisonCondition.Less](x, y) ||
                    _comparisonFunctions[ComparisonCondition.Equal](x, y));

            _comparisonFunctions.Add(ComparisonCondition.NotEqual, (x, y) => _comparisonFunctions[ComparisonCondition.Equal](x, y) == false);
        }
コード例 #9
0
 /// <inheritdoc />
 /// <summary>Writes the JSON representation of the object.</summary>
 /// <param name="writer">The <see cref="JsonWriter" /> to write to.</param>
 /// <param name="value">The value.</param>
 /// <param name="serializer">The calling serializer.</param>
 public override void WriteJson(JsonWriter writer, ComparisonCondition <T> value, JsonSerializer serializer)
 {
     writer.WriteValue(value.ToString());
 }
コード例 #10
0
        public Market2View(Market2ViewModel viewModel, IRegionManager regionManager, IEventAggregator eventAggregator,
                           IMessageService messageService, IMessagesOutlookService messagesOutlookService, IFileManagerService fileManagerService)
            : base(viewModel, regionManager, eventAggregator, messageService)
        {
            _viewModel = viewModel;

            _messagesOutlookService = messagesOutlookService;
            _fileManagerService     = fileManagerService;
            InitializeComponent();

            _viewModel.IsShownDoneItemsChanged += () =>
            {
                var recordFilter = ((XamDataGrid)ContentControl.Content).FieldLayouts[0].RecordFilters
                                   .Where(filter => filter.FieldName == "IsDone")
                                   .OrderBy(filter => filter.Version)
                                   .Last();
                recordFilter.Conditions.Clear();

                //если нужно скрыть реализованные строки
                if (_viewModel.IsShownDoneItems == false)
                {
                    ComparisonCondition condition = new ComparisonCondition(ComparisonOperator.Equals, false);
                    recordFilter.Conditions.Add(condition);
                }
            };

            _viewModel.IsShownLoosenItemsChanged += () =>
            {
                var recordFilter = ((XamDataGrid)ContentControl.Content).FieldLayouts[0].RecordFilters
                                   .Where(rf => rf.FieldName == "IsLoosen")
                                   .OrderBy(filter => filter.Version)
                                   .Last();
                recordFilter.Conditions.Clear();

                //если нужно скрыть проигранные строки
                if (_viewModel.IsShownLoosenItems == false)
                {
                    ComparisonCondition condition = new ComparisonCondition(ComparisonOperator.Equals, false);
                    recordFilter.Conditions.Add(condition);
                }
            };

            _viewModel.IsShownOnlyReportsItemsChanged += () =>
            {
                var recordFilter = ((XamDataGrid)ContentControl.Content).FieldLayouts[0].RecordFilters
                                   .Where(rf => rf.FieldName == "ForReport")
                                   .OrderBy(filter => filter.Version)
                                   .Last();
                recordFilter.Conditions.Clear();

                //если нужно показать только строки для отчета
                if (_viewModel.IsShownOnlyReportsItems)
                {
                    ComparisonCondition condition = new ComparisonCondition(ComparisonOperator.Equals, true);
                    recordFilter.Conditions.Add(condition);
                }
            };

            //приложения проекта
            viewModel.SelectedProjectItemChanged += projectItem =>
            {
                if (projectItem != null)
                {
                    _currentUri         = new Uri(_fileManagerService.GetPath(projectItem.Project));
                    this.Browser.Source = _currentUri;
                }
            };

            viewModel.Outlook.SelectedMessageChanged += msg =>
            {
                if (msg != null)
                {
                    WebBrowserForMessages.NavigateToString(FixHtml(msg.BodyHtml));
                }
                else
                {
                    WebBrowserForMessages.Navigate("about:blank");
                }
            };
            this.Loaded += OnLoaded;
        }
コード例 #11
0
ファイル: UploadManager.cs プロジェクト: inga-lovinde/FLocal
        public static Upload UploadFile(Stream fileStream, string filename, DateTime uploadDate, User uploader, int?id)
        {
            string extension = filename.Split('.').Last().ToLower();

            if (!allowedExtensions.Contains(extension))
            {
                throw new FLocalException("Unsupported extension '" + extension + "'");
            }
            if (fileStream.Length > MAX_UPLOAD_FILESIZE)
            {
                throw new FLocalException("File is too big");
            }

            byte[] data      = new byte[fileStream.Length];
            int    readBytes = fileStream.Read(data, 0, (int)fileStream.Length);

            if (readBytes != fileStream.Length)
            {
                throw new FLocalException("File is incomplete (read " + readBytes + " of " + fileStream.Length + ")");
            }

            string            file_md5  = Util.md5(fileStream);
            AbstractCondition condition = new ComparisonCondition(
                Upload.TableSpec.instance.getColumnSpec(Upload.TableSpec.FIELD_HASH),
                ComparisonType.EQUAL,
                file_md5
                );

            int?uploadId = null;

            try {
                if (Config.instance.mainConnection.GetCountByConditions(Upload.TableSpec.instance, condition) > 0)
                {
                    throw new _AlreadyUploadedException();
                }
                Config.Transactional(transaction => {
                    Config.instance.mainConnection.lockTable(transaction, Upload.TableSpec.instance);

                    /*if(Config.instance.mainConnection.GetCountByConditions(Upload.TableSpec.instance, condition, new JoinSpec[0]) > 0) {
                     *      throw new _AlreadyUploadedException();
                     * }*/
                    //TODO: ???

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Config.instance.UploaderUrl + "Upload/?extension=" + extension + "&signature=" + Util.md5(file_md5 + " " + Config.instance.SaltUploader));
                    request.Method         = "POST";
                    request.ContentLength  = data.Length;
                    Stream requestStream   = request.GetRequestStream();
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();

                    HttpWebResponse response;
                    try {
                        response = (HttpWebResponse)request.GetResponse();
                    } catch (WebException e) {
                        response = (HttpWebResponse)e.Response;
                    }
                    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                        string result = reader.ReadToEnd();
                        if (result != "OK")
                        {
                            throw new CriticalException("Cannot upload file to upload service: " + result);
                        }
                    }

                    Dictionary <string, string> row = new Dictionary <string, string>();
                    if (id.HasValue)
                    {
                        row[Upload.TableSpec.FIELD_ID] = id.ToString();
                    }
                    row[Upload.TableSpec.FIELD_HASH]       = file_md5;
                    row[Upload.TableSpec.FIELD_EXTENSION]  = extension;
                    row[Upload.TableSpec.FIELD_UPLOADDATE] = uploadDate.ToUTCString();
                    row[Upload.TableSpec.FIELD_USERID]     = uploader.id.ToString();
                    row[Upload.TableSpec.FIELD_SIZE]       = data.Length.ToString();
                    row[Upload.TableSpec.FIELD_FILENAME]   = filename;
                    uploadId = int.Parse(Config.instance.mainConnection.insert(transaction, Upload.TableSpec.instance, row));
                });
            } catch (_AlreadyUploadedException) {
                throw new AlreadyUploadedException(
                          int.Parse(
                              Config.instance.mainConnection.LoadIdsByConditions(
                                  Upload.TableSpec.instance,
                                  condition,
                                  Diapasone.unlimited
                                  ).Single()
                              )
                          );
            }
            return(Upload.LoadById(uploadId.Value));
        }