Here are the examples of the csharp api System.Reflection.PropertyInfo.SetValue(object, object, object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1840 Examples
19
View Source File : DbBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void CreateDbContext()
{
var sp = Services.BuildServiceProvider();
var dbLogger = new DbLogger(Options, sp.GetService<IDbLoggerProvider>());
var accountResolver = sp.GetService<IAccountResolver>();
//获取数据库适配器的程序集
var dbAdapterreplacedemblyName = replacedembly.GetCallingreplacedembly().GetName().Name!.Replace("Core", "Adapter.") + Options.Provider;
var dbAdapterreplacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(dbAdapterreplacedemblyName));
//创建数据库上下文实例,通过反射设置属性
DbContext = (IDbContext)Activator.CreateInstance(_dbContextType);
_dbContextType.GetProperty("Options")?.SetValue(DbContext, Options);
_dbContextType.GetProperty("Logger")?.SetValue(DbContext, dbLogger);
_dbContextType.GetProperty("Adapter")?.SetValue(DbContext, CreateDbAdapter(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
_dbContextType.GetProperty("SchemaProvider")?.SetValue(DbContext, CreateSchemaProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
_dbContextType.GetProperty("CodeFirstProvider")?.SetValue(DbContext, CreateCodeFirstProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly, Services));
_dbContextType.GetProperty("AccountResolver")?.SetValue(DbContext, accountResolver);
// ReSharper disable once replacedignNullToNotNullAttribute
Services.AddSingleton(_dbContextType, DbContext);
}
19
View Source File : SetPropertyAction.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private void UpdatePropertyValue(object targetObject)
{
var targetType = targetObject.GetType();
var propertyInfo = targetType.GetRuntimeProperty(PropertyName);
ValidateProperty(targetType.Name, propertyInfo);
Exception innerException = null;
try
{
object result;
var propertyType = propertyInfo.PropertyType;
var propertyTypeInfo = propertyType.GetTypeInfo();
if (Value is null)
{
result = propertyTypeInfo.IsValueType ? Activator.CreateInstance(propertyType) : null;
}
else if (propertyTypeInfo.IsreplacedignableFrom(Value.GetType().GetTypeInfo()))
{
result = Value;
}
else
{
var valuereplacedtring = Value.ToString();
result = propertyTypeInfo.IsEnum ? Enum.Parse(propertyType, valuereplacedtring, false) : TypeConverterHelper.Convert(valuereplacedtring, propertyType.FullName);
}
propertyInfo.SetValue(targetObject, result, new object[0]);
}
catch (FormatException ex)
{
innerException = ex;
}
catch (ArgumentException ex)
{
innerException = ex;
}
if (innerException != null)
{
throw new ArgumentException("Cannot set value.", innerException);
}
}
19
View Source File : DbContext.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void InitPropSets() {
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
foreach (var prop in props) {
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
prop.SetValue(this, set);
AllSets.Add(prop.Name, set);
}
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
{
if (enreplacedy == null) return;
if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();
if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
{
if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
{
prop.SetValue(enreplacedy, value, null);
return;
}
if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
{
field.SetValue(enreplacedy, value);
return;
}
throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
}
Action<object, string, object> func = null;
try
{
func = _dicSetPropertyOrFieldValue
.GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
.GetOrAdd(propertyName, pn =>
{
var t = enreplacedyType;
MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
var parm1 = Expression.Parameter(typeof(object));
var parm2 = Expression.Parameter(typeof(string));
var parm3 = Expression.Parameter(typeof(object));
var var1Parm = Expression.Variable(t);
var exps = new List<Expression>(new Expression[] {
Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
});
if (memberinfo != null)
{
exps.Add(
Expression.replacedign(
Expression.MakeMemberAccess(var1Parm, memberinfo),
Expression.Convert(
parm3,
memberinfo.GetPropertyOrFieldType()
)
)
);
}
return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
});
}
catch
{
System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
return;
}
func(enreplacedy, propertyName, value);
}
19
View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
//ILRuntime doesn't support nullable valuetype
Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
Type value_type = inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClreplaced || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType();
var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;
if (vt.IsreplacedignableFrom(json_type))
return reader.Value;
if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
{
if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
return reader.Value;
}
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
custom_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
base_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe it's an enum
if (vt.IsEnum)
return Enum.ToObject (vt, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (vt, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
{
item = (int) item;
}
else
{
item = rt.CheckCLRTypes(item);
}
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
if (value_type is ILRuntime.Reflection.ILRuntimeType)
instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
else
instance = Activator.CreateInstance(value_type);
bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string key = (string) reader.Value;
if (t_data.Properties.ContainsKey(key))
{
PropertyMetadata prop_data =
t_data.Properties[key];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(
instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(
instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format(
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, key));
}
else
{
ReadSkip(reader);
continue;
}
}
var dict = ((IDictionary) instance);
var elem_type = t_data.ElementType;
object readValue = ReadValue(elem_type, reader);
var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
: t_data.ElementType;
//value 是枚举的情况没处理,毕竟少
if (isIntKey)
{
var dictValueType = value_type.GetGenericArguments()[1];
IConvertible convertible = dictValueType as IConvertible;
if (convertible == null)
{
//自定义类型扩展
if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
{
var v = Convert.ChangeType(readValue.ToString(), dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(Convert.ToInt32(key), readValue);
// throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
}
}
else
{
var v = Convert.ChangeType(readValue, dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(key, readValue);
}
}
}
}
return instance;
}
19
View Source File : PropertyDecorator.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public override object Read(object value, ProtoReader source)
{
Helpers.Debugreplacedert(value != null);
//object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null;
object oldVal = Tail.RequiresOldValue ? property.GetGetMethod(true).Invoke(value, null) : null;
object newVal = Tail.Read(oldVal, source);
if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no replacedign*
{
if (shadowSetter == null)
{
property.SetValue(value, newVal, null);
}
else
{
shadowSetter.Invoke(value, new object[] { newVal });
}
}
return null;
}
19
View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
static object ParseObject(Type type, string json) {
object instance = FormatterServices.GetUninitializedObject(type);
//The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
List<string> elems = Split(json);
if (elems.Count % 2 != 0)
return instance;
Dictionary<string, FieldInfo> nameToField;
Dictionary<string, PropertyInfo> nameToProperty;
if (!fieldInfoCache.TryGetValue(type, out nameToField)) {
nameToField = type.GetFields().Where(field => field.IsPublic).ToDictionary(field => field.Name);
fieldInfoCache.Add(type, nameToField);
}
if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) {
nameToProperty = type.GetProperties().ToDictionary(p => p.Name);
propertyInfoCache.Add(type, nameToProperty);
}
for (int i = 0; i < elems.Count; i += 2) {
if (elems[i].Length <= 2)
continue;
string key = elems[i].Substring(1, elems[i].Length - 2);
string value = elems[i + 1];
FieldInfo fieldInfo;
PropertyInfo propertyInfo;
if (nameToField.TryGetValue(key, out fieldInfo))
fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value));
else if (nameToProperty.TryGetValue(key, out propertyInfo))
propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null);
}
return instance;
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToCreate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("ID") != null)
{
types.GetProperty("ID").SetValue(source, Guid.NewGuid().ToString().ToUpper(), null);
}
if (types.GetProperty("CreateTime") != null)
{
types.GetProperty("CreateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("CreateID") != null)
{
types.GetProperty("CreateID").SetValue(source, userSession.UserID, null);
types.GetProperty("CreateName").SetValue(source, userSession.UserName, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToCreate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("ID") != null)
{
types.GetProperty("ID").SetValue(source, Guid.NewGuid().ToString().ToUpper(), null);
}
if (types.GetProperty("CreateTime") != null)
{
types.GetProperty("CreateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("CreateID") != null)
{
types.GetProperty("CreateID").SetValue(source, userSession.UserID, null);
types.GetProperty("CreateName").SetValue(source, userSession.UserName, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToUpdate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
}
if (types.GetProperty("UpdateName") != null)
{
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static TSource ToUpdate<TSource>(this TSource source, UserSessionVM userSession)
{
var types = source.GetType();
if (types.GetProperty("UpdateTime") != null)
{
types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
}
if (types.GetProperty("UpdateID") != null)
{
types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
}
if (types.GetProperty("UpdateName") != null)
{
types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
}
return source;
}
19
View Source File : VxFormColumnBase.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
private void CreateFormElementReferencePoco<TValue>(object model, PropertyInfo propertyInfo,
RenderTreeBuilder builder, Layout.VxFormElementDefinition formColumnDefinition)
{
var valueChanged = Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck(
EventCallback.Factory.Create<TValue>(
this, EventCallback.Factory.
CreateInferred(this, __value => propertyInfo.SetValue(model, __value),
(TValue)propertyInfo.GetValue(model))));
// Create an expression to set the ValueExpression-attribute.
var constant = Expression.Constant(model, model.GetType());
var exp = Expression.Property(constant, propertyInfo.Name);
var lamb = Expression.Lambda<Func<TValue>>(exp);
var formElementReference = new FormElementReference<TValue>()
{
Value = (TValue)propertyInfo.GetValue(model),
ValueChanged = valueChanged,
ValueExpression = lamb,
FormColumnDefinition = formColumnDefinition
};
var elementType = typeof(VxFormElementLoader<TValue>);
builder.OpenComponent(0, elementType);
builder.AddAttribute(1, nameof(VxFormElementLoader<TValue>.ValueReference), formElementReference);
builder.CloseComponent();
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this Enreplacedy enreplacedy, string sPropertyName, object value)
{
enreplacedy.GetType().GetProperty(sPropertyName).SetValue(enreplacedy, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this EnreplacedyMetadata enreplacedyMetadata, string sPropertyName, object value)
{
enreplacedyMetadata.GetType().GetProperty(sPropertyName).SetValue(enreplacedyMetadata, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this AttributeMetadata attributeMetadata, string sPropertyName, object value)
{
attributeMetadata.GetType().GetProperty(sPropertyName).SetValue(attributeMetadata, value, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetFieldValue(this object inputObject, string propertyName, object propertyVal)
{
Type type = inputObject.GetType();
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
Type propertyType = propertyInfo.PropertyType;
var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType;
propertyVal = Convert.ChangeType(propertyVal, targetType);
propertyInfo.SetValue(inputObject, propertyVal, null);
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetSealedPropertyValue(this Microsoft.Xrm.Sdk.Metadata.ManyToManyRelationshipMetadata manyToManyRelationshipMetadata, string sPropertyName, object value)
{
manyToManyRelationshipMetadata.GetType().GetProperty(sPropertyName).SetValue(manyToManyRelationshipMetadata, value, null);
}
19
View Source File : WrappedException.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void TryUnWrapCustomProperties(Exception exception)
{
if (this.CustomProperties != null)
{
foreach (var property in GetCustomPropertiesInfo())
{
if (this.CustomProperties.ContainsKey(property.Name))
{
try
{
var propertyValue = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(CustomProperties[property.Name]), property.PropertyType);
property.SetValue(exception, propertyValue);
}
catch
{
// skip this property
}
}
}
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.CancelAfter(10000);
throw new TaskAgentJobTokenExpiredException("");
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestNullAgentNameIgnored()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatchesJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var jobDispatcher = new JobDispatcher();
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
jobDispatcher.Initialize(hc);
var ts = new CancellationTokenSource();
Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
string strMessage = JsonUtility.ToString(message);
_processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(56));
_processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>()))
.Callback((StartProcessDelegate startDel) => { startDel("1", "2"); });
_processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var request = new TaskAgentJobRequest();
PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));
_runnerServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));
//Actt
jobDispatcher.Run(message);
//replacedert
await jobDispatcher.WaitAsync(CancellationToken.None);
replacedert.False(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should not set task complete token for regular agent.");
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request);
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnJobNotFoundExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobNotFoundExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.CancelAfter(10000);
throw new TaskAgentJobNotFoundException("");
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestNewAgentNameUpdatesSettings()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var newName = "NewName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.Is<RunnerSettings>(settings => settings.AgentName == newName)), Times.Once);
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestSameAgentNameIgnored()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var newName = "OldName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestRecoverFromExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestRecoverFromExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.True(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(8));
_runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
_runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Once);
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestFirstRenewRetrySixTimes()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestFirstRenewRetrySixTimes));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count <= 5)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.CancelAfter(10000);
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.False(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should failed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(6));
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnExpiredRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count == 1)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count < 5)
{
throw new TimeoutException("");
}
else if (count == 5)
{
lockUntilProperty.SetValue(request, DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(11)));
throw new TimeoutException("");
}
else
{
cancellationTokenSource.CancelAfter(10000);
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
_runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
_runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Never);
}
}
19
View Source File : JobDispatcherL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatchesOneTimeJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var jobDispatcher = new JobDispatcher();
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
jobDispatcher.Initialize(hc);
var ts = new CancellationTokenSource();
Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
string strMessage = JsonUtility.ToString(message);
_processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(56));
_processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>()))
.Callback((StartProcessDelegate startDel) => { startDel("1", "2"); });
_processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var request = new TaskAgentJobRequest();
PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));
_runnerServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));
//Act
jobDispatcher.Run(message, true);
//replacedert
await jobDispatcher.WaitAsync(CancellationToken.None);
replacedert.True(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should set task complete token for one time agent.");
replacedert.True(jobDispatcher.RunOnceJobCompleted.Task.Result, "JobDispatcher should set task complete token to 'TRUE' for one time agent.");
}
}
19
View Source File : MessageListenerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DeleteSession()
{
using (TestHostContext tc = CreateTestContext())
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = tc.GetTrace();
// Arrange.
var expectedSession = new TaskAgentSession();
PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());
_runnerServer
.Setup(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token))
.Returns(Task.FromResult(expectedSession));
_credMgr.Setup(x => x.LoadCredentials()).Returns(new VssCredentials());
_store.Setup(x => x.GetCredentials()).Returns(new CredentialData() { Scheme = Constants.Configuration.OAuthAccessToken });
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
replacedert.True(result);
_runnerServer
.Setup(x => x.DeleteAgentSessionAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
await listener.DeleteSessionAsync();
//replacedert
_runnerServer
.Verify(x => x.DeleteAgentSessionAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>()), Times.Once());
}
}
19
View Source File : MessageListenerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void GetNextMessage()
{
using (TestHostContext tc = CreateTestContext())
using (var tokenSource = new CancellationTokenSource())
{
Tracing trace = tc.GetTrace();
// Arrange.
var expectedSession = new TaskAgentSession();
PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());
_runnerServer
.Setup(x => x.CreateAgentSessionAsync(
_settings.PoolId,
It.Is<TaskAgentSession>(y => y != null),
tokenSource.Token))
.Returns(Task.FromResult(expectedSession));
_credMgr.Setup(x => x.LoadCredentials()).Returns(new VssCredentials());
_store.Setup(x => x.GetCredentials()).Returns(new CredentialData() { Scheme = Constants.Configuration.OAuthAccessToken });
_store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));
// Act.
MessageListener listener = new MessageListener();
listener.Initialize(tc);
bool result = await listener.CreateSessionAsync(tokenSource.Token);
replacedert.True(result);
var arMessages = new TaskAgentMessage[]
{
new TaskAgentMessage
{
Body = "somebody1",
MessageId = 4234,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
},
new TaskAgentMessage
{
Body = "somebody2",
MessageId = 4235,
MessageType = JobCancelMessage.MessageType
},
null, //should be skipped by GetNextMessageAsync implementation
null,
new TaskAgentMessage
{
Body = "somebody3",
MessageId = 4236,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
}
};
var messages = new Queue<TaskAgentMessage>(arMessages);
_runnerServer
.Setup(x => x.GetAgentMessageAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token))
.Returns(async (Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) =>
{
await Task.Yield();
return messages.Dequeue();
});
TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token);
TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token);
TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token);
replacedert.Equal(arMessages[0], message1);
replacedert.Equal(arMessages[1], message2);
replacedert.Equal(arMessages[4], message3);
//replacedert
_runnerServer
.Verify(x => x.GetAgentMessageAsync(
_settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token), Times.Exactly(arMessages.Length));
}
}
19
View Source File : NeuralLearner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
private static void SetPropertyValues<U>(string propertyName,
object objectInconcern, U valueToSet)
{
var prop = objectInconcern.GetType().GetProperty(propertyName
, BindingFlags.Public | BindingFlags.Instance);
var types = prop != null && prop.ToString() != "" ? prop.ToString().Split(' ')[0] : "";
var typeToParse = types.Replace("System.", "");
if (null == prop || !prop.CanWrite || types == "") return;
prop.SetValue(objectInconcern, valueToSet, null);
}
19
View Source File : HookInterceptor.cs
License : MIT License
Project Creator : AdamCarballo
License : MIT License
Project Creator : AdamCarballo
private static void OnFormatted(List<string> data) {
var filteredMethods = HookAttributesParser.HookAttributes.ToArray();
object param = null;
for (int i = 0; i < data.Count; i++) {
if (data[i].StartsWith(UrlParam)) {
param = data[i].Replace(UrlParam, string.Empty);
} else {
filteredMethods = filteredMethods.Where(x => x.Key.Length > i && x.Key[i] == data[i]).ToArray();
LogVerbose(string.Format("Number of attributes found in {0} group: {1}", data[i], filteredMethods.Length));
}
}
for (int i = 0; i < filteredMethods.Length; i++) {
LogVerbose("Reflection calling: " + filteredMethods[i].Value.Value.Name);
var attributeType = filteredMethods[i].Value.Value.GetCustomAttribute(typeof(HookAttribute));
if (attributeType is HookField) {
if (param == null) return;
var info = filteredMethods[i].Value.Value as FieldInfo;
var parsedParam = GetParsedParameter(info.FieldType, param);
info.SetValue(filteredMethods[i].Value.Key, parsedParam);
} else if (attributeType is HookProperty) {
if (param == null) return;
var info = filteredMethods[i].Value.Value as PropertyInfo;
var parsedParam = GetParsedParameter(info.PropertyType, param);
info.SetValue(filteredMethods[i].Value.Key, parsedParam);
} else if (attributeType is HookMethod) {
var info = filteredMethods[i].Value.Value as MethodInfo;
// Check if method has parameters
var parameters = info.GetParameters();
if (parameters.Length <= 0) {
info.Invoke(filteredMethods[i].Value.Key, null);
} else {
var parsedParam = GetParsedParameter(parameters[0].ParameterType, param);
info.Invoke(filteredMethods[i].Value.Key, new[] {parsedParam});
}
}
}
}
19
View Source File : CopyObjectExtensions.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
public static void CopyPropertiesTo(this object source, object dest, PropertyInfo[] destProps)
{
if (source.GetType().FullName != dest.GetType().FullName)
{
//can't copy state over a type with a different name: surely it's a different type
return;
}
var sourceProps = source.GetType()
.GetProperties()
.Where(x => x.CanRead)
.ToList();
foreach (var sourceProp in sourceProps)
{
var targetProperty = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
if (targetProperty != null)
{
var sourceValue = sourceProp.GetValue(source, null);
if (sourceValue != null && sourceValue.GetType().IsEnum)
{
sourceValue = Convert.ChangeType(sourceValue, Enum.GetUnderlyingType(sourceProp.PropertyType));
}
try
{
targetProperty.SetValue(dest, sourceValue, null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unable to copy property '{targetProperty.Name}' of state ({source.GetType()}) to new state after hot reload (Exception: '{DumpExceptionMessage(ex)}')");
}
}
}
}
19
View Source File : CrmOrganizationServiceContext.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
void IUpdatable.SetValue(object targetResource, string propertyName, object propertyValue)
{
Tracing.FrameworkInformation("CrmOrganizationServiceContext", "SetValue", "targetResource={0}, propertyName={1}, propertyValue={2}", targetResource, propertyName, propertyValue);
var type = targetResource.GetType();
var pi = type.GetProperty(propertyName);
if (pi == null)
{
throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
}
if (pi.CanWrite && IsReadOnlyEnreplacedyProperty(targetResource, propertyName))
{
var value = ParseValue(propertyValue);
pi.SetValue(targetResource, value, null);
var target = targetResource as Enreplacedy;
if (target != null)
{
UpdateObject(target);
}
}
}
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 : GenericExtensions.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public static T GetCopyOf<T>(this Component comp, T other) where T : Component {
Type type = comp.GetType();
if (type != other.GetType()) return null; // type mis-match
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
PropertyInfo[] pinfos = type.GetProperties(flags);
foreach (var pinfo in pinfos) {
if (pinfo.CanWrite) {
try {
pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
}
catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
}
}
FieldInfo[] finfos = type.GetFields(flags);
foreach (var finfo in finfos)
finfo.SetValue(comp, finfo.GetValue(other));
return comp as T;
}
19
View Source File : SettingsWindow.xaml.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
private void BrowseThemeHyperlink_Click(object sender, RoutedEventArgs e)
{
Hyperlink hyperlink = (Hyperlink)sender;
OpenFileDialog dialog = new OpenFileDialog();
string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string initialPath = Path.Combine(localAppDataPath, @"Microsoft\Windows\Themes");
dialog.Filter = "Theme files|*.theme";
dialog.replacedle = "Select a theme";
dialog.InitialDirectory = initialPath;
if (dialog.ShowDialog() == true)
{
PropertyInfo propertyInfo = _autoFileSaver.Model.GetType().GetProperty((string)hyperlink.Tag);
propertyInfo.SetValue(_autoFileSaver.Model, dialog.FileName, null);
}
}
19
View Source File : Configuration.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : 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
View Source File : SettingsWindow.xaml.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
private void BrowseWallpaperHyperlink_Click(object sender, RoutedEventArgs e)
{
Hyperlink hyperlink = (Hyperlink)sender;
OpenFileDialog dialog = new OpenFileDialog();
string initialPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dialog.Filter = "Image files|*.jpg;*.jpeg;*.png|All files|*.*";
dialog.replacedle = "Select a wallpaper";
dialog.InitialDirectory = initialPath;
if (dialog.ShowDialog() == true)
{
PropertyInfo propertyInfo = _autoFileSaver.Model.GetType().GetProperty((string)hyperlink.Tag);
propertyInfo.SetValue(_autoFileSaver.Model, dialog.FileName, null);
}
}
19
View Source File : EditorGUIHelper.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public static bool Header(string replacedle, SerializedProperty group, SerializedProperty enabledField, Action resetAction)
{
var field = ReflectionUtils.GetFieldInfoFromPath(enabledField.serializedObject.targetObject, enabledField.propertyPath);
object parent = null;
PropertyInfo prop = null;
if (field != null && field.IsDefined(typeof(GetSetAttribute), false))
{
var attr = (GetSetAttribute)field.GetCustomAttributes(typeof(GetSetAttribute), false)[0];
parent = ReflectionUtils.GetParentObject(enabledField.propertyPath, enabledField.serializedObject.targetObject);
prop = parent.GetType().GetProperty(attr.name);
}
var display = group == null || group.isExpanded;
var enabled = enabledField.boolValue;
var rect = GUILayoutUtility.GetRect(16f, 22f, FxStyles.header);
GUI.Box(rect, replacedle, FxStyles.header);
var toggleRect = new Rect(rect.x + 4f, rect.y + 4f, 13f, 13f);
var e = Event.current;
var popupRect = new Rect(rect.x + rect.width - FxStyles.paneOptionsIcon.width - 5f, rect.y + FxStyles.paneOptionsIcon.height / 2f + 1f, FxStyles.paneOptionsIcon.width, FxStyles.paneOptionsIcon.height);
GUI.DrawTexture(popupRect, FxStyles.paneOptionsIcon);
if (e.type == EventType.Repaint)
FxStyles.headerCheckbox.Draw(toggleRect, false, false, enabled, false);
if (e.type == EventType.MouseDown)
{
const float kOffset = 2f;
toggleRect.x -= kOffset;
toggleRect.y -= kOffset;
toggleRect.width += kOffset * 2f;
toggleRect.height += kOffset * 2f;
if (toggleRect.Contains(e.mousePosition))
{
enabledField.boolValue = !enabledField.boolValue;
if (prop != null)
prop.SetValue(parent, enabledField.boolValue, null);
e.Use();
}
else if (popupRect.Contains(e.mousePosition))
{
var popup = new GenericMenu();
popup.AddItem(GetContent("Reset"), false, () => resetAction());
popup.AddSeparator(string.Empty);
popup.AddItem(GetContent("Copy Settings"), false, () => CopySettings(group));
if (CanPaste(group))
popup.AddItem(GetContent("Paste Settings"), false, () => PasteSettings(group));
else
popup.AddDisabledItem(GetContent("Paste Settings"));
popup.ShowAsContext();
}
else if (rect.Contains(e.mousePosition) && group != null)
{
display = !display;
group.isExpanded = !group.isExpanded;
e.Use();
}
}
return display;
}
19
View Source File : ZSocketSetup.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public ZSocketSetup SetSocketOption<T>(Expression<Func<ZSocket, T>> property, T value)
{
PropertyInfo propertyInfo;
if (property.Body is MemberExpression)
{
propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
}
else
{
propertyInfo = ((MemberExpression)((UnaryExpression)property.Body).Operand).Member as PropertyInfo;
}
if (propertyInfo == null)
{
throw new InvalidOperationException("The specified ZSocket member is not a property: " + property.Body);
}
_socketInitializers.Add(s => propertyInfo.SetValue(s, value, null));
return this;
}
19
View Source File : AuthenticationSchemeOptionsSerializer.cs
License : MIT License
Project Creator : Aguafrommars
License : MIT License
Project Creator : Aguafrommars
protected virtual object Deserialize(string value, Type type)
{
var result = JsonConvert.DeserializeObject(value, type, JsonSerializerSettings);
var requireHttpsMetaDataProperty = type.GetProperty("RequireHttpsMetadata");
if (requireHttpsMetaDataProperty != null && value.Contains("\"RequireHttpsMetadata\":false"))
{
requireHttpsMetaDataProperty.SetValue(result, false);
}
return result;
}
19
View Source File : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : 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
View Source File : ClientRegisterationConverter.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : 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
View Source File : AdminStoreTestBase.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task AddParentEnreplacedy(ServiceProvider provider, TEnreplacedy create, string parentPropetyName, Type parentPropetyType)
{
var parentStoreType = typeof(IAdminStore<>).MakeGenericType(parentPropetyType);
var parentStore = provider.GetRequiredService(parentStoreType) as IAdminStore;
var parent = await parentStore.CreateAsync(CreateParentEntiy(parentPropetyType)).ConfigureAwait(false) as IEnreplacedyId;
var parentPropety = create.GetType().GetProperty(parentPropetyName);
parentPropety.SetValue(create, parent.Id);
}
19
View Source File : AdminStoreTestBase.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task<TEnreplacedy> CreateEnreplacedyGraphAsync(IEnumerable<PropertyInfo> navigationProperties, ServiceProvider provider, IAdminStore<TEnreplacedy> sut)
{
var create = new TEnreplacedy
{
Id = Guid.NewGuid().ToString()
};
var parentPropetyName = GetParentIdName(create.GetType());
if (parentPropetyName != null)
{
var parentPropetyType = GetParentType(parentPropetyName);
await AddParentEnreplacedy(provider, create, parentPropetyName, parentPropetyType).ConfigureAwait(false);
}
var enreplacedy = await sut.CreateAsync(create).ConfigureAwait(false);
foreach (var property in navigationProperties)
{
var subEnreplacedyType = property.PropertyType;
if (subEnreplacedyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
subEnreplacedyType = subEnreplacedyType.GetGenericArguments()[0];
var parentPropety = subEnreplacedyType.GetProperty(GetSubEnreplacedyParentIdName(enreplacedy.GetType()));
var subEnreplacedy = Activator.CreateInstance(subEnreplacedyType);
parentPropety.SetValue(subEnreplacedy, enreplacedy.Id);
var storeType = typeof(IAdminStore<>).MakeGenericType(subEnreplacedyType);
var subStore = provider.GetRequiredService(storeType) as IAdminStore;
await subStore.CreateAsync(subEnreplacedy).ConfigureAwait(false);
continue;
}
await AddParentEnreplacedy(provider, create, $"{property.Name}Id", property.PropertyType).ConfigureAwait(false);
}
await sut.UpdateAsync(enreplacedy).ConfigureAwait(false);
return enreplacedy;
}
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 ReadEnumarableString(JsonReader reader, ClientRegisteration existingValue, PropertyInfo property)
{
var value = new List<string>();
reader.Read();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
value.Add(reader.Value as string);
}
property.SetValue(existingValue, value);
}
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 : AdminStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task PopulateSubEnreplacediesAsync(string idName, string path, TEnreplacedy enreplacedy)
{
var property = _enreplacedyType.GetProperty(path);
var value = property.GetValue(enreplacedy);
if (value == null)
{
if (property.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
value = Activator.CreateInstance(typeof(Collection<>).MakeGenericType(property.PropertyType.GetGenericArguments()));
}
else
{
value = Activator.CreateInstance(property.PropertyType);
}
property.SetValue(enreplacedy, value);
}
if (value is ICollection collection)
{
foreach (var v in collection)
{
await PopulateSubEnreplacedyAsync("Id", v).ConfigureAwait(false);
var idProperty = v.GetType().GetProperty(idName);
idProperty.SetValue(v, enreplacedy.Id);
}
return;
}
var parentIdProperty = _enreplacedyType.GetProperty($"{path}Id");
((IEnreplacedyId)value).Id = parentIdProperty.GetValue(enreplacedy) as string;
await PopulateSubEnreplacedyAsync("Id", value).ConfigureAwait(false);
parentIdProperty.SetValue(enreplacedy, ((IEnreplacedyId)value).Id);
}
See More Examples