public ColumnModel(string name, Type type) { Name = name; DisplayName = name; Type = type; ColumnFilter = new ColumnFilter(Type); }
private object GetValueField(ColumnFilter filter) { switch (filter.Type.Name) { case "Int16": return(filter.Value); case "Int32": return(filter.Value); case "Int64": return(filter.Value); case "String": return($"'{filter.Value}'"); case "Decimal": return($"{filter.Value}"); case "Double": return($"{filter.Value}"); default: throw new Exception($"Tipo não mapeado {filter.Type}"); } }
public override IColumnFilter CreateColumnFilter(ColumnFilterStorage storage) { ColumnFilter columnFilter = new ColumnFilter(); columnFilter.SetStorage(storage); return(columnFilter); }
public bool HasFiltering() { bool ret = false; foreach (KeyValuePair <string, TextBox> entry in filtering_textBoxes.ToArray()) { String key = entry.Key; TextBox tb = entry.Value; if (tb.Text != "") { ret = true; } } // also check the internal filters (needed ???) foreach (KeyValuePair <string, ColumnFilter> entry in columnFilters) { String key = entry.Key; ColumnFilter filter = entry.Value; if (filter.FilterValue != "") { ret = true; } } return(ret); }
int DrawColumn(IDrawer2D drawer, string header, int columnI, int x, ColumnFilter filter) { int y = table.Y + 3; int maxWidth = table.ColumnWidths[columnI]; bool separator = columnI > 0; DrawTextArgs args = new DrawTextArgs(header, titleFont, true); TableEntry headerEntry = default(TableEntry); DrawColumnEntry(drawer, ref args, maxWidth, x, ref y, ref headerEntry); maxIndex = table.Count; y += 5; for (int i = table.CurrentIndex; i < table.Count; i++) { TableEntry entry = table.Get(i); args = new DrawTextArgs(filter(entry), font, true); if ((i == table.SelectedIndex || entry.Featured) && !separator) { int startY = y - 3; int height = Math.Min(startY + (entryHeight + 4), table.Y + table.Height) - startY; drawer.Clear(GetGridCol(entry.Featured, i == table.SelectedIndex), table.X, startY, table.Width, height); } if (!DrawColumnEntry(drawer, ref args, maxWidth, x, ref y, ref entry)) { maxIndex = i; break; } } if (separator && !game.ClassicBackground) { drawer.Clear(LauncherSkin.BackgroundCol, x - 7, table.Y, 2, table.Height); } return(maxWidth + 5); }
public static void ClearStaticValues() { _Accounts = null; _Columns = null; _TweetTasks = null; _BackgroundLoadColumns = null; #if !BACKGROUND_AGENT _FollowMessageShown = null; _ProtectedAccounts = null; _Filters = null; _GlobalFilter = null; _RetweetAsMentions = null; _TweetsPerRequest = null; _DefaultMuteTime = null; _Drafts = null; _ReadLaterCredentials = null; _Background = null; _FirstInit = null; _FontSize = null; _ReadPositions = null; _RecoverReadPositions = null; _EnabledGeolocation = null; _TweetGeotagging = null; _BufferProfiles = null; _BufferAccessToken = null; _TrialStart = null; _CouponCodeValidated = null; _ReloadOptions = null; _TopicPlace = null; _TopicPlaceId = null; #endif }
/// <summary> /// Update the internal filter /// </summary> /// <param name="textBox"></param> /// <param name="header"></param> private void UpdateFilter(TextBox textBox, DataGridColumnHeader header) { // Try to get the property bound to the column. // This should be stored as datacontext. string columnName = header.DataContext != null? header.DataContext.ToString() : ""; ColumnFilter filter; if (!columnFilters.TryGetValue(columnName, out filter)) { var dataGridBoundColumn = header.Column as DataGridBoundColumn; if (dataGridBoundColumn != null) { var binding = dataGridBoundColumn.Binding as Binding; if (binding != null) { filter = new ColumnFilter { ColumnName = columnName, ColumnBinding = binding }; columnFilters.Add(filter.ColumnName, filter); } } } if (filter != null) { filter.FilterValue = textBox.Text; } }
/// // private void remember_textbox_list(TextBox filterTextBox, DataGridColumnHeader header) // { // int i = 9; // List<TextBox> new_list = new List<TextBox>();/ // // m_filtertb.Add(filterTextBox); //pestrela: clear filter feature // // } // public void ClearFiltering() { var a = filtering_textBoxes; // clear the text boxes foreach (KeyValuePair <string, TextBox> entry in filtering_textBoxes) { String key = entry.Key; TextBox tb = entry.Value; String old_contents = tb.Text; tb.Text = ""; } // also clear the internal filters foreach (KeyValuePair <string, ColumnFilter> entry in columnFilters) { String key = entry.Key; ColumnFilter filter = entry.Value; filter.FilterValue = ""; } ApplyFilters(); }
public void SetFilter(LogViewer.LogColumnType column, string pattern) { if (string.IsNullOrEmpty(pattern)) { m_Filters[column] = s_MatchAllFilter; return; } var isNegated = pattern.StartsWith(NegationPrefix) && pattern.Length > NegationPrefix.Length; var regexPattern = pattern; if (isNegated) { regexPattern = pattern.Substring(NegationPrefix.Length); } var access = MakeLineAccess(column); var regex = new Regex(regexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); var filter = new ColumnFilter(pattern, l => { var isMatch = regex.IsMatch(access(l) ?? string.Empty); return(isNegated ? !isMatch : isMatch); }); m_Filters[column] = filter; }
public void SplitLineIntoColumn() { //columnfilter string line = "12/09/2020 , comment written"; string[] columns = ColumnFilter.ApplyColumnFilter(line, 0, 1); string[] actualColumn = line.Split(','); Assert.True(columns[0] == actualColumn[0] && columns[1] == actualColumn[1]); }
/// <summary> /// Filters the grid based on tool. /// </summary> /// <param name="tool">The tool.</param> private void FilterGridBasedOnTool(RadialMenuTool tool) { string key = tool.Key; CategoryType category; try { // get the CategoryType from the Tag if (tool.Tag is CategoryType) { category = (CategoryType)tool.Tag; // if the currentGridData is still the defualt data, bind the Inventory data to the grid if (this.currentGridData == MainForm.DefaultGridData) { this.gridInventory.DataSource = AutoPartsCatalog.Instance.InventoryTable; this.currentGridData = UI.Inventory; } // apply a filter to the Category column based on the CategoryType UltraGridBand band = this.gridInventory.DisplayLayout.Bands["Inventory"]; ColumnFilter filter = band.ColumnFilters["Category"]; if (filter.FilterConditions.Count > 0) { filter.FilterConditions[0].CompareValue = (int)category; } else { filter.FilterConditions.Add(FilterComparisionOperator.Equals, (int)category); } // add secondary filter to the Components column filter = band.ColumnFilters["Component"]; if (string.IsNullOrEmpty(key) == false) { if (filter.FilterConditions.Count > 0) { filter.FilterConditions[0].CompareValue = key; } else { filter.FilterConditions.Add(FilterComparisionOperator.Equals, key); } } else { filter.ClearFilterConditions(); } this.ChangeHeader(category, key); } } finally { this.gridInventory.DisplayLayout.PerformAutoResizeColumns(false, PerformAutoSizeType.VisibleRows); } }
public static FileImporter DetectFileType(string path) { if (path.ToLower().EndsWith(".sail")) { throw new Exception(@".sail files cannot be imported, use ""open"" instead."); } else if (path.ToLower().EndsWith(".gpx") /*&& ValidateXmlWithSchema(path, GpxImporter.GpxXsdUrl,GpxImporter.GpxXsdPath)*/) { GpxImporter gi = new GpxImporter(); return(gi); } else if (path.ToLower().EndsWith(".kml") /*&& ValidateXmlWithSchema(path, KmlImporter.KmlXsdUrl, KmlImporter.KmlXsdPath)*/) { KmlImporter ki = new KmlImporter(); return(ki); } else if (path.ToLower().EndsWith(".vcc")) { VccImporter vi = new VccImporter(); return(vi); } else { StreamReader reader = new StreamReader(path); string firstLine = reader.ReadLine(); reader.Close(); if (firstLine.Contains(",")) { //possibly a csv format char[] splitter = new char[] { ',' }; string[] parts = firstLine.Split(splitter); if (parts[0].StartsWith("$") || parts[0].StartsWith("!")) { NmeaImporter ni = new NmeaImporter(); return(ni); } else { //csv format List <string> mappings = CsvImporter.AutoDetectColumnMappings(parts); ColumnAssignment ca = new ColumnAssignment(mappings, path); ca.ShowDialog(); mappings = ca.ColumnMappings; ColumnFilter cf = new ColumnFilter(ca.Filters, path, ca.SkipFirstRow); CsvImporter ci = new CsvImporter(mappings, cf.FilterValues, ca.SkipFirstRow); return(ci); } } else { throw new Exception("Format Could not be determined"); } } }
public static void InitializeColumnInfo(IExplorerViewModel explorerModel) { explorerModel.FileList.Columns.ColumnList = new ColumnInfo[] { ColumnInfo.FromTemplate("Name", "GridLabelTemplate", "EntryModel.Label", new ValueComparer <IEntryModel>(p => p.Label), 200), ColumnInfo.FromBindings("Type", "EntryModel.Description", "", new ValueComparer <IEntryModel>(p => p.Description), 200), ColumnInfo.FromBindings("Time", "EntryModel.LastUpdateTimeUtc", "", new ValueComparer <IEntryModel>(p => (p is DiskEntryModelBase) ? (p as DiskEntryModelBase).LastUpdateTimeUtc : DateTime.MinValue), 200), ColumnInfo.FromTemplate("Size", "GridSizeTemplate", "", new ValueComparer <IEntryModel>(p => (p is DiskEntryModelBase) ? (p as DiskEntryModelBase).Size : 0), 200), ColumnInfo.FromBindings("FSI.Attributes", "EntryModel.Attributes", "", new ValueComparer <IEntryModel>(p => (p is FileSystemInfoModel) ? (p as FileSystemInfoModel).Attributes : System.IO.FileAttributes.Normal), 200) }; explorerModel.FileList.Columns.ColumnFilters = new ColumnFilter[] { ColumnFilter.CreateNew <IEntryModel>("0 - 9", "EntryModel.Label", e => Regex.Match(e.Label, "^[0-9]").Success), ColumnFilter.CreateNew <IEntryModel>("A - H", "EntryModel.Label", e => Regex.Match(e.Label, "^[A-Ha-h]").Success), ColumnFilter.CreateNew <IEntryModel>("I - P", "EntryModel.Label", e => Regex.Match(e.Label, "^[I-Pi-i]").Success), ColumnFilter.CreateNew <IEntryModel>("Q - Z", "EntryModel.Label", e => Regex.Match(e.Label, "^[Q-Zq-z]").Success), ColumnFilter.CreateNew <IEntryModel>("The rest", "EntryModel.Label", e => Regex.Match(e.Label, "^[^A-Za-z0-9]").Success), ColumnFilter.CreateNew <IEntryModel>("Today", "EntryModel.LastUpdateTimeUtc", e => { DateTime dt = DateTime.UtcNow; return(e.LastUpdateTimeUtc.Year == dt.Year && e.LastUpdateTimeUtc.Month == dt.Month && e.LastUpdateTimeUtc.Day == dt.Day); }), ColumnFilter.CreateNew <IEntryModel>("Earlier this month", "EntryModel.LastUpdateTimeUtc", e => { DateTime dt = DateTime.UtcNow; return(e.LastUpdateTimeUtc.Year == dt.Year && e.LastUpdateTimeUtc.Month == dt.Month); }), ColumnFilter.CreateNew <IEntryModel>("Earlier this year", "EntryModel.LastUpdateTimeUtc", e => { DateTime dt = DateTime.UtcNow; return(e.LastUpdateTimeUtc.Year == dt.Year); }), ColumnFilter.CreateNew <IEntryModel>("A long time ago", "EntryModel.LastUpdateTimeUtc", e => { DateTime dt = DateTime.UtcNow; return(e.LastUpdateTimeUtc.Year != dt.Year); }), ColumnFilter.CreateNew <IEntryModel>("Directories", "EntryModel.Description", e => e.IsDirectory), ColumnFilter.CreateNew <IEntryModel>("Files", "EntryModel.Description", e => !e.IsDirectory) }; }
public async Task <IEnumerable <FilteredUser> > SearchAsync(int residenitalId, string name) { var columnsToFilter = ColumnFilter.GetNames <UserEf>(x => x.Name, x => x.LastName, x => x.Email); var entities = await _repository.AsNoTracking() .Where(x => x.ResidentialId == residenitalId) .Contains(name, columnsToFilter).ToListAsync(); return(_mapper.Map <IEnumerable <FilteredUser> >(entities)); }
private void setFilter(string value) { _selectedFilter = value; FileList.ProcessedEntries.SetFilters( ColumnFilter.CreateNew <IEntryModel>(value, "FullPath", e => e.IsDirectory || PathFE.MatchFileMasks( e.Profile.Path.GetFileName(e.FullPath), value))); NotifyOfPropertyChange(() => SelectedFilter); }
void updateFilters() { //if (All.Filter == null) All.Filter = (e) => e != null && CustomFilter(e) && ColumnFilter.Match(_colFilters, _filterObjectGetter((VM)e)); //else // All.Filter = (e) => // All.Filter(e) && CustomFilter(e) && // ColumnFilter.Match(_colFilters, (e as IEntryViewModel).EntryModel); }
public ColumnFilter BuildStatement <TEntity>(string key, string value, StatementOperation operation = StatementOperation.Equals) where TEntity : BaseEntity { var baseTableName = this.queryBuilder.GetTableName <TEntity>(); var result = new ColumnFilter(); result.KeyName = $"{baseTableName}.{key}"; result.Filter = this.statementBuilder[operation].Invoke(result.KeyName, $"@{result.Params.Count}"); result.Params.Add(new SqlParameter($"@{result.Params.Count}", value)); return(result); }
private bool IntFilter(int value, string filterExpression, ColumnFilter column) { if (string.IsNullOrEmpty(filterExpression)) { column.InvalidFilter = false; return(true); } filterExpression = StringHelper.RemoveAllWhitespace(filterExpression); int lenght = filterExpression.Length; int filterInt; if (int.TryParse(filterExpression, out filterInt)) { column.InvalidFilter = false; return(filterInt == value); } else if (lenght > 2 && filterExpression.Contains('_')) { var parts = filterExpression.Split('_'); if (parts.Length == 2) { if (int.TryParse(parts[0], out int i1) && int.TryParse(parts[1], out int i2) && i1 < i2) { column.InvalidFilter = false; return(value >= i1 && value <= i2); } } } else if (filterExpression.StartsWith("<") && lenght > 1 && int.TryParse(filterExpression.Remove(0, 1), out filterInt)) { column.InvalidFilter = false; return(value < filterInt); } else if (filterExpression.StartsWith("<=") && lenght > 2 && int.TryParse(filterExpression.Remove(0, 2), out filterInt)) { column.InvalidFilter = false; return(value <= filterInt); } else if (filterExpression.StartsWith(">") && lenght > 1 && int.TryParse(filterExpression.Remove(0, 1), out filterInt)) { column.InvalidFilter = false; return(value > filterInt); } else if (filterExpression.StartsWith(">=") && lenght > 2 && int.TryParse(filterExpression.Remove(0, 2), out filterInt)) { column.InvalidFilter = false; return(value >= filterInt); } column.InvalidFilter = true; return(false); }
private Statement GetDateTimeFilterClause(ColumnFilter filter) { var clauseParameters = new List <DBParameterKeyValue>(); var clauseText = string.Empty; for (var i = 0; i < filter.Values.Count(); i++) { var currentValue = filter.Values.ElementAt(i); DateTime parsedValue; if (DateTime.TryParseExact(currentValue, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedValue) || DateTime.TryParseExact(currentValue, @"yyyy-MM-dd\THH:mm:ss\Z", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedValue) || DateTime.TryParseExact(currentValue, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedValue)) { // Current format sample: '2019-05-14 14:44:39' currentValue = $"{parsedValue.Year.ToString("D4")}-{parsedValue.Month.ToString("D2")}-{parsedValue.Day.ToString("D2")}"; currentValue += $" {parsedValue.Hour.ToString("D2")}:{parsedValue.Minute.ToString("D2")}:{parsedValue.Second.ToString("D2")}"; } if (i != 0) { clauseText += filter.FilterMethod == FilterMethod.Including ? " OR " : " AND "; } if (filter.FilterRigor == FilterRigor.Contains) { clauseText += $" CONVERT(varchar(19), {filter.Column.Name.SanitizeSQL()}, 20)"; if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += " NOT"; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("DateTimeFilterValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $" LIKE '%' + {filterValueParameter.Key} + '%'"; } else if (filter.FilterRigor == FilterRigor.Equals) { clauseText += $" CONVERT(DATETIME, CONVERT(VARCHAR(19), {filter.Column.Name.SanitizeSQL()}, 20)) "; if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += "!"; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("DateTimeFilterValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $"= {filterValueParameter.Key}"; } } return(new Statement(clauseText, clauseParameters)); }
public SLORMContext Filter(ColumnFilterRequest filterRequest) { if (filterRequest == null) { throw new ArgumentNullException(nameof(filterRequest)); } var column = ColumnsInTable.GetFromName(filterRequest.ColumnName); if (column == null) { return(this); } // Filtering incorrect value formats if (filterRequest.FilterRigor == FilterRigor.Equals) { switch (column.DataType) { case ColumnDataType.Number: double parsedValue; foreach (var currentValue in filterRequest.Values) { if (!double.TryParse(currentValue, out parsedValue)) { return(this); } } break; case ColumnDataType.Date: DateTime parsedDateValue; foreach (var currentValue in filterRequest.Values) { if (!DateTime.TryParse(currentValue, out parsedDateValue)) { return(this); } } break; } } var columnToFilter = new ColumnFilter(column, filterRequest); ColumnsToFilter.Add(columnToFilter); return(this); }
private static OperatorEnum GetOperator(this ColumnFilter filter) { OperatorEnum?result = null; switch (filter.Operation.ToLower()) { case "equlas": case "equals": result = OperatorEnum.Equals; break; case "notEquals": result = OperatorEnum.NotEquals; break; case "lessthan": result = OperatorEnum.LessThan; break; case "greaterthan": result = OperatorEnum.GreaterThan; break; case "contains": result = OperatorEnum.Contains; break; case "notcontains": result = OperatorEnum.NotContains; break; case "startswith": result = OperatorEnum.StartsWith; break; case "endswith": result = OperatorEnum.EndsWith; break; default: result = null; break; } if (!result.HasValue) { throw new InvalidOperationException(); } return(result.Value); }
public string ParseFilter(ColumnFilter filter) { switch (filter.Type) { default: case FilterType.Equals: return($"{filter.Column} = '{filter.Value.ToString()}'"); case FilterType.Like: return($"{filter.Column} LIKE '%{filter.Value.ToString()}%'"); case FilterType.NotLike: return($"{filter.Column} NOT LIKE '%{filter.Value.ToString()}%'"); } }
public void ThrowExceptionIfColumnNumberIsOutOfRange(int expectedColumnNumber) { const string csvPath = @"D:\a\review-case-s21b11\review-case-s21b11\sample-review\review-report.csv"; var checkPath = PathExistence.CheckFileExistOrNot(csvPath); if (checkPath) { var lines = System.IO.File.ReadAllLines(csvPath); Assert.Throws <System.IndexOutOfRangeException>(() => ColumnFilter.PrintCsvColumn(lines, expectedColumnNumber)); } else { Assert.True(false); } }
public async Task <PaginatedList <ExpenseCategory> > GetAllAsync(int residentialId, Parameter parameter) { var columnsToFilter = ColumnFilter.GetNames <ExpenseCategoryEf>(x => x.Name, x => x.Description); var query = _repository.AsNoTracking() .Where(x => x.ResidentialId == residentialId) .Contains(parameter.Filter, columnsToFilter).ApplySort(parameter.SortBy, parameter.IsSortDesc); var totalOfItems = await query.CountAsync(); var entities = await query.Take(parameter.Page, parameter.ItemsPerPage).ToListAsync(); var models = _mapper.Map <IEnumerable <ExpenseCategory> >(entities); return(new PaginatedList <ExpenseCategory>(models, totalOfItems)); }
private FrmMain ConfigureColumnFilter() { ColumnFilter = new ColumnFilter() .ConfigureVisibility("DOCUMENTO", () => chkDocumento.Checked) .ConfigureVisibility("DTNASC", () => chkDtNasc.Checked) .ConfigureVisibility("NOME", () => chkNome.Checked) .ConfigureVisibility("ENDERECO", () => chkEndereco.Checked) .ConfigureVisibility("NUM", () => chkNumero.Checked) .ConfigureVisibility("COMP", () => chkComplemento.Checked) .ConfigureVisibility("BAIRRO", () => chkBairro.Checked) .ConfigureVisibility("CIDADE", () => chkCidade.Checked) .ConfigureVisibility("CEP", () => chkCep.Checked) .ConfigureVisibility("PAI", () => chkPai.Checked) .ConfigureVisibility("MAE", () => chkMae.Checked); return(this); }
public async Task <PaginatedList <User> > GetAllAsync(int residenitalId, Parameter parameter) { var columnsToFilter = ColumnFilter.GetNames <UserEf>(x => x.Name, x => x.LastName, x => x.Email); var query = _repository.AsNoTracking() .Where(x => x.ResidentialId == residenitalId) .Include(x => x.Residential).Include(x => x.UserRoles).ThenInclude(x => x.Role) .Contains(parameter.Filter, columnsToFilter).ApplySort(parameter.SortBy, parameter.IsSortDesc); var totalOfItems = await query.CountAsync(); var entities = await query.Take(parameter.Page, parameter.ItemsPerPage).ToListAsync(); var models = _mapper.Map <IEnumerable <User> >(entities); return(new PaginatedList <User>(models, totalOfItems)); }
public void FullConstructor_WhenValidArguments_ShouldReturnInstanceWithCorrectData() { // Arrange var column = new TableColumn("columnName", Enums.ColumnDataType.Date); var valueToFilter = new List <string>() { "aa" }; var filterRigor = FilterRigor.Contains; var filterMethod = FilterMethod.Excluding; // Act var columnFilter = new ColumnFilter(column, valueToFilter, filterRigor, filterMethod);; // Assert Assert.Equal(column, columnFilter.Column); Assert.Equal(filterRigor, columnFilter.FilterRigor); Assert.Equal(filterMethod, columnFilter.FilterMethod); }
private Statement GetNumberFilterClause(ColumnFilter filter) { var clauseParameters = new List <DBParameterKeyValue>(); var clauseText = string.Empty; var sanitizedColumnName = filter.Column.Name.SanitizeSQL(); for (var i = 0; i < filter.Values.Count(); i++) { var currentValue = filter.Values.ElementAt(i); if (i != 0) { clauseText += filter.FilterMethod == FilterMethod.Including ? " OR " : " AND "; } if (filter.FilterRigor == FilterRigor.Contains) { clauseText += $" CONVERT(varchar(64), {sanitizedColumnName})"; if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += " NOT"; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("FilterNumberValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $" LIKE '%' + {filterValueParameter.Key} + '%'"; } else if (filter.FilterRigor == FilterRigor.Equals) { clauseText += $" {sanitizedColumnName} "; if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += "!"; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("FilterNumberValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $"= {filterValueParameter.Key}"; } } return(new Statement(clauseText, clauseParameters)); }
/// <summary> /// Updates the header. /// </summary> private void UpdateHeader() { switch (this.ultraTabControl1.SelectedTab.Key) { case "SearchGrid": if (this.currentGridData == UI.Delivery) { this.lblCurrent.Text = Properties.Resources.PendingDeliveries; this.lblPrevious.Text = string.Empty; return; } CategoryType category; UltraGridBand band = this.gridInventory.DisplayLayout.Bands["Inventory"]; ColumnFilter filter = band.ColumnFilters["Category"]; if (filter.FilterConditions.Count > 0) { category = (CategoryType)filter.FilterConditions[0].CompareValue; string subCategory = string.Empty; filter = band.ColumnFilters["Component"]; if (filter.FilterConditions.Count > 0) { subCategory = (string)filter.FilterConditions[0].CompareValue; } this.ChangeHeader(category, subCategory); } else { // shouldn't get here Debug.Fail(""); this.lblCurrent.Text = string.Empty; this.lblPrevious.Text = string.Empty; } break; case "DeliverySchedule": this.lblCurrent.Text = Properties.Resources.Deliveries; this.lblPrevious.Text = string.Empty; break; } }
private Statement getStringFilterClause(ColumnFilter filter) { var clauseParameters = new List <DBParameterKeyValue>(); var clauseText = $"( {filter.Column.Name.SanitizeSQL()} "; for (var i = 0; i < filter.Values.Count(); i++) { var currentValue = filter.Values.ElementAt(i); if (i != 0) { clauseText += filter.FilterMethod == FilterMethod.Including ? " OR" : " AND"; clauseText += $" {filter.Column.Name.SanitizeSQL()} "; } if (filter.FilterRigor == FilterRigor.Contains) { if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += "NOT "; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("StringFilterValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $"LIKE '%' + {filterValueParameter.Key} + '%'"; } else if (filter.FilterRigor == FilterRigor.Equals) { if (filter.FilterMethod == FilterMethod.Excluding) { clauseText += "!"; } var filterValueParameter = new DBParameterKeyValue(GetParameterName("StringFilterValue"), currentValue); clauseParameters.Add(filterValueParameter); clauseText += $"= {filterValueParameter.Key}"; } } clauseText += " )"; return(new Statement(clauseText, clauseParameters)); }
public List<string> GetColumns(ColumnFilter filter) { StreamReader reader = new StreamReader(pcaxisFile); /* * String to hold PC-AXIS records. */ String record = ""; /* * String to hold PC-AXIS keyword of each record. */ String keyword = ""; /* * Strings to hold info for CSV header line. */ String heading = ""; String stub = ""; String contents = null; /* * Keeps all the Keywords found in the file */ string contVariable = ""; //holds all the keywords to be used as columns Dictionary<string, ColumnInformation> keywordsUsed = new Dictionary<string, ColumnInformation>(); //Regex extractRecord = new Regex("^(?<keyword>[^\\(=]+)(\\((?<var>\"[^\"]+\")\\))?=(TLIST\\((?<tlist>.+)\\),?)?(?<value>[^;]*);$", RegexOptions.IgnoreCase | RegexOptions.Singleline); bool stopreading = false; while (!reader.EndOfStream && !stopreading) { /* * The following is required because we are not sure if a delimiter * has been used at the end of each line for the DATA record. * Later on, we use \n as a delimiter. */ string val = null; record += '\n'; string firstSection = GetFirstLineSection(reader); if (firstSection.ToLower() == "data=") { stopreading = true; break; } if (!reader.EndOfStream) record += firstSection + reader.ReadLine().Trim(); else record += firstSection; if (record.EndsWith(";", StringComparison.InvariantCulture)) { /* * Record complete. Trim unecessary whitespace. */ record = record.Trim(); Match m = extractRecord.Match(record); keyword = m.Groups["keyword"].Value; val = m.Groups["value"].Value.Trim(); if (keyword.Equals("CONTENTS", StringComparison.InvariantCultureIgnoreCase)) { contents = val; } else if (keyword.Equals("STUB", StringComparison.InvariantCultureIgnoreCase)) { stub = val; } else if (keyword.Equals("HEADING", StringComparison.InvariantCultureIgnoreCase)) { heading = val; //} else if ( // keyword.Equals("MATRIX", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SUBJECT-CODE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SUBJECT-AREA", StringComparison.InvariantCultureIgnoreCase) // || keyword.Equals("UNITS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DECIMALS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("TITLE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase) // || keyword.Equals("UPDATE-FREQUENCY", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("TABLE_ID", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SOURCE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DATABASE", StringComparison.InvariantCultureIgnoreCase) // || keyword.Equals("REFPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("BASEPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CONTENTS", StringComparison.InvariantCultureIgnoreCase) // || keyword.Equals("LAST-UPDATED", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("STOCKFA", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CFPRICES", StringComparison.InvariantCultureIgnoreCase) // || keyword.Equals("DAYADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SEASADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("UNITS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CONTACT", StringComparison.InvariantCultureIgnoreCase) // ) { // if (!keywordsUsed.Contains(keyword)) // keywordsUsed.Add(keyword); } else if (keyword.Equals("CONTVARIABLE", StringComparison.InvariantCultureIgnoreCase)) { contVariable = val.Replace("\"", "").Replace("#", " ").Replace("\n", " "); } else if (record.StartsWith(keyword + "=") && ( keyword.Equals("MATRIX", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SUBJECT-CODE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SUBJECT-AREA", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("UNITS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DECIMALS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("TITLE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("UPDATE-FREQUENCY", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("TABLE_ID", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SOURCE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DATABASE", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("REFPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("BASEPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CONTENTS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("LAST-UPDATED", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("STOCKFA", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CFPRICES", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DAYADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SEASADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("UNITS", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CONTACT", StringComparison.InvariantCultureIgnoreCase) ) ) { if (!keywordsUsed.ContainsKey(keyword)) { ColumnInformation ci = new ColumnInformation(); ci.ColumnName = FormatColumnHeader(keyword); val = val.Replace("\"", "").Replace("#", " ").Replace("\n", " "); ci.Value = val; keywordsUsed[keyword] = ci; } } else if (!string.IsNullOrEmpty(contVariable) && record.StartsWith(keyword + "(") && ( keyword.Equals("REFPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("BASEPERIOD", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CONTACT", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("LAST-UPDATED", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("STOCKFA", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("CFPRICES", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("DAYADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("SEASADJ", StringComparison.InvariantCultureIgnoreCase) || keyword.Equals("UNITS", StringComparison.InvariantCultureIgnoreCase) ) ) { if (!keywordsUsed.ContainsKey(keyword)) { ColumnInformation ci = new ColumnInformation(); ci.ColumnName = FormatColumnHeader(keyword); ci.IsContVar = true; val = val.Replace("\"", "").Replace("#", " ").Replace("\n", " "); //ci.Values.Add(variable, val); keywordsUsed[keyword] = ci; } else { ColumnInformation ci = keywordsUsed[keyword]; ci.ColumnName = FormatColumnHeader(keyword); ci.IsContVar = true; val = val.Replace("\"", "").Replace("#", " ").Replace("\n", " "); //ci.Values.Add(variable, val); } } else if (keyword.Equals("TIMEVAL", StringComparison.InvariantCultureIgnoreCase)) { string tList = m.Groups["tlist"].Value; char freq = tList[0]; ColumnInformation ci = new ColumnInformation(); ci.ColumnName = "FREQ"; ci.Value = freq.ToString(); keywordsUsed["FREQ"] = ci; ci = new ColumnInformation(); ci.ColumnName = "TIME_FORMAT"; ci.Value = TransformFREQToSDMXFormat(freq.ToString()); keywordsUsed["TIME_FORMAT"] = ci; } record = ""; } } char separator = ','; /* * Prepare CSV header String and write it. */ if (!String.IsNullOrEmpty(stub)) { stub += separator; } if (!String.IsNullOrEmpty(heading)) { heading += separator; } if (contents == null) { Console.WriteLine("NO CONTENTS RECORD DEFINED! MANDATORY!"); } String csvHeaderString = stub + heading + contents + ",\"OBS_STATUS\""; List<string> headers = GetColumnHeaders(csvHeaderString); List<string> retval = new List<string>(); if (filter == ColumnFilter.All || filter == ColumnFilter.Main) foreach (string header in headers) { retval.Add(header.Replace("\"", "")); } if(filter!= ColumnFilter.Main && filter!= ColumnFilter.ContVariable) foreach (ColumnInformation col in keywordsUsed.Values) { if(filter== ColumnFilter.KeywordsSingleValue && !col.IsContVar || filter== ColumnFilter.ContVariableKeywords && col.IsContVar || filter == ColumnFilter.All) retval.Add(col.ColumnName); } if (filter == ColumnFilter.ContVariable) retval.Add(FormatColumnHeader(contVariable)); return retval; }
/// <summary> /// Tries to create a filter descriptor that filters this field using the value returned by this mapping. /// </summary> /// <param name="dataContext"> /// The data context. /// </param> /// <param name="filter"> /// The filter. /// </param> /// <returns> /// <c>true</c> if the filter was created successfully; otherwise, <c>false</c>. /// </returns> public bool TryCreateFilter(IDataContext dataContext, out ColumnFilter filter) { filter = null; return false; }
/// <summary> /// Tries to create a filter descriptor that filters this field using the value returned by this mapping. /// </summary> /// <param name="dataContext"> /// The data context. /// </param> /// <param name="filter"> /// The filter. /// </param> /// <returns> /// <c>true</c> if the filter was created successfully; otherwise, <c>false</c>. /// </returns> public bool TryCreateFilter(IDataContext dataContext, out ColumnFilter filter) { filter = null; var value = GetValue(dataContext); if (value == null) return false; if (string.Empty.Equals(value)) return false; if (DateTime.MinValue.Equals(value)) return false; filter = new ColumnFilter(Property.Name, value); return true; }
/// <summary> /// Tries to create a filter descriptor that filters this field using the value returned by this mapping. /// </summary> /// <param name="dataContext"> /// The data context. /// </param> /// <param name="filter"> /// The filter. /// </param> /// <returns> /// <c>true</c> if the filter was created successfully; otherwise, <c>false</c>. /// </returns> public bool TryCreateFilter(IDataContext dataContext, out ColumnFilter filter) { filter = null; var itemId = GetCrossReferenceItemId(dataContext); if (itemId == null) return false; filter = new ColumnFilter(Property.Name, itemId); return true; }
/// <summary> /// Loads the filter control /// </summary> /// <param name="path">Control path</param> /// <param name="fieldSourceName">Field source name</param> /// <param name="value">Field value</param> /// <param name="filterDefinition">Filter definition</param> /// <param name="filterColumn">Filter column</param> private CMSAbstractBaseFilterControl LoadFilterControl(string path, string fieldSourceName, string value, UniGridFilterField filterDefinition, ColumnFilter filterColumn = null) { string fullPath = (path.StartsWithCSafe("~/") ? path : FilterDirectoryPath + path.TrimStart('/')); // Load the filter control CMSAbstractBaseFilterControl filterControl = LoadUserControl(fullPath) as CMSAbstractBaseFilterControl; if (filterControl != null) { // Setup the filter control filterControl.ID = fieldSourceName; filterControl.FilteredControl = this; if (!RequestHelper.IsPostBack()) { filterControl.Value = value; } filterDefinition.ValueControl = filterControl; filterDefinition.ControlPath = path; ISimpleDataContainer filterSimpleDataContainer = filterControl as ISimpleDataContainer; // If filter control is ISimpleDataContainer we can set specified parameters if they are provided if (filterColumn != null && filterSimpleDataContainer != null && filterColumn.CustomFilterParameters != null && filterColumn.CustomFilterParameters.Parameters != null) { filterColumn.CustomFilterParameters.Parameters.ForEach(parameter => filterSimpleDataContainer.SetValue(parameter.Name, parameter.Value)); } } return filterControl; }
/// <summary> /// Add filter field to the filter table. /// </summary> /// <param name="filter">Filter definition</param> /// <param name="columnSourceName">Column source field name</param> /// <param name="fieldDisplayName">Field display name</param> /// <param name="filterWrapperControl">Wrapper control for filter</param> /// <param name="filterValue">Filter value</param> private void AddFilterField(ColumnFilter filter, string columnSourceName, string fieldDisplayName, Control filterWrapperControl, string filterValue) { string fieldSourceName = filter.Source ?? columnSourceName; if (String.IsNullOrEmpty(fieldSourceName) || (filter == null) || (filterWrapperControl == null)) { return; } string fieldPath = filter.Path; string filterFormat = filter.Format; int filterSize = filter.Size; Unit filterWidth = filter.Width; Panel fieldWrapperPanel = new Panel() { CssClass = "form-group" }; Panel fieldLabelPanel = new Panel() { CssClass = "filter-form-label-cell" }; Panel fieldOptionPanel = new Panel() { CssClass = "filter-form-condition-cell" }; Panel fieldInputPanel = new Panel() { CssClass = "filter-form-value-cell" }; // Ensure fieldSourceName is JavaScript valid fieldSourceName = fieldSourceName.Replace(ALL, "__ALL__"); int index = GetNumberOfFilterFieldsWithSameSourceColumn(fieldSourceName); string filterControlID = fieldSourceName + (index > 0 ? index.ToString() : String.Empty); Label textName = new Label { Text = String.IsNullOrEmpty(fieldDisplayName) ? String.Empty : fieldDisplayName + ":", ID = String.Format("{0}Name", filterControlID), EnableViewState = false, CssClass = "control-label" }; fieldLabelPanel.Controls.Add(textName); fieldWrapperPanel.Controls.Add(fieldLabelPanel); // Filter value string value = null; if (filterValue != null) { value = ValidationHelper.GetString(filterValue, null); } // Filter definition UniGridFilterField filterDefinition = new UniGridFilterField(); filterDefinition.Type = filter.Type; filterDefinition.Label = textName; filterDefinition.Format = filterFormat; filterDefinition.FilterRow = fieldWrapperPanel; // Set the filter default value string defaultValue = filter.DefaultValue; // Remember default values of filter field controls for potential UniGrid reset string optionFilterFieldValue = null; string valueFilterFieldValue = null; switch (filterDefinition.Type) { // Text filter case UniGridFilterTypeEnum.Text: { CMSDropDownList textOptionFilterField = new CMSDropDownList(); ControlsHelper.FillListWithTextSqlOperators(textOptionFilterField); textOptionFilterField.ID = filterControlID; // Set the value SetDropdownValue(value, null, textOptionFilterField); optionFilterFieldValue = textOptionFilterField.SelectedValue; LocalizedLabel lblSelect = new LocalizedLabel { EnableViewState = false, CssClass = "sr-only", AssociatedControlID = textOptionFilterField.ID, ResourceString = "filter.mode" }; fieldOptionPanel.Controls.Add(lblSelect); fieldOptionPanel.Controls.Add(textOptionFilterField); fieldWrapperPanel.Controls.Add(fieldOptionPanel); CMSTextBox textValueFilterField = new CMSTextBox { ID = String.Format("{0}TextValue", filterControlID) }; // Set value SetTextboxValue(value, defaultValue, textValueFilterField); valueFilterFieldValue = textValueFilterField.Text; if (filterSize > 0) { textValueFilterField.MaxLength = filterSize; } if (!filterWidth.IsEmpty) { textValueFilterField.Width = filterWidth; } fieldInputPanel.Controls.Add(textValueFilterField); fieldWrapperPanel.Controls.Add(fieldInputPanel); textName.AssociatedControlID = textValueFilterField.ID; filterDefinition.OptionsControl = textOptionFilterField; filterDefinition.ValueControl = textValueFilterField; } break; // Boolean filter case UniGridFilterTypeEnum.Bool: { CMSDropDownList booleanOptionFilterField = new CMSDropDownList(); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.selectall"), String.Empty)); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.yes"), "1")); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.no"), "0")); booleanOptionFilterField.ID = filterControlID; textName.AssociatedControlID = booleanOptionFilterField.ID; // Set the value SetDropdownValue(value, defaultValue, booleanOptionFilterField); valueFilterFieldValue = booleanOptionFilterField.SelectedValue; // Set input panel wide for boolean Drop-down list fieldInputPanel.CssClass = "filter-form-value-cell-wide"; fieldInputPanel.Controls.Add(booleanOptionFilterField); fieldWrapperPanel.Controls.Add(fieldInputPanel); filterDefinition.ValueControl = booleanOptionFilterField; } break; // Integer filter case UniGridFilterTypeEnum.Integer: case UniGridFilterTypeEnum.Double: { CMSDropDownList numberOptionFilterField = new CMSDropDownList(); numberOptionFilterField.Items.Add(new ListItem(GetString("filter.equals"), "=")); numberOptionFilterField.Items.Add(new ListItem(GetString("filter.notequals"), "<>")); numberOptionFilterField.Items.Add(new ListItem(GetString("filter.lessthan"), "<")); numberOptionFilterField.Items.Add(new ListItem(GetString("filter.greaterthan"), ">")); numberOptionFilterField.ID = filterControlID; // Set the value SetDropdownValue(value, null, numberOptionFilterField); optionFilterFieldValue = numberOptionFilterField.SelectedValue; LocalizedLabel lblSelect = new LocalizedLabel { EnableViewState = false, CssClass = "sr-only", AssociatedControlID = numberOptionFilterField.ID, ResourceString = "filter.mode" }; // Add filter field fieldOptionPanel.Controls.Add(lblSelect); fieldOptionPanel.Controls.Add(numberOptionFilterField); fieldWrapperPanel.Controls.Add(fieldOptionPanel); CMSTextBox numberValueFilterField = new CMSTextBox { ID = String.Format("{0}NumberValue", filterControlID) }; // Set value SetTextboxValue(value, defaultValue, numberValueFilterField); valueFilterFieldValue = numberValueFilterField.Text; if (filterSize > 0) { numberValueFilterField.MaxLength = filterSize; } if (!filterWidth.IsEmpty) { numberValueFilterField.Width = filterWidth; } numberValueFilterField.EnableViewState = false; fieldInputPanel.Controls.Add(numberValueFilterField); fieldWrapperPanel.Controls.Add(fieldInputPanel); filterDefinition.OptionsControl = numberOptionFilterField; filterDefinition.ValueControl = numberValueFilterField; } break; case UniGridFilterTypeEnum.Site: { // Site selector fieldPath = "~/CMSFormControls/Filters/SiteFilter.ascx"; } break; case UniGridFilterTypeEnum.Custom: // Load custom path { if (String.IsNullOrEmpty(fieldPath)) { throw new Exception("[UniGrid.AddFilterField]: Filter field path is not set"); } } break; default: // Not supported filter type throw new Exception("[UniGrid.AddFilterField]: Filter type '" + filterDefinition.Type + "' is not supported. Supported filter types: integer, double, bool, text, site, custom."); } // Else if filter path is defined use custom filter if (fieldPath != null) { // Add to the controls collection CMSAbstractBaseFilterControl filterControl = LoadFilterControl(fieldPath, filterControlID, value, filterDefinition, filter); if (filterControl != null) { // Set default value if (!String.IsNullOrEmpty(defaultValue)) { filterControl.SelectedValue = defaultValue; } fieldInputPanel.Controls.Add(filterControl); } fieldInputPanel.CssClass = "filter-form-value-cell-wide"; fieldWrapperPanel.Controls.Add(fieldInputPanel); } RaiseOnFilterFieldCreated(fieldSourceName, filterDefinition); FilterFields[String.Format("{0}{1}", fieldSourceName, (index > 0 ? "#" + index : String.Empty))] = filterDefinition; filterWrapperControl.Controls.Add(fieldWrapperPanel); // Store initial filter state for potential UniGrid reset if (filterDefinition.OptionsControl != null) { InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.OptionsControl, optionFilterFieldValue)); } if (filterDefinition.ValueControl != null) { if (!(filterDefinition.ValueControl is CMSAbstractBaseFilterControl)) { InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.ValueControl, valueFilterFieldValue)); } } }
protected bool Equals(ColumnFilter other) { return string.Equals(ColumnCaption, other.ColumnCaption) && Equals(FilterOperation, other.FilterOperation) && string.Equals(Operand, other.Operand); }
/// <summary> /// Add filter field to the filter table. /// </summary> /// <param name="filter">Filter definition</param> /// <param name="columnSourceName">Column source field name</param> /// <param name="fieldDisplayName">Field display name</param> /// <param name="filterTable">Filter table</param> /// <param name="filterOption">Filter option</param> /// <param name="filterValue">Filter value</param> private void AddFilterField(ColumnFilter filter, string columnSourceName, string fieldDisplayName, Table filterTable, object filterOption, object filterValue) { string fieldType = filter.Type; string fieldPath = filter.Path; string filterFormat = filter.Format; string fieldSourceName = filter.Source ?? columnSourceName; int filterSize = filter.Size; Unit filterWidth = filter.Width; TableRow tRow = new TableRow(); TableCell tCellName = new TableCell(); TableCell tCellOption = new TableCell(); TableCell tCellValue = new TableCell(); // Ensure fieldSourceName is JavaScript valid fieldSourceName = fieldSourceName.Replace(ALL, "__ALL__"); // Label Label textName = new Label { Text = String.IsNullOrEmpty(fieldDisplayName) ? "" : fieldDisplayName + ":", ID = fieldSourceName + "Name", EnableViewState = false }; tCellName.Controls.Add(textName); tRow.Cells.Add(tCellName); // Filter option string option = null; if (filterOption != null) { option = ValidationHelper.GetString(filterOption, null); } // Filter value string value = null; if (filterValue != null) { value = ValidationHelper.GetString(filterValue, null); } // Filter definition UniGridFilterField filterDefinition = new UniGridFilterField(); filterDefinition.Type = (fieldType != null) ? fieldType.ToLowerCSafe() : "custom"; filterDefinition.Label = textName; filterDefinition.Format = filterFormat; filterDefinition.FilterRow = tRow; string customPath = null; // Set the filter default value string defaultValue = filter.DefaultValue; // Remember default values of filter field controls for potential UniGrid reset string optionFilterFieldValue = null; string valueFilterFieldValue = null; switch (filterDefinition.Type) { // Text filter case "text": { DropDownList textOptionFilterField = new DropDownList(); textOptionFilterField.Items.Add(new ListItem("LIKE", "LIKE")); textOptionFilterField.Items.Add(new ListItem("NOT LIKE", "NOT LIKE")); textOptionFilterField.Items.Add(new ListItem("=", "=")); textOptionFilterField.Items.Add(new ListItem("<>", "<>")); textOptionFilterField.CssClass = "ContentDropdown"; textOptionFilterField.ID = fieldSourceName; // Set the value SetDropdownValue(value, null, textOptionFilterField); optionFilterFieldValue = textOptionFilterField.SelectedValue; LocalizedLabel lblSelect = new LocalizedLabel { EnableViewState = false, Display = false, AssociatedControlID = textOptionFilterField.ID, ResourceString = "general.select" }; tCellOption.Controls.Add(lblSelect); tCellOption.Controls.Add(textOptionFilterField); tRow.Cells.Add(tCellOption); // Add text field TextBox textValueFilterField = new TextBox { ID = fieldSourceName + "TextValue", CssClass = "FilterTextBox", }; // Set value SetTextboxValue(value, defaultValue, textValueFilterField); valueFilterFieldValue = textValueFilterField.Text; if (filterSize > 0) { textValueFilterField.MaxLength = filterSize; } if (!filterWidth.IsEmpty) { textValueFilterField.Width = filterWidth; } tCellValue.Controls.Add(textValueFilterField); tRow.Cells.Add(tCellValue); textName.AssociatedControlID = textValueFilterField.ID; filterDefinition.OptionsControl = textOptionFilterField; filterDefinition.ValueControl = textValueFilterField; } break; // Boolean filter case "bool": { DropDownList booleanOptionFilterField = new DropDownList(); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.selectall"), "")); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.yes"), "1")); booleanOptionFilterField.Items.Add(new ListItem(GetString("general.no"), "0")); booleanOptionFilterField.CssClass = "ContentDropdown"; booleanOptionFilterField.ID = fieldSourceName; textName.AssociatedControlID = booleanOptionFilterField.ID; // Set the value SetDropdownValue(value, defaultValue, booleanOptionFilterField); valueFilterFieldValue = booleanOptionFilterField.SelectedValue; tCellValue.Controls.Add(booleanOptionFilterField); tRow.Cells.Add(tCellValue); filterDefinition.ValueControl = booleanOptionFilterField; } break; // Integer filter case "integer": case "double": { DropDownList numberOptionFilterField = new DropDownList(); numberOptionFilterField.Items.Add(new ListItem("=", "=")); numberOptionFilterField.Items.Add(new ListItem("<>", "<>")); numberOptionFilterField.Items.Add(new ListItem("<", "<")); numberOptionFilterField.Items.Add(new ListItem(">", ">")); numberOptionFilterField.CssClass = "ContentDropdown"; numberOptionFilterField.ID = fieldSourceName; // Set the value SetDropdownValue(value, null, numberOptionFilterField); optionFilterFieldValue = numberOptionFilterField.SelectedValue; LocalizedLabel lblSelect = new LocalizedLabel { EnableViewState = false, Display = false, AssociatedControlID = numberOptionFilterField.ID, ResourceString = "general.select" }; // Add filter field tCellOption.Controls.Add(lblSelect); tCellOption.Controls.Add(numberOptionFilterField); tRow.Cells.Add(tCellOption); TextBox numberValueFilterField = new TextBox { ID = fieldSourceName + "NumberValue", }; // Set value SetTextboxValue(value, defaultValue, numberValueFilterField); valueFilterFieldValue = numberValueFilterField.Text; if (filterSize > 0) { numberValueFilterField.MaxLength = filterSize; } if (!filterWidth.IsEmpty) { numberValueFilterField.Width = filterWidth; } numberValueFilterField.EnableViewState = false; tCellValue.Controls.Add(numberValueFilterField); tRow.Cells.Add(tCellValue); filterDefinition.OptionsControl = numberOptionFilterField; filterDefinition.ValueControl = numberValueFilterField; } break; case "site": { // Site selector customPath = "~/CMSFormControls/Filters/SiteFilter.ascx"; } break; case "custom": // Load custom path { if (String.IsNullOrEmpty(fieldPath)) { throw new Exception("[UniGrid.AddFilterField]: Filter field path is not set"); } customPath = fieldPath; } break; default: // Not supported filter type throw new Exception("[UniGrid.AddFilterField]: Filter type '" + filterDefinition.Type + "' is not supported. Supported filter types: integer, double, bool, text, site, custom."); } // Else if filter path is defined use custom filter if (customPath != null) { customPath = (customPath.StartsWithCSafe("~/") ? customPath : FilterDirectoryPath + customPath.TrimStart('/')); // Add to the controls collection CMSAbstractBaseFilterControl filterControl = LoadFilterControl(fieldPath, fieldSourceName, value, filterDefinition, customPath); if (filterControl != null) { // Set default value if (!String.IsNullOrEmpty(defaultValue)) { filterControl.SelectedValue = defaultValue; } tCellValue.Controls.Add(filterControl); } tCellValue.Attributes["colspan"] = "2"; tRow.Cells.Add(tCellValue); } RaiseOnFilterFieldCreated(fieldSourceName, filterDefinition); FilterFields[fieldSourceName] = filterDefinition; filterTable.Rows.Add(tRow); // Store initial filter state for potential UniGrid reset if (filterDefinition.OptionsControl != null) { InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.OptionsControl, optionFilterFieldValue)); } if (filterDefinition.ValueControl != null) { if (!(filterDefinition.ValueControl is CMSAbstractBaseFilterControl)) { InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.ValueControl, valueFilterFieldValue)); } } }
public void UpdateTest() { // Arrange. const int CrId1 = 111; const int CrId2 = 222; const string ReferencedProcessName = "CRProcess"; var value1 = new object(); var dataContext = Mock.Create<IDataContext>(Behavior.Loose); var typeConverter = new Mock<ITypeConverter>(); typeConverter.Setup(x => x.Convert<int?>(value1)).Returns(CrId1); var filter = new ColumnFilter("TestField", null); var keyField = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => keyField.IsKey).Returns(true); Mock.Arrange(() => keyField.TryCreateFilter(dataContext, out filter)).Returns(true); var dtm = new Mock<IDynamicTypeManager>(); var runtimeDatabase = Mock.Create<IRuntimeDatabase>(Behavior.Loose); Mock.Arrange(() => runtimeDatabase.FindItems(ReferencedProcessName, Arg.IsAny<IEnumerable<ColumnFilter>>())) .Returns<string, IEnumerable<ColumnFilter>>( (processName, filters) => { var filtersArray = filters.ToArray(); if (filtersArray.Length == 1 && filtersArray.Contains(filter)) return new Collection<int> { CrId2 }; return new Collection<int>(); }); // Update with direct value. var mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), dc => dc == dataContext ? value1 : null, false, typeConverter.Object, dtm.Object, runtimeDatabase, null); var editItem = new TestEditable(); // Act. mapping.Update(dataContext, editItem); // Assert. Assert.AreEqual(CrId1, editItem.CR); // Update with key subfields. mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), null, false, typeConverter.Object, dtm.Object, runtimeDatabase, new[] { keyField }); editItem = new TestEditable(); // Act. mapping.Update(dataContext, editItem); // Assert. Assert.AreEqual(CrId2, editItem.CR); }
public void TryCreateFilterTest() { // Arrange. const string ReferencedProcessName = "CRProcess"; const int Id1 = 111; const int Id2 = 222; var value1 = new object(); var dataContext = Mock.Create<IDataContext>(Behavior.Loose); var filter1 = new ColumnFilter("TestField", null); var keyField1 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => keyField1.IsKey).Returns(true); Mock.Arrange(() => keyField1.TryCreateFilter(dataContext, out filter1)).Returns(true); var filter2 = new ColumnFilter("TestField", null); var keyField2 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => keyField2.IsKey).Returns(true); Mock.Arrange(() => keyField2.TryCreateFilter(dataContext, out filter2)).Returns(true); var dtm = new Mock<IDynamicTypeManager>(); var runtimeDatabase = Mock.Create<IRuntimeDatabase>(Behavior.Loose); Mock.Arrange(() => runtimeDatabase.FindItems(ReferencedProcessName, Arg.IsAny<IEnumerable<ColumnFilter>>())) .Returns<string, IEnumerable<ColumnFilter>>( (processName, filters) => { var filtersArray = Enumerable.ToArray(filters); if (filtersArray.Length == 1 && Enumerable.Contains(filtersArray, filter1)) return new Collection<int> { Id2 }; return new Collection<int>(); }); var typeConverter = Mock.Create<ITypeConverter>(Behavior.Loose); Mock.Arrange(() => typeConverter.Convert<int?>(value1)).Returns(Id1); // CR field is mapped. Value is not null. var mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), dc => dc == dataContext ? value1 : null, false, typeConverter, dtm.Object, runtimeDatabase, null); ColumnFilter filter; // Act / Assert. Assert.IsTrue(mapping.TryCreateFilter(dataContext, out filter)); Assert.AreEqual("CR", filter.ColumnName); Assert.AreEqual(Id1, filter.Value); // CR field is mapped. Value is null. mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), dc => null, false, typeConverter, dtm.Object, runtimeDatabase, null); // Act / Assert. Assert.IsFalse(mapping.TryCreateFilter(dataContext, out filter)); // CR field has key fields. Value is found. mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), null, false, typeConverter, dtm.Object, runtimeDatabase, new[] { keyField1 }); // Act / Assert. Assert.IsTrue(mapping.TryCreateFilter(dataContext, out filter)); Assert.AreEqual("CR", filter.ColumnName); Assert.AreEqual(Id2, filter.Value); // CR field has key fields. Value is not found. mapping = new SingleCrossReferenceFieldMapping( ReflectionHelper.GetProperty<TestEditable>(x => x.CR), null, false, typeConverter, dtm.Object, runtimeDatabase, new[] { keyField2 }); // Act / Assert. Assert.IsFalse(mapping.TryCreateFilter(dataContext, out filter)); }
/// <summary> /// Tries to create a filter descriptor that filters this field using the value returned by this mapping. /// </summary> /// <param name="dataContext"> /// The data context. /// </param> /// <param name="filter"> /// The filter. /// </param> /// <returns> /// <c>true</c> if the filter was created successfully; otherwise, <c>false</c>. /// </returns> public bool TryCreateFilter(IDataContext dataContext, out ColumnFilter filter) { filter = null; var value = GetValue(dataContext); if (!IsValidKey(value)) return false; filter = new ColumnFilter(Property.Name, value); return true; }
public void WhenExistingItemsAreFoundInsertOrUpdateExecutesUpdate() { // Arrange. const string ProcessName = "TestProcess"; var dataContext = Mock.Create<IDataContext>(Behavior.Loose); var mapping1 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping1.IsKey).Returns(true); var mapping2 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping2.IsKey).Returns(false); var mapping3 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping3.IsKey).Returns(true); var filter1 = new ColumnFilter("Field1", null); Mock.Arrange(() => mapping1.TryCreateFilter(dataContext, out filter1)).Returns(true); var filter2 = new ColumnFilter("Field2", null); Mock.Arrange(() => mapping3.TryCreateFilter(dataContext, out filter2)).Returns(true); var itemEdit1 = CreateEditableRoot(111); var itemEdit2 = CreateEditableRoot(222); SetupGetEditableRoot(ProcessName, itemEdit1, itemEdit2); var runtimeDatabase = Mock.Create<IRuntimeDatabase>(Behavior.Loose); Mock.Arrange(() => runtimeDatabase.FindItems(ProcessName, Arg.IsAny<IEnumerable<ColumnFilter>>())) .Returns<string, IEnumerable<ColumnFilter>>( (processName, filters) => { var filtersArray = filters.ToArray(); if (filtersArray.Length == 2 && filtersArray.Contains(filter1) && filtersArray.Contains(filter2)) return new Collection<int> { 111, 222 }; return new Collection<int>(); }); var applicationContext = Mock.Create<IApplicationContext>(Behavior.Loose); var dataContextFactory = Mock.Create<IEditableRootDataContextFactory>(Behavior.Loose); var logger = Mock.Create<ILogger>(Behavior.Loose); var itemUpdater = new IntegrationServiceMethod( ProcessName, new[] { mapping1, mapping2, mapping3 }, null, _dtm, applicationContext, runtimeDatabase, dataContextFactory, logger); // Act. var result = itemUpdater.InsertOrUpdate(dataContext); // Assert. Mock.Assert(() => mapping1.Update(dataContext, itemEdit1), Occurs.Once()); Mock.Assert(() => mapping1.Update(dataContext, itemEdit2), Occurs.Once()); Mock.Assert(() => mapping2.Update(dataContext, itemEdit1), Occurs.Once()); Mock.Assert(() => mapping2.Update(dataContext, itemEdit2), Occurs.Once()); Mock.Assert(() => mapping3.Update(dataContext, itemEdit1), Occurs.Once()); Mock.Assert(() => mapping3.Update(dataContext, itemEdit2), Occurs.Once()); Mock.Assert(() => itemEdit1.Save(), Occurs.Once()); Mock.Assert(() => itemEdit2.Save(), Occurs.Once()); Assert.IsNull(result); Assert.IsTrue(applicationContext.User.Identity is IntegrationServiceIdentity); }
public void InsertTest() { // Arrange. const string ProcessName = "TestProcess"; var dataContext = Mock.Create<IDataContext>(Behavior.Loose); var mapping1 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping1.IsKey).Returns(true); var mapping2 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping2.IsKey).Returns(false); var mapping3 = Mock.Create<IProcessFieldMapping>(Behavior.Loose); Mock.Arrange(() => mapping3.IsKey).Returns(true); var filter1 = new ColumnFilter("Field1", null); Mock.Arrange(() => mapping1.TryCreateFilter(dataContext, out filter1)).Returns(true); var filter2 = new ColumnFilter("Field2", null); Mock.Arrange(() => mapping3.TryCreateFilter(dataContext, out filter2)).Returns(true); var newEdit = CreateEditableRoot(0); Mock.Arrange(() => _dtm.NewEditableRoot<IEditableRoot>(ProcessName)).Returns(newEdit); var runtimeDatabase = Mock.Create<IRuntimeDatabase>(Behavior.Loose); Mock.Arrange(() => runtimeDatabase.FindItems(ProcessName, Arg.IsAny<IEnumerable<ColumnFilter>>())) .Returns<string, IEnumerable<ColumnFilter>>( (processName, filters) => { var filtersArray = filters.ToArray(); if (filtersArray.Length == 2 && filtersArray.Contains(filter1) && filtersArray.Contains(filter2)) return new Collection<int>(); return null; }); var applicationContext = Mock.Create<IApplicationContext>(Behavior.Loose); var editableRootDataContextFactory = Mock.Create<IEditableRootDataContextFactory>(Behavior.Loose); var logger = Mock.Create<ILogger>(Behavior.Loose); var serviceMethod = new IntegrationServiceMethod( ProcessName, new[] { mapping1, mapping2, mapping3 }, null, _dtm, applicationContext, runtimeDatabase, editableRootDataContextFactory, logger); // Act. var result = serviceMethod.Insert(dataContext); // Assert. Mock.Assert(() => mapping1.Update(dataContext, newEdit), Occurs.Once()); Mock.Assert(() => mapping2.Update(dataContext, newEdit), Occurs.Once()); Mock.Assert(() => mapping3.Update(dataContext, newEdit), Occurs.Once()); Mock.Assert(() => newEdit.Save(), Occurs.Once()); Assert.IsNull(result); Assert.IsTrue(applicationContext.User.Identity is IntegrationServiceIdentity); }