Here are the examples of the csharp api System.Type.GetProperties() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2825 Examples
19
Source : Configuration.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public void Override(CommandBase command)
{
foreach (var property in typeof(Configuration).GetProperties())
{
if (property.GetValue(this) is object value)
{
typeof(CommandBase).GetProperty(property.Name).SetValue(command, value);
}
}
}
19
Source : Extensions.cs
with MIT License
from Adyen
with MIT License
from Adyen
public static string ToClreplacedDefinitionString(this object o)
{
try
{
var t = o.GetType();
var propertyString = new StringBuilder().AppendLine($"clreplaced {o.GetType().Name} {{");
foreach (var prop in t.GetProperties())
{
var propertyValue = prop.GetValue(o, null);
propertyString.Append("\t")
.AppendLine(propertyValue != null
? $"{prop.Name}: {propertyValue}".ToIndentedString()
: $"{prop.Name}: null");
}
propertyString.AppendLine("}");
return propertyString.ToString();
}
catch
{
return o.ToString();
}
}
19
Source : StoredProc.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public virtual SpParameter[] GetParameters(TRequest parameters)
{
var type = typeof(TRequest);
return type.GetProperties()
.OfType<PropertyInfo>()
.Select(info => new SpParameter(info.Name, info.GetValue(parameters, null)))
.ToArray();
}
19
Source : Map.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static Dictionary<string, object> ToDictionary<T>(T obj)
{
var type = obj.GetType();
var properties = type.GetProperties()
.Where(p => p.PropertyType.IsValueType || p.PropertyType == typeof(string));
var dictionary = new Dictionary<string, object>(properties.Count());
foreach (var property in properties)
{
dictionary.Add(property.Name, property.GetValue(obj));
}
return dictionary;
}
19
Source : ExportButtom.razor.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private async Task Download()
{
var token = await _service.GetOneTimeToken().ConfigureAwait(false);
var builder = new StringBuilder(_settings.ApiBaseUrl);
if (!_settings.ApiBaseUrl.EndsWith('/'))
{
builder.Append('/');
}
builder.Append(EnreplacedyPath);
var dictionary = typeof(PageRequest)
.GetProperties()
.Where(p => p.Name != nameof(PageRequest.Select) &&
p.Name != nameof(PageRequest.Take) &&
p.GetValue(Request) != null)
.ToDictionary(p => p.Name.ToLowerInvariant(), p => p.GetValue(Request).ToString());
dictionary.Add("format", "export");
dictionary.Add("otk", token);
var url = QueryHelpers.AddQueryString(builder.ToString(), dictionary);
await _jsRuntime.InvokeVoidAsync("open", url, "_blank").ConfigureAwait(false);
}
19
Source : HttpStoreBase.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public virtual async Task<PageResponse<T>> GetAsync(PageRequest request, CancellationToken cancellationToken = default)
{
request = request ?? new PageRequest();
var dictionary = typeof(PageRequest)
.GetProperties()
.Where(p => p.GetValue(request) != null)
.ToDictionary(p => p.Name.ToLowerInvariant(), p => p.GetValue(request).ToString());
var httpClient = await HttpClientFactory
.ConfigureAwait(false);
using (var response = await httpClient.GetAsync(GetUri(httpClient, QueryHelpers.AddQueryString(BaseUri, dictionary)), cancellationToken)
.ConfigureAwait(false))
{
await EnsureSuccess(response)
.ConfigureAwait(false);
return await DeserializeResponse<PageResponse<T>>(response)
.ConfigureAwait(false);
}
}
19
Source : ApplicationDbContext.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var property in GetType().GetProperties().Where(p => p.PropertyType.ImplementsGenericInterface(typeof(IQueryable<>))))
{
var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
modelBuilder.Enreplacedy(enreplacedyType).ToTable($"AspNet{property.Name}");
}
modelBuilder.Enreplacedy<User>().Ignore(u => u.Preplacedword);
modelBuilder.Enreplacedy<User>().HasIndex(u => u.NormalizedEmail)
.HasDatabaseName("EmailIndex")
.IsUnique(false);
modelBuilder.Enreplacedy<User>().HasIndex(u => u.NormalizedUserName)
.HasDatabaseName("UserNameIndex")
.IsUnique();
modelBuilder.Enreplacedy<User>().Property(u => u.NormalizedUserName).HasMaxLength(256);
modelBuilder.Enreplacedy<User>().Property(u => u.UserName).HasMaxLength(256);
modelBuilder.Enreplacedy<User>().Property(u => u.NormalizedEmail).HasMaxLength(256);
modelBuilder.Enreplacedy<User>().Property(u => u.Email).HasMaxLength(256);
modelBuilder.Enreplacedy<Role>().HasIndex(r => r.NormalizedName)
.HasDatabaseName("RoleNameIndex")
.IsUnique();
modelBuilder.Enreplacedy<Role>().Property(r => r.NormalizedName).HasMaxLength(256);
modelBuilder.Enreplacedy<Role>().Property(r => r.Name).HasMaxLength(256);
modelBuilder.Enreplacedy<UserLogin>().HasKey(l => l.Id);
modelBuilder.Enreplacedy<UserLogin>().HasIndex(l => new { l.LoginProvider, l.ProviderKey }).IsUnique();
modelBuilder.Enreplacedy<UserRole>().HasKey(l => l.Id);
modelBuilder.Enreplacedy<UserRole>().HasIndex(r => new { r.RoleId, r.UserId }).IsUnique();
modelBuilder.Enreplacedy<UserToken>().HasKey(l => l.Id);
modelBuilder.Enreplacedy<UserToken>().HasIndex(t => new { t.UserId, t.LoginProvider, t.Name }).IsUnique();
base.OnModelCreating(modelBuilder);
}
19
Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
{
var enreplacedy = await _session.LoadAsync<TEnreplacedy>($"{_enreplacedybasePath}{id}", cancellationToken).ConfigureAwait(false);
if (enreplacedy == null)
{
throw new InvalidOperationException($"Enreplacedy type {typeof(TEnreplacedy).Name} at id {id} is not found");
}
_session.Delete(enreplacedy);
var iCollectionType = typeof(ICollection<>);
var iEnreplacedyIdType = typeof(IEnreplacedyId);
var subEnreplacediesProperties = _enreplacedyType.GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.ImplementsGenericInterface(iCollectionType) && p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(iEnreplacedyIdType));
foreach(var subEnreplacedyProperty in subEnreplacediesProperties)
{
var collection = subEnreplacedyProperty.GetValue(enreplacedy) as ICollection;
if (collection != null)
{
foreach (IEnreplacedyId subItem in collection)
{
_session.Delete(subItem.Id);
}
}
}
await OnDeleteEnreplacedyAsync(enreplacedy, cancellationToken).ConfigureAwait(false);
await _session.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Enreplacedy {EnreplacedyId} deleted", enreplacedy.Id);
}
19
Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async Task<TEnreplacedy> UpdateAsync(TEnreplacedy enreplacedy, CancellationToken cancellationToken = default)
{
enreplacedy = enreplacedy ?? throw new ArgumentNullException(nameof(enreplacedy));
var storedEnreplacedy = await _collection.AsQueryable()
.FirstOrDefaultAsync(e => e.Id == enreplacedy.Id, cancellationToken)
.ConfigureAwait(false);
if (storedEnreplacedy == null)
{
throw new InvalidOperationException($"Enreplacedy type {typeof(TEnreplacedy).Name} at id {enreplacedy.Id} is not found");
}
if (enreplacedy is IAuditable auditable)
{
auditable.ModifiedAt = DateTime.UtcNow;
}
var properties = typeof(TEnreplacedy).GetProperties()
.Where(p => !p.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)));
foreach (var property in properties)
{
property.SetValue(storedEnreplacedy, property.GetValue(enreplacedy));
}
await _collection.ReplaceOneAsync(Builders<TEnreplacedy>.Filter.Eq(e => e.Id, enreplacedy.Id), storedEnreplacedy, cancellationToken: cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Enreplacedy {EnreplacedyId} updated", enreplacedy.Id, enreplacedy);
return enreplacedy;
}
19
Source : EntityExtension.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static void Copy<TEnreplacedy>(this TEnreplacedy from, TEnreplacedy to) where TEnreplacedy : Enreplacedy.IEnreplacedyId
{
var properties = typeof(TEnreplacedy).GetProperties()
.Where(p => !p.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)));
foreach (var property in properties)
{
property.SetValue(to, property.GetValue(from));
}
}
19
Source : ImportService.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static Dictionary<string, IEnumerable> GetSubEnreplacedies(T enreplacedy)
{
var collectionPropertyList = typeof(T).GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null);
var dictionary = new Dictionary<string, IEnumerable>(collectionPropertyList.Count());
foreach(var property in collectionPropertyList)
{
if (property.GetValue(enreplacedy) is not IEnumerable values)
{
continue;
}
dictionary[property.Name] = values;
property.SetValue(enreplacedy, null); // remove sub enreplacedies from enreplacedy object
}
return dictionary;
}
19
Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
{
using var session = await _collection.Database.Client.StartSessionAsync(cancellationToken: cancellationToken);
var isTransactionSupported = session.Client.Cluster.Description.Type != ClusterType.Standalone;
if (isTransactionSupported)
{
session.StartTransaction();
}
var enreplacedy = await _collection.AsQueryable()
.FirstOrDefaultAsync(e => e.Id == id, cancellationToken)
.ConfigureAwait(false);
if (enreplacedy == null)
{
throw new InvalidOperationException($"Enreplacedy type {typeof(TEnreplacedy).Name} at id {id} is not found");
}
await _collection.DeleteOneAsync(session, Builders<TEnreplacedy>.Filter.Eq(e => e.Id, id), cancellationToken: cancellationToken).ConfigureAwait(false);
var iCollectionType = typeof(ICollection<>);
var iEnreplacedyIdType = typeof(IEnreplacedyId);
var subEnreplacediesProperties = _enreplacedyType.GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.ImplementsGenericInterface(iCollectionType) && p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(iEnreplacedyIdType));
var dataBase = _collection.Database;
foreach (var subEnreplacedyProperty in subEnreplacediesProperties)
{
var subCollection = dataBase.GetCollection<BsonDoreplacedent>(subEnreplacedyProperty.PropertyType.GetGenericArguments()[0].Name);
await subCollection.DeleteManyAsync(session, new BsonDoreplacedent(GetSubEnreplacedyParentIdName(_enreplacedyType), id), cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (isTransactionSupported)
{
await session.CommitTransactionAsync(cancellationToken).ConfigureAwait(false);
}
_logger.LogInformation("Enreplacedy {EnreplacedyId} deleted", enreplacedy.Id, enreplacedy);
}
19
Source : ClientRegisterationConverter.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void DeserializeJwks(JsonReader reader, ClientRegisteration existingValue, System.Reflection.PropertyInfo property)
{
do
{
reader.Read();
} while (reader.TokenType != JsonToken.StartArray);
var keys = new List<JsonWebKey>();
var propertyList = typeof(JsonWebKey).GetProperties();
while (reader.TokenType != JsonToken.EndArray)
{
reader.Read();
if (reader.TokenType != JsonToken.StartObject)
{
break;
}
var jwk = new JsonWebKey();
while (reader.TokenType != JsonToken.EndObject)
{
reader.Read();
if (reader.TokenType != JsonToken.PropertyName)
{
continue;
}
var p = propertyList.FirstOrDefault(p => p.Name == (string)reader.Value);
if (p == null)
{
continue;
}
p.SetValue(jwk, reader.Readreplacedtring());
}
keys.Add(jwk);
}
property.SetValue(existingValue, new JsonWebKeys
{
Keys = keys
});
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void AddStoresForContext(IServiceCollection services, Type dbContextType)
{
foreach (var property in dbContextType.GetProperties().Where(p => p.PropertyType.ImplementsGenericInterface(typeof(IQueryable<>)) &&
p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(typeof(IEnreplacedyId))))
{
var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
var adminStoreType = typeof(AdminStore<,>)
.MakeGenericType(enreplacedyType.GetTypeInfo(), dbContextType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(adminStoreType);
var cacheAdminStoreType = typeof(CacheAdminStore<,>)
.MakeGenericType(adminStoreType.GetTypeInfo(), enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(cacheAdminStoreType);
var iAdminStoreType = typeof(IAdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(iAdminStoreType, cacheAdminStoreType);
}
}
19
Source : AdminStoreTestBase.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static IEnumerable<PropertyInfo> GetNavigrationProperties()
{
var properties = typeof(TEnreplacedy).GetProperties();
var collectionProperties = properties
.Where(p => p.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)));
var navigationProperties = properties
.Where(p => properties.Any(e => e.Name == $"{p.Name}Id"));
return collectionProperties.Concat(navigationProperties);
}
19
Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private async Task PopulateSubEnreplacedyAsync(string idName, object subEnreplacedy)
{
var type = subEnreplacedy.GetType();
var idProperty = type.GetProperty(idName);
var id = idProperty.GetValue(subEnreplacedy);
var loaded = await _session.LoadAsync<object>(id as string).ConfigureAwait(false);
if (loaded == null)
{
return;
}
// remove navigation
var iCollectionType = typeof(ICollection<>);
var iEnreplacedyIdType = typeof(IEnreplacedyId);
var subEnreplacediesProperties = type.GetProperties().Where(p => p.PropertyType.IsGenericType &&
p.PropertyType.ImplementsGenericInterface(iCollectionType) &&
p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(iEnreplacedyIdType));
foreach (var subEnreplacedyProperty in subEnreplacediesProperties)
{
subEnreplacedyProperty.SetValue(loaded, null);
}
CloneEnreplacedy(subEnreplacedy, type, loaded);
idProperty.SetValue(subEnreplacedy, ((IEnreplacedyId)loaded).Id);
}
19
Source : ClientRegisterationConverter.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public override ClientRegisteration ReadJson(JsonReader reader, Type objectType, ClientRegisteration existingValue, bool hasExistingValue, JsonSerializer serializer)
{
existingValue = new ClientRegisteration();
var properties = objectType.GetProperties();
while (reader.Read())
{
if (reader.TokenType != JsonToken.PropertyName)
{
continue;
}
var propertyInfo = ((string)reader.Value).Split('#');
var propertyName = propertyInfo[0];
var property = properties.FirstOrDefault(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false)
.Any(a => a is JsonPropertyAttribute jsonProperty && jsonProperty.PropertyName == propertyName));
if (property == null)
{
continue;
}
if (property.PropertyType == typeof(IEnumerable<LocalizableProperty>))
{
ReadLocalizableProperty(reader, existingValue, propertyInfo, property);
continue;
}
if (property.PropertyType == typeof(string))
{
property.SetValue(existingValue, reader.Readreplacedtring());
continue;
}
if (property.PropertyType == typeof(IEnumerable<string>))
{
ReadEnumarableString(reader, existingValue, property);
continue;
}
if (property.PropertyType == typeof(JsonWebKeys))
{
DeserializeJwks(reader, existingValue, property);
}
}
return existingValue;
}
19
Source : ClientRegisterationConverter.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private JObject SerializedProperties(object value)
{
var jObject = new JObject();
var properties = value.GetType().GetProperties();
foreach (var property in properties)
{
var jsonPropertyAttribute = property.GetCustomAttributes(typeof(JsonPropertyAttribute), false)
.FirstOrDefault(a => a is JsonPropertyAttribute jsonProperty) as JsonPropertyAttribute;
var propertyName = jsonPropertyAttribute?.PropertyName ?? property.Name;
if (property.PropertyType == typeof(IEnumerable<LocalizableProperty>))
{
SerializeLocalizableProperty(property, value, propertyName, jObject);
continue;
}
var v = property.GetValue(value);
if (v == null)
{
continue;
}
if (v is JsonWebKeys jsonWebKeys)
{
SerializeJwks(jObject, propertyName, jsonWebKeys);
continue;
}
jObject.Add(new JProperty(propertyName, v));
}
return jObject;
}
19
Source : TypeExtensions.cs
with MIT License
from ahydrax
with MIT License
from ahydrax
private static object CreateSampleInstanceInternal(this Type type, int currentDepth, int maxDepth)
{
if (currentDepth > maxDepth) return GetDefaultValue(type);
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
var propertyType = property.PropertyType;
if (propertyType.CanBeInstantiated())
{
type.GetProperty(property.Name).SetValue(instance,
propertyType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth));
}
if (typeof(IEnumerable).IsreplacedignableFrom(propertyType)
&& propertyType != typeof(string))
{
var elementType = propertyType.IsArray
? propertyType.GetElementType()
: propertyType.GenericTypeArguments[0];
var array = Array.CreateInstance(elementType, 1);
array.SetValue(
elementType.CanBeInstantiated()
? elementType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth)
: GetDefaultValue(elementType),
0);
type.GetProperty(property.Name).SetValue(instance, array);
}
}
return instance;
}
19
Source : ScrollBar.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
public void ScrollBarManagedProperties()
{
if (ManagedProperties.Count > 0)
{
foreach (ClManagedProperty ClManagedProperty1 in ManagedProperties.Base_obj)
{
object obj1 = ClManagedProperty1.ManagedObject;
string prop1 = "";
float ratio1 = 1.0f;
if (ClManagedProperty1.Ratio == null)
{
}
else
{
ratio1 = Convert.ToSingle(ClManagedProperty1.Ratio.AsNumber());
}
System.Reflection.PropertyInfo[] myPropertyInfo;
myPropertyInfo = obj1.GetType().GetProperties();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributeData1 =
myPropertyInfo[i].CustomAttributes;
foreach (System.Reflection.CustomAttributeData CustomAttribute1 in CustomAttributeData1)
{
string quote = "\"";
string text = CustomAttribute1.ToString();
if (text.Contains("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote))
{
text = text.Replace("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote, "");
text = text.Replace(quote + ", " + quote, " ");
text = text.Replace(quote + ")]", "");
string[] stringSeparators = new string[] { };
string[] result = text.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
if (ClManagedProperty1.ManagedProperty == result[0])
{
prop1 = result[1];
break;
}
}
}
}
System.Type Type1 = obj1.GetType();
float _Value = Convert.ToSingle(v_h_ScrollBar.Value);
int res = Convert.ToInt32(ratio1 * _Value);
if (Type1.GetProperty(prop1).PropertyType.ToString() != "System.String")
{
Type1.GetProperty(prop1).SetValue(obj1, res);
}
else
{
Type1.GetProperty(prop1).SetValue(obj1, res.ToString());
}
}
}
}
19
Source : ConfigurationExtensions.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
private static void HydrateInstance(ref object config, ConfigSection section)
{
var props = config.GetType().GetProperties();
foreach (var prop in props)
{
// Must have a set method for this to work, otherwise continue on
if (prop.SetMethod == null)
continue;
var entry = section.GetValue(prop.Name);
object? value = null;
if (typeof(string) == prop.PropertyType)
{
// We do NOT want to override value if nothing was provided
if(!string.IsNullOrEmpty(entry))
prop.SetValue(config, entry);
continue;
}
// We need to address collections a bit differently
// They can come in the form of "root:section:name" with a string representation OR
// "root:section:name:0" <--- this is not detectable when checking the above path
if (typeof(IEnumerable).IsreplacedignableFrom(prop.PropertyType))
{
value = string.IsNullOrEmpty(section.GetValue(prop.Name))
? section.Config
.GetSection(section.GetPath(prop.Name)).Get(prop.PropertyType)
: Newtonsoft.Json.JsonConvert.DeserializeObject(entry, prop.PropertyType);
if (value == null)
continue;
prop.SetValue(config, value);
}
// From this point onward we require the 'entry' value to have something useful
if (string.IsNullOrEmpty(entry))
continue;
try
{
// Primitive types are simple to convert
if (prop.PropertyType.IsPrimitive)
value = Convert.ChangeType(entry, prop.PropertyType);
else
{
// The following types require a different approach
if (prop.PropertyType.IsEnum)
value = Enum.Parse(prop.PropertyType, entry);
else if (typeof(TimeSpan) == prop.PropertyType)
value = TimeSpan.Parse(entry);
else if (typeof(DateTime) == prop.PropertyType)
value = DateTime.Parse(entry);
else if (typeof(DateTimeOffset) == prop.PropertyType)
value = DateTimeOffset.Parse(entry);
}
// Update value within our config instance
prop.SetValue(config, value);
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"Unable to convert value of '{entry}' to type '{prop.PropertyType.Name}' for prop '{prop.Name}' in config '{config.GetType().Name}'\n\t\t{ex.Message}");
}
}
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void BindParameters(DbCommand cmd, params object[] pramsArray)
{
if (pramsArray != null)
{
foreach (object prams in pramsArray)
{
if (prams == null || prams is string)
continue;
foreach (System.Reflection.PropertyInfo prop in prams.GetType().GetProperties())
{
DbParameter p = cmd.CreateParameter();
p.ParameterName = prop.Name;
p.Value = prop.GetValue(prams, null);
if (p.Value != null)
cmd.Parameters.Add(p);
}
}
}
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void DumpException(Exception ex, string sql, params object[] pramsArray)
{
StringBuilder sb = new StringBuilder();
if (pramsArray != null)
{
foreach (object prams in pramsArray)
{
if (prams != null)
{
System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
//props.ToList().ForEach(p => sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null)));
foreach (var p in props)
sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
}
}
}
TraceLogger.Instance.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
TraceLogger.Instance.WriteException(ex);
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected static string MakeInsert(string tableName, object prams)
{
string sql;
List<string> cols = new List<string>();
List<string> vals = new List<string>();
{
System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
foreach(var p in props)
{
if (p.GetValue(prams, null) != null)
{
cols.Add(p.Name);
vals.Add("@" + p.Name);
}
};
}
sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", tableName, string.Join(",", cols.ToArray()), string.Join(",", vals.ToArray()));
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected static string MakeUpdate(string tableName, object prams, object condition)
{
string sql;
string filter = MakeFilter(condition);
List<string> vals = new List<string>();
{
System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
//props.Where(p => p.GetValue(prams, null) != null).ToList().ForEach(p => vals.Add(p.Name + "=@" + p.Name));
foreach (var p in props)
{
if (p.GetValue(prams, null) != null)
vals.Add(p.Name + "=@" + p.Name);
}
}
sql = string.Format("UPDATE [{0}] SET {1} {2}", tableName, string.Join(",", vals.ToArray()), filter);
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string MakeFilter(object condition)
{
string filter = string.Empty;
if (condition != null)
{
if (condition is string)
{
filter = string.IsNullOrEmpty(condition as string) ? "" : " WHERE " + condition;
}
else
{
List<string> vals = new List<string>();
System.Reflection.PropertyInfo[] props = condition.GetType().GetProperties();
//props.ToList().ForEach(p =>
foreach(var p in props)
{
vals.Add((p.GetValue(condition, null) != null) ? (p.Name + "=@" + p.Name) : (p.Name + " IS NULL"));
};
if (vals.Count > 0)
filter = " WHERE " + string.Join(" AND ", vals.ToArray());
}
}
return filter;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string MakeOrder(object order)
{
string sql = string.Empty;
if (order != null)
{
if (order is string)
{
sql = string.IsNullOrEmpty(order as string) ? "" : "ORDER BY " + order;
}
else
{
List<string> vals = new List<string>();
System.Reflection.PropertyInfo[] props = order.GetType().GetProperties();
foreach(var p in props)
{
string val = p.GetValue(order, null) as string;
if (string.Equals(val, "DESC", StringComparison.OrdinalIgnoreCase))
vals.Add(p.Name + " DESC");
else
vals.Add(p.Name);
};
if (vals.Count > 0)
sql = " ORDER BY " +string.Join(",", vals.ToArray());
}
}
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected static string MakeInsert(string tableName, object prams)
{
string sql;
StringBuilder cols = new StringBuilder();
StringBuilder vals = new StringBuilder();
{
var props = prams.GetType().GetProperties();
foreach (var p in props)
{
if (Attribute.IsDefined(p, typeof(InsertIgnore)))
continue;
if (p.CanRead && p.GetValue(prams, null) != null)
{
cols.Append(cols.Length > 0 ? "," : null).Append(p.Name);
vals.Append(vals.Length > 0 ? "," : null).Append("@").Append(p.Name);
}
};
}
sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", tableName, cols, vals);
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected static string MakeUpdate(string tableName, object prams, object condition)
{
string sql;
string filter = MakeFilter(condition);
StringBuilder vals = new StringBuilder();
{
var props = prams.GetType().GetProperties();
foreach (var p in props)
{
if (Attribute.IsDefined(p, typeof(UpdateIgnore)))
continue;
if (p.CanRead)
{
vals.Append(vals.Length > 0 ? "," : null);
if (p.GetValue(prams, null) != null)
vals.Append(p.Name).Append("=@").Append(p.Name);
else
vals.Append(p.Name).Append("=NULL");
}
}
}
sql = string.Format("UPDATE [{0}] SET {1} {2}", tableName, vals, filter);
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected static string MakeFilter(object condition)
{
string filter = string.Empty;
if (condition != null)
{
if (condition is string)
{
filter = string.IsNullOrEmpty(condition as string) ? "" : " WHERE " + condition;
}
else
{
StringBuilder vals = new StringBuilder();
var props = condition.GetType().GetProperties();
foreach (var p in props)
{
if (p.CanRead)
{
vals.Append(vals.Length > 0 ? " AND " : null);
if (p.GetValue(condition, null) != null)
vals.Append(p.Name).Append("=@").Append(p.Name);
else
vals.Append(p.Name).Append(" IS NULL");
}
};
if (vals.Length > 0)
filter = vals.Insert(0, " WHERE ").Append(" ").ToString();
}
}
return filter;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string MakeOrder(object order)
{
string sql = string.Empty;
if (order != null)
{
if (order is string)
{
sql = string.IsNullOrEmpty(order as string) ? "" : "ORDER BY " + order;
}
else
{
StringBuilder cols = new StringBuilder();
var props = order.GetType().GetProperties();
foreach (var p in props)
{
string val = p.GetValue(order, null) as string;
if (string.Equals(val, "DESC", StringComparison.OrdinalIgnoreCase))
cols.Append(p.Name).Append(" DESC");
else
cols.Append(p.Name);
};
if (cols.Length > 0)
sql = cols.Insert(0, " ORDER BY ").Append(" ").ToString();
}
}
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void DumpException(Exception ex, string sql, params object[] pramsArray)
{
StringBuilder sb = new StringBuilder();
if (pramsArray != null)
{
foreach (object prams in pramsArray)
{
if (prams != null)
{
System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
foreach (var p in props)
sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
}
}
}
TraceLog.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
TraceLog.WriteException(ex);
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void BindParameters(DbCommand cmd, params object[] pramsArray)
{
if (pramsArray != null)
{
foreach (object prams in pramsArray)
{
if (prams == null || prams is string)
continue;
foreach (var prop in prams.GetType().GetProperties())
{
DbParameter p = cmd.CreateParameter();
p.ParameterName = prop.Name;
p.Value = prop.GetValue(prams, null);
if (prop.PropertyType.IsArray)
p.Value = DataConverter.Convert(p.Value);
if (p.Value != null)
cmd.Parameters.Add(p);
}
}
}
}
19
Source : MongoRepository.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public async Task UpdateAsync<T>(FilterDefinition<T> filter, Dictionary<string, string> updateDic)
{
// 要修改的字段
var list = new List<UpdateDefinition<T>>();
var properties = typeof(T).GetProperties().Select(p => p.Name);
foreach (var kvp in updateDic)
{
if (properties.Contains(kvp.Key))
{
list.Add(Builders<T>.Update.Set(kvp.Key, kvp.Value));
}
}
var updateDefinition = Builders<T>.Update.Combine(list);
await GetCollection<T>().UpdateManyAsync(filter, updateDefinition);
}
19
Source : NpoiHelper.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public MemoryStream ExportExcel<T>(
List<T> dataList,
Dictionary<string, string> dic,
string sheetName = "")
{
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet(sheetName);
// 行下标
var rowNum = 1;
var replacedleRow = sheet.CreateRow(rowNum);
// 列下标
var colNum = 0;
// 获取属性
var positionDic = new Dictionary<string, int>();
// 设置标题
foreach (var item in dic)
{
replacedleRow.CreateCell(colNum).SetCellValue(item.Value);
positionDic.Add(item.Value, colNum);
colNum++;
}
// 设置内容
rowNum++;
var properties = typeof(T).GetProperties();
foreach (var item in dataList)
{
var row = sheet.CreateRow(rowNum);
for (int i = 0; i < properties.Length; i++)
{
// 属性字典中没有该属性运行下一个属性
if (!dic.ContainsKey(properties[i].Name))
{
continue;
}
// 获取属性值
var value = properties[i].GetValue(item)?.ToString();
//获取对应列下标,并设定值
var colIndex = positionDic[dic[properties[i].Name]];
row.CreateCell(colIndex).SetCellValue(value);
}
}
var ms = new MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
//return File(ms, "application/vns.ms-excel", $"{filename}"); ;
return ms;
}
19
Source : APIDocGeneratorMiddleware.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private List<Argument> GenerateArguments(MethodInfo method)
{
var args = new List<Argument>();
foreach (var param in method.GetParameters())
{
if (param.ParameterType.IsClreplaced && param.ParameterType != typeof(string))
{
foreach (var prop in param.ParameterType.GetProperties())
{
args.Add(new Argument
{
Name = GetArgumentName(prop, prop.Name),
Required = JudgeRequired(prop.PropertyType, prop.CustomAttributes),
Type = ConvertTypeToArgumentType(prop.PropertyType)
});
}
}
else
{
args.Add(new Argument
{
Name = GetArgumentName(param, param.Name),
Required = !param.HasDefaultValue && JudgeRequired(param.ParameterType, param.CustomAttributes),
Type = ConvertTypeToArgumentType(param.ParameterType)
});
}
}
return args;
}
19
Source : MongoRepository.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public void Update<T>(T t)
{
// 条件
var id = t.GetType().GetProperty("_id").GetValue(t).ToString();
var filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
// 要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updateDefinition = Builders<T>.Update.Combine(list);
GetCollection<T>().UpdateOne(filter, updateDefinition);
}
19
Source : MongoRepository.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public async Task UpdateAsync<T>(T t)
{
// 条件
var id = t.GetType().GetProperty("Id").GetValue(t).ToString();
var filter = Builders<T>.Filter.Eq("_id", id);
// 要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updateDefinition = Builders<T>.Update.Combine(list);
await GetCollection<T>().UpdateOneAsync(filter, updateDefinition);
}
19
Source : MongoRepository.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public void Update<T>(FilterDefinition<T> filter, Dictionary<string, string> updateDic)
{
// 要修改的字段
var list = new List<UpdateDefinition<T>>();
var properties = typeof(T).GetProperties().Select(p => p.Name);
foreach (var kvp in updateDic)
{
if (properties.Contains(kvp.Key))
{
list.Add(Builders<T>.Update.Set(kvp.Key, kvp.Value));
}
}
var updateDefinition = Builders<T>.Update.Combine(list);
GetCollection<T>().UpdateMany(filter, updateDefinition);
}
19
Source : CSVGenerator.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public byte[] BuildFromCollection<T>(IEnumerable<T> items) where T : new()
{
var csv = new StringBuilder();
var type = typeof(T);
var properties = new List<PropertyInfo>();
var replacedle = new StringBuilder();
foreach (var prop in type.GetProperties().Where(t => t.GetCustomAttributes(typeof(CSVProperty), true).Any()))
{
properties.Add(prop);
var attribute = prop.GetCustomAttributes(typeof(CSVProperty), true).FirstOrDefault();
replacedle.Append($@"""{(attribute as CSVProperty)?.Name}"",");
}
csv.AppendLine(replacedle.ToString().Trim(','));
foreach (var item in items)
{
var newLine = new StringBuilder();
foreach (var prop in properties)
{
var propValue = prop.GetValue(item)?.ToString() ?? "null";
propValue = propValue.Replace("\r", "").Replace("\n", "").Replace("\\", "").Replace("\"", "");
newLine.Append($@"""{propValue}"",");
}
csv.AppendLine(newLine.ToString().Trim(','));
}
return csv.ToString().StringToBytes();
}
19
Source : InstranceMaker.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public static object Make(this Type type)
{
if (type == typeof(string))
{
return "an example string.";
}
else if (type == typeof(int) || type == typeof(int?))
{
return 0;
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
return DateTime.UtcNow;
}
else if (type == typeof(Guid) || type == typeof(Guid?))
{
return Guid.NewGuid();
}
else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
{
return DateTimeOffset.UtcNow;
}
else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?))
{
return TimeSpan.FromMinutes(37);
}
else if (type == typeof(bool) || type == typeof(bool?))
{
return true;
}
// List
else if (type.IsGenericType && type.GetGenericTypeDefinition().GetInterfaces().Any(t => t.IsreplacedignableFrom(typeof(IEnumerable))))
{
var itemType = type.GetGenericArguments()[0];
return GetArrayWithInstanceInherts(itemType);
}
// Array
else if (type.GetInterface(typeof(IEnumerable<>).FullName ?? string.Empty) != null)
{
var itemType = type.GetElementType();
var list = GetArrayWithInstanceInherts(itemType);
var array = Array.CreateInstance(itemType ?? typeof(string[]), list.Count);
list.CopyTo(array, 0);
return array;
}
else
{
var instance = GenerateWithConstructor(type);
if (instance != null)
{
foreach (var property in instance.GetType().GetProperties())
{
if (property.CustomAttributes.Any(t => t.AttributeType == typeof(JsonIgnoreAttribute)))
{
property.SetValue(instance, null);
}
else if (property.CustomAttributes.Any(t => t.AttributeType == typeof(InstanceMakerIgnore)))
{
property.SetValue(instance, null);
}
else if (property.SetMethod != null)
{
property.SetValue(instance, Make(property.PropertyType));
}
}
}
return instance;
}
}
19
Source : LinqToSql.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
protected object GetSingleValue(Expression ex)
{
if (ex.NodeType == ExpressionType.MemberAccess)
{
if (ex.ToString().Contains("DisplayClreplaced") || (ex as MemberExpression).Expression == null)
return Expression.Lambda(ex).Compile().DynamicInvoke();
var member = (ex as MemberExpression).Expression as ConstantExpression;
if (member?.Value.GetType().GetFields(_bindingFlags).Length > 0)
return member?.Value.GetType().GetFields(_bindingFlags).First().GetValue(member.Value);
else if (member?.Value.GetType().GetProperties().Length > 0)
return member?.Value.GetType().GetProperties().First().GetValue(member.Value);
else
return null;
}
else
{
var member = (ex as ConstantExpression);
return member?.Value;
}
}
19
Source : LinqToSql.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
protected Expression VisitConstantFixed(ConstantExpression c, string memName = "")
{
IQueryable q = c.Value as IQueryable;
var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
var isEnum = StringifyText != null;
string type = null;
if (isEnum)
type = CleanText();
if (q == null && c.Value == null)
{
sb.Append("NULL");
}
else if (q == null)
{
switch (Type.GetTypeCode(c.Value.GetType()))
{
case TypeCode.Boolean:
sb.Append(((bool)c.Value) ? (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1") : (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0"));
break;
case TypeCode.String:
CleanDecoder(string.Format("String[{0}]", c.Value));
break;
case TypeCode.DateTime:
CleanDecoder(string.Format("Date[{0}]", c.Value));
break;
case TypeCode.Object:
object value = null;
Type fieldType = null;
if (c.Value.GetType().GetFields(_bindingFlags).Length > 0 && (string.IsNullOrEmpty(memName) || c.Value.GetType().GetFields(_bindingFlags).Any(x => x.Name == memName)))
{
var field = string.IsNullOrEmpty(memName)
? c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault()
: c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault(x => x.Name == memName);
fieldType = field?.FieldType;
value = field?.GetValue(c.Value);
}
else
{
var field = string.IsNullOrEmpty(memName)
? c.Value.GetType().GetProperties().FirstOrDefault()
: c.Value.GetType().GetProperties().FirstOrDefault(x => x.Name == memName);
fieldType = field?.PropertyType;
value = field?.GetValue(c.Value);
}
if (value == null && fieldType == null)
break;
CleanDecoder(ValuetoSql(value, isEnum, fieldType));
break;
default:
if (isEnum && SavedTypes.ContainsKey(type))
{
var enumtype = SavedTypes[type];
var v = c.Value.ConvertValue(enumtype);
CleanDecoder(ValuetoSql(v, isEnum));
break;
}
CleanDecoder(ValuetoSql(c.Value, isEnum));
break;
}
}
return c;
}
19
Source : CodeGenerator.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void SetProperties(object instance, string varName, object defaultValues)
{
var instanceType = instance.GetType();
var listsToAdd = new Dictionary<string, IList>();
foreach (var pi in instanceType.GetProperties())
{
// check the [CodeGeneration] attribute
var cga = this.GetFirstAttribute<CodeGenerationAttribute>(pi);
if (cga != null && !cga.GenerateCode)
{
continue;
}
string name = varName + "." + pi.Name;
object value = pi.GetValue(instance, null);
object defaultValue = pi.GetValue(defaultValues, null);
// check if lists are equal
if (this.AreListsEqual(value as IList, defaultValue as IList))
{
continue;
}
// add items of lists
var list = value as IList;
if (list != null)
{
listsToAdd.Add(name, list);
continue;
}
// only properties with public setters are used
var setter = pi.GetSetMethod();
if (setter == null || !setter.IsPublic)
{
continue;
}
// skip default values
if ((value != null && value.Equals(defaultValue)) || value == defaultValue)
{
continue;
}
this.SetProperty(name, value);
}
// Add the items of the lists
foreach (var kvp in listsToAdd)
{
var name = kvp.Key;
var list = kvp.Value;
this.AddItems(name, list);
}
}
19
Source : PropertyTable.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void UpdateFields(IEnumerable items)
{
Type type = this.GereplacedemType(items);
if (type == null)
{
return;
}
this.Columns.Clear();
foreach (var pi in type.GetProperties())
{
// TODO: support Browsable and Displayname attributes
var header = pi.Name;
this.Fields.Add(new ItemsTableField(header, pi.Name, null, Alignment.Left));
}
}
19
Source : Reflection.cs
with MIT License
from alexis-
with MIT License
from alexis-
public static void CopyProperties(this object source, object destination)
{
// If any this null throw an exception
if (source == null || destination == null)
throw new Exception("Source or/and Destination Objects are null");
// Getting the Types of the objects
Type typeDest = destination.GetType();
Type typeSrc = source.GetType();
// Iterate the Properties of the source instance and
// populate them from their desination counterparts
PropertyInfo[] srcProps = typeSrc.GetProperties();
foreach (PropertyInfo srcProp in srcProps)
{
if (!srcProp.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeDest.GetProperty(srcProp.Name);
if (targetProperty == null)
{
continue;
}
if (!targetProperty.CanWrite)
{
continue;
}
if (targetProperty.GetSetMethod(true) != null && targetProperty.GetSetMethod(true).IsPrivate)
{
continue;
}
if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0)
{
continue;
}
if (!targetProperty.PropertyType.IsreplacedignableFrom(srcProp.PropertyType))
{
continue;
}
// Preplaceded all tests, lets set the value
targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
}
}
19
Source : Level.cs
with MIT License
from AlFasGD
with MIT License
from AlFasGD
public static Level MergeLevels(params Level[] levels)
{
if (levels.Length == 1)
return levels[0];
if (levels.Length == 0)
throw new Exception("Cannot merge 0 levels.");
Level result = levels[0].Clone();
for (int i = 1; i < levels.Length; i++)
{
result.LevelObjects.AddRange(levels[i].LevelObjects);
result.Guidelines.AddRange(levels[i].Guidelines);
result.BuildTime += levels[i].BuildTime;
if (levels[i].BinaryVersion > result.BinaryVersion)
result.BinaryVersion = levels[i].BinaryVersion;
}
result.ColorChannels = LevelColorChannels.GetCommonColors(levels);
result.Guidelines.RemoveDuplicatedGuidelines();
var properties = typeof(Level).GetProperties();
foreach (var p in properties)
{
if (p.GetCustomAttributes(typeof(CommonMergedPropertyAttribute), false).Length > 0)
{
bool common = true;
for (int i = 1; i < levels.Length && common; i++)
if (!(common = p.GetValue(result) != p.GetValue(levels[i])))
p.SetValue(result, default);
}
}
return result;
}
19
Source : LevelObjectFactory.cs
with MIT License
from AlFasGD
with MIT License
from AlFasGD
private static void GenerateSelfExecutingCode()
{
const string clreplacedName = "PropertyAccessInfoGenerator";
const string methodAName = "GetAppropriateGenericA";
const string methodBName = "GetAppropriateGenericB";
var getAppropriateGenericACode = new StringBuilder();
var getAppropriateGenericBCode = new StringBuilder();
// With the current indentation, the produced source is badly formatted, but at least this looks better
// In the following code, nameof and constants have been purposefully selectively used for "obvious" reasons
var propertyTypes = new HashSet<Type>();
foreach (var o in objectTypes)
{
var types = o.GetProperties().Select(p => p.PropertyType);
foreach (var t in types)
propertyTypes.Add(t);
var fullName = o.FullName;
getAppropriateGenericACode.Append($@"
if (objectType == typeof({fullName}))
return {methodBName}<{fullName}>(propertyType, info);");
}
foreach (var p in propertyTypes)
{
var fullName = p.FullName;
getAppropriateGenericBCode.Append($@"
if (propertyType == typeof({fullName}))
return new {nameof(PropertyAccessInfo)}<TO, {fullName}>(info);");
}
var allCode =
$@"
using System;
using System.Reflection;
namespace GDAPI.Special
{{
public static partial clreplaced {clreplacedName}
{{
public static {nameof(PropertyAccessInfo)} {methodAName}(Type objectType, Type propertyType, PropertyInfo info)
{{
{getAppropriateGenericACode}
throw new Exception(); // Don't make compiler sad
}}
public static {nameof(PropertyAccessInfo)} {methodBName}<TO>(Type propertyType, PropertyInfo info)
{{
{getAppropriateGenericBCode}
throw new Exception();
}}
}}
}}
";
// Compile all code
var provider = new CSharpCodeProvider();
var options = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", "System.dll", "System.CodeDom.dll" });
var replacedembly = provider.CompilereplacedemblyFromSource(options, allCode).Compiledreplacedembly;
var type = replacedembly.GetType(clreplacedName);
GetAppropriateGenericA = type.GetMethod(methodAName).CreateDelegate(typeof(Func<Type, Type, PropertyInfo, PropertyAccessInfo>)) as Func<Type, Type, PropertyInfo, PropertyAccessInfo>;
GetAppropriateGenericB = type.GetMethod(methodBName).CreateDelegate(typeof(Func<Type, PropertyInfo, PropertyAccessInfo>)) as Func<Type, PropertyInfo, PropertyAccessInfo>; // maybe useless?
}
19
Source : OpenApiSchemaExtensions.cs
with MIT License
from aliencube
with MIT License
from aliencube
[Obsolete("This method is now obsolete", error: true)]
public static Dictionary<string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
{
type.ThrowIfNullOrDefault();
var schema = (OpenApiSchema)null;
var schemeName = type.GetOpenApiTypeName(namingStrategy);
if (depth == 8)
{
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
depth++;
if (type.IsJObjectType())
{
schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiNullable(out var unwrappedValueType))
{
schema = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
schema.Nullable = true;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
if (!attribute.IsNullOrDefault())
{
var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());
schema.Extensions.Add("x-ms-visibility", visibility);
}
if (type.IsUnflaggedEnumType())
{
var converterAttribute = type.GetCustomAttribute<JsonConverterAttribute>();
if (!converterAttribute.IsNullOrDefault()
&& typeof(StringEnumConverter).IsreplacedignableFrom(converterAttribute.ConverterType))
{
var enums = type.ToOpenApiStringCollection(namingStrategy);
schema.Type = "string";
schema.Format = null;
schema.Enum = enums;
schema.Default = enums.First();
}
else
{
var enums = type.ToOpenApiIntegerCollection();
schema.Enum = enums;
schema.Default = enums.First();
}
}
if (type.IsSimpleType())
{
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiDictionary())
{
schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiArray())
{
schema.Type = "array";
schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
var allProperties = type.IsInterface
? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
: type.GetProperties();
var properties = allProperties.Where(p => !p.ExistsCustomAttribute<JsonIgnoreAttribute>());
var retVal = new Dictionary<string, OpenApiSchema>();
foreach (var property in properties)
{
var visiblity = property.GetCustomAttribute<OpenApiSchemaVisibilityAttribute>(inherit: false);
var propertyName = property.GetJsonPropertyName(namingStrategy);
var ts = property.DeclaringType.GetGenericArguments();
if (!ts.Any())
{
if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var enumReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = enumReference };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else if (property.PropertyType.IsOpenApiDictionary())
{
var elementType = property.PropertyType.GetGenericArguments()[1];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var elementReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = new OpenApiSchema() { Reference = elementReference }
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
}
}
else if (property.PropertyType.IsOpenApiArray())
{
var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(elementReference);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = new OpenApiSchema()
{
Reference = reference1
}
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
}
}
else
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = reference1 };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
continue;
}
var reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiRootReferenceId()
};
var referenceSchema = new OpenApiSchema() { Reference = reference };
if (!ts.Contains(property.PropertyType))
{
if (property.PropertyType.IsOpenApiDictionary())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
continue;
}
if (property.PropertyType.IsOpenApiArray())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
}
retVal[schemeName] = schema;
return retVal;
}
19
Source : HttpClientExtensions.cs
with MIT License
from alimon808
with MIT License
from alimon808
public async static Task<HttpResponseMessage> PostFormDataAsync<T>(this HttpClient client, string url, T viewModel, KeyValuePair<string, string>? antiForgeryToken = null)
{
var list = viewModel.GetType()
.GetProperties()
.Select(t => new KeyValuePair<string, string>(t.Name, (t.GetValue(viewModel) ?? new object()).ToString()))
.ToList();
if (antiForgeryToken.HasValue)
list.Add(antiForgeryToken.Value);
var formData = new FormUrlEncodedContent(list);
return await client.PostAsync(url, formData);
}
See More Examples