public void Test_WeaklyTyped_Set( ) { using (var property = new PropertyReflector(Agent007, "id")) { Assert.NotNull(property.PropertyInfo, $"Property named \"id\" not found in type {Agent007.GetType( )}"); Assert.NotNull(property.GetValue(Agent007), $"Value returned was null."); var id = property.GetValue(Agent007); property.SetValue(Agent007, Guid.NewGuid( )); Assert.AreNotEqual(id, property.GetValue(Agent007), "Expected change in Agent007's id did not occur."); } }
/// <summary> /// This Compare method helps to compare the values and it will return the SortDirection. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(object x, object y) { var group = (x as Group); var group1 = (y as Group); for (int i = 0; i < (x as Group).GetTopLevelGroup().GroupDescriptions.Count; i++) { if (group.Records == null) { group = group.Groups.FirstOrDefault() as Group; group1 = group1.Groups.FirstOrDefault() as Group; } } object record = group.Records.FirstOrDefault().Data; object record1 = group1.Records.FirstOrDefault().Data; var key1 = PropertyReflector.GetValue(record, ColumnName); var key2 = PropertyReflector.GetValue(record1, ColumnName); char[] first = key1.ToString().ToCharArray(); char[] second = key2.ToString().ToCharArray(); int compareFirstValue = Convert.ToInt32(first[0]); int compareSecondValue = Convert.ToInt32(second[0]); var diff = compareFirstValue.CompareTo(compareSecondValue); if (diff > 0) { return(SortDirection == ListSortDirection.Ascending ? 1 : -1); } if (diff == -1) { return(SortDirection == ListSortDirection.Ascending ? -1 : 1); } return(0); }
public static void ApplyCorrectYeKe(this object entity) { if (entity == null) { return; } var properties = entity .GetType() .GetProperties() .Where(p => string.Equals(p.PropertyType.Name, AppConsts.StringDataTypeName, StringComparison.CurrentCultureIgnoreCase)) .ToList(); var propertyReflector = new PropertyReflector(); foreach (var memberInfo in properties) { var name = memberInfo.Name; var targetObjectValue = propertyReflector.GetValue(entity, name); if (targetObjectValue != null) { propertyReflector .SetValue(entity, name, targetObjectValue.ToString().ApplyUnifiedYeKe()); } } }
public static void ApplyCorrectYeKeToProperties(this object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } var propertyInfos = obj.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where(p => p.CanRead && p.CanWrite && p.PropertyType == typeof(string)); var propertyReflector = new PropertyReflector(); foreach (var propertyInfo in propertyInfos) { var propName = propertyInfo.Name; var value = propertyReflector.GetValue(obj, propName); if (value != null) { var strValue = value.ToString(); var newVal = strValue.ApplyCorrectYeKe(); if (newVal == strValue) { continue; } propertyReflector.SetValue(obj, propName, newVal); } } }
public void Test_StronglyTyped_InvalidCast_Get( ) { using (var property = new PropertyReflector <string>(Agent007, "id")) { Assert.Catch <InvalidCastException>(() => property.GetValue(Agent007), "Expected InvalidCastException to be raised when attempting to" + " retrieve property of type Guid as a string."); } }
public void Test_WeaklyTyped_TargetException_Get( ) { using (var property = new PropertyReflector(typeof(Person), "id")) { // This is a non-static field thus property access requires a target object instance. Assert.Catch <TargetException>(() => property.GetValue(null), "Expected TargetException to be raised when attempting to " + "retrieve the value of non-static property."); } }
/// <summary> /// This Compare method helps to compare the values and it will return the SortDirection. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(object x, object y) { var group = (x as Group); var group1 = (y as Group); for (int i = 0; i < (x as Group).GetTopLevelGroup().GroupDescriptions.Count; i++) { if (group.Records == null) { group = group.Groups.FirstOrDefault() as Group; group1 = group1.Groups.FirstOrDefault() as Group; } } object record = group.Records.FirstOrDefault().Data; object record1 = group1.Records.FirstOrDefault().Data; var key1 = PropertyReflector.GetValue(record, ColumnName); var key2 = PropertyReflector.GetValue(record1, ColumnName); var ColumnType = key1.GetType(); int compareFirstValue = 0, compareSecondValue = 0; DateTime date = (DateTime)key1; DateTime date1 = (DateTime)key2; if (GroupMode == DateGroupingMode.Month) { compareFirstValue = date.Month; compareSecondValue = date1.Month; } else if (GroupMode == DateGroupingMode.Year) { compareFirstValue = date.Year; compareSecondValue = date.Year; } else if (GroupMode == DateGroupingMode.Week) { compareFirstValue = date.Day; compareSecondValue = date1.Day; } else { var dt = (DateRange)group.Key; var dt1 = (DateRange)group1.Key; compareFirstValue = (int)dt; compareSecondValue = (int)dt1; } var diff = compareFirstValue.CompareTo(compareSecondValue); if (diff > 0) { return(SortDirection == ListSortDirection.Ascending ? 1 : -1); } if (diff == -1) { return(SortDirection == ListSortDirection.Ascending ? -1 : 1); } return(0); }
public void Test_StronglyTyped_Get( ) { using (var property = new PropertyReflector <Guid>(Agent007, "id")) { Assert.NotNull(property.PropertyInfo, $"Property named \"id\" not found in type {Agent007.GetType( )}"); Assert.NotNull(property.GetValue(Agent007), $"Value returned was null."); Assert.IsTrue(property.Value is Guid, $"Unexpected value type for property \"id\" in {Agent007.GetType( )}, " + $"expected {typeof( Guid )}."); } }
public void Test_WeaklyTyped_Get( ) { // Wrapping instantiation in a using statements allows for automatic disposable of the reflector when // it's no longer required. using (var property = new PropertyReflector(Agent007, "id")) { Assert.NotNull(property.PropertyInfo, $"Property named \"id\" not found in type {Agent007.GetType( )}"); Assert.NotNull(property.GetValue(Agent007), $"Value returned was null."); } }
public static void ApplyCorrectYeKe(this DbContext dbContext) { if (dbContext == null) { return; } //پیدا کردن موجودیتهای تغییر کرده var changedEntities = dbContext.ChangeTracker .Entries() .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified); foreach (var item in changedEntities) { var entity = item.Entity; if (item.Entity == null) { continue; } //یافتن خواص قابل تنظیم و رشتهای این موجودیتها var propertyInfos = entity.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where(p => p.CanRead && p.CanWrite && p.PropertyType == typeof(string)); var propertyReflector = new PropertyReflector(); //اعمال یکپارچگی نهایی foreach (var propertyInfo in propertyInfos) { var propName = propertyInfo.Name; var value = propertyReflector.GetValue(entity, propName); if (value != null) { var strValue = value.ToString(); var newVal = strValue.ApplyCorrectYeKe(); if (newVal == strValue) { continue; } propertyReflector.SetValue(entity, propName, newVal); } } } }
public override object?Resolve(object?value) { if (value == null || Name == null) { return(null); } if (PropReflector != null) { return(PropReflector.GetValue(value)); } PropReflector = value.GetType().GetProperty(Name)?.GetReflector(); if (PropReflector == null) { Name = null; return(null); } return(PropReflector?.GetValue(value)); }
private void applyCorrectYeKe() { //پیدا کردن موجودیتهای تغییر کرده var changedEntities = this.ChangeTracker .Entries() .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified); foreach (var item in changedEntities) { if (item.Entity == null) { continue; } //یافتن خواص قابل تنظیم و رشتهای این موجودیتها var propertyInfos = item.Entity.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where(p => p.CanRead && p.CanWrite && p.PropertyType == typeof(string)); var pr = new PropertyReflector(); //اعمال یکپارچگی نهایی foreach (var propertyInfo in propertyInfos) { var propName = propertyInfo.Name; var val = pr.GetValue(item.Entity, propName); if (val != null) { var newVal = val.ToString().Replace("ي", "ی").Replace("ؤ", "و").Replace("ة", "ه"); //var newVal = val.ToString().Replace("ی", "ی").Replace("ک", "ک"); if (newVal == val.ToString()) { continue; } pr.SetValue(item.Entity, propName, newVal); } } } }
public object AspectCoreGetter() { return(_reflector.GetValue(_indexerEntity)); }
public object AspectCore_Reflector_Get_Property() { return(_fieldReflector.GetValue(_instance)); }
/// <summary> /// Método que monta uma coleção de <code>ListItem</code> para alimentar um <code>DropDownList</code> /// contento no campo texto(que será exibido para o usuário) "N" propriedades concatenadas e separadas /// por "-". /// </summary> /// <remarks> /// Para efetuar a mesma ação contendo apenas um campo texto(que será exibido para o usuário) basta utilizar /// a maneira nativa que é: alimentar a propriedade <code>DataTextField</code> com o campo texto e /// <code>DataValueField</code> com o campo valor. /// Quando se trata de utilizar atributos de classes que estão em um relacionamento nos nomes de campo /// basta colocar no nome do atributo o nome do relacionamento separador que é ponto (".") e o nome do atributo, /// ou seja, utilizar NomeDoRelacionamento.NomeDoAtributo. /// Por exemplo: numa classe "Pessoa" que tem um relacionamento chamado "RelatPerfil" com uma classe "Perfil", /// onde a classe perfil possui um atributo "NomePerfil", para utilizar esse atributo bastaria utilizar /// "RelatPerfil.NomePerfil". Assim como num atributo do tipo string chamado "Nome" na classe Pessoa seria /// chamado apenas de "Nome". Outra funcionalidade interessante é limitar o tamanho máximo da string. /// Quando chamamos um atributo com um limitador de caracteres que é ("|") o valor do atributo aparecerá /// com o número máximo de caracteres equivalente ao número que segue o "|". Por exemplo, quando quero /// que apareça o atributo "Nome" da classe "Pessoa" com no máximo 10 caracteres eu chamarei assim: /// "Nome|10". /// </remarks> /// <param name="colecaoEntidades">coleção que conterá os objetos tornados em item de exibição do /// dropdownlist</param> /// <param name="nomeValor">string com o nome da propriedade que será o valor do item do dropdownlist</param> /// <param name="nomesCampos">array de strings com os campos que serão o texto dos items do dropdownlist</param> /// <param name="selectedValue">string com o valor(Value) do listitem que será selecionado no dropdownlist</param> /// <returns>coleção com os ListItens de dropdownlist</returns> /// <exception cref="Petrobras.TINE.Util.Web.WebUtilException">Se passar por parâmetro /// propriedades inexistentes</exception> protected ListItem[] MontarColecaoDeListItemParaDropdownList(ArrayList colecaoEntidades, string nomeValor, string[] nomesCampos, string selectedValue) { ListItem[] colecaoListItem = new ListItem[colecaoEntidades.Count]; PropertyReflector pr = new PropertyReflector(); try { int contador = -1; foreach (Object item in colecaoEntidades) { contador += 1; String valor = pr.GetValue(item, nomeValor).ToString(); String texto = ""; String temp = ""; foreach (String nome in nomesCampos) { //Se existe este caracter separador no nome do atributo, então o tamanho da string deve //ser limitado, senão entra no atributo do ListItem a string inteira. if (nome.Contains("|")) { //Separa-se em duas strings, a string com o nome do atributo cujo valor deve ser //buscado por reflection e a segunda string dizendo quantos caracteres do valor devem //ser colocados no listitem. Por exemplo em "NomeDoAtributo|30" buscar-se-á //o valor contido no atributo NomeDoAtributo, porém apenas sua substring de até //30 caracteres. char separador = '|'; String[] atributo = nome.Split(separador); int tamanhoString = int.Parse(atributo[1]); temp = pr.GetValue(item, atributo[0]).ToString(); //Testa se o tamanho da string é maior que o tamanho pedido, //para saber se deve usar sibstring ou não if (tamanhoString < temp.Length) { if (!string.IsNullOrEmpty(texto)) { texto = texto + " - " + temp.Substring(0, tamanhoString) + "..."; } else { texto = temp.Substring(0, tamanhoString) + "..."; } } else { if (!string.IsNullOrEmpty(texto)) { texto = texto + " - " + temp; } else { texto = temp; } } } else { if (!string.IsNullOrEmpty(texto)) { texto = texto + " - " + pr.GetValue(item, nome).ToString(); } else { texto = pr.GetValue(item, nome).ToString(); } } } ListItem listItem = new ListItem(texto, valor); if (listItem.Value.Equals(selectedValue)) { listItem.Selected = true; } colecaoListItem[contador] = listItem; } } //Exceções do namespace refletion catch (AmbiguousMatchException ame) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro de reflection do tipo \"AmbiguousMatchException\": " + ame.Message, ame); } catch (TargetParameterCountException tpe) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro de reflection do tipo \"AmbiguousMatchException\": " + tpe.Message, tpe); } catch (TargetInvocationException tie) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro de reflection do tipo \"TargetInvocationException\": " + tie.Message, tie); } catch (TargetException te) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro de reflection do tipo \"TargetException\": " + te.Message, te); } //Exceções do namespace system catch (ArgumentNullException ane) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro do tipo \"ArgumentNullException\": " + ane.Message, ane); } catch (MethodAccessException mae) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro do tipo \"MethodAccessException\": " + mae.Message, mae); } catch (InvalidOperationException ioe) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro do tipo \"InvalidOperationException\": " + ioe.Message, ioe); } catch (ArgumentException ae) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro do tipo \"ArgumentException\": " + ae.Message, ae); } catch (NullReferenceException nre) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro do tipo \"NullReferenceException\": " + nre.Message + " Provavelmente você utilizou uma propriedade que o objeto não tem", nre); } catch (Exception e) { throw new WebUtilException("Erro interno de sistema. Favor contactar 881. Erro de tipo desconhecido: " + e.Message, e); } return(colecaoListItem); }