Here are the examples of the csharp api System.Reflection.PropertyInfo.GetValue(object, System.Reflection.BindingFlags, System.Reflection.Binder, object[], System.Globalization.CultureInfo) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1106 Examples
19
View Source File : ScAllColumnTypes.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task Exec(IScenarioContext context)
{
bool isPostgres = context.Dialect == SqlDialect.PgSql;
var table = new TableItAllColumnTypes(isPostgres);
await context.Database.Statement(table.Script.DropAndCreate());
var testData = GetTestData(isPostgres);
await InsertDataInto(table, testData)
.MapData(Mapping)
.Exec(context.Database);
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
var map = cfg.CreateMap<IDataRecord, AllColumnTypesDto>();
map
.ForMember(nameof(table.ColByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableFixedSizeByteArray), c => c.Ignore())
.ForMember(nameof(table.ColFixedSizeByteArray), c => c.Ignore());
if (isPostgres)
{
map
.ForMember(nameof(table.ColByte), c => c.Ignore())
.ForMember(nameof(table.ColNullableByte), c => c.Ignore());
}
if (context.Dialect == SqlDialect.MySql)
{
map
.ForMember(nameof(table.ColBoolean), c => c.MapFrom((r, dto) => r.GetBoolean(r.GetOrdinal(nameof(table.ColBoolean)))))
.ForMember(nameof(table.ColNullableBoolean), c => c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableBoolean))) ? (bool?)null : r.GetBoolean(r.GetOrdinal(nameof(table.ColNullableBoolean)))))
.ForMember(nameof(table.ColGuid), c => c.MapFrom((r, dto) => r.GetGuid(r.GetOrdinal(nameof(table.ColGuid)))))
.ForMember(nameof(table.ColNullableGuid), c=>c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableGuid)))? (Guid?)null : r.GetGuid(r.GetOrdinal(nameof(table.ColNullableGuid)))));
}
}));
var expr = Select(table.Columns)
.From(table).Done();
context.WriteLine(PgSqlExporter.Default.ToSql(expr));
var result = await expr
.QueryList(context.Database, r =>
{
var allColumnTypesDto = mapper.Map<IDataRecord, AllColumnTypesDto>(r);
allColumnTypesDto.ColByteArrayBig = StreamToByteArray(table.ColByteArrayBig.GetStream(r));
allColumnTypesDto.ColByteArraySmall = table.ColByteArraySmall.Read(r);
allColumnTypesDto.ColNullableByteArrayBig = table.ColNullableByteArrayBig.Read(r);
allColumnTypesDto.ColNullableByteArraySmall = table.ColNullableByteArraySmall.Read(r);
allColumnTypesDto.ColFixedSizeByteArray = table.ColFixedSizeByteArray.Read(r);
allColumnTypesDto.ColNullableFixedSizeByteArray = table.ColNullableFixedSizeByteArray.Read(r);
return allColumnTypesDto;
});
static byte[] StreamToByteArray(Stream stream)
{
var buffer = new byte[stream.Length];
using MemoryStream ms = new MemoryStream(buffer);
stream.CopyTo(ms);
var result = buffer;
stream.Dispose();
return result;
}
for (int i = 0; i < testData.Length; i++)
{
if (!Equals(testData[i], result[i]))
{
var props = typeof(AllColumnTypesDto).GetProperties();
foreach (var propertyInfo in props)
{
context.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(testData[i])} - {propertyInfo.GetValue(result[i])}");
}
throw new Exception("Input and output are not identical!");
}
}
if (context.Dialect == SqlDialect.TSql)
{
var data = await Select(AllTypes.GetColumns(table))
.From(table)
.QueryList(context.Database, (r) => AllTypes.Read(r, table));
if (data.Count != 2)
{
throw new Exception("Incorrect reading using models");
}
await InsertDataInto(table, data).MapData(AllTypes.GetMapping).Exec(context.Database);
}
Console.WriteLine("'All Column Type Test' is preplaceded");
}
19
View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
{
try
{
var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于
var fieldProp = GetFieldPropertyInfo(player, field);
if (fieldProp == null)
{
return false;
}
var objectValue = fieldProp.GetValue(player);
var typeCode = Type.GetTypeCode(fieldProp.GetType());
switch (typeCode)
{
case TypeCode.Int32:
return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));
case TypeCode.Int64:
return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));
case TypeCode.Decimal:
return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));
case TypeCode.Double:
return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));
case TypeCode.Boolean:
return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));
case TypeCode.DateTime:
return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));
case TypeCode.String:
return relations.Contains(strValue.CompareTo(objectValue));
default:
throw new Exception($"不支持的数据类型: {typeCode}");
}
}
catch (Exception ex)
{
_logger.LogError($"CheckField Exception:{ex}");
return false;
}
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void Show()
{
OpLock.Apply();
try
{
Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
if (!cache_prop.ContainsKey(item.GetType()))
{
_reflectProps(item.GetType());
}
if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
{
var insp = new InspectPanel();
currentEdit = insp;
int idx = 0;
foreach (var kv in itemProps)
{
string name = kv.Key;
Type propType = kv.Value.PropertyType;
object value = kv.Value.GetValue(item, null);
value = Convert.ToSingle(value);
ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();
LogProp(propType, name, value);
if(idx == 0)
{
insp.UpdateName(idx,name);
if(con is IntConstraint)
{
//Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
}
else if(con is FloatConstraint)
{
//Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
}
else
{
throw new ArgumentException();
}
//Logger.LogDebug($"Check3 {value}-{value.GetType()}");
insp.UpdateValue(idx, (float)value);
}
else
{
insp.AppendPropPanel(name);
if (con is IntConstraint)
{
insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
}
else if (con is FloatConstraint)
{
insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
}
else
{
throw new ArgumentException();
}
insp.UpdateValue(idx, (float)value);
insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));
}
//insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
insp.AddListener(idx, (v) => {
if (ItemManager.Instance.currentSelect == null)
return;
object val;
try
{
if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
{
val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
}
else
val = Convert.ChangeType(v, kv.Value.PropertyType);
ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
}
catch
{
Logger.LogError("Error occour at Inspect OnValue Chnaged");
Hide();
}
});
idx++;
}
}
else
{
Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
}
}
catch(NullReferenceException e)
{
Logger.LogError($"NulRef Error at Inspector.Show:{e}");
OpLock.Undo();
}
}
19
View Source File : VelocityEmitterEditor.cs
License : MIT License
Project Creator : aarthificial
License : MIT License
Project Creator : aarthificial
private static bool TryGetRendererData(out ForwardRendererData data)
{
if (!(GraphicsSettings.currentRenderPipeline is UniversalRenderPipelinereplacedet pipeline))
{
data = null;
return false;
}
data = typeof(UniversalRenderPipelinereplacedet).GetProperty(
"scriptableRendererData",
BindingFlags.Instance | BindingFlags.NonPublic
)
?.GetValue(pipeline) as ForwardRendererData;
return data != null;
}
19
View Source File : MixedRealityInspectorUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static Rect GetEditorMainWindowPos()
{
var containerWinType = AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).FirstOrDefault(t => t.Name == "ContainerWindow");
if (containerWinType == null)
{
throw new MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
}
var showModeField = containerWinType.GetField("m_ShowMode", BindingFlags.NonPublic | BindingFlags.Instance);
var positionProperty = containerWinType.GetProperty("position", BindingFlags.Public | BindingFlags.Instance);
if (showModeField == null || positionProperty == null)
{
throw new MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity");
}
var windows = Resources.FindObjectsOfTypeAll(containerWinType);
foreach (var win in windows)
{
var showMode = (int)showModeField.GetValue(win);
if (showMode == 4) // main window
{
var pos = (Rect)positionProperty.GetValue(win, null);
return pos;
}
}
throw new NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity");
}
19
View Source File : GeneratedInternalTypeHelper.g.i.cs
License : GNU General Public License v3.0
Project Creator : AdhocAdam
License : GNU General Public License v3.0
Project Creator : AdhocAdam
protected override object GetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, System.Globalization.CultureInfo culture) {
return propertyInfo.GetValue(target, System.Reflection.BindingFlags.Default, null, null, culture);
}
19
View Source File : Hotkeys.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
[MenuItem("Edit/HotKeys/Toggle Lock &q")]
static void ToggleInspectorLock() {
if (_mouseOverWindow == null) {
if (!EditorPrefs.HasKey("LockableInspectorIndex"))
EditorPrefs.SetInt("LockableInspectorIndex", 0);
int i = EditorPrefs.GetInt("LockableInspectorIndex");
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
Object[] findObjectsOfTypeAll = Resources.FindObjectsOfTypeAll(type);
_mouseOverWindow = (EditorWindow)findObjectsOfTypeAll[i];
}
if (_mouseOverWindow != null && _mouseOverWindow.GetType().Name == "InspectorWindow") {
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
PropertyInfo propertyInfo = type.GetProperty("isLocked");
bool value = (bool)propertyInfo.GetValue(_mouseOverWindow, null);
propertyInfo.SetValue(_mouseOverWindow, !value, null);
_mouseOverWindow.Repaint();
}
}
19
View Source File : ExportButtom.razor.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : 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
View Source File : HttpStoreBase.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : 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
View Source File : ClientRegisterationConverter.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private static void ReadLocalizableProperty(JsonReader reader, ClientRegisteration existingValue, string[] propertyInfo, PropertyInfo property)
{
var value = property.GetValue(existingValue) as List<LocalizableProperty>;
if (value == null)
{
value = new List<LocalizableProperty>();
}
value.Add(new LocalizableProperty
{
Culture = propertyInfo.Length > 1 ? propertyInfo[1] : null,
Value = reader.Readreplacedtring()
});
property.SetValue(existingValue, value);
}
19
View Source File : MemoryCacheManager.cs
License : MIT License
Project Creator : ahmet-cetinkaya
License : MIT License
Project Creator : ahmet-cetinkaya
public void RemoveByPattern(string pattern)
{
var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection",
BindingFlags.NonPublic | BindingFlags.Instance);
var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;
var cacheCollectionValues = new List<ICacheEntry>();
foreach (var cacheItem in cacheEntriesCollection)
{
ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
cacheCollectionValues.Add(cacheItemValue);
}
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = cacheCollectionValues
.Where(d => regex.IsMatch(d.Key.ToString()))
.Select(d => d.Key)
.ToList();
foreach (var key in keysToRemove) _memoryCache.Remove(key);
}
19
View Source File : Optional.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var type = property.PropertyType;
if (!type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IOptional)))
return property;
// we cache the PropertyInfo object here (it's captured in closure). we don't have direct
// access to the property value so we have to reflect into it from the parent instance
// we use UnderlyingName instead of PropertyName in case the C# name is different from the Json name.
var declaringMember = property.DeclaringType.GetTypeInfo().DeclaredMembers
.FirstOrDefault(e => e.Name == property.UnderlyingName);
switch (declaringMember)
{
case PropertyInfo declaringProp:
property.ShouldSerialize = instance => // instance here is the declaring (parent) type
{
var optionalValue = declaringProp.GetValue(instance);
return (optionalValue as IOptional).HasValue;
};
return property;
case FieldInfo declaringField:
property.ShouldSerialize = instance => // instance here is the declaring (parent) type
{
var optionalValue = declaringField.GetValue(instance);
return (optionalValue as IOptional).HasValue;
};
return property;
default:
throw new InvalidOperationException(
"Can only serialize Optional<T> members that are fields or properties");
}
}
19
View Source File : Drop.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public void Apply(CollectionWorkSpace<T> workspace)
{
var property = typeof(T).GetProperty(PropertyName);
var toRemove = workspace.List.FirstOrDefault(t => property?.GetValue(t, null)?.Equals(ExpectValue) ?? false);
if (toRemove is not null)
{
workspace.List.Remove(toRemove);
}
}
19
View Source File : Patch.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public void Apply(CollectionWorkSpace<T> workspace)
{
var property = typeof(T).GetProperty(SearchPropertyName);
var patchProperty = typeof(T).GetProperty(PatchPropertyName);
var toPatch = workspace.List.FirstOrDefault(t => property?.GetValue(t, null)?.Equals(ExpectValue) ?? false);
if (toPatch is not null)
{
patchProperty?.SetValue(toPatch, NewValue);
}
}
19
View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
public override bool TryGetIndex (GetIndexBinder binder, object[] indexes, out object result)
{
if (WrapsNullInstance) ThrowNullException ($"invoke an indexer");
if (WrapsType) ThrowTargetException ($"invoke an indexer");
UnwrapArgs (indexes);
string newParent = _path + "[" + string.Join (",", indexes) + "]";
try
{
if (_type.IsArray && indexes.All (x => x is int))
result = new Uncapsulator (newParent, _options, ((Array)Value).GetValue (indexes.Select (x => (int)x).ToArray ()));
else
{
var indexer = SelectIndexer (indexes);
var returnValue = indexer.GetValue (Value, _instanceFlags, null, indexes, null);
result = new Uncapsulator (newParent, _options, returnValue, callSiteType: indexer.PropertyType);
}
}
catch (Exception ex)
{
throw new MemberAccessException ($"Unable to invoke get-indexer on type '{_type}' - {ex.Message}", ex).Wrap ();
}
return true;
}
19
View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public static DisableBatchingType GetDisableBatching( Shader s )
{
return ( DisableBatchingType ) ShaderEx.Type.GetProperty( "disableBatching", BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( s, new object[ 0 ] );
}
19
View Source File : YellowTeleportationPortal.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
private void SetProperties(BlueTeleportationPortal a)
{
foreach (var p in properties)
p.SetValue(this, p.GetValue(a));
Y = a.Y + a.YellowTeleportationPortalDistance;
Rotation = a.Rotation;
}
19
View Source File : CloudEventContentTests.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
[TestMethod]
public void Given_CloudEvent_When_Instantiated_Should_HaveProperty()
{
var data = "hello world";
var ev = new AnotherFakeEvent();
ev.EventType = "com.example.someevent";
ev.CloudEventsVersion = "0.1";
ev.Source = (new Uri("http://localhost")).ToString();
ev.EventId = Guid.NewGuid().ToString();
ev.Data = data;
var content = new FakeCloudEventContent<string>(ev);
var pi = typeof(FakeCloudEventContent<string>).GetProperty("CloudEvent", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty);
pi.GetValue(content).Should().NotBeNull();
pi.GetValue(content).Should().Be(ev);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
LConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
L = Log.Logger = LConfig.CreateLogger();
Type[] BindOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t == typeof(Options) || t.IsSubclreplacedOf(typeof(Options))).ToArray();
MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments"
&& m.GetGenericArguments().Count() == BindOptionTypes.Count()).First();
Parser p = new Parser();
ParserResult<object> result = (ParserResult<object>)parseArgumentsMethod.MakeGenericMethod(BindOptionTypes).Invoke(p, new object[] { p, args });
result.WithNotParsed((IEnumerable<Error> errors) =>
{
HelpText help = GetAutoBuiltHelpText(result);
help.MaximumDisplayWidth = Console.WindowWidth;
help.Copyright = string.Empty;
help.Heading = new HeadingInfo("Compute.NET Bindings CLI", Version.ToString(3));
help.AddPreOptionsLine(string.Empty);
if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
{
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
{
HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
if (error.Type != null)
{
help.AddVerbs(error.Type);
}
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
{
help.AddVerbs(BindOptionTypes);
L.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
{
help.AddVerbs(BindOptionTypes);
help.AddPreOptionsLine("No library selected. Select a library or verb from the options below:");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
{
MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
{
MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
{
UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"Unknown option: {error.Token}.");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}");
help.AddVerbs(BindOptionTypes);
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
})
.WithParsed<Options>(o =>
{
if (string.IsNullOrEmpty(o.ModuleName))
{
Log.Error($"You must select a MKL module to create bindings for. Use the --help option to get the list of available modules.");
Exit(ExitResult.INVALID_OPTIONS);
}
if (!string.IsNullOrEmpty(o.Root) && !Directory.Exists(o.Root))
{
Log.Error($"The library root directory specified {o.Root} does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!string.IsNullOrEmpty(o.Root))
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(o.Root));
}
foreach (PropertyInfo prop in o.GetType().GetProperties())
{
ProgramOptions.Add(prop.Name, prop.GetValue(o));
}
})
.WithParsed<MKLOptions>(o =>
{
if (!ProgramOptions.ContainsKey("RootDirectory"))
{
string e = Environment.GetEnvironmentVariable("MKLROOT");
if (string.IsNullOrEmpty(e))
{
L.Error("The --root option was not specified and the MKLROOT environment variable was not found.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!Directory.Exists(e))
{
L.Error("The --root option was not specified and the directory specified by the MKLROOT environment variable does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
ProgramOptions.Add("Root", e);
}
else
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));
}
}
ProgramLibrary = new MKL(ProgramOptions);
ConsoleDriver.Run(ProgramLibrary);
if (ProgramLibrary.CleanAndFixup())
{
Exit(ExitResult.SUCCESS);
}
else
{
Exit(ExitResult.ERROR_DURING_CLEANUP);
}
})
.WithParsed<CUDAOptions>(o =>
{
if (!ProgramOptions.ContainsKey("RootDirectory"))
{
string e = Environment.GetEnvironmentVariable("CUDA_PATH");
if (string.IsNullOrEmpty(e))
{
L.Error("The --root option was not specified and the CUDA_PATH environment variable was not found.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!Directory.Exists(e))
{
L.Error("The --root option was not specified and the directory specified by the CUDA_PATH environment variable does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
ProgramOptions.Add("Root", e);
}
else
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));
}
}
ProgramLibrary = new CUDA(ProgramOptions);
ConsoleDriver.Run(ProgramLibrary);
if (ProgramLibrary.CleanAndFixup())
{
Exit(ExitResult.SUCCESS);
}
else
{
Exit(ExitResult.ERROR_DURING_CLEANUP);
}
});
}
19
View Source File : Program.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
LConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.Enrich.WithProcessId()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
L = Log.Logger = LConfig.CreateLogger();
Type[] BenchmarkOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t.IsSubclreplacedOf(typeof(Options))).ToArray();
MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" && m.GetGenericArguments().Count() == BenchmarkOptionTypes.Count()).First();
Parser p = new Parser();
ParserResult<object> result = (ParserResult<object>) parseArgumentsMethod.MakeGenericMethod(BenchmarkOptionTypes).Invoke(p , new object[] { p, args });
result.WithNotParsed((IEnumerable<Error> errors) =>
{
HelpText help = GetAutoBuiltHelpText(result);
help.MaximumDisplayWidth = Console.WindowWidth;
help.Copyright = string.Empty;
help.Heading = new HeadingInfo("jemalloc.NET", Version.ToString(3));
help.AddPreOptionsLine(string.Empty);
if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
{
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
{
HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
if (error.Type != null)
{
help.AddVerbs(error.Type);
}
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
{
help.AddVerbs(BenchmarkOptionTypes);
L.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
{
help.AddVerbs(BenchmarkOptionTypes);
help.AddPreOptionsLine("No category selected. Select a category from the options below:");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
{
MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
{
MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
{
UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"Unknown option: {error.Token}.");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(' ', errors.Select(e => e.Tag.ToString()).ToArray())}");
help.AddVerbs(BenchmarkOptionTypes);
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
})
.WithParsed((Options o) =>
{
foreach (PropertyInfo prop in o.GetType().GetProperties())
{
BenchmarkOptions.Add(prop.Name, prop.GetValue(o));
}
if (o.ColdStart)
{
JemBenchmarkJobAttribute.ColdStartOverride = true;
}
if (o.TargetCount > 0)
{
JemBenchmarkJobAttribute.TargetCountOverride = o.TargetCount;
}
if (o.Once)
{
JemBenchmarkJobAttribute.ColdStartOverride = true;
JemBenchmarkJobAttribute.TargetCountOverride = 1;
}
})
.WithParsed<MallocBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.MALLOC);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Fragment)
{
BenchmarkOptions.Add("Operation", Operation.FRAGMENT);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --fill.");
Exit(ExitResult.SUCCESS);
}
else
{
Benchmark(o);
}
})
.WithParsed<FixedBufferBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.BUFFER);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Math)
{
BenchmarkOptions.Add("Operation", Operation.MATH);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill.");
Exit(ExitResult.SUCCESS);
}
else
{
Benchmark(o);
}
})
.WithParsed<SafeArrayBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.NARRAY);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Math)
{
BenchmarkOptions.Add("Operation", Operation.MATH);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
})
.WithParsed<HugeNativeArrayBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.HUGEARRAY);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill or --math.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
})
.WithParsed<VectorBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.VECTOR);
if (o.Mandelbrot)
{
BenchmarkOptions.Add("Operation", Operation.MANDELBROT);
o.Float = true;
o.Int8 = o.Int16 = o.Int32 = o.Int64 = o.Double = o.String = o.Udt = false;
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Test)
{
BenchmarkOptions.Add("Operation", Operation.TEST);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select a vector operation to benchmark with --mandel or --fill or --test.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
});
}
19
View Source File : CustomEffectFactory.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
private int GetterImpl(IntPtr thisPtr, IntPtr dataPtr, int datasize, out int actualSize)
{
actualSize = Marshal.SizeOf<U>();
if (dataPtr == IntPtr.Zero)
return Result.Ok.Code;
var shadow = ToShadow(thisPtr);
var callback = (ID2D1EffectImpl)shadow.Callback;
var value = (U)PropertyInfo.GetValue(callback);
Marshal.StructureToPtr(value, dataPtr, true);
return Result.Ok.Code;
}
19
View Source File : PropertyViewModelFactory.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public PropertyViewModel Create(object model, PropertyInfo propertyInfo, object? index)
{
object? value = null;
try
{
value = propertyInfo.GetValue(model, index is null ? null : new object[] { index });
}
catch
{
}
Type type = value?.GetType() ?? propertyInfo.PropertyType;
PropertyViewModel propertyViewModel;
if (factories.TryGetValue(type, out IPropertyViewModelFactory factory))
{
propertyViewModel = factory.Create(model, propertyInfo);
}
else
{
if (factories.TryGetValue(type, out IPropertyViewModelFactory? propertyFactory))
{
propertyViewModel = propertyFactory.Create(model, propertyInfo);
}
else
{
propertyViewModel = value switch
{
null => new NullPropertyViewModel(model, propertyInfo),
Enum _ => new EnumPropertyViewModel(model, propertyInfo),
IList _ => new CollectionPropertyViewModel(model, propertyInfo),
_ => new ClreplacedPropertyViewModel(model, propertyInfo)
};
}
}
19
View Source File : MemberInfoExtensions.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static object? GetMemberValue(this MemberInfo memberInfo, object? obj)
{
ShaderResourceAttribute? shaderResourceAttribute = memberInfo.GetCustomAttribute<ShaderResourceAttribute>();
return shaderResourceAttribute?.ResourceType ?? memberInfo switch
{
FieldInfo fieldInfo => obj is null ? null : fieldInfo.GetValue(obj),
PropertyInfo propertyInfo => obj is null ? null : propertyInfo.GetValue(obj),
_ => null
};
19
View Source File : MemberInfoExtensions.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static Type? GetMemberType(this MemberInfo memberInfo, object? obj = null)
{
ShaderResourceAttribute? shaderResourceAttribute = memberInfo.GetCustomAttribute<ShaderResourceAttribute>();
return shaderResourceAttribute?.ResourceType ?? memberInfo switch
{
FieldInfo fieldInfo => obj is null ? fieldInfo.FieldType : fieldInfo.GetValue(obj)?.GetType() ?? fieldInfo.FieldType,
PropertyInfo propertyInfo => obj is null ? propertyInfo.PropertyType : propertyInfo.GetValue(obj)?.GetType() ?? propertyInfo.PropertyType,
_ => null
};
19
View Source File : DSharpUtil.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public static string GetSessionId(this DiscordVoiceState voiceState)
=> (string)_sessionIdProperty.GetValue(voiceState);
19
View Source File : DSharpUtil.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public static string GetVoiceToken(this VoiceServerUpdateEventArgs voiceServerUpdateEventArgs)
=> (string)_voiceTokenProperty.GetValue(voiceServerUpdateEventArgs);
19
View Source File : GradientEditor.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public override void PaintValue(PaintValueEventArgs e)
{
if(e.Value is GradientStyle)
{
// Create chart graphics object
if(_chartGraph == null)
{
_chartGraph = new ChartGraphics(null);
}
_chartGraph.Graphics = e.Graphics;
// Try to get original color from the object
Color color1 = Color.Black;
Color color2 = Color.White;
if(e.Context != null && e.Context.Instance != null)
{
// Get color properties using reflection
PropertyInfo propertyInfo = e.Context.Instance.GetType().GetProperty("BackColor");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
propertyInfo = e.Context.Instance.GetType().GetProperty("BackColor");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
// If object do not have "BackColor" property try using "Color" property
propertyInfo = e.Context.Instance.GetType().GetProperty("Color");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
}
}
propertyInfo = e.Context.Instance.GetType().GetProperty("BackSecondaryColor");
if(propertyInfo != null)
{
color2 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
propertyInfo = e.Context.Instance.GetType().GetProperty("BackSecondaryColor");
if(propertyInfo != null)
{
color2 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
}
}
// Check if colors are valid
if(color1 == Color.Empty)
{
color1 = Color.Black;
}
if(color2 == Color.Empty)
{
color2 = Color.White;
}
if(color1 == color2)
{
color2 = Color.FromArgb(color1.B, color1.R, color1.G);
}
// Draw gradient sample
if((GradientStyle)e.Value != GradientStyle.None)
{
Brush brush = _chartGraph.GetGradientBrush( e.Bounds, color1, color2, (GradientStyle)e.Value);
e.Graphics.FillRectangle( brush, e.Bounds);
brush.Dispose();
}
}
}
19
View Source File : HatchStyleEditor.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public override void PaintValue(PaintValueEventArgs e)
{
if(e.Value is ChartHatchStyle)
{
// Create chart graphics object
if(_chartGraph == null)
{
_chartGraph = new ChartGraphics(null);
}
_chartGraph.Graphics = e.Graphics;
// Try to get original color from the object
Color color1 = Color.Black;
Color color2 = Color.White;
if(e.Context != null && e.Context.Instance != null)
{
// Get color properties using reflection
PropertyInfo propertyInfo = e.Context.Instance.GetType().GetProperty("BackColor");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
propertyInfo = e.Context.Instance.GetType().GetProperty("BackColor");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
// If object do not have "BackColor" property try using "Color" property
propertyInfo = e.Context.Instance.GetType().GetProperty("Color");
if(propertyInfo != null)
{
color1 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
}
}
propertyInfo = e.Context.Instance.GetType().GetProperty("BackSecondaryColor");
if(propertyInfo != null)
{
color2 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
else
{
propertyInfo = e.Context.Instance.GetType().GetProperty("BackSecondaryColor");
if(propertyInfo != null)
{
color2 = (Color)propertyInfo.GetValue(e.Context.Instance, null);
}
}
}
// Check if colors are valid
if(color1 == Color.Empty)
{
color1 = Color.Black;
}
if(color2 == Color.Empty)
{
color2 = Color.White;
}
if(color1 == color2)
{
color2 = Color.FromArgb(color1.B, color1.R, color1.G);
}
// Draw hatch sample
if((ChartHatchStyle)e.Value != ChartHatchStyle.None)
{
Brush brush = _chartGraph.GetHatchBrush((ChartHatchStyle)e.Value,color1, color2);
e.Graphics.FillRectangle( brush, e.Bounds);
brush.Dispose();
}
}
}
19
View Source File : SpellPanelConfigViewModel.Visual.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private void FirstSpell_PropertyChanged(
object sender,
PropertyChangedEventArgs e)
{
var targets = new[]
{
nameof(Spell.WarningTime),
nameof(Spell.ChangeFontColorsWhenWarning),
nameof(Spell.IsReverse),
nameof(Spell.BarWidth),
nameof(Spell.BarHeight),
nameof(Spell.SpellIconSize),
nameof(Spell.HideSpellName),
nameof(Spell.OverlapRecastTime),
nameof(Spell.ReduceIconBrightness),
nameof(Spell.ProgressBarVisible),
nameof(Spell.HideCounter),
nameof(Spell.DontHide),
};
if (!targets.Contains(e.PropertyName))
{
return;
}
var pi = typeof(Spell).GetProperty(e.PropertyName);
var value = pi.GetValue(this.FirstSpell);
foreach (var spell in this.Spells)
{
pi.SetValue(spell, value);
}
}
19
View Source File : TimelineModel.DefaultValues.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private void SetDefaultValues()
{
var defaults = this.Defaults.Union(GetSuperDefaultValues())
.Where(x => (x.Enabled ?? true));
this.Walk((element) =>
{
inheritsElement(element);
setDefaultValuesToElement(element);
return false;
});
void setDefaultValuesToElement(TimelineBase element)
{
try
{
foreach (var def in defaults
.Where(x => x.TargetElement == element.TimelineType))
{
var pi = GetPropertyInfo(element, def.TargetAttribute);
if (pi == null)
{
continue;
}
var value = pi.GetValue(element);
if (value == null)
{
object defValue = null;
if (def.Value != null)
{
var type = pi.PropertyType;
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = Nullable.GetUnderlyingType(type);
}
if (!type.IsEnum)
{
defValue = Convert.ChangeType(def.Value, type);
}
else
{
defValue = Enum.Parse(type, def.Value, true);
}
}
if (defValue != null)
{
pi.SetValue(element, defValue);
}
}
}
}
catch (Exception ex)
{
Logger.Write($"{TimelineConstants.LogSymbol} Load default values error.", ex);
}
}
void inheritsElement(TimelineBase element)
{
if (string.IsNullOrEmpty(element.Inherits))
{
return;
}
var super = default(TimelineBase);
this.Walk(x =>
{
if (x.Enabled.GetValueOrDefault() &&
x.TimelineType == element.TimelineType &&
!string.IsNullOrEmpty(x.Name) &&
string.Equals(x.Name, element.Inherits, StringComparison.OrdinalIgnoreCase))
{
super = x;
return true;
}
return false;
});
if (super == null)
{
return;
}
var properties = super.GetType().GetProperties(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
foreach (var pi in properties)
{
var superValue = pi.GetValue(super);
if (superValue == null)
{
continue;
}
var targetValue = pi.GetValue(element);
if (targetValue == null)
{
pi.SetValue(element, superValue);
}
}
}
}
19
View Source File : MessagePropertyIntercepter.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
protected override object GetObjectProperty(string name)
{
PropertyInfo propertyInfo = this.messageType.GetProperty(name, publicBinding);
if (name.StartsWith("NMS"))
{
if (null != propertyInfo && propertyInfo.CanRead)
{
return propertyInfo.GetValue(this.message, null);
}
else
{
FieldInfo fieldInfo = this.messageType.GetField(name, publicBinding);
if (null != fieldInfo)
{
return fieldInfo.GetValue(this.message);
}
}
}
return base.GetObjectProperty(name);
}
19
View Source File : AIEditorExtensions.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
internal static void Setreplacedle(this EditorWindow win, string replacedle, Texture2D icon)
{
#if UNITY_5 || UNITY_2017
win.replacedleContent = new GUIContent(replacedle, icon);
#else
win.replacedle = replacedle;
//Set the tab icon. Since texture are destroyed between playmode changes, we have to reapply this.
var propertyInfo = typeof(EditorWindow).GetProperty("cachedreplacedleContent", BindingFlags.Instance | BindingFlags.NonPublic);
if (propertyInfo != null)
{
var style = (GUIContent)propertyInfo.GetValue(win, null);
style.image = icon;
}
#endif
}
19
View Source File : WrappedPropertyInfo.cs
License : MIT License
Project Creator : Aragas
License : MIT License
Project Creator : Aragas
public override object? GetValue(object? obj, object?[]? index) => _propertyInfoImplementation.GetValue(_instance, index);
19
View Source File : WrappedPropertyInfo.cs
License : MIT License
Project Creator : Aragas
License : MIT License
Project Creator : Aragas
public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) =>
_propertyInfoImplementation.GetValue(_instance, invokeAttr, binder, index, culture);
19
View Source File : BuildingInputState.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
private bool ModifiedProperty([CallerMemberName] string callerMemberName = null)
{
var member = callerMemberName.Replace("Brush", "").Replace("FontWeight", "");
var propertyInfo = typeof(Sia2024RecordEx).GetProperty(member);
return !AreEqual((double) propertyInfo.GetValue(_siaRoom),
(double) propertyInfo.GetValue(Sia2024Record.Lookup(_siaRoom)));
}
19
View Source File : ExceptionTelemetryConverter.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
private void EnrichWithExceptionProperties(LogEvent logEvent, ExceptionTelemetry exceptionTelemetry)
{
Type exceptionType = logEvent.Exception.GetType();
PropertyInfo[] exceptionProperties = exceptionType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo exceptionProperty in exceptionProperties)
{
string key = String.Format(_options.PropertyFormat, exceptionProperty.Name);
var value = exceptionProperty.GetValue(logEvent.Exception)?.ToString();
exceptionTelemetry.Properties[key] = value;
}
}
19
View Source File : ToolboxEditorToolbar.cs
License : MIT License
Project Creator : arimger
License : MIT License
Project Creator : arimger
private static IEnumerator Initialize()
{
while (toolbar == null)
{
//try to find aldready created Toolbar object
var toolbars = Resources.FindObjectsOfTypeAll(toolbarType);
if (toolbars == null || toolbars.Length == 0)
{
yield return null;
continue;
}
else
{
toolbar = toolbars[0];
}
}
#if UNITY_2020_1_OR_NEWER
var backend = guiBackend.GetValue(toolbar);
var elements = visualTree.GetValue(backend, null) as VisualElement;
#else
var elements = visualTree.GetValue(toolbar, null) as VisualElement;
#endif
#if UNITY_2019_1_OR_NEWER
var container = elements[0];
#else
var container = elements[0] as IMGUIContainer;
#endif
//create additional gui handler for new elements
var handler = onGuiHandler.GetValue(container) as Action;
handler -= OnGui;
handler += OnGui;
onGuiHandler.SetValue(container, handler);
}
19
View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : artiomchi
License : MIT License
Project Creator : artiomchi
private static object? GetValueInternal<TSource>(this Expression expression, LambdaExpression container, Func<string, IProperty?> propertyFinder, bool useExpressionCompiler, bool nested)
{
switch (expression.NodeType)
{
case ExpressionType.Call:
{
var methodExp = (MethodCallExpression)expression;
var context = methodExp.Object?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true);
var arguments = methodExp.Arguments.Select(a => a.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true)).ToArray();
return methodExp.Method.Invoke(context, arguments);
}
case ExpressionType.Coalesce:
{
var coalesceExp = (BinaryExpression)expression;
var left = coalesceExp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
var right = coalesceExp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
if (left == null)
return right;
if (left is not IKnownValue)
return left;
if (left is not IKnownValue leftValue)
leftValue = new ConstantValue(left);
if (right is not IKnownValue rightValue)
rightValue = new ConstantValue(right);
return new KnownExpression(expression.NodeType, leftValue, rightValue);
}
case ExpressionType.Conditional:
{
var conditionalExp = (ConditionalExpression)expression;
var ifTrue = conditionalExp.IfTrue.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
var ifFalse = conditionalExp.IfFalse.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
var conditionExp = conditionalExp.Test.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
if (conditionExp is not IKnownValue knownCondition)
knownCondition = new ConstantValue(conditionExp);
if (ifTrue is not IKnownValue knownTrue)
knownTrue = new ConstantValue(ifTrue);
if (ifFalse is not IKnownValue knownFalse)
knownFalse = new ConstantValue(ifFalse);
return new KnownExpression(expression.NodeType, knownTrue, knownFalse, knownCondition);
}
case ExpressionType.Constant:
{
return ((ConstantExpression)expression).Value;
}
case ExpressionType.Convert:
{
var convertExp = (UnaryExpression)expression;
if (!nested)
return convertExp.Operand.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
var value = convertExp.Operand.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true);
return Convert.ChangeType(value, convertExp.Type, CultureInfo.InvariantCulture);
}
case ExpressionType.MemberAccess:
{
var memberExp = (MemberExpression)expression;
switch (memberExp.Member)
{
case FieldInfo fInfo:
return fInfo.GetValue(memberExp.Expression?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true));
case PropertyInfo pInfo:
if (!nested && memberExp.Expression?.NodeType == ExpressionType.Parameter && typeof(TSource).Equals(memberExp.Expression.Type))
{
var isLeftParam = memberExp.Expression.Equals(container.Parameters[0]);
if (isLeftParam || memberExp.Expression.Equals(container.Parameters[1]))
{
var property = propertyFinder(pInfo.Name)
?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.UnknownProperty, pInfo.Name));
return new PropertyValue(pInfo.Name, isLeftParam, property);
}
}
return pInfo.GetValue(memberExp.Expression?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true));
default:
throw new UnsupportedExpressionException(expression);
}
}
case ExpressionType.NewArrayInit:
{
var arrayExp = (NewArrayExpression)expression;
var result = Array.CreateInstance(arrayExp.Type.GetElementType()!, arrayExp.Expressions.Count);
for (int i = 0; i < arrayExp.Expressions.Count; i++)
result.SetValue(arrayExp.Expressions[i].GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true), i);
return result;
}
case ExpressionType.Add:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.Subtract:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.And:
case ExpressionType.Or:
{
var exp = (BinaryExpression)expression;
if (!nested)
{
var leftArg = exp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, false);
if (leftArg is not IKnownValue leftArgKnown)
if (leftArg is KnownExpression leftArgExp)
leftArgKnown = leftArgExp.Value1;
else
leftArgKnown = new ConstantValue(leftArg);
var rightArg = exp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, false);
if (rightArg is not IKnownValue rightArgKnown)
if (rightArg is KnownExpression rightArgExp)
rightArgKnown = rightArgExp.Value1;
else
rightArgKnown = new ConstantValue(rightArg);
if (leftArgKnown != null && rightArgKnown != null)
return new KnownExpression(exp.NodeType, leftArgKnown, rightArgKnown);
}
if (exp.Method != null)
return exp.Method.Invoke(
null,
BindingFlags.Static | BindingFlags.Public,
null,
new[] {
exp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true),
exp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true)
},
CultureInfo.InvariantCulture);
break;
}
}
// If we can't translate it to a known expression, just get the value
if (useExpressionCompiler)
return Expression.Lambda<Func<object>>(
Expression.Convert(expression, typeof(object)))
.Compile()();
throw new UnsupportedExpressionException(expression);
}
19
View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private Tuple<Type, string> SearchForStartupAttribute(string friendlyName, IList<string> errors, ref bool conflict)
{
friendlyName = friendlyName ?? string.Empty;
bool foundAnyInstances = false;
Tuple<Type, string> fullMatch = null;
replacedembly matchedreplacedembly = null;
foreach (var replacedembly in _referencedreplacedemblies)
{
Attribute[] attributes;
try
{
// checking attribute's name first and only then instantiating it
// then we are filtering attributes by name second time as inheritors could be added by calling to GetCustomAttributes(type)
attributes = replacedembly.GetCustomAttributesData()
.Where(data => MatchesStartupAttribute(data.AttributeType))
.Select(data => data.AttributeType)
.SelectMany(type => replacedembly.GetCustomAttributes(type))
.Distinct()
.ToArray();
}
catch (CustomAttributeFormatException)
{
continue;
}
foreach (var owinStartupAttribute in attributes.Where(attribute => MatchesStartupAttribute(attribute.GetType())))
{
Type attributeType = owinStartupAttribute.GetType();
foundAnyInstances = true;
// Find the StartupType property.
PropertyInfo startupTypeProperty = attributeType.GetProperty(Constants.StartupType, typeof(Type));
if (startupTypeProperty == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyMissing,
attributeType.replacedemblyQualifiedName, replacedembly.FullName));
continue;
}
var startupType = startupTypeProperty.GetValue(owinStartupAttribute, null) as Type;
if (startupType == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyEmpty, replacedembly.FullName));
continue;
}
// FriendlyName is an optional property.
string friendlyNameValue = string.Empty;
PropertyInfo friendlyNameProperty = attributeType.GetProperty(Constants.FriendlyName, typeof(string));
if (friendlyNameProperty != null)
{
friendlyNameValue = friendlyNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
}
if (!string.Equals(friendlyName, friendlyNameValue, StringComparison.OrdinalIgnoreCase))
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.FriendlyNameMismatch,
friendlyNameValue, friendlyName, replacedembly.FullName));
continue;
}
// MethodName is an optional property.
string methodName = string.Empty;
PropertyInfo methodNameProperty = attributeType.GetProperty(Constants.MethodName, typeof(string));
if (methodNameProperty != null)
{
methodName = methodNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
}
if (fullMatch != null)
{
conflict = true;
errors.Add(string.Format(CultureInfo.CurrentCulture,
LoaderResources.Exception_AttributeNameConflict,
matchedreplacedembly.GetName().Name, fullMatch.Item1, replacedembly.GetName().Name, startupType, friendlyName));
}
else
{
fullMatch = new Tuple<Type, string>(startupType, methodName);
matchedreplacedembly = replacedembly;
}
}
}
if (!foundAnyInstances)
{
errors.Add(LoaderResources.NoOwinStartupAttribute);
}
if (conflict)
{
return null;
}
return fullMatch;
}
19
View Source File : OmniSharpTestBase.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
protected OmniSharpProjectSnapshotManagerBase CreateProjectSnapshotManager(bool allowNotifyListeners = false)
{
var dispatcher = _dispatcherProperty.GetValue(Dispatcher);
var testSnapshotManager = _createProjectSnapshotManagerMethod.Invoke(null, new object[] { dispatcher });
_allowNotifyListenersProperty.SetValue(testSnapshotManager, allowNotifyListeners);
var snapshotManager = (OmniSharpProjectSnapshotManagerBase)_omniSharpProjectSnapshotMangerConstructor.Invoke(new[] { testSnapshotManager });
return snapshotManager;
}
19
View Source File : PdfHelper.cs
License : MIT License
Project Creator : aspose-pdf
License : MIT License
Project Creator : aspose-pdf
public static void ImportGroupedData<TKey, TValue>(this Aspose.Pdf.Table table, IEnumerable<GroupViewModel<TKey, TValue>> groupedData)
{
var headRow = table.Rows.Add();
var props = typeof(TValue).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
headRow.Cells.Add(prop.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute dd ? dd.Name : prop.Name);
}
foreach (var group in groupedData)
{
// Add group row to table
var row = table.Rows.Add();
var cell = row.Cells.Add(group.Key.ToString());
cell.ColSpan = props.Length;
cell.BackgroundColor = Aspose.Pdf.Color.DarkGray;
cell.DefaultCellTextState.ForegroundColor = Aspose.Pdf.Color.White;
foreach (var item in group.Values)
{
// Add data row to table
var dataRow = table.Rows.Add();
// Add cells
foreach (var t in props)
{
var dataItem = t.GetValue(item, null);
if (t.GetCustomAttribute(typeof(DataTypeAttribute)) is DataTypeAttribute dataType)
switch (dataType.DataType)
{
case DataType.Currency:
dataRow.Cells.Add(string.Format("{0:C}", dataItem));
break;
case DataType.Date:
var dateTime = (DateTime)dataItem;
if (t.GetCustomAttribute(typeof(DisplayFormatAttribute)) is DisplayFormatAttribute df)
{
dataRow.Cells.Add(string.IsNullOrEmpty(df.DataFormatString)
? dateTime.ToShortDateString()
: string.Format(df.DataFormatString, dateTime));
}
break;
default:
dataRow.Cells.Add(dataItem.ToString());
break;
}
else
{
dataRow.Cells.Add(dataItem.ToString());
}
}
}
}
}
19
View Source File : SoundIODeviceTest.cs
License : MIT License
Project Creator : atsushieno
License : MIT License
Project Creator : atsushieno
[Test]
public void Properties ()
{
var api = new SoundIO ();
api.Connect ();
try {
api.FlushEvents ();
var dev = api.GetOutputDevice (api.DefaultOutputDeviceIndex);
foreach (var p in typeof (SoundIODevice).GetProperties ()) {
try {
p.GetValue (dev);
} catch (Exception ex) {
replacedert.Fail ("Failed to get property " + p + " : " + ex);
}
}
} finally {
api.Disconnect ();
api.Dispose ();
}
}
19
View Source File : SoundIOInStreamTest.cs
License : MIT License
Project Creator : atsushieno
License : MIT License
Project Creator : atsushieno
[Test]
public void Properties ()
{
var api = new SoundIO ();
api.Connect ();
try {
api.FlushEvents ();
var dev = api.GetInputDevice (api.DefaultInputDeviceIndex);
using (var stream = dev.CreateInStream ()) {
foreach (var p in typeof (SoundIOInStream).GetProperties ()) {
try {
p.GetValue (stream);
} catch (Exception ex) {
replacedert.Fail ("Failed to get property " + p + " : " + ex);
}
}
}
} finally {
api.Disconnect ();
api.Dispose ();
}
}
19
View Source File : SoundIOOutStreamTest.cs
License : MIT License
Project Creator : atsushieno
License : MIT License
Project Creator : atsushieno
[Test]
public void Properties ()
{
var api = new SoundIO ();
api.Connect ();
try {
api.FlushEvents ();
var dev = api.GetOutputDevice (api.DefaultOutputDeviceIndex);
using (var stream = dev.CreateOutStream ()) {
foreach (var p in typeof (SoundIOOutStream).GetProperties ()) {
try {
switch (p.Name) {
case "Layout":
var cl = stream.Layout;
foreach (var pcl in typeof (SoundIOChannelLayout).GetProperties ())
Console.Error.WriteLine (pcl + " : " + pcl.GetValue (cl));
break;
default:
p.GetValue (stream);
break;
}
} catch (Exception ex) {
replacedert.Fail ("Failed to get property " + p + " : " + ex.InnerException);
}
}
}
} finally {
api.Disconnect ();
api.Dispose ();
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : atsushieno
License : MIT License
Project Creator : atsushieno
static void PrintDevice (SoundIODevice dev)
{
Console.WriteLine ($" {dev.Id} - {dev.Name}");
foreach (var pi in typeof (SoundIODevice).GetProperties ())
Console.WriteLine ($" {pi.Name}: {pi.GetValue (dev)}");
}
19
View Source File : SurfaceCurveTest.cs
License : MIT License
Project Creator : Autodesk
License : MIT License
Project Creator : Autodesk
protected Guid InternalIdAccessor(PSSurfaceCurve surfaceCurve)
{
PropertyInfo propertyInfo =
surfaceCurve.GetType().GetProperty("InternalId", BindingFlags.NonPublic | BindingFlags.Instance);
return (Guid) propertyInfo.GetValue(surfaceCurve, null);
}
19
View Source File : DatabaseEntityTest.cs
License : MIT License
Project Creator : Autodesk
License : MIT License
Project Creator : Autodesk
protected string IdentifierAccessor(PSDatabaseEnreplacedy enreplacedy)
{
PropertyInfo propertyInfo =
enreplacedy.GetType().GetProperty("Identifier", BindingFlags.NonPublic | BindingFlags.Instance);
return (string) propertyInfo.GetValue(enreplacedy, null);
}
19
View Source File : CsvExporter.cs
License : MIT License
Project Creator : Autodesk-Forge
License : MIT License
Project Creator : Autodesk-Forge
internal static void ExportUsersCsv(List<int> arrayOfIndices)
{
List<HqUser> users = new List<HqUser>();
arrayOfIndices.ForEach((index) => users.Add(DataController.AccountUsers[index]));
// Create Column Headers
string csv = "";
PropertyInfo[] props = typeof(HqUser).GetProperties();
foreach (PropertyInfo prop in props)
{
csv += prop.Name.ToString() + DefaultConfig.delimiter;
}
csv += Environment.NewLine;
// If Export CSV and CSV with Services buttons are clicked
if (users != null)
{
//create rows in CSV
foreach (HqUser user in users)
{
foreach (PropertyInfo prop in props)
{
if (prop.Name.ToString() == "last_sign_in" || prop.Name.ToString() == "created_at" || prop.Name.ToString() == "updated_at")
{
try
{
DateTime date = (DateTime)prop.GetValue(user);
string d = date.ToString(DefaultConfig.dateFormat);
csv += d + DefaultConfig.delimiter.ToString();
continue;
}
catch
{
csv += "error parsing date" + DefaultConfig.delimiter.ToString();
continue;
}
}
if (prop.Name.ToString() == "phone")
{
// Collect phone number from the nested phone object
string phone_string = (string)prop.GetValue(user);
try
{
Phone phone = JsonConvert.DeserializeObject<Phone>(phone_string);
if (phone != null)
csv += phone.Number.ToString() + DefaultConfig.delimiter.ToString();
else
csv += DefaultConfig.delimiter.ToString();
continue;
}
catch
{
csv += phone_string + DefaultConfig.delimiter.ToString();
continue;
}
}
if (prop.Name.ToString() == "about_me")
{
string about_me = (string)prop.GetValue(user);
if(about_me != null)
{
if (about_me.Length == 0)
{
csv += DefaultConfig.delimiter.ToString();
continue;
}
if (DefaultConfig.delimiter != ',')
{
csv += about_me.ToString() + DefaultConfig.delimiter.ToString();
continue;
}
csv += about_me.Replace(',', ' ') + DefaultConfig.delimiter.ToString();
continue;
}
else
{
csv += DefaultConfig.delimiter.ToString();
continue;
}
}
csv += prop.GetValue(user) + DefaultConfig.delimiter.ToString();
}
//foreach (FieldInfo field in fields)
//{
// if (field.Name.ToString() == "last_sign_in" || field.Name.ToString() == "created_at" || field.Name.ToString() == "updated_at")
// {
// DateTime date = (DateTime)field.GetValue(user);
// string d = date.ToString("yyyy-MM-dd");
// csv += d + Config.delimiter.ToString();
// }
// else
// {
// csv += field.GetValue(user) + Config.delimiter.ToString();
// }
//}
csv += Environment.NewLine;
}
}
Random rnd = new Random();
int length = 20;
var fileName = "";
for (var i = 0; i < length; i++)
{
fileName += ((char)(rnd.Next(1, 26) + 64)).ToString();
}
string path = @"c:\temp\BIM360_AccountUser_" + fileName + ".csv";
System.IO.File.WriteAllText(path, csv);
System.Diagnostics.Process.Start(path);
}
19
View Source File : DataController.cs
License : MIT License
Project Creator : Autodesk-Forge
License : MIT License
Project Creator : Autodesk-Forge
public static string AddProject(BimProject project, string accountId = null, int rowIndex = -1)
{
BimProjectsApi _projectsApi = new BimProjectsApi(GetToken, _options);
project.include_name_to_request_body = true;
// replace empty strings with null
PropertyInfo[] properties = project.GetType().GetProperties();
foreach (PropertyInfo propInfo in properties)
{
if (typeof(string) == propInfo.PropertyType)
{
string s = propInfo.GetValue(project) as string; //as string;
if (s != null && s.Equals(""))
{
propInfo.SetValue(project, null);
}
}
}
bool success = false;
BimProject newProject = null;
IRestResponse response = _projectsApi.PostProject(project, accountId);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
newProject = JsonConvert.DeserializeObject<BimProject>(response.Content);
success = true;
}
// In certain case, the BIM 360 backend takes more than 10 seconds to handle the request,
// this will result in 504 gateway timeout error, but the project should be already successfully
// created, add this check to fix this issue.
if( response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout )
{
Thread.Sleep(3000);
List<BimProject> projectList = GetProjects(@"-created_at");
newProject = projectList.FirstOrDefault();
success = newProject != null && newProject.name == project.name;
}
if( success )
{
if (_AllProjects == null)
{
_AllProjects = GetProjects();
}
if (accountId == null)
{
_AllProjects.Add(newProject);
}
if (rowIndex > -1)
{
_projectTable.Rows[rowIndex]["id"] = newProject.id;
_projectTable.Rows[rowIndex]["result"] = ResultCodes.ProjectCreated;
}
Log.Info($"- project {newProject.name} created with ID {newProject.id}!");
return newProject.id;
}
else
{
ResponseContent content = null;
content = JsonConvert.DeserializeObject<ResponseContent>(response.Content);
string msg = ((content != null && content.message != null) ? content.message : null);
if (rowIndex > -1)
{
_projectTable.Rows[rowIndex]["result"] = ResultCodes.Error;
_projectTable.Rows[rowIndex]["result_message"] = msg;
}
Log.Warn($"Status Code: {response.StatusCode.ToString()}\t Message: {msg}");
return "error";
}
}
19
View Source File : WebApiArg.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
private string CreateNameValue(string name, object? value, bool isClreplacedAllowed)
{
if (value == null)
return UriFormat(name, null);
if (value is string str)
return UriFormat(name, str);
if (value is DateTime dt)
return UriFormat(name, dt.ToString("o", System.Globalization.CultureInfo.InvariantCulture));
TypeInfo ti = value.GetType().GetTypeInfo();
if (ti.IsEnum || ti.IsValueType)
return UriFormat(name, value.ToString());
if (ti.IsClreplaced)
{
if (!isClreplacedAllowed)
ThrowComplexityException(ti);
var sb = new StringBuilder();
foreach (var pi in ti.DeclaredProperties.Where(x => x.CanRead && x.CanWrite))
{
// Only support serialization of JsonProperty's.
var jpa = pi.GetCustomAttribute<JsonPropertyAttribute>(true);
if (jpa == null)
continue;
// Ignore nulls.
object pVal = pi.GetValue(value);
if (pVal == null)
continue;
// Define name, and out strings directly.
string pName = ArgType == WebApiArgType.FromUriUseProperties ? jpa.PropertyName! : name + "." + jpa.PropertyName;
if (pVal is string pstr)
{
UriAppend(sb, UriFormat(pName, pstr));
continue;
}
// Iterate enumerables where they contain non-clreplaced types only.
if (pVal is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
if (item != null)
UriAppend(sb, CreateNameValue(pName, item, false));
}
continue;
}
// Ignore default values.
var pti = pi.PropertyType.GetTypeInfo();
if (pti.IsValueType || pti.IsEnum)
{
object defaultValue = Activator.CreateInstance(pi.PropertyType);
if (defaultValue is IComparable comparer && comparer.CompareTo(pVal) == 0)
continue;
}
else
{
var waafa = pi.GetCustomAttribute<WebApiArgFormatterAttribute>();
if (waafa != null)
{
var converter = (IPropertyMapperConverter)Activator.CreateInstance(waafa.ConverterType);
if (converter.SrceType != pi.PropertyType || converter.DestType != typeof(string))
throw new InvalidOperationException($"Converter Type '{waafa.ConverterType.Name}' must have SrceType of '{pi.PropertyType.Name}' and DestType of 'string'.");
UriAppend(sb, CreateNameValue(pName, converter.ConvertToDest(pVal), false));
continue;
}
ThrowComplexityException(ti);
}
UriAppend(sb, UriFormat(pName, pVal is DateTime dt2 ? dt2.ToString("o", System.Globalization.CultureInfo.InvariantCulture) : pVal.ToString()));
}
return sb.ToString();
}
return string.Format(System.Globalization.CultureInfo.InvariantCulture, QueryStringFormat, base.Name, Uri.EscapeDataString(value.ToString()));
}
See More Examples