public override bool Match(string filter) { if (string.IsNullOrEmpty(filter)) { return(true); } return(Type.Contains(filter) || Id.Contains(filter) || (Fields?.Any(x => x.Match(filter)) ?? false)); }
public override async Task <RepositoryResponse <bool> > SaveSubModelsAsync(MixAttributeSetData parent, MixCmsContext _context, IDbContextTransaction _transaction) { var result = new RepositoryResponse <bool>() { IsSucceed = true }; if (result.IsSucceed) { foreach (var item in Values) { if (result.IsSucceed) { if (Fields.Any(f => f.Id == item.AttributeFieldId)) { item.Priority = item.Field.Priority; item.DataId = parent.Id; item.Specificulture = parent.Specificulture; var saveResult = await item.SaveModelAsync(false, _context, _transaction); ViewModelHelper.HandleResult(saveResult, ref result); } else { var delResult = await item.RemoveModelAsync(false, _context, _transaction); ViewModelHelper.HandleResult(delResult, ref result); } } else { break; } } } return(result); }
public InMemoryTable( Entity entity, bool isTopTable, bool isLeafTable, int primaryKeyIndex) { Name = entity.ExternalName; IsTopTable = isTopTable; IsLeafTable = isLeafTable; PrimaryKeyIndex = primaryKeyIndex; Fields = entity.Fields.Where(_ => !_.NoSave).Select(_ => new NameAndType(_.ExternalName, _.FieldType)).ToList(); if (Fields.Any(_ => string.IsNullOrEmpty(_.Name))) { throw new ArgumentException($"Table '{Name}' contains empty column name"); } var dupCheck = Fields.ToLookup(_ => _.Name.ToUpper(), _ => _).Where(_ => _.Count() != 1).Select(_ => _.Key).ToList(); if (dupCheck.Any()) { throw new ArgumentException($"Table '{Name}' contains duplicate column names '{string.Join("','", dupCheck)}'"); } Rows = new List <TableRow>(); }
public string GetAccountName() { var accountName = ""; if (Provider.HasUserName) { var userNameField = GetFieldsByKey(FieldTypeKey.UserName).FirstOrDefault(); if (userNameField != null) { accountName = userNameField.Value.ToString(); } } if (Provider.HasEmail) { var emailField = GetFieldsByKey(FieldTypeKey.Email).FirstOrDefault(); if (emailField != null) { if (!string.IsNullOrEmpty(accountName)) { accountName += " - "; } accountName += emailField.Value; } } if (string.IsNullOrEmpty(accountName)) { if (Fields.Any()) { accountName = Fields.First().Value.ToString(); } } if (string.IsNullOrEmpty(accountName)) { accountName = "< not set >"; } return(accountName); }
public bool HasInput() { return(Fields.Any(f => f.Input)); }
public bool ShouldUpdateMaster() { return(!IsMaster && (Fields.Any(f => f.KeyType.HasFlag(KeyType.Foreign) || (Denormalize && f.Output && !f.KeyType.HasFlag(KeyType.Primary))))); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteStringValue(Name); if (Fields.Any()) { writer.WritePropertyName("fields"); writer.WriteStartArray(); foreach (var item in Fields) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } else { writer.WriteNull("fields"); } if (ScoringProfiles != null && ScoringProfiles.Any()) { writer.WritePropertyName("scoringProfiles"); writer.WriteStartArray(); foreach (var item in ScoringProfiles) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (DefaultScoringProfile != null) { writer.WritePropertyName("defaultScoringProfile"); writer.WriteStringValue(DefaultScoringProfile); } if (CorsOptions != null) { writer.WritePropertyName("corsOptions"); writer.WriteObjectValue(CorsOptions); } if (Suggesters != null && Suggesters.Any()) { writer.WritePropertyName("suggesters"); writer.WriteStartArray(); foreach (var item in Suggesters) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Analyzers != null && Analyzers.Any()) { writer.WritePropertyName("analyzers"); writer.WriteStartArray(); foreach (var item in Analyzers) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Tokenizers != null && Tokenizers.Any()) { writer.WritePropertyName("tokenizers"); writer.WriteStartArray(); foreach (var item in Tokenizers) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (TokenFilters != null && TokenFilters.Any()) { writer.WritePropertyName("tokenFilters"); writer.WriteStartArray(); foreach (var item in TokenFilters) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (CharFilters != null && CharFilters.Any()) { writer.WritePropertyName("charFilters"); writer.WriteStartArray(); foreach (var item in CharFilters) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (EncryptionKey != null) { writer.WritePropertyName("encryptionKey"); writer.WriteObjectValue(EncryptionKey); } if (Similarity != null) { writer.WritePropertyName("similarity"); writer.WriteObjectValue(Similarity); } if (_etag != null) { writer.WritePropertyName("@odata.etag"); writer.WriteStringValue(_etag); } writer.WriteEndObject(); }
public virtual bool HasFields() { return(Fields != null && Fields.Any()); }
public bool Has(string name) { return(Fields.Any(f => f.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))); }
protected override void OnCompleteFields( IDictionary <NameString, ObjectFieldDefinition> fields, ISet <MemberInfo> handledMembers) { HashSet <string> subscribeResolver = null; if (Definition.Fields.IsImplicitBinding() && Definition.FieldBindingType is not null) { FieldDescriptorUtilities.AddImplicitFields( this, Definition.FieldBindingType, p => { var descriptor = ObjectFieldDescriptor.New( Context, p, Definition.RuntimeType, Definition.FieldBindingType); if (Definition.IsExtension && Context.TypeInspector.IsMemberIgnored(p)) { descriptor.Ignore(); } Fields.Add(descriptor); return(descriptor.CreateDefinition()); }, fields, handledMembers, include: IncludeField, includeIgnoredMembers : Definition.IsExtension); } base.OnCompleteFields(fields, handledMembers); bool IncludeField(IReadOnlyList <MemberInfo> all, MemberInfo current) { NameString name = Context.Naming.GetMemberName(current, MemberKind.ObjectField); if (Fields.Any(t => t.Definition.Name.Equals(name))) { return(false); } if (subscribeResolver is null) { subscribeResolver = new HashSet <string>(); foreach (MemberInfo member in all) { HandlePossibleSubscribeMember(member); } } return(!subscribeResolver.Contains(current.Name)); } void HandlePossibleSubscribeMember(MemberInfo member) { if (member.IsDefined(typeof(SubscribeAttribute))) { if (member.GetCustomAttribute <SubscribeAttribute>() is { With : not null } attr) { subscribeResolver.Add(attr.With); } } } }
public override byte[] ToByteArray() { StringBuilder builder = new StringBuilder(); builder.Append("<atom:entry xmlns:atom=\"http://www.w3.org/2005/atom\">"); builder.Append("<atom:category scheme=\"tag:cecity.com,2008/lifetime/schemas#type\" term=\"tag:cecity.com,2008/lifetime/schemas#user\"></atom:category>"); builder.Append("<atom:content type=\"application/vnd.medbiq.member+xml\"></atom:content>"); builder.Append("<Members xmlns:a=\"http://ns.medbiq.org/address/v1/\" xmlns:ltd=\"tag:cecity.com,2008:/lifetime/data\" xmlns:n=\"http://ns.medbiq.org/name/v1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://ns.medbiq.org/member/v1/ http://ns.medbiq.org/member/v1/member.xsd\">"); builder.Append("<Member restrictions=\"Confidential\" xmlns=\"http://ns.medbiq.org/member/v1/\">"); builder.AppendFormat("<UniqueID domain=\"tag:aboto.org,2008/\">{0}</UniqueID>", Username); builder.AppendFormat("<Password>{0}</Password>", Password); builder.Append("<Security>"); builder.AppendFormat("<SecurityQuestion>{0}</SecurityQuestion>", SecurityQuestion); builder.AppendFormat("<SecurityAnswer>{0}</SecurityAnswer>", SecurityAnswer); builder.Append("</Security>"); builder.Append("<Name>"); builder.AppendFormat("<n:GivenName>{0}</n:GivenName>", FirstName); builder.AppendFormat("<n:FamilyName>{0}</n:FamilyName>", LastName); builder.AppendFormat("<n:Degree>{0}</n:Degree>", Degree); builder.Append("</Name>"); builder.Append("<Address>"); builder.AppendFormat("<a:StreetAddressLine>{0}</a:StreetAddressLine>", PreProcessString(Address)); builder.AppendFormat("<a:StreetAddressLine>{0}</a:StreetAddressLine>", PreProcessString(Address2)); builder.AppendFormat("<a:City>{0}</a:City>", PreProcessString(City)); builder.AppendFormat("<a:StateOrProvince>{0}</a:StateOrProvince>", State); builder.AppendFormat("<a:PostalCode>{0}</a:PostalCode>", PostalCode); builder.Append("<a:Country>"); builder.AppendFormat("<a:CountryCode>{0}</a:CountryCode>", CountryCode); builder.Append("</a:Country>"); builder.Append("</Address>"); if (OccupationInfo != null) { builder.Append("<OccupationInfo>"); builder.AppendFormat("<Occupation>{0}</Occupation>", string.IsNullOrEmpty(OccupationInfo.Occupation) ? "~~" : OccupationInfo.Occupation); builder.AppendFormat("<OccupationTitle>{0}</OccupationTitle>", string.IsNullOrEmpty(OccupationInfo.OccupationTitle) ? "~~" : OccupationInfo.OccupationTitle); builder.AppendFormat("<Privileges>{0}</Privileges>", string.IsNullOrEmpty(OccupationInfo.Privileges) ? "~~" : OccupationInfo.Privileges); builder.AppendFormat("<Practice>{0}</Practice>", string.IsNullOrEmpty(OccupationInfo.Practice) ? "~~" : OccupationInfo.Practice); builder.AppendFormat("<StartDate>{0}</StartDate>", OccupationInfo.StartDate.ToString("YYYY-mm-dd")); builder.AppendFormat("<EndDate>{0}</EndDate>", OccupationInfo.EndDate.ToString("YYYY-mm-dd")); if (OccupationInfo.Specialties != null && OccupationInfo.Specialties.Any()) { foreach (var specialty in OccupationInfo.Specialties) { builder.AppendFormat("<Specialty>{0}</Specialty>", specialty); } } builder.AppendFormat("<OccupationStatus>{0}</OccupationStatus>", OccupationInfo.OccupationStatus); builder.Append("</OccupationInfo>"); } builder.Append("<PersonalInfo>"); builder.AppendFormat("<EmailAddress>{0}</EmailAddress>", EmailAddress); builder.Append("</PersonalInfo>"); builder.Append("<XtensibleInfo>"); builder.AppendFormat("<ltd:GroupID>{0}</ltd:GroupID>", string.IsNullOrEmpty(GroupId) ? "~~" : GroupId); builder.Append("<rdf:RDF>"); builder.Append("<ltd:ThirdPartyfields>"); builder.Append("<ltd:Members rdf:parseType=\"Collection\">"); if (Fields != null && Fields.Any()) { foreach (var field in Fields) { if (!string.IsNullOrEmpty(field.Name)) { builder.AppendFormat("<ltd:Field ltd:dataType=\"http://www.w3.org/2001/XMLSchema#string\" ltd:name=\"{0}\" ltd:value=\"{1}\"></ltd:Field>", field.Name, PreProcessString(field.Value)); } } } builder.Append("</ltd:Members>"); builder.Append("</ltd:ThirdPartyfields>"); builder.Append("</rdf:RDF>"); builder.Append("</XtensibleInfo>"); builder.Append("</Member>"); builder.Append("</Members>"); builder.Append("</atom:entry>"); byte[] byteArray = Encoding.UTF8.GetBytes(builder.ToString()); return(byteArray); }
/// <summary> /// Creates the UI of the entire control /// </summary> private void Refresh() { if (_controlRoot == null) { return; } // Clear root element children. _controlRoot.Children.Clear(); _controlRoot.ColumnDefinitions.Clear(); if (_editFeature != null && GeodatabaseFeature.Schema != null && Fields != null) { foreach (var control in _fieldControls.Keys.Select(key => _fieldControls[key]).OfType <FeatureDataField>()) { control.PropertyChanged -= ControlOnPropertyChanged; } _fieldControls.Clear(); HasEdits = false; HasError = false; // Get collection of fields with supported field types. var supportedFields = _editFeature.Schema.Fields.Where(fieldInfo => !_notSupportFieldTypes.Contains(fieldInfo.Type)); if (Fields == null || !Fields.Any()) { // default to only editable fields var editableSupportedFields = supportedFields.Where(fieldInfo => fieldInfo.IsEditable); _validFieldNames = editableSupportedFields.Select(fieldInfo => fieldInfo.Name); } else { _validFieldNames = Fields.Contains("*") ? supportedFields.Select(fieldInfo => fieldInfo.Name) // All Fields (*) : Fields.Intersect(from fieldInfo in supportedFields select fieldInfo.Name); // specific fields provided by user } // Create UI for each field foreach (var fieldName in _validFieldNames) { // Get the field information from schema for this field. var fieldInfo = _editFeature.GetFieldInfo(fieldName); // default the label text to field alias if not null or empty var labelText = !string.IsNullOrEmpty(fieldInfo.Alias) ? fieldInfo.Alias : fieldInfo.Name; var isReadOnly = false; // default readonly to false Style labelStyle = null; Style containerStyle = null; DataTemplate inputTemplate = null; DataTemplate dateTimeTemplate = null; // if user has wired into the on generating event we will expose // some overridable information for each field. if (GeneratingField != null) { // Create a new event argument for field. var args = new GeneratingFieldEventArgs(fieldName, labelText, fieldInfo.Type) { IsReadOnly = IsReadOnly }; // Raise the event for user GeneratingField(this, args); // If user changed the label text or set the // field to read-only then we will use these // during UI creation. labelText = args.LabelText; isReadOnly = args.IsReadOnly; labelStyle = args.LabelStyle; inputTemplate = args.InputTemplate; dateTimeTemplate = args.DateTimeTemplate; containerStyle = args.ContainerStyle; } // create label ui var label = CreateLabel(labelText); label.Style = labelStyle ?? LabelStyle; // create edit control ui var control = CreateControl(_editFeature, fieldInfo, IsReadOnly ? IsReadOnly : isReadOnly); if (fieldInfo.Type == FieldType.Date) { // Form or Field override of input template property. if (dateTimeTemplate != null || DateTimeTemplate != null) { ((FeatureDataField)control).InputTemplate = dateTimeTemplate ?? DateTimeTemplate; } else if (inputTemplate != null || InputTemplate != null) { ((FeatureDataField)control).InputTemplate = inputTemplate ?? InputTemplate; } } else { // Form or Field override of input template property. if (inputTemplate != null || InputTemplate != null) { ((FeatureDataField)control).InputTemplate = inputTemplate ?? InputTemplate; } } // create container control var container = CreateContainer(); container.Style = containerStyle ?? ContainerStyle; // Add label and edit control to container container.Children.Add(label); container.Children.Add(control); // Set the Grid.Row attached property to the container Grid.SetRow(container, _controlRoot.RowDefinitions.Count); // Create a new RowDefinition for the container _controlRoot.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // Add each edit control to a lookup table that can be used // to invoke save and cancel commands on FeatureDataField. _fieldControls.Add(fieldName, control); // Add continer to the Grid _controlRoot.Children.Add(container); } } }
protected override void Validate() { switch (Method) { case "shorthand": if (String.IsNullOrEmpty(T)) { Error("The shorthand transform requires t attribute."); } break; case "format": if (Format == String.Empty) { Error("The format transform requires a format parameter."); } else { if (Format.IndexOf('{') == -1) { Error("The format transform's format must contain a curly braced place-holder."); } else if (Format.IndexOf('}') == -1) { Error("The format transform's format must contain a curly braced place-holder."); } } break; case "left": case "right": if (Index == 0) { Error("The {0} transform requires a length parameter.", Method); } break; case "copy": if (Parameter == String.Empty && !Parameters.Any()) { Error("The copy transform requires at least one parameter."); } break; case "javascript": //done at higher level break; case "fromsplit": case "fromxml": if (!Fields.Any()) { Error("The {0} transform requires a collection of output fields.", Method); } if (Method == "fromsplit" && Separator == Constants.DefaultSetting) { Error("The fromsplit method requires a separator."); } break; case "padleft": if (TotalWidth == 0) { Error("The padleft transform requires total width."); } if (PaddingChar == default(char)) { Error("The padleft transform requires a padding character."); } break; case "padright": if (TotalWidth == 0) { Error("The padright transform requires total width."); } if (PaddingChar == default(char)) { Error("The padright transform requires a padding character."); } break; case "map": if (Map == string.Empty) { Error("The map method requires a map method"); } break; case "splitlength": if (Separator == Constants.DefaultSetting) { Error("The splitlength transform requires a separator."); } break; case "contains": if (Value == string.Empty) { Error("The contains validator requires a value."); } break; case "is": if (Type == Constants.DefaultSetting) { Error("The is validator requires a type."); } break; case "trimstart": case "trimend": case "trim": if (TrimChars == string.Empty) { Error("The {0} transform requires trim-chars.", Method); } break; case "join": if (Separator == Constants.DefaultSetting) { Error("The {0} transform requires a separator.", Method); } break; case "timezone": if (FromTimeZone == Constants.DefaultSetting) { Error("The {0} transform requires from-time-zone to be set.", Method); } if (ToTimeZone == Constants.DefaultSetting) { Error("The {0} transform requires to-time-zone to be set.", Method); } break; case "htmldecode": case "xmldecode": case "tostring": case "toupper": case "tolower": case "decompress": break; default: Error("The {0} transform method is undefined.", Method); break; } }
//Нет в 13.2 //protected override FrameworkElement CreateContent(Type valueType, DataType? dataType) protected override FrameworkElement CreateContentAndInitializeUI() { FrameworkElement result = null; if (!string.IsNullOrEmpty(LookUpCode) && LookupType == RclLookupType.None) { LookupType = RclLookupType.Default; } switch (LookupType) { case RclLookupType.Default: case RclLookupType.DefaultGrid: var customComboBoxEditRcl = new CustomComboBoxEditRcl { Name = string.Format("{0}_{1}", Name, LookupType), IsWfDesignMode = IsWfDesignMode, LookupType = LookupType, LookUpCodeEditorFilterExt = IsWfDesignMode ? WfDesignModeLookUpCodeEditorFilterExt : LookUpFilterExt, LookUpCodeEditor = LookUpCode, UseFunctionKeys = UseFunctionKeys, ParentKeyPreview = ParentKeyPreview, HotKey = HotKey, CustomDisplayMember = CustomDisplayMember, LookupTitle = DisplayName }; if (MaxRowsOnPage.HasValue) { customComboBoxEditRcl.MaxRowsOnPage = MaxRowsOnPage.Value; } result = customComboBoxEditRcl; break; case RclLookupType.SelectControl: VerticalAlignment = VerticalAlignment.Stretch; var select = new CustomSelectControl { LookUpCodeEditorFilterExt = IsWfDesignMode ? WfDesignModeLookUpCodeEditorFilterExt : LookUpFilterExt, LookUpCodeEditor = LookUpCode, UseFunctionKeys = UseFunctionKeys, ParentKeyPreview = ParentKeyPreview, CustomDisplayMember = CustomDisplayMember, ExternalItemsSource = ItemsSource, DisplayMember = DisplayMember, ValueMember = ValueMember }; if (MaxRowsOnPage.HasValue) { select.MaxRowsOnPage = MaxRowsOnPage.Value; } if ((CloseDialogOnSelectedItemChanged || CloseDialog) && CloseDialogCommand != null) { select.CommandParameter = ValueDataFieldConstants.CreateDefaultParameter(ValueDataFieldConstants.Value); select.Command = CloseDialogCommand; } result = select; break; case RclLookupType.SelectGridControl: case RclLookupType.List: VerticalAlignment = VerticalAlignment.Stretch; //debug //if (IsWfDesignMode) // Fields = GetGridFields(); // var customSelectView = new CustomSelectView { ItemsSourceType = FieldType, IsWfDesignMode = IsWfDesignMode, AutoShowAutoFilterRowWhenRowsCountMoreThan = -1, LookUpCodeEditorFilterExt = IsWfDesignMode ? WfDesignModeLookUpCodeEditorFilterExt : LookUpFilterExt, LookUpCodeEditor = LookUpCode, Source = ItemsSource, DisplaySetting = DisplaySetting.HasValue ? DisplaySetting.Value : SettingDisplay.List, VerifyColumnsSourceChanged = true, ShowSelectMenuItem = LookupType == RclLookupType.SelectGridControl, MaxRows = MaxRows, Fields = Fields != null && Fields.Any() ? new ObservableCollection <DataField>(Fields) : null, AllowAutoShowAutoFilterRow = AllowAutoShowAutoFilterRow, DoNotAllowUpdateShowAutoFilterRowFromXml = DoNotAllowUpdateShowAutoFilterRowFromXml, ShowAutoFilterRow = ShowAutoFilterRow, ShowTotalRow = ShowTotalRow, DoNotActionOnEnterKey = DoNotActionOnEnterKey, BestFitColumnNames = BestFitColumnNames, FormatConditions = FormatConditions }; if (ShowControlMenu.HasValue) { customSelectView.ShowMenu = ShowControlMenu.Value; } if (IsWfDesignMode && string.IsNullOrEmpty(customSelectView.LookUpCodeEditor) && customSelectView.Source == null && FieldType != null) { customSelectView.Source = new[] { Activator.CreateInstance(FieldType) }; } if (FooterMenu != null && FooterMenu.Length > 0) { customSelectView.AddFooterMenuItems(FooterMenu, FontSize, IsWfDesignMode); } if ((CloseDialogOnSelectedItemChanged || CloseDialog) && CloseDialogCommand != null) { customSelectView.Command = CloseDialogCommand; } result = customSelectView; break; } if (IsMemoView) { result = new MemoEdit { ShowIcon = false, //PopupWidth = 250, MemoTextWrapping = TextWrapping.Wrap, MemoVerticalScrollBarVisibility = ScrollBarVisibility.Hidden, MemoHorizontalScrollBarVisibility = ScrollBarVisibility.Hidden }; } if (typeof(IList).IsAssignableFrom(FieldType)) { result = CreateContentSubListView(FieldType); } if (result == null) { result = CreateContentInternal(); } if (result == null) { result = base.CreateContentAndInitializeUI(); var textEdit = result as TextEdit; if (textEdit != null) { textEdit.TextWrapping = TextWrapping.Wrap; if (textEdit.TextWrapping == TextWrapping.Wrap) { textEdit.HorizontalContentAlignment = HorizontalAlignment.Left; textEdit.VerticalContentAlignment = VerticalAlignment.Top; } if (!String.IsNullOrEmpty(BackGroundColor)) { var brushconverter = new BrushConverter(); ((TextEdit)result).Background = brushconverter.ConvertFromString(BackGroundColor) as Brush; } } } var termilalUi = result as IRclUi; if (termilalUi == null) { //Гридам не навязывать стандартную обработку клавиш. if (LookupType != RclLookupType.SelectGridControl && LookupType != RclLookupType.List) { if (CloseDialog) { KeyHelper.SetCloseDialogElement(result); } if (IsDoNotMovedFocusOnNextControl) { KeyHelper.SetDoNotMovedFocusOnNextControl(result); } result.PreviewKeyDown += (s, e) => KeyHelper.PreviewKeyDown(result, e); } } else { termilalUi.IsMovedFocusOnNextControl = !CloseDialog; } if (IsFocused || SetFocus) { result.BackgroundFocus(); } if (IsWfDesignMode) { var themeName = ThemeManager.GetThemeName(this); if (string.IsNullOrEmpty(themeName)) { themeName = StyleKeys.RclDefaultThemeName; } ThemeManager.SetThemeName(result, themeName); } return(result); }
public bool ContainsKey(string key) { return(Fields.Any(f => f.Field.Key == key)); }
private bool HasFieldFor(string name) { return(Fields.Any(GetCompareNamesPredicate(name))); }
public RelationSqlExpression ToRelation() { Debug.Assert(Fields.Any()); return(new ConcreteRelationSqlExpression(SqlBuilder, Tokens.Enclose("(", ")"))); }
/// <summary> /// Looks for sdt field in document specified by <paramref name="name"/>, <paramref name="tag"/> or both <paramref name="name"/> and <paramref name="tag"/> /// </summary> /// <param name="name">Name of field</param> /// <param name="tag">Name of tag of field</param> public bool Contains(string name = null, string tag = null) { return(Fields.Any(x => SearchPredicate(x, name, tag))); }
private List<NamedConnection> PrepareIo(IEnumerable<TflIo> collection, Fields fields) { var namedConnections = new List<NamedConnection>(); var entity = fields.Any() ? fields[0].Entity : "None"; foreach (var io in collection) { Func<Row, bool> shouldRun = row => true; if (!io.RunField.Equals(string.Empty)) { var f = io.RunField; var match = fields.Find(f).ToArray(); if (match.Length > 0) { var field = match[0]; if (io.RunType.Equals(DEFAULT)) { io.RunType = field.SimpleType; } var op = (ComparisonOperator)Enum.Parse(typeof(ComparisonOperator), io.RunOperator, true); var simpleType = Common.ToSimpleType(io.RunType); var value = Common.ConversionMap[simpleType](io.RunValue); shouldRun = row => Common.CompareMap[op](row[field.Alias], value); } else { _process.Logger.EntityWarn(entity, "Field {0} specified in {1} output doesn't exist. It will not affect the output.", io.RunField, io.Name); } } namedConnections.Add(new NamedConnection { Name = io.Name, Connection = _process.Connections.GetConnectionByName(io.Connection).Connection, ShouldRun = shouldRun }); } return namedConnections; }
public bool HasFieldWithValue(string fieldName, string fieldValue) => Fields.Any(f => f.Name == fieldName && f.Value == fieldValue);
public IActionResult OnGet() { Init(); var entMan = new EntityManager(); var recMan = new RecordManager(); #region << InitPage >> int pager = 1; string sortBy = ""; QuerySortType sortOrder = QuerySortType.Ascending; PageUtils.GetListQueryParams(PageContext.HttpContext, out pager, out sortBy, out sortOrder); Pager = pager; SortBy = sortBy; SortOrder = sortOrder; ErpEntity = entMan.ReadEntity(ParentRecordId ?? Guid.Empty).Object; if (ErpEntity == null) { return(NotFound()); } ReadAccess = SecurityContext.HasEntityPermission(EntityPermission.Read, ErpEntity); CreateAccess = SecurityContext.HasEntityPermission(EntityPermission.Create, ErpEntity); UpdateAccess = SecurityContext.HasEntityPermission(EntityPermission.Update, ErpEntity); DeleteAccess = SecurityContext.HasEntityPermission(EntityPermission.Delete, ErpEntity); if (string.IsNullOrWhiteSpace(ReturnUrl)) { ReturnUrl = $"/sdk/objects/entity/r/{ErpEntity.Id}/"; } Fields = ErpEntity.Fields.OrderBy(x => x.Name).ToList(); var idField = Fields.Single(x => x.Name == "id"); Fields.Remove(idField); Fields = Fields.OrderBy(x => x.Name).ToList(); Fields.Insert(0, idField); List <QueryObject> filterQueries = new List <QueryObject>(); #region << Process filters >> var submittedFilters = PageUtils.GetPageFiltersFromQuery(PageContext.HttpContext); if (submittedFilters.Count > 0) { foreach (var filter in submittedFilters) { if (!ErpEntity.Fields.Any(x => x.Name == filter.Name)) { continue; } switch (filter.Type) { case FilterType.EQ: filterQueries.Add(EntityQuery.QueryEQ(filter.Name, filter.Value)); break; case FilterType.CONTAINS: filterQueries.Add(EntityQuery.QueryContains(filter.Name, filter.Value)); break; case FilterType.FTS: filterQueries.Add(EntityQuery.QueryFTS(filter.Name, filter.Value)); break; case FilterType.STARTSWITH: filterQueries.Add(EntityQuery.QueryStartsWith(filter.Name, filter.Value)); break; case FilterType.REGEX: filterQueries.Add(EntityQuery.QueryRegex(filter.Name, filter.Value)); break; } } } #endregion #region << Process Sort >> var sort = new List <QuerySortObject> { new QuerySortObject("id", QuerySortType.Ascending) }; if (!String.IsNullOrWhiteSpace(SortBy) && Fields.Any(x => x.Name == SortBy)) { sort = new List <QuerySortObject> { new QuerySortObject(SortBy, SortOrder == QuerySortType.Ascending ? QuerySortType.Ascending : QuerySortType.Descending) } } ; #endregion if (!ReadAccess) { Records = new List <EntityRecord>(); TotalCount = 0; Validation.Message = "You have no permissions to view records."; Validation.Errors.Add(new ValidationError("", "You have no permissions to view records.")); } else { EntityQuery enQuery = null; if (filterQueries.Any()) { enQuery = new EntityQuery(ErpEntity.Name, query: EntityQuery.QueryAND(filterQueries.ToArray()), sort: sort.ToArray(), skip: (pager - 1) * PagerSize, limit: PagerSize); } else { enQuery = new EntityQuery(ErpEntity.Name, sort: sort.ToArray(), skip: (pager - 1) * PagerSize, limit: PagerSize); } var queryResponse = recMan.Find(enQuery); if (!queryResponse.Success) { throw new Exception(queryResponse.Message); } Records = queryResponse.Object.Data; TotalCount = (int)recMan.Count(enQuery).Object; } ReturnUrlEncoded = HttpUtility.UrlEncode(PageUtils.GetCurrentUrl(PageContext.HttpContext)); PageDescription = PageUtils.GenerateListPageDescription(PageContext.HttpContext, "", TotalCount); HeaderToolbar.AddRange(AdminPageUtils.GetEntityAdminSubNav(ErpEntity, "data")); #endregion #region << Create Columns >> Columns.Add(new GridColumn() { Name = "", Label = "", Width = "90px", Sortable = false, Searchable = false }); foreach (var field in Fields) { var fieldAccess = GetFieldAccess(field); var searchAndSortAvailable = field.Searchable && (fieldAccess == FieldAccess.Full || fieldAccess == FieldAccess.ReadOnly); var column = new GridColumn() { Name = field.Name, Label = field.Label, Sortable = searchAndSortAvailable, Searchable = searchAndSortAvailable }; if (field.GetFieldType() == FieldType.GuidField) { column.Width = "1%"; } Columns.Add(column); } #endregion #region << Filters >> foreach (var field in Fields) { //remove fields with no access from search var fieldAccess = GetFieldAccess(field); var searchable = field.Searchable && (fieldAccess == FieldAccess.Full || fieldAccess == FieldAccess.ReadOnly); if (!searchable) { continue; } if (field.Name == "id") { dynamic filterObj = new ExpandoObject(); filterObj.Name = field.Name; filterObj.Label = field.Label; filterObj.Type = FilterType.EQ; filterObj.AllowedTypes = new List <FilterType> { FilterType.EQ }; Filters.Add(filterObj); } else if (field.Searchable) { dynamic filterObj = new ExpandoObject(); filterObj.Name = field.Name; filterObj.Label = field.Label; filterObj.Type = FilterType.EQ; filterObj.AllowedTypes = new List <FilterType> { FilterType.EQ, FilterType.NOT }; var fieldType = field.GetFieldType(); if (fieldType == FieldType.TextField || fieldType == FieldType.MultiLineTextField || fieldType == FieldType.UrlField || fieldType == FieldType.EmailField || fieldType == FieldType.HtmlField || fieldType == FieldType.SelectField || fieldType == FieldType.MultiSelectField) { filterObj.AllowedTypes.Add(FilterType.REGEX); filterObj.AllowedTypes.Add(FilterType.FTS); filterObj.AllowedTypes.Add(FilterType.STARTSWITH); filterObj.AllowedTypes.Add(FilterType.CONTAINS); } Filters.Add(filterObj); } } #endregion return(Page()); }
public bool Has(BaseSchemaField field) { return(Fields.Any(f => f.Name.Equals(field.Name, StringComparison.InvariantCultureIgnoreCase))); }
// Nested indent have to be set for each Nested element and subelement separately, or after generation manualy to select nested code and indent it with tab // Setting it automaticaly and propagating could be done if the parent sets the child's parent reference (to itself) when the child is added/assigned to a parent. Parent setter is internal. // http://softwareengineering.stackexchange.com/questions/261453/what-is-the-best-way-to-initialize-a-childs-reference-to-its-parent public override string ToString() { if (AutoGenerateProperties) { Properties.Clear(); foreach (var field in Fields) { Properties.Add(new Property(field.BuiltInDataType, field.Name) { IsGetOnly = IsGetOnly }); } } string result = string.Empty; result += $"{Package}"; result += Util.NewLine; result += Util.NewLine; if (Imports.Any()) { foreach (var import in Imports) { result += $"{import}"; result += Util.NewLine; } } result += Util.NewLine; if (Annotations.Any()) { foreach (var annotation in Annotations) { result += annotation; result += Util.NewLine; } } result += base.ToString(); result += (BaseClass != null || Interfaces?.Count > 0) ? $" : " : ""; result += BaseClass ?? ""; result += (BaseClass != null && Interfaces?.Count > 0) ? $", " : ""; result += Interfaces?.Count > 0 ? string.Join(", ", Interfaces) : ""; result += " {"; result += Util.NewLine; result += string.Join("", Fields); var visibleConstructors = Constructors.Where(a => a.IsVisible); bool hasFieldsBeforeConstructor = visibleConstructors.Any() && Fields.Any(); result += string.Join("," + Util.NewLine, EnumList); result += hasFieldsBeforeConstructor ? Util.NewLine : ""; result += string.Join(Util.NewLine, visibleConstructors); bool hasMembersAfterConstructor = (visibleConstructors.Any() || Fields.Any()) && (Properties.Any() || Methods.Any()); result += hasMembersAfterConstructor ? Util.NewLine : ""; result += string.Join(HasPropertiesSpacing ? Util.NewLine : "", Properties); bool hasPropertiesAndMethods = Properties.Count > 0 && Methods.Count > 0; result += hasMembersAfterConstructor ? Util.NewLine : ""; result += string.Join(Util.NewLine, Methods); result += NestedClasses.Count > 0 ? Util.NewLine : ""; result += string.Join(Util.NewLine, NestedClasses); result += Util.NewLine + "}"; return(result); }
public override void Generate(StreamWriter sw, string indent, CodeGenerationOptions opt, GenerationInfo gen_info) { opt.ContextTypes.Push(this); // interfaces don't nest, so generate as siblings foreach (GenBase nest in NestedTypes) { nest.Generate(sw, indent, opt, gen_info); sw.WriteLine(); } var staticMethods = Methods.Where(m => m.IsStatic); if (Fields.Any() || staticMethods.Any()) { string name = hasManagedName ? Name.Substring(1) + "Consts" : Name.Substring(1); sw.WriteLine("{0}[Register (\"{1}\"{2}, DoNotGenerateAcw=true)]", indent, RawJniName, this.AdditionalAttributeString()); sw.WriteLine("{0}public abstract class {1} : Java.Lang.Object {{", indent, name); sw.WriteLine(); sw.WriteLine("{0}\tinternal {1} ()", indent, name); sw.WriteLine("{0}\t{{", indent); sw.WriteLine("{0}\t}}", indent); var seen = new HashSet <string> (); bool needsClassRef = GenFields(sw, indent + "\t", opt, seen) || staticMethods.Any(); foreach (var iface in GetAllImplementedInterfaces().OfType <InterfaceGen>()) { sw.WriteLine(); sw.WriteLine("{0}\t// The following are fields from: {1}", indent, iface.JavaName); bool v = iface.GenFields(sw, indent + "\t", opt, seen); needsClassRef = needsClassRef || v; } foreach (var m in Methods.Where(m => m.IsStatic)) { opt.CodeGenerator.WriteMethod(m, sw, indent + "\t", opt, this, true); } if (needsClassRef) { sw.WriteLine(); opt.CodeGenerator.WriteClassHandle(this, sw, indent + "\t", opt, name); } sw.WriteLine("{0}}}", indent, Name); sw.WriteLine(); if (!hasManagedName) { sw.WriteLine("{0}[Register (\"{1}\"{2}, DoNotGenerateAcw=true)]", indent, RawJniName, this.AdditionalAttributeString()); sw.WriteLine("{0}[global::System.Obsolete (\"Use the '{1}' type. This type will be removed in a future release.\")]", indent, name); sw.WriteLine("{0}public abstract class {1}Consts : {1} {{", indent, name); sw.WriteLine(); sw.WriteLine("{0}\tprivate {1}Consts ()", indent, name); sw.WriteLine("{0}\t{{", indent); sw.WriteLine("{0}\t}}", indent); sw.WriteLine("{0}}}", indent); sw.WriteLine(); } } if (IsConstSugar) { return; } GenerateDeclaration(sw, indent, opt); if (!AssemblyQualifiedName.Contains('/')) { GenerateExtensionsDeclaration(sw, indent, opt, null); } GenerateInvoker(sw, indent, opt); GenerateEventHandler(sw, indent, opt); opt.ContextTypes.Pop(); }
public bool ShouldSerializeFields() => Fields?.Any() ?? false;
public override void Validate() { var errors = new RulesException <QpPlugin>(); base.Validate(errors); if (!string.IsNullOrEmpty(LoadedContractInvalidMessage)) { errors.ErrorFor(n => ServiceUrl, $"{QpPluginStrings.LoadedContractInvalidMessage}: {LoadedContractInvalidMessage}"); } if (!string.IsNullOrEmpty(ParsedContractInvalidMessage)) { errors.ErrorFor(n => Contract, $"{QpPluginStrings.ParsedContractInvalidMessage}: {ParsedContractInvalidMessage}"); } if (!string.IsNullOrEmpty(ServiceUrl) && !UrlHelpers.IsValidWebFolderUrl(ServiceUrl)) { errors.ErrorFor(n => ServiceUrl, QpPluginStrings.ServiceUrlInvalidFormat); } if (ContractParsed) { if (string.IsNullOrEmpty(Contract)) { errors.ErrorFor(n => ServiceUrl, QpPluginStrings.ContractNotEntered); } else { if (string.IsNullOrEmpty(Code)) { errors.ErrorFor(n => ServiceUrl, QpPluginStrings.CodeNotEntered); } else { if (QpPluginRepository.CodeExists(this)) { errors.ErrorFor(n => Code, QpPluginStrings.CodeExists); } } if (string.IsNullOrEmpty(Version)) { errors.ErrorFor(n => ServiceUrl, QpPluginStrings.VersionNotEntered); } else { if (Version.Length > MaxVersionLength) { errors.ErrorFor(n => Version, String.Format(QpPluginStrings.VersionMaxLengthExceeded, null, MaxVersionLength)); } else if (OldVersion == Version) { errors.ErrorFor(n => Version, QpPluginStrings.VersionEqual); } } if (Fields.Any(n => String.IsNullOrEmpty(n.Name))) { errors.ErrorForModel(QpPluginStrings.FieldNameNotEntered); } if (Fields.Any(n => n.Name.Length > MaxFieldNameLength)) { errors.ErrorForModel(String.Format(QpPluginStrings.FieldNameMaxLengthExceeded, null, MaxFieldNameLength)); } if (Fields.GroupBy(n => n.Name.ToLower() + n.RelationType).Any(g => g.Count() > 1)) { errors.ErrorForModel(QpPluginStrings.FieldNameDuplicate); } } } if (!errors.IsEmpty) { throw errors; } }
public async Task <CipherView> DecryptAsync() { var model = new CipherView(this); await DecryptObjAsync(model, this, new HashSet <string> { "Name", "Notes" }, OrganizationId); switch (Type) { case Enums.CipherType.Login: model.Login = await Login.DecryptAsync(OrganizationId); break; case Enums.CipherType.SecureNote: model.SecureNote = await SecureNote.DecryptAsync(OrganizationId); break; case Enums.CipherType.Card: model.Card = await Card.DecryptAsync(OrganizationId); break; case Enums.CipherType.Identity: model.Identity = await Identity.DecryptAsync(OrganizationId); break; default: break; } if (Attachments?.Any() ?? false) { model.Attachments = new List <AttachmentView>(); var tasks = new List <Task>(); async Task decryptAndAddAttachmentAsync(Attachment attachment) { var decAttachment = await attachment.DecryptAsync(OrganizationId); model.Attachments.Add(decAttachment); } foreach (var attachment in Attachments) { tasks.Add(decryptAndAddAttachmentAsync(attachment)); } await Task.WhenAll(tasks); } if (Fields?.Any() ?? false) { model.Fields = new List <FieldView>(); var tasks = new List <Task>(); async Task decryptAndAddFieldAsync(Field field) { var decField = await field.DecryptAsync(OrganizationId); model.Fields.Add(decField); } foreach (var field in Fields) { tasks.Add(decryptAndAddFieldAsync(field)); } await Task.WhenAll(tasks); } if (PasswordHistory?.Any() ?? false) { model.PasswordHistory = new List <PasswordHistoryView>(); var tasks = new List <Task>(); async Task decryptAndAddHistoryAsync(PasswordHistory ph) { var decPh = await ph.DecryptAsync(OrganizationId); model.PasswordHistory.Add(decPh); } foreach (var ph in PasswordHistory) { tasks.Add(decryptAndAddHistoryAsync(ph)); } await Task.WhenAll(tasks); } return(model); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteStringValue(Name); writer.WritePropertyName("type"); writer.WriteStringValue(Type.ToString()); if (IsKey != null) { writer.WritePropertyName("key"); writer.WriteBooleanValue(IsKey.Value); } if (IsRetrievable != null) { writer.WritePropertyName("retrievable"); writer.WriteBooleanValue(IsRetrievable.Value); } if (IsSearchable != null) { writer.WritePropertyName("searchable"); writer.WriteBooleanValue(IsSearchable.Value); } if (IsFilterable != null) { writer.WritePropertyName("filterable"); writer.WriteBooleanValue(IsFilterable.Value); } if (IsSortable != null) { writer.WritePropertyName("sortable"); writer.WriteBooleanValue(IsSortable.Value); } if (IsFacetable != null) { writer.WritePropertyName("facetable"); writer.WriteBooleanValue(IsFacetable.Value); } if (AnalyzerName != null) { writer.WritePropertyName("analyzer"); writer.WriteStringValue(AnalyzerName.Value.ToString()); } if (SearchAnalyzerName != null) { writer.WritePropertyName("searchAnalyzer"); writer.WriteStringValue(SearchAnalyzerName.Value.ToString()); } if (IndexAnalyzerName != null) { writer.WritePropertyName("indexAnalyzer"); writer.WriteStringValue(IndexAnalyzerName.Value.ToString()); } if (SynonymMapNames != null && SynonymMapNames.Any()) { writer.WritePropertyName("synonymMaps"); writer.WriteStartArray(); foreach (var item in SynonymMapNames) { writer.WriteStringValue(item); } writer.WriteEndArray(); } if (Fields != null && Fields.Any()) { writer.WritePropertyName("fields"); writer.WriteStartArray(); foreach (var item in Fields) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); }
public bool FieldExists(string name) => Fields.Any(t => t.IsNamed(name));
public bool Bitwise() { return(Fields.Any()); }
protected override void Validate() { if (Name == "Control" && Alias == Name) { Error("An entity may not be named 'Control' without an alias. Please provide an alias."); } // if validation has been defined, check to see if corresponding valid and message fields are present and create them if not var calculatedKeys = new HashSet <string>(CalculatedFields.Select(f => f.Alias ?? f.Name).Distinct(), StringComparer.OrdinalIgnoreCase); if (Fields.Any(f => f.Validators.Any())) { foreach (var field in Fields.Where(f => f.Validators.Any())) { if (!calculatedKeys.Contains(field.ValidField)) { CalculatedFields.Add(new Field { Name = field.ValidField, Alias = field.ValidField, Input = false, Type = "bool", Default = "true", IsCalculated = true }); } if (!calculatedKeys.Contains(field.MessageField)) { CalculatedFields.Add(new Field { Name = field.MessageField, Alias = field.MessageField, Length = "255", Default = "", IsCalculated = true, Input = false }); } } // create an entity-wide valid field if necessary if (ValidField == string.Empty) { var valid = Alias + "Valid"; if (!CalculatedFields.Any(f => f.Name.Equals(valid))) { var add = new Field { Name = valid, Alias = valid, Type = "bool", ValidField = valid, Input = false, IsCalculated = true, Default = "true" }; add.Validators.Add(new Operation { Method = "all", Operator = "equals", Value = "true", Parameters = GetAllFields().Where(f => f.ValidField != string.Empty).Select(f => f.ValidField).Distinct().Select(n => new Parameter { Field = n }).ToList() }); CalculatedFields.Add(add); ValidField = valid; } } } var fields = GetAllFields().ToArray(); var names = new HashSet <string>(fields.Select(f => f.Name).Distinct()); var aliases = new HashSet <string>(fields.Select(f => f.Alias)); ValidateVersion(names, aliases); ValidateFilter(names, aliases); ValidateOrder(names, aliases); foreach (var field in GetAllOutputFields().Where(f => f.Sortable == "true" && !string.IsNullOrEmpty(f.SortField))) { if (GetField(field.SortField) == null) { Error($"Can't find sort field {field.SortField} defined in field {field.Alias}."); } } }