public void SetUp() { _reflectionHelpers = new ReflectionHelpers(); _target = new ReflectionConfigurator(_reflectionHelpers); }
/// <summary> /// Returns a BForms select element based on BsControlAttribute /// </summary> public static MvcHtmlString BsSelectFor <TModel, TKey>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, BsSelectList <TKey> > > expression, IDictionary <string, object> htmlAttributes, IDictionary <string, object> dataOptions) { if (htmlAttributes == null) { htmlAttributes = new Dictionary <string, object>(); } if (dataOptions == null) { dataOptions = new Dictionary <string, object>(); } var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); var name = ExpressionHelper.GetExpressionText(expression); //get list object from expression var selectList = expression.Compile().Invoke(htmlHelper.ViewData.Model); string htmlSelect; string optionLabel = null; var allowMultiple = false; //copy from BsSelectList.SelectedValues to SelectListItem.Selected if (selectList != null && selectList.SelectedValues != null && selectList.Items != null && selectList.Items.Any()) { var selectedValuesStr = new List <string>(); var bsKeyType = typeof(TKey); if (typeof(IEnumerable).IsAssignableFrom(bsKeyType) && bsKeyType != typeof(string)) { var selectedValues = (IEnumerable)selectList.SelectedValues; selectedValuesStr = (from object selectedValue in selectedValues select ReflectionHelpers.GetNonEnumerableValue(selectedValue)).ToList(); } else { selectedValuesStr.Add(ReflectionHelpers.GetNonEnumerableValue(selectList.SelectedValues)); } foreach (var item in selectList.Items) { if (selectedValuesStr.Contains(item.Value)) { item.Selected = true; } } } //add optionLabel from Watermark if (!string.IsNullOrEmpty(metadata.Watermark)) { optionLabel = metadata.Watermark; } //set data- options if (dataOptions.Any()) { htmlAttributes.MergeAttribute("data-options", dataOptions.ToJsonString()); } //determine the select type BsControlAttribute bsControl = null; if (ReflectionHelpers.TryGetAttribute(name, typeof(TModel), out bsControl)) { //add bs- control type var bsCssClass = bsControl.ControlType.GetDescription(); if (bsControl.IsReadonly) { htmlAttributes.MergeAttribute("readonly", "readonly"); } switch (bsControl.ControlType) { case BsControlType.TagList: allowMultiple = true; htmlSelect = BsTagListInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.CheckBoxList: allowMultiple = true; htmlSelect = BsRadioListInternal(htmlHelper, name, selectList, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.RadioButtonList: allowMultiple = false; htmlSelect = BsRadioListInternal(htmlHelper, name, selectList, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.ListBox: case BsControlType.ListBoxGrouped: allowMultiple = true; htmlSelect = BsSelectInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.DropDownList: case BsControlType.DropDownListGrouped: case BsControlType.Autocomplete: allowMultiple = false; htmlSelect = BsSelectInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.ListBoxRemote: allowMultiple = true; htmlSelect = BsHiddenInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.DropDownListRemote: allowMultiple = false; htmlSelect = BsHiddenInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, allowMultiple, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.ButtonGroupDropdown: htmlSelect = BsButtonGroupDropdownInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, bsCssClass, metadata).ToHtmlString(); break; case BsControlType.MixedButtonGroup: htmlSelect = BsMixedButtonGroupDropdownInternal(htmlHelper, name, selectList, optionLabel, htmlAttributes, bsCssClass, metadata).ToHtmlString(); break; default: throw new ArgumentException("The " + name + " of type " + bsControl.ControlType.GetDescription() + " does not match a select element"); } } else { throw new InvalidOperationException("The " + name + " property is not decorated with a BsControlAttribute"); } //add info tooltip var description = new MvcHtmlString(""); if (!string.IsNullOrEmpty(metadata.Description)) { description = htmlHelper.BsDescription(name); } return(MvcHtmlString.Create(htmlSelect + description.ToHtmlString())); }
public void WriteToXML(string file) { XElement RootElement = ReflectionHelpers.ConvertPropertyToXML(this); RootElement.Save(file, SaveOptions.None); }
public void ShouldFailToCreateClassWithoutDefaultConstructor() { ReflectionHelpers.CreateInstance <ClassWithoutDefaultConstuctor>(); }
private static MvcHtmlString BsSelectInternal <TKey>(this HtmlHelper htmlHelper, string name, BsSelectList <TKey> selectList, string optionLabel, IDictionary <string, object> htmlAttributes, bool allowMultiple, string bsCssClass, ModelMetadata metadata = null) { //TODO: refactoring //bind the selected values BsSelectList.SelectedValues name += ".SelectedValues"; var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("Null Or Empty", "name"); } bool usedViewData = false; // If we got a null selectList, try to use ViewData to get the list of items. if (selectList == null) { selectList = htmlHelper.GetSelectData <TKey>(fullName); usedViewData = true; } object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (!usedViewData) { if (defaultValue == null) { defaultValue = htmlHelper.ViewData.Eval(name); if (defaultValue != null) { var type = ReflectionHelpers.ResolveNullableType(typeof(TKey)); if (type.IsEnum) { var enumValues = Enum.GetValues(type); foreach (var enumValue in enumValues) { if (enumValue.ToString() == defaultValue.ToString()) { defaultValue = (int)enumValue; } } } } } } if (defaultValue != null) { var defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue }; var values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); var selectedValues = new HashSet <string>(values, StringComparer.OrdinalIgnoreCase); var newSelectList = new BsSelectList <TKey> { SelectedValues = selectList.SelectedValues }; foreach (var item in selectList.Items) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Items.Add(item); } selectList = newSelectList; } // Convert each ListItem to an <option> tag var listItemBuilder = new StringBuilder(); // Make optionLabel the first item that gets rendered. if (optionLabel != null) { listItemBuilder.AppendLine( ListItemToOption(new BsSelectListItem { Text = optionLabel, Value = String.Empty, Selected = false })); } if (selectList.Items.Any(x => string.IsNullOrEmpty(x.GroupKey))) { //build options foreach (var item in selectList.Items) { listItemBuilder.AppendLine(ListItemToOption(item)); } } else { //build options with optgroup foreach (var group in selectList.Items.GroupBy(i => i.GroupKey)) { string groupName = selectList.Items.Where(i => i.GroupKey == group.Key).Select(it => it.GroupName).FirstOrDefault(); listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\">", groupName, group.Key)); foreach (var item in group) { listItemBuilder.AppendLine(ListItemToOption(item)); } listItemBuilder.AppendLine("</optgroup>"); } } var tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", fullName, true); tagBuilder.AddCssClass(bsCssClass); tagBuilder.AddCssClass("form-control"); tagBuilder.GenerateId(fullName); if (allowMultiple) { tagBuilder.MergeAttribute("multiple", "multiple"); } tagBuilder.BsSelectListValidation(htmlHelper, fullName, metadata); return(MvcHtmlString.Create(tagBuilder.ToString())); }
private static ReadElement GetElementReader(ContentTypeReaderManager manager, MemberInfo member) { var property = member as PropertyInfo; var field = member as FieldInfo; Debug.Assert(field != null && property != null); if (property != null) { // Properties must have at least a getter. if (!property.CanRead) { return(null); } // Skip over indexer properties. if (property.GetIndexParameters().Any()) { return(null); } } // Are we explicitly asked to ignore this item? if (member.GetCustomAttribute <ContentSerializerIgnoreAttribute>() != null) { return(null); } var contentSerializerAttribute = member.GetCustomAttribute <ContentSerializerAttribute>(); if (contentSerializerAttribute == null) { if (property != null) { // There is no ContentSerializerAttribute, so non-public // properties cannot be deserialized. if (!ReflectionHelpers.PropertyIsPublic(property)) { return(null); } // If the read-only property has a type reader, // and CanDeserializeIntoExistingObject is true, // then it is safe to deserialize into the existing object. if (!property.CanWrite) { var typeReader = manager.GetTypeReader(property.PropertyType); if (typeReader == null || !typeReader.CanDeserializeIntoExistingObject) { return(null); } } } else { // There is no ContentSerializerAttribute, so non-public // fields cannot be deserialized. if (!field.IsPublic) { return(null); } // evolutional: Added check to skip initialise only fields if (field.IsInitOnly) { return(null); } } } Type elementType; Action <object, object> setter; if (property != null) { elementType = property.PropertyType; if (property.CanWrite) { setter = (o, v) => property.SetValue(o, v, null); } else { setter = (o, v) => { } }; } else { elementType = field.FieldType; setter = field.SetValue; } // Shared resources get special treatment. if (contentSerializerAttribute != null && contentSerializerAttribute.SharedResource) { return((input, parent) => { input.ReadSharedResource <object>((value) => setter(parent, value)); }); } // We need to have a reader at this point. var reader = manager.GetTypeReader(elementType); if (reader == null) { if (elementType == typeof(Array)) { reader = new ArrayReader <Array>(); } else { throw new ContentLoadException( $"Content reader could not be found for {elementType.FullName} type."); } } // We use the construct delegate to pick the correct existing // object to be the target of deserialization. Func <object, object> construct = parent => null; if (property != null && !property.CanWrite) { construct = parent => property.GetValue(parent, null); } return((input, parent) => { var existing = construct.Invoke(parent); var obj2 = input.ReadObject(reader, existing); setter(parent, obj2); }); }
protected string FieldPath <TValue>(Expression <Func <CinemachineGroupComposer, TValue> > expr) { return(ReflectionHelpers.GetFieldPath(expr)); }
private EmbeddedType CreateEmbeddedType(Type type) { #if NET40 Type typeInfo = type; #else TypeInfo typeInfo = type.GetTypeInfo(); #endif string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(true); ConstructorInfo[] constructors = type.GetConstructors(defaultBindingFlags); JsNativeFunction nativeConstructorFunction = (callee, isConstructCall, args, argCount, callbackData) => { object result; JsValue resultValue; object[] processedArgs = GetHostItemMemberArguments(args); if (processedArgs.Length == 0 && typeInfo.IsValueType) { result = Activator.CreateInstance(type); resultValue = MapToScriptType(result); return(resultValue); } JsValue undefinedValue = JsValue.Undefined; if (constructors.Length == 0) { CreateAndSetError(string.Format(Strings.Runtime_HostTypeConstructorNotFound, typeName)); return(undefinedValue); } var bestFitConstructor = (ConstructorInfo)ReflectionHelpers.GetBestFitMethod( constructors, processedArgs); if (bestFitConstructor == null) { CreateAndSetReferenceError(string.Format( Strings.Runtime_SuitableConstructorOfHostTypeNotFound, typeName)); return(undefinedValue); } ReflectionHelpers.FixArgumentTypes(ref processedArgs, bestFitConstructor.GetParameters()); try { result = bestFitConstructor.Invoke(processedArgs); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as WrapperException; JsValue errorValue = wrapperException != null? CreateErrorFromWrapperException(wrapperException) : JsErrorHelpers.CreateError(string.Format( Strings.Runtime_HostTypeConstructorInvocationFailed, typeName, exception.Message)) ; JsContext.SetException(errorValue); return(undefinedValue); } resultValue = MapToScriptType(result); return(resultValue); }; GCHandle embeddedTypeHandle = GCHandle.Alloc(type); IntPtr embeddedTypePtr = GCHandle.ToIntPtr(embeddedTypeHandle); JsValue objValue = JsValue.CreateExternalObject(embeddedTypePtr, _embeddedTypeFinalizeCallback); JsValue typeValue = JsValue.CreateFunction(nativeConstructorFunction); SetNonEnumerableProperty(typeValue, ExternalObjectPropertyName, objValue); var embeddedType = new EmbeddedType(type, typeValue, new List <JsNativeFunction> { nativeConstructorFunction }); ProjectFields(embeddedType); ProjectProperties(embeddedType); ProjectMethods(embeddedType); FreezeObject(typeValue); return(embeddedType); }
private void ProjectProperties(EmbeddedItem externalItem) { Type type = externalItem.HostType; object obj = externalItem.HostObject; JsValue typeValue = externalItem.ScriptValue; IList <JsNativeFunction> nativeFunctions = externalItem.NativeFunctions; bool instance = externalItem.IsInstance; string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); PropertyInfo[] properties = type.GetProperties(defaultBindingFlags); foreach (PropertyInfo property in properties) { string propertyName = property.Name; JsValue descriptorValue = JsValue.CreateObject(); descriptorValue.SetProperty("enumerable", JsValue.True, true); if (property.GetGetMethod() != null) { JsNativeFunction nativeGetFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue undefinedValue = JsValue.Undefined; if (instance && obj == null) { CreateAndSetTypeError(string.Format( Strings.Runtime_InvalidThisContextForHostObjectProperty, propertyName)); return(undefinedValue); } object result; try { result = property.GetValue(obj, new object[0]); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as WrapperException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? string.Format(Strings.Runtime_HostObjectPropertyGettingFailed, propertyName, exception.Message) : string.Format(Strings.Runtime_HostTypePropertyGettingFailed, propertyName, typeName, exception.Message) ; errorValue = JsErrorHelpers.CreateError(errorMessage); } JsContext.SetException(errorValue); return(undefinedValue); } JsValue resultValue = MapToScriptType(result); return(resultValue); }; nativeFunctions.Add(nativeGetFunction); JsValue getMethodValue = JsValue.CreateFunction(nativeGetFunction); descriptorValue.SetProperty("get", getMethodValue, true); } if (property.GetSetMethod() != null) { JsNativeFunction nativeSetFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue undefinedValue = JsValue.Undefined; if (instance && obj == null) { CreateAndSetTypeError(string.Format( Strings.Runtime_InvalidThisContextForHostObjectProperty, propertyName)); return(undefinedValue); } object value = MapToHostType(args[1]); ReflectionHelpers.FixPropertyValueType(ref value, property); try { property.SetValue(obj, value, new object[0]); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as WrapperException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? string.Format(Strings.Runtime_HostObjectPropertySettingFailed, propertyName, exception.Message) : string.Format(Strings.Runtime_HostTypePropertySettingFailed, propertyName, typeName, exception.Message) ; errorValue = JsErrorHelpers.CreateError(errorMessage); } JsContext.SetException(errorValue); return(undefinedValue); } return(undefinedValue); }; nativeFunctions.Add(nativeSetFunction); JsValue setMethodValue = JsValue.CreateFunction(nativeSetFunction); descriptorValue.SetProperty("set", setMethodValue, true); } typeValue.DefineProperty(propertyName, descriptorValue); } }
public void RenameProfile(bool addUniqueKey, bool useSameName) { var profileText = BasicProfileTextForCopyAndRename; var fromName = "basic_profile"; var toName = fromName + (useSameName ? "" : "2"); if (addUniqueKey) { profileText += "toolkit_artifact_guid=" + UniqueKey; } using (var tester = new SharedCredentialsFileTestFixture(profileText)) { // read the profile CredentialProfile before; Assert.IsTrue(tester.CredentialsFile.TryGetProfile(fromName, out before)); // rename it tester.CredentialsFile.RenameProfile(fromName, toName); CredentialProfile profile1Reread; if (useSameName) { Assert.IsTrue(tester.CredentialsFile.TryGetProfile(fromName, out profile1Reread)); } else { Assert.IsFalse(tester.CredentialsFile.TryGetProfile(fromName, out profile1Reread)); } // make sure one with the new name exists CredentialProfile after; Assert.IsTrue(tester.CredentialsFile.TryGetProfile(toName, out after)); if (useSameName) { Assert.AreEqual(before.Name, after.Name); } else { Assert.AreNotEqual(before.Name, after.Name); } // make sure the unique key is the same as before the rename if (addUniqueKey) { Assert.AreEqual(UniqueKey.ToString("D"), CredentialProfileUtils.GetUniqueKey(before)); } else { Assert.IsNull(CredentialProfileUtils.GetUniqueKey(before)); } Assert.AreEqual(CredentialProfileUtils.GetUniqueKey(before), CredentialProfileUtils.GetUniqueKey(after)); // make sure everything is the same (except for the name if it's a real rename) if (!useSameName) { ReflectionHelpers.Invoke(after, "Name", before.Name); } Assert.AreEqual(before, after); // make sure comments and other properties are unchanged after the rename tester.AssertCredentialsFileContents(profileText.Replace(fromName, toName)); } }
public void CopyProfile(bool addUniqueKey, bool addAnotherSection, bool useSameName) { var profileText = BasicProfileTextForCopyAndRename; var fromName = "basic_profile"; var toName = fromName + (useSameName ? "" : "2"); if (addUniqueKey) { profileText += "toolkit_artifact_guid=" + UniqueKey + Environment.NewLine; } var anotherSection = addAnotherSection ? "[another_section]" + Environment.NewLine + "propertyx=valuex" + Environment.NewLine: ""; using (var tester = new SharedCredentialsFileTestFixture(profileText + anotherSection)) { // read the profile CredentialProfile profile1; Assert.IsTrue(tester.CredentialsFile.TryGetProfile(fromName, out profile1)); // copy it tester.CredentialsFile.CopyProfile(fromName, toName); // make sure the original is untouched CredentialProfile profile1Reread; Assert.IsTrue(tester.CredentialsFile.TryGetProfile(fromName, out profile1Reread)); Assert.AreEqual(profile1, profile1Reread); // make sure the copy exists CredentialProfile profile2; Assert.IsTrue(tester.CredentialsFile.TryGetProfile(toName, out profile2)); if (useSameName) { Assert.AreEqual(profile1.Name, profile2.Name); } else { Assert.AreNotEqual(profile1.Name, profile2.Name); } if (addUniqueKey) { if (useSameName) { Assert.AreEqual(UniqueKey.ToString("D"), CredentialProfileUtils.GetUniqueKey(profile1)); Assert.AreEqual(CredentialProfileUtils.GetUniqueKey(profile1), CredentialProfileUtils.GetUniqueKey(profile2)); } else { Assert.AreEqual(UniqueKey.ToString("D"), CredentialProfileUtils.GetUniqueKey(profile1)); Assert.AreNotEqual(CredentialProfileUtils.GetUniqueKey(profile1), CredentialProfileUtils.GetUniqueKey(profile2)); } } else { Assert.IsNull(CredentialProfileUtils.GetUniqueKey(profile1)); Assert.IsNull(CredentialProfileUtils.GetUniqueKey(profile2)); } var contentsAfter = profileText; if (!useSameName) { // make sure the comments and everything got copied contentsAfter = (contentsAfter + anotherSection).TrimEnd() + Environment.NewLine; if (addUniqueKey) { contentsAfter += profileText.Replace(fromName, toName) .Replace(CredentialProfileUtils.GetUniqueKey(profile1).ToString(), CredentialProfileUtils.GetUniqueKey(profile2).ToString()).TrimEnd(); } else { contentsAfter += profileText.Replace(fromName, toName); } } tester.AssertCredentialsFileContents(contentsAfter); // make sure everything else on the copy is the same as the original string profile1Guid = CredentialProfileUtils.GetUniqueKey(profile1); CredentialProfileUtils.SetUniqueKey(profile2, profile1Guid == null ? (Guid?)null : new Guid(profile1Guid)); ReflectionHelpers.Invoke(profile2, "Name", profile1.Name); Assert.AreEqual(profile1, profile2); //make sure the additional key came along var value1 = CredentialProfileUtils.GetProperty(profile1, "property"); var value2 = CredentialProfileUtils.GetProperty(profile2, "property"); Assert.AreEqual("value", value1); Assert.AreEqual(value1, value2); } }
private void ProjectMethods(JsValue target, Type type, bool instance) { string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); MethodInfo[] methods = type.GetMethods(defaultBindingFlags); IEnumerable <IGrouping <string, MethodInfo> > methodGroups = methods.GroupBy(m => m.Name); foreach (IGrouping <string, MethodInfo> methodGroup in methodGroups) { string methodName = methodGroup.Key; MethodInfo[] methodCandidates = methodGroup.ToArray(); JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue thisValue = args[0]; JsValue undefinedValue = JsValue.Undefined; object thisObj = null; if (instance) { if (!thisValue.HasExternalData) { JsValue errorValue = JsErrorHelpers.CreateTypeError( string.Format(Strings.Runtime_InvalidThisContextForHostObjectMethod, methodName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } thisObj = MapToHostType(thisValue); } object[] processedArgs = MapToHostType(args.Skip(1).ToArray()); var bestFitMethod = (MethodInfo)ReflectionHelpers.GetBestFitMethod( methodCandidates, processedArgs); if (bestFitMethod == null) { JsValue errorValue = JsErrorHelpers.CreateReferenceError( string.Format(Strings.Runtime_SuitableMethodOfHostObjectNotFound, methodName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } ReflectionHelpers.FixArgumentTypes(ref processedArgs, bestFitMethod.GetParameters()); object result; try { result = bestFitMethod.Invoke(thisObj, processedArgs); } catch (Exception e) { string errorMessage = instance ? string.Format( Strings.Runtime_HostObjectMethodInvocationFailed, methodName, e.Message) : string.Format( Strings.Runtime_HostTypeMethodInvocationFailed, methodName, typeName, e.Message) ; JsValue errorValue = JsErrorHelpers.CreateError(errorMessage); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } JsValue resultValue = MapToScriptType(result); return(resultValue); }; _nativeFunctions.Add(nativeFunction); JsValue methodValue = JsValue.CreateFunction(nativeFunction); target.SetProperty(methodName, methodValue, true); } }
private void ProjectProperties(JsValue target, Type type, bool instance) { string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); PropertyInfo[] properties = type.GetProperties(defaultBindingFlags); foreach (PropertyInfo property in properties) { string propertyName = property.Name; JsValue descriptorValue = JsValue.CreateObject(); descriptorValue.SetProperty("enumerable", JsValue.True, true); if (property.GetGetMethod() != null) { JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue thisValue = args[0]; JsValue undefinedValue = JsValue.Undefined; object thisObj = null; if (instance) { if (!thisValue.HasExternalData) { JsValue errorValue = JsErrorHelpers.CreateTypeError( string.Format(Strings.Runtime_InvalidThisContextForHostObjectProperty, propertyName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } thisObj = MapToHostType(thisValue); } object result; try { result = property.GetValue(thisObj, new object[0]); } catch (Exception e) { string errorMessage = instance ? string.Format( Strings.Runtime_HostObjectPropertyGettingFailed, propertyName, e.Message) : string.Format( Strings.Runtime_HostTypePropertyGettingFailed, propertyName, typeName, e.Message) ; JsValue errorValue = JsErrorHelpers.CreateError(errorMessage); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } JsValue resultValue = MapToScriptType(result); return(resultValue); }; _nativeFunctions.Add(nativeFunction); JsValue getMethodValue = JsValue.CreateFunction(nativeFunction); descriptorValue.SetProperty("get", getMethodValue, true); } if (property.GetSetMethod() != null) { JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue thisValue = args[0]; JsValue undefinedValue = JsValue.Undefined; object thisObj = null; if (instance) { if (!thisValue.HasExternalData) { JsValue errorValue = JsErrorHelpers.CreateTypeError( string.Format(Strings.Runtime_InvalidThisContextForHostObjectProperty, propertyName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } thisObj = MapToHostType(thisValue); } object value = MapToHostType(args.Skip(1).First()); ReflectionHelpers.FixPropertyValueType(ref value, property); try { property.SetValue(thisObj, value, new object[0]); } catch (Exception e) { string errorMessage = instance ? string.Format( Strings.Runtime_HostObjectPropertySettingFailed, propertyName, e.Message) : string.Format( Strings.Runtime_HostTypePropertySettingFailed, propertyName, typeName, e.Message) ; JsValue errorValue = JsErrorHelpers.CreateError(errorMessage); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } return(undefinedValue); }; _nativeFunctions.Add(nativeFunction); JsValue setMethodValue = JsValue.CreateFunction(nativeFunction); descriptorValue.SetProperty("set", setMethodValue, true); } target.DefineProperty(propertyName, descriptorValue); } }
private JsValue CreateConstructor(Type type) { TypeInfo typeInfo = type.GetTypeInfo(); string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(true); ConstructorInfo[] constructors = type.GetConstructors(defaultBindingFlags); JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue resultValue; JsValue undefinedValue = JsValue.Undefined; object[] processedArgs = MapToHostType(args.Skip(1).ToArray()); object result; if (processedArgs.Length == 0 && typeInfo.IsValueType) { result = Activator.CreateInstance(type); resultValue = MapToScriptType(result); return(resultValue); } if (constructors.Length == 0) { JsValue errorValue = JsErrorHelpers.CreateError( string.Format(Strings.Runtime_HostTypeConstructorNotFound, typeName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } var bestFitConstructor = (ConstructorInfo)ReflectionHelpers.GetBestFitMethod( constructors, processedArgs); if (bestFitConstructor == null) { JsValue errorValue = JsErrorHelpers.CreateReferenceError( string.Format(Strings.Runtime_SuitableConstructorOfHostTypeNotFound, typeName)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } ReflectionHelpers.FixArgumentTypes(ref processedArgs, bestFitConstructor.GetParameters()); try { result = bestFitConstructor.Invoke(processedArgs); } catch (Exception e) { JsValue errorValue = JsErrorHelpers.CreateError( string.Format(Strings.Runtime_HostTypeConstructorInvocationFailed, typeName, e.Message)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } resultValue = MapToScriptType(result); return(resultValue); }; _nativeFunctions.Add(nativeFunction); JsValue constructorValue = JsValue.CreateFunction(nativeFunction); return(constructorValue); }
protected override void mapBindings() { base.mapBindings(); var helper = new ReflectionHelpers(); //map singletons foreach(var kvp in _map.interfaceMap) { //injectionBinder.Bind(helper.GetTypeInAssemblies(kvp.Key)) // .ToValue(Activator.CreateInstance(helper.GetTypeInAssemblies(kvp.Value))).ToSingleton(); injectionBinder.Bind(helper.GetTypeInAssemblies(kvp.Key)).To(helper.GetTypeInAssemblies(kvp.Value)).ToSingleton(); } foreach(var namedStringType in _map.namedStringTypes) { injectionBinder.Bind(namedStringType.Key).To(namedStringType.Value); } GetPlatform(); SetupAnalytics(helper); var buildConfig = ResourceLoader.Load<BuildConfigSO>(); injectionBinder.Bind<BuildConfigSO>().ToValue(buildConfig); IVR vrCamera = mapCamera(helper); injectionBinder.Bind<IRoutineRunner>().ToValue(SingletonManager.instance.AddSingleton<RoutineRunner>()); //{"interfaceMap":{"IController":"UnityDefaultInputAxisController","IVR":"OculusDesktopVR"},"interfaceToMultipleMaps":{"IAnalytics":["CountlyAnalytics"]},"namedStringTypes":{},"namedIntTypes":{}} const string CameraSettingsJsonName = "CameraSettingsJson"; var cameraSettingsJson = _map.namedStringTypes.ContainsKey(CameraSettingsJsonName) ? _map.namedStringTypes[CameraSettingsJsonName] : null; LoadCamera(vrCamera, vrCamera.GetCameraSettingsSO(), cameraSettingsJson); var lifecycle = SingletonManager.instance.AddSingleton<MonobehaviourLifecycleMessages>(); injectionBinder.Bind<IMonobehaviourLifecycleMessages>().ToValue(lifecycle); SetupLoggers(helper); //NOTE: not setting StartSignal mapping, leaving that up to subloggers! }
private void ProjectMethods(EmbeddedItem externalItem) { Type type = externalItem.HostType; object obj = externalItem.HostObject; JsValue typeValue = externalItem.ScriptValue; IList <JsNativeFunction> nativeFunctions = externalItem.NativeFunctions; bool instance = externalItem.IsInstance; string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); IEnumerable <MethodInfo> methods = type.GetMethods(defaultBindingFlags) .Where(ReflectionHelpers.IsFullyFledgedMethod); IEnumerable <IGrouping <string, MethodInfo> > methodGroups = methods.GroupBy(m => m.Name); foreach (IGrouping <string, MethodInfo> methodGroup in methodGroups) { string methodName = methodGroup.Key; MethodInfo[] methodCandidates = methodGroup.ToArray(); JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { JsValue undefinedValue = JsValue.Undefined; if (instance && obj == null) { CreateAndSetTypeError(string.Format( Strings.Runtime_InvalidThisContextForHostObjectMethod, methodName)); return(undefinedValue); } object[] processedArgs = GetHostItemMemberArguments(args); var bestFitMethod = (MethodInfo)ReflectionHelpers.GetBestFitMethod( methodCandidates, processedArgs); if (bestFitMethod == null) { CreateAndSetReferenceError(string.Format( Strings.Runtime_SuitableMethodOfHostObjectNotFound, methodName)); return(undefinedValue); } ReflectionHelpers.FixArgumentTypes(ref processedArgs, bestFitMethod.GetParameters()); object result; try { result = bestFitMethod.Invoke(obj, processedArgs); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as WrapperException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? string.Format(Strings.Runtime_HostObjectMethodInvocationFailed, methodName, exception.Message) : string.Format(Strings.Runtime_HostTypeMethodInvocationFailed, methodName, typeName, exception.Message) ; errorValue = JsErrorHelpers.CreateError(errorMessage); } JsContext.SetException(errorValue); return(undefinedValue); } JsValue resultValue = MapToScriptType(result); return(resultValue); }; nativeFunctions.Add(nativeFunction); JsValue methodValue = JsValue.CreateFunction(nativeFunction); typeValue.SetProperty(methodName, methodValue, true); } }
protected void SetupAnalytics(ReflectionHelpers helper) { string analyticsTypeName = typeof(IAnalytics).Name; List<Type> analyticsSystems = new List<Type>(); if(_map.interfaceToMultipleMaps.ContainsKey(analyticsTypeName)) { var multiAnalytics = _map.interfaceToMultipleMaps[analyticsTypeName]; foreach(var analyticsSystemName in multiAnalytics) { try { var system = helper.GetTypeInAssemblies(analyticsSystemName); if(system == null) { Debug.LogError("Didd not find desired analytics system:" + analyticsSystemName); continue; } analyticsSystems.Add(system); } catch(Exception e) { Debug.LogError("error setting up analytics system:" + analyticsSystemName + " error:" + e); } } } string initStringKey = InterfaceNamedInjections.ANALYTICS_INITIALIZATION.ToString(); List<string> listOfInitParams = new List<string>(); try { if(_map.namedStringTypes.ContainsKey(initStringKey)) { string initString = _map.namedStringTypes[initStringKey]; if(initString != null) { listOfInitParams = initString.JsonDeserialize<List<string>>(); } } } catch(Exception e) { Debug.LogError("Error while decodnig analytics init:" + e); //fall back to null analytics here? } injectionBinder.Bind<List<string>>() .ToValue(listOfInitParams) .ToName(InterfaceNamedInjections.ANALYTICS_INITIALIZATION); List<IAnalytics> analyticsSystemInstances = new List<IAnalytics>(); foreach(var analyticsSystem in analyticsSystems) { //Debug.Log("Initializing analytics sytem:" + analyticsSystem.Name); analyticsSystemInstances.Add(Activator.CreateInstance(analyticsSystem) as IAnalytics); } injectionBinder.Bind<List<IAnalytics>>().ToValue(analyticsSystemInstances); injectionBinder.Bind<IAnalytics>().To<AnalyticsManager>().ToSingleton(); }
private void ComponentList(Rect m_rect) { GUIUnstrip.BeginVertical(GUIContent.none, GUI.skin.box, null); m_compScroll = GUIUnstrip.BeginScrollView(m_compScroll); GUILayout.Label("<b><size=15>Components</size></b>", new GUILayoutOption[0]); GUIUnstrip.BeginHorizontal(new GUILayoutOption[0]); CompPages.DrawLimitInputArea(); if (CompPages.ItemCount > CompPages.ItemsPerPage) { CompPages.CurrentPageLabel(); GUILayout.EndHorizontal(); GUIUnstrip.BeginHorizontal(new GUILayoutOption[0]); if (GUILayout.Button("< Prev", new GUILayoutOption[] { GUILayout.Width(80) })) { CompPages.TurnPage(Turn.Left, ref this.m_compScroll); } if (GUILayout.Button("Next >", new GUILayoutOption[] { GUILayout.Width(80) })) { CompPages.TurnPage(Turn.Right, ref this.m_compScroll); } } GUILayout.EndHorizontal(); GUIUnstrip.BeginHorizontal(new GUILayoutOption[0]); var width = m_rect.width / 2 - 135f; m_addComponentInput = GUIUnstrip.TextField(m_addComponentInput, new GUILayoutOption[] { GUILayout.Width(width) }); if (GUILayout.Button("Add Comp", new GUILayoutOption[0])) { if (ReflectionHelpers.GetTypeByName(m_addComponentInput) is Type compType) { if (typeof(Component).IsAssignableFrom(compType)) { #if CPP TargetGO.AddComponent(Il2CppType.From(compType)); #else TargetGO.AddComponent(compType); #endif } else { ExplorerCore.LogWarning($"Type '{compType.Name}' is not assignable from Component!"); } } else { ExplorerCore.LogWarning($"Could not find a type by the name of '{m_addComponentInput}'!"); } } GUILayout.EndHorizontal(); GUI.skin.button.alignment = TextAnchor.MiddleLeft; if (m_cachedDestroyList.Count > 0) { m_cachedDestroyList.Clear(); } if (m_components != null) { int start = CompPages.CalculateOffsetIndex(); for (int j = start; (j < start + CompPages.ItemsPerPage && j < CompPages.ItemCount); j++) { var component = m_components[j]; if (!component) { continue; } var type = #if CPP component.GetIl2CppType(); #else component.GetType(); #endif GUIUnstrip.BeginHorizontal(new GUILayoutOption[0]); if (ReflectionHelpers.BehaviourType.IsAssignableFrom(type)) { #if CPP BehaviourEnabledBtn(component.TryCast <Behaviour>()); #else BehaviourEnabledBtn(component as Behaviour); #endif } else { GUIUnstrip.Space(26); } if (GUILayout.Button("<color=cyan>" + type.Name + "</color>", new GUILayoutOption[] { GUILayout.Width(m_rect.width / 2 - 100) })) { ReflectObject(component); } if (GUILayout.Button("<color=red>-</color>", new GUILayoutOption[] { GUILayout.Width(20) })) { m_cachedDestroyList.Add(component); } GUILayout.EndHorizontal(); } } GUI.skin.button.alignment = TextAnchor.MiddleCenter; if (m_cachedDestroyList.Count > 0) { for (int i = m_cachedDestroyList.Count - 1; i >= 0; i--) { var comp = m_cachedDestroyList[i]; GameObject.Destroy(comp); } } GUIUnstrip.EndScrollView(); GUILayout.EndVertical(); }
public IEnumerator ConstructTK2DDungeonHook(Action <TK2DDungeonAssembler, Dungeon, tk2dTileMap> orig, TK2DDungeonAssembler self, Dungeon d, tk2dTileMap map) { for (int j = 0; j < d.data.Width; j++) { for (int k = 0; k < d.data.Height; k++) { try { self.BuildTileIndicesForCell(d, map, j, k); } catch (Exception ex) { if (ChaosConsole.DebugExceptions) { ETGModConsole.Log("[DEBUG] Exception caught in TK2DDungeonAssembler.ConstructTK2DDungeonHook at TK2DDungeonAssembler.BuildTileIndicesForCell!"); } Debug.Log("Exception caught in TK2DDungeonAssembler.ConstructTK2DDungeonHook at TK2DDungeonAssembler.BuildTileIndicesForCell!"); Debug.LogException(ex); } } } yield return(null); TileIndices tileIndices = ReflectionHelpers.ReflectGetField <TileIndices>(typeof(TK2DDungeonAssembler), "t", self); if (d.tileIndices.tilesetId == GlobalDungeonData.ValidTilesets.WESTGEON || d.tileIndices.tilesetId == GlobalDungeonData.ValidTilesets.FINALGEON) { for (int l = 0; l < d.data.Width; l++) { for (int m = 0; m < d.data.Height; m++) { CellData cellData = d.data.cellData[l][m]; if (cellData != null) { if (cellData.type == CellType.FLOOR) { BuildShadowIndex(self, tileIndices, cellData, d, map, l, m); } else if (cellData.type == CellType.PIT) { BuildPitShadowIndex(self, tileIndices, cellData, d, map, l, m); } } } } } TK2DInteriorDecorator decorator = new TK2DInteriorDecorator(self); decorator.PlaceLightDecoration(d, map); for (int i = 0; i < d.data.rooms.Count; i++) { if (d.data.rooms[i].area.prototypeRoom == null || d.data.rooms[i].area.prototypeRoom.usesProceduralDecoration) { decorator.HandleRoomDecoration(d.data.rooms[i], d, map); } else { decorator.HandleRoomDecorationMinimal(d.data.rooms[i], d, map); } if (i % 5 == 0) { yield return(null); } } if ((d.data.rooms.Count - 1) % 5 != 0) { yield return(null); } map.Editor__SpriteCollection = tileIndices.dungeonCollection; if (d.ActuallyGenerateTilemap) { IEnumerator BuildTracker = map.DeferredBuild(tk2dTileMap.BuildFlags.Default); while (BuildTracker.MoveNext()) { yield return(null); } } yield break; }
internal void ConfigureEurekaServices(IServiceCollection services) { services .AddOptions <EurekaClientOptions>() .Configure <IConfiguration>((options, config) => { config.GetSection(EurekaClientOptions.EUREKA_CLIENT_CONFIGURATION_PREFIX).Bind(options); // Eureka is enabled by default. If eureka:client:enabled was not set then check spring:cloud:discovery:enabled if (options.Enabled && config.GetValue <bool?>(EurekaClientOptions.EUREKA_CLIENT_CONFIGURATION_PREFIX + ":enabled") is null && config.GetValue <bool?>(_springDiscoveryEnabled) == false) { options.Enabled = false; } }) .PostConfigure <IConfiguration>((options, config) => { var info = GetServiceInfo(config); EurekaPostConfigurer.UpdateConfiguration(config, info, options); }); services .AddOptions <EurekaInstanceOptions>() .Configure <IConfiguration>((options, config) => config.GetSection(EurekaInstanceOptions.EUREKA_INSTANCE_CONFIGURATION_PREFIX).Bind(options)) .PostConfigure <IServiceProvider>((options, serviceProvider) => { var config = serviceProvider.GetRequiredService <IConfiguration>(); var appInfo = serviceProvider.GetRequiredService <IApplicationInstanceInfo>(); var inetOptions = config.GetSection(InetOptions.PREFIX).Get <InetOptions>(); options.NetUtils = new InetUtils(inetOptions); options.ApplyNetUtils(); var endpointAssembly = "Steeltoe.Management.EndpointBase"; if (ReflectionHelpers.IsAssemblyLoaded(endpointAssembly)) { var actuatorOptionsType = ReflectionHelpers.FindType(new string[] { endpointAssembly }, new string[] { "Steeltoe.Management.Endpoint.Hypermedia.ActuatorManagementOptions" }); var endpointOptionsBaseType = ReflectionHelpers.FindType(new string[] { "Steeltoe.Management.Abstractions" }, new string[] { "Steeltoe.Management.IEndpointOptions" }); var mgmtOptions = serviceProvider.GetService(actuatorOptionsType); if (mgmtOptions is object) { var basePath = (string)actuatorOptionsType.GetProperty("Path").GetValue(mgmtOptions) + '/'; if (string.IsNullOrEmpty(config.GetValue <string>(EurekaInstanceOptions.EUREKA_INSTANCE_CONFIGURATION_PREFIX + ":HealthCheckUrlPath"))) { var healthOptionsType = ReflectionHelpers.FindType(new string[] { endpointAssembly }, new string[] { "Steeltoe.Management.Endpoint.Health.IHealthOptions" }); var healthOptions = serviceProvider.GetService(healthOptionsType); if (healthOptions is object) { options.HealthCheckUrlPath = basePath + ((string)endpointOptionsBaseType.GetProperty("Path").GetValue(healthOptions)).TrimStart('/'); } } if (string.IsNullOrEmpty(config.GetValue <string>(EurekaInstanceOptions.EUREKA_INSTANCE_CONFIGURATION_PREFIX + ":StatusPageUrlPath"))) { var infoOptionsType = ReflectionHelpers.FindType(new string[] { endpointAssembly }, new string[] { "Steeltoe.Management.Endpoint.Info.IInfoOptions" }); var infoOptions = serviceProvider.GetService(infoOptionsType); if (infoOptions is object) { options.StatusPageUrlPath = basePath + ((string)endpointOptionsBaseType.GetProperty("Path").GetValue(infoOptions)).TrimStart('/'); } } } } var info = GetServiceInfo(config); EurekaPostConfigurer.UpdateConfiguration(config, info, options, info?.ApplicationInfo ?? appInfo); }); services.TryAddSingleton(serviceProvider => { var clientOptions = serviceProvider.GetRequiredService <IOptions <EurekaClientOptions> >(); return(new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(clientOptions.Value.CacheTTL) }); }); }
public static void ConvertPsxPatchToPsp(string filename) { Dictionary <string, byte[]> fileList = new Dictionary <string, byte[]>(); using (ZipFile zipFile = new ZipFile(filename)) { foreach (ZipEntry entry in zipFile) { byte[] bytes = new byte[entry.Size]; StreamUtils.ReadFully(zipFile.GetInputStream(entry), bytes); fileList[entry.Name] = bytes; } } File.Delete(filename); if (fileList["type"].ToUTF8String() == Context.US_PSX.ToString()) { List <byte> amBytes = new List <byte>(fileList["actionMenus"]); amBytes.AddRange(PSPResources.Binaries.ActionEvents.Sub(0xE0, 0xE2)); fileList["actionMenus"] = amBytes.ToArray(); AllJobs aj = new AllJobs(Context.US_PSX, fileList["jobs"]); List <Job> jobs = new List <Job>(aj.Jobs); AllJobs defaultPspJobs = new AllJobs(Context.US_PSP, PSPResources.Binaries.Jobs); for (int i = 0; i < jobs.Count; i++) { jobs[i].Equipment.Unknown1 = defaultPspJobs.Jobs[i].Equipment.Unknown1; jobs[i].Equipment.Unknown2 = defaultPspJobs.Jobs[i].Equipment.Unknown2; jobs[i].Equipment.Unknown3 = defaultPspJobs.Jobs[i].Equipment.Unknown3; jobs[i].Equipment.FellSword = defaultPspJobs.Jobs[i].Equipment.FellSword; jobs[i].Equipment.LipRouge = defaultPspJobs.Jobs[i].Equipment.LipRouge; jobs[i].Equipment.Unknown6 = defaultPspJobs.Jobs[i].Equipment.Unknown6; jobs[i].Equipment.Unknown7 = defaultPspJobs.Jobs[i].Equipment.Unknown7; jobs[i].Equipment.Unknown8 = defaultPspJobs.Jobs[i].Equipment.Unknown8; } for (int i = 160; i < 169; i++) { jobs.Add(defaultPspJobs.Jobs[i]); } ReflectionHelpers.SetFieldOrProperty(aj, "Jobs", jobs.ToArray()); fileList["jobs"] = aj.ToByteArray(Context.US_PSP); JobLevels jl = new JobLevels(Context.US_PSX, fileList["jobLevels"]); JobLevels pspJobLevels = new JobLevels(Context.US_PSP, PSPResources.Binaries.JobLevels); foreach (string jobName in new string[19] { "Archer", "Arithmetician", "Bard", "BlackMage", "Chemist", "Dancer", "Dragoon", "Geomancer", "Knight", "Mime", "Monk", "Mystic", "Ninja", "Orator", "Samurai", "Summoner", "Thief", "TimeMage", "WhiteMage" }) { Requirements psxR = ReflectionHelpers.GetFieldOrProperty <Requirements>(jl, jobName); Requirements pspR = ReflectionHelpers.GetFieldOrProperty <Requirements>(pspJobLevels, jobName); psxR.Unknown1 = pspR.Unknown1; psxR.Unknown2 = pspR.Unknown2; psxR.DarkKnight = pspR.DarkKnight; psxR.OnionKnight = pspR.OnionKnight; } ReflectionHelpers.SetFieldOrProperty(jl, "OnionKnight", pspJobLevels.OnionKnight); ReflectionHelpers.SetFieldOrProperty(jl, "DarkKnight", pspJobLevels.DarkKnight); ReflectionHelpers.SetFieldOrProperty(jl, "Unknown", pspJobLevels.Unknown); fileList["jobLevels"] = jl.ToByteArray(Context.US_PSP); List <byte> ssBytes = new List <byte>(fileList["skillSets"]); ssBytes.AddRange(PSPResources.Binaries.SkillSets.Sub(ssBytes.Count)); fileList["skillSets"] = ssBytes.ToArray(); fileList["entd5"] = PSPResources.Binaries.ENTD5.ToArray(); fileList["type"] = Encoding.UTF8.GetBytes(Context.US_PSP.ToString()); fileList["pspItemAttributes"] = PSPResources.Binaries.NewItemAttributes.ToArray(); fileList["pspItems"] = PSPResources.Binaries.NewItems.ToArray(); if (!AllPropositions.CanFixBuggyLevelBonuses(Context.US_PSP)) { fileList["BuggyPropositions"] = new byte[0]; } else if (fileList.ContainsKey("BuggyPropositions")) { fileList.Remove("BuggyPropositions"); } } using (FileStream outFile = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite)) using (ZipOutputStream output = new ZipOutputStream(outFile)) { foreach (KeyValuePair <string, byte[]> entry in fileList) { WriteFileToZip(output, entry.Key, entry.Value); } } }
/// <summary> /// Returns a list of IObjectControl that edit the given ObjectToEdit. /// </summary> /// <param name="model">Object the IObjectControl should edit.</param> /// <param name="requestedTabTypes">Limits what types of iObjectControl should be returned. If the iObjectControl is not of any type in this IEnumerable, it will not be used. If empty or nothing, no constraints will be applied, which is not recommended because the iObjectControl could be made for a different environment (for example, a Windows Forms user control being used in a WPF environment).</param> /// <param name="manager">Instance of the current plugin manager.</param> /// <returns>An IEnumerable of object controls for the given model.</returns> /// <remarks>This version of <see cref="GetRefreshedTabs(Object, IEnumerable(Of Type), PluginManager)"/> searches for view models, then finds paths to the views.</remarks> private static IEnumerable <IViewControl> GetViewControlsByViewModel(object model, IEnumerable <Type> requestedTabTypes, ApplicationViewModel appViewModel, PluginManager manager) { Dictionary <object, List <IViewControl> > targetTabs = new Dictionary <object, List <IViewControl> >(); var modelType = model.GetType().GetTypeInfo(); List <object> viewModels = new List <object>(); viewModels.AddRange(appViewModel.GetViewModelsForModel(model)); viewModels.Add(model); // We'll consider the model itself a view model, if anything directly targets it // Get all tabs that could be used for the model, given the RequestedTabTypes constraint var availableTabs = (from viewModel in viewModels from view in GetViewControls(manager) let viewModelSortOrder = viewModel is GenericViewModel ? ((viewModel as GenericViewModel).SortOrder) : 0 where requestedTabTypes.Any(x => ReflectionHelpers.IsOfType(view, x.GetTypeInfo())) && view.GetSupportedTypes().Any(x => ReflectionHelpers.IsOfType(viewModel.GetType().GetTypeInfo(), x)) && view.SupportsObject(viewModel) orderby viewModelSortOrder, view.GetSortOrder(modelType, true) select new { viewModel, view, viewModelSortOrder = viewModel is GenericViewModel ? ((viewModel as GenericViewModel).SortOrder) : 0 }) .ToList(); var realTabs = availableTabs.Where(x => !x.view.GetIsBackupControl()).ToList(); foreach (var item in realTabs) { if (!targetTabs.ContainsKey(item.viewModel)) { targetTabs.Add(item.viewModel, new List <IViewControl>()); } targetTabs[item.viewModel].Add(item.view); } // Find the supported backup controls foreach (var item in availableTabs.Where(x => x.view.GetIsBackupControl()).Select(x => x.viewModel).Distinct()) { if (!realTabs.Where(x => x.view.SupportsObject(item)).Any()) { var usableBackup = availableTabs.Where(x => x.view.SupportsObject(item)).OrderByDescending(x => x.view.GetSortOrder(item.GetType().GetTypeInfo(), true)).FirstOrDefault(); if (usableBackup != null) { if (!targetTabs.ContainsKey(item)) { targetTabs.Add(item, new List <IViewControl>()); } targetTabs[item].Add(usableBackup.view); } } } // Create new instances and set targets var newTabs = new List <IViewControl>(); foreach (var item in targetTabs) { foreach (var view in item.Value) { var tab = manager.CreateNewInstance(view) as IViewControl; //Set the appropriate object tab.ViewModel = item.Key; newTabs.Add(tab); } } return(newTabs); }
public void GetConstants() { var constants = ReflectionHelpers.GetConstants(typeof(RegionShippingCost.Regions)); Assert.That(constants.Count(), Is.EqualTo(3)); }
/// <summary> /// Returns a list of view controls that edit the given ViewModel. /// </summary> /// <param name="viewModel">ViewModel for which to find view controls</param> /// <param name="requestedTabTypes">Limits what types of iObjectControl should be returned. If the iObjectControl is not of any type in this IEnumerable, it will not be used. If empty or nothing, no constraints will be applied, which is not recommended because the iObjectControl could be made for a different environment (for example, a Windows Forms user control being used in a WPF environment).</param> /// <param name="appViewModel">Instance of the current application ViewModel.</param> /// <returns>An IEnumerable of object controls for the given model.</returns> /// <remarks>This version of <see cref="GetViewControls(Object, IEnumerable(Of Type), PluginManager)"/> searches for views, then finds paths to the model.</remarks> private static IEnumerable <IViewControl> GetViewControlsByView(object viewModel, IEnumerable <Type> RequestedTabTypes, ApplicationViewModel appViewModel, PluginManager manager) { if (viewModel == null) { throw (new ArgumentNullException(nameof(viewModel))); } var modelType = viewModel.GetType().GetTypeInfo(); var allTabs = new List <IViewControl>(); var objControls = GetViewControls(manager); foreach (var etab in objControls.Where(x => RequestedTabTypes.Any(y => ReflectionHelpers.IsOfType(x, y.GetTypeInfo()))).OrderBy(x => x.GetSortOrder(modelType, true))) { bool isMatch = false; GenericViewModel currentViewModel = null; //Check to see if the tab support the type of the given object var supportedTypes = etab.GetSupportedTypes(); foreach (var typeInfo in supportedTypes) { if (typeInfo.IsInterface) { //The target is an interface. Check to see if there's a view model that implements it. //Otherwise, check the model //Get the view model for the model from the IOUI mangaer var viewmodelsForModel = appViewModel.GetViewModelsForModel(viewModel); //If there are none, and the model is a FileViewModel, get the view models that way if (ReferenceEquals(viewmodelsForModel, null) && viewModel is FileViewModel) { viewmodelsForModel = (viewModel as FileViewModel).GetViewModels(appViewModel); } //If we still can't find anything, set viewModelsForModel to an empty enumerable if (ReferenceEquals(viewmodelsForModel, null)) { viewmodelsForModel = Array.Empty <GenericViewModel>(); } // Of the view models that support the model, select the ones that the current view supports var availableViewModels = viewmodelsForModel.Where(x => ReflectionHelpers.IsOfType(x, typeInfo)); if (availableViewModels != null && availableViewModels.Any()) { // This view model fits the critera var first = availableViewModels.First(); isMatch = etab.SupportsObject(first); currentViewModel = first; if (isMatch) { break; } } else if (ReflectionHelpers.IsOfType(viewModel, typeInfo)) { // The model implements this interface isMatch = etab.SupportsObject(viewModel); if (isMatch) { break; } } } else if (ReflectionHelpers.IsOfType(viewModel, typeInfo)) { // The model is the same type as the target isMatch = etab.SupportsObject(viewModel); if (isMatch) { break; } } else if (ReflectionHelpers.IsOfType(typeInfo, typeof(GenericViewModel).GetTypeInfo())) { // The object control is targeting a view model // First, check to see if there's any view models for this model (i.e., is this an open file?) var viewmodelsForModel = appViewModel.GetViewModelsForModel(viewModel); if (ReferenceEquals(viewmodelsForModel, null) && viewModel is FileViewModel) { viewmodelsForModel = (viewModel as FileViewModel).GetViewModels(appViewModel); } //If there are, check to see if the target view supports the view model if (viewmodelsForModel != null) { var potentialViewModel = viewmodelsForModel.FirstOrDefault(x => ReflectionHelpers.IsOfType(x, typeInfo)) as GenericViewModel; if (potentialViewModel != null) { //This view model supports our model isMatch = etab.SupportsObject(potentialViewModel); currentViewModel = potentialViewModel; if (isMatch) { break; } } } } } // This is a supported tab. We're adding it! if (isMatch) { // Create another instance of etab, since etab is our cached, search-only instance. var tab = manager.CreateNewInstance(etab) as IViewControl; // Set the appropriate object if (currentViewModel != null) { //We have a view model that the view wants tab.ViewModel = currentViewModel; } else if (tab.SupportsObject(viewModel)) { // This model is what the view wants tab.ViewModel = viewModel; } allTabs.Add(tab); } } var backupTabs = new List <IViewControl>(); var notBackup = new List <IViewControl>(); //Sort the backup vs non-backup tabs foreach (var item in allTabs) { if (item.GetIsBackupControl()) { backupTabs.Add(item); } else { notBackup.Add(item); } } //And use the non-backup ones if available if (notBackup.Count > 0) { return(notBackup); } else { var toUse = backupTabs.OrderBy(x => x.GetSortOrder(modelType, true)).FirstOrDefault(); if (toUse == null) { return(Array.Empty <IViewControl>()); } else { return(new[] { toUse }); } } }
private static MvcHtmlString BsHiddenInternal <TKey>(this HtmlHelper htmlHelper, string name, BsSelectList <TKey> selectList, string optionLabel, IDictionary <string, object> htmlAttributes, bool allowMultiple, string bsCssClass, ModelMetadata metadata = null) { name += ".SelectedValues"; var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("Null Or Empty", "name"); } var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttribute("type", "hidden"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("class", bsCssClass + " form-control"); tagBuilder.MergeAttribute("name", fullName, true); tagBuilder.MergeAttribute("placeholder", optionLabel); tagBuilder.GenerateId(fullName); if (selectList != null) { if (selectList.Items != null) { if (allowMultiple) { var selectedItems = selectList.Items.Where(x => x.Selected).ToList(); if (selectedItems.Any()) { tagBuilder.MergeAttribute("data-init", JsonConvert.SerializeObject(selectedItems.Select(x => new { id = x.Value, text = x.Text }))); } } else { var selectedItem = selectList.Items.Where(x => x.Selected).FirstOrDefault(); if (selectedItem != null) { tagBuilder.MergeAttribute("data-init", JsonConvert.SerializeObject(new { id = selectedItem.Value, text = selectedItem.Text })); } } } if (selectList.SelectedValues != null) { var value = ""; if (ReflectionHelpers.IsList(selectList.SelectedValues)) { var arr = new List <string>(); foreach (var item in selectList.SelectedValues as IEnumerable) { arr.Add(item.ToString()); } value = string.Join(",", arr); } else { value = selectList.SelectedValues.ToString(); } tagBuilder.MergeAttribute("value", value); } } if (allowMultiple) { tagBuilder.MergeAttribute("multiple", "multiple"); } tagBuilder.BsSelectListValidation(htmlHelper, fullName, metadata); return(MvcHtmlString.Create(tagBuilder.ToString())); }
//////////////// public EditorButton() { ReflectionHelpers.Get(typeof(UICommon), null, "ButtonConfigTexture", out this.EditorButtonTex); }
private void CreateRigs(CinemachineVirtualCamera[] copyFrom) { // Invalidate the cache m_Rigs = null; mOribitals = null; string[] rigNames = RigNames; float[] softCenterDefaultsV = new float[] { 0.5f, 0.55f, 0.6f }; for (int i = 0; i < rigNames.Length; ++i) { CinemachineVirtualCamera src = null; if (copyFrom != null && copyFrom.Length > i) { src = copyFrom[i]; } CinemachineVirtualCamera rig = null; if (CreateRigOverride != null) { rig = CreateRigOverride(this, rigNames[i], src); } else { // If there is an existing rig with this name, delete it List <Transform> list = new List <Transform>(); foreach (Transform child in transform) { if (child.GetComponent <CinemachineVirtualCamera>() != null && child.gameObject.name == rigNames[i]) { list.Add(child); } } foreach (Transform child in list) { DestroyImmediate(child.gameObject); } // Create a new rig with default components GameObject go = new GameObject(rigNames[i]); go.transform.parent = transform; rig = go.AddComponent <CinemachineVirtualCamera>(); if (src != null) { ReflectionHelpers.CopyFields(src, rig); } else { go = rig.GetComponentOwner().gameObject; go.AddComponent <CinemachineOrbitalTransposer>(); go.AddComponent <CinemachineComposer>(); } } // Set up the defaults rig.InvalidateComponentPipeline(); CinemachineOrbitalTransposer orbital = rig.GetCinemachineComponent <CinemachineOrbitalTransposer>(); if (orbital == null) { orbital = rig.AddCinemachineComponent <CinemachineOrbitalTransposer>(); // should not happen } if (src == null) { // Only set defaults if not copying orbital.m_Radius = DefaultRadius[i]; orbital.m_HeightOffset = DefaultHeight[i]; CinemachineComposer composer = rig.GetCinemachineComponent <CinemachineComposer>(); if (composer != null) { composer.m_HorizontalDamping = composer.m_VerticalDamping = 0; composer.m_ScreenX = 0.5f; composer.m_ScreenY = softCenterDefaultsV[i]; composer.m_DeadZoneWidth = composer.m_DeadZoneHeight = 0; composer.m_SoftZoneWidth = composer.m_SoftZoneHeight = 0.8f; composer.m_BiasX = composer.m_BiasY = 0; } } } }
public virtual object CreateConnection(string connectionString) { return(ReflectionHelpers.CreateInstance(_type, new object[] { connectionString })); }
public void UpdateView() { ignoreChanges = true; commonAbilitiesEditor.Ability = ability; abilityAttributesEditor.Visible = ability.IsNormal; bool showEffect = ability.Effect != null && ability.Default.Effect != null; effectComboBox.Visible = showEffect; effectLabel.Visible = showEffect; abilityAttributesEditor.Attributes = ability.Attributes; foreach (NumericUpDownWithDefault spinner in spinners) { spinner.SetValueAndDefault( ReflectionHelpers.GetFieldOrProperty <byte>(ability, spinner.Tag.ToString()), ReflectionHelpers.GetFieldOrProperty <byte>(ability.Default, spinner.Tag.ToString())); } arithmeticksPanel.Visible = ability.IsArithmetick; chargingPanel.Visible = ability.IsCharging; jumpingPanel.Visible = ability.IsJumping; itemUsePanel.Visible = ability.IsItem; abilityIdPanel.Visible = ability.IsOther; throwingPanel.Visible = ability.IsThrowing; if (FFTPatch.Context == Context.US_PSP && ourContext != Context.US_PSP) { ourContext = Context.US_PSP; itemUseComboBox.Items.Clear(); itemUseComboBox.Items.AddRange(pspItems.ToArray()); effectComboBox.DataSource = new List <Effect>(Effect.PSPEffects.Values); throwingComboBox.DataSource = pspItemTypes; } else if (FFTPatch.Context == Context.US_PSX && ourContext != Context.US_PSX) { ourContext = Context.US_PSX; itemUseComboBox.Items.Clear(); itemUseComboBox.Items.AddRange(psxItems.ToArray()); effectComboBox.DataSource = new List <Effect>(Effect.PSXEffects.Values); throwingComboBox.DataSource = psxItemTypes; } if (showEffect) { effectComboBox.SetValueAndDefault(ability.Effect, ability.Default.Effect); } if (ability.IsItem) { itemUseComboBox.SetValueAndDefault(ability.Item, ability.Default.Item); } if (ability.IsThrowing) { throwingComboBox.SetValueAndDefault(ability.Throwing, ability.Default.Throwing); } ignoreChanges = false; }
public void Register() { manager.RegisterRoleSession(RoleSessionName, samlCredentials); fixture.AssertJsonProperty(RoleSessionName, SettingsConstants.RoleSession, (string)ReflectionHelpers.Invoke(samlCredentials, "ToJson")); }
public void SetUp() { _target = new ReflectionHelpers(); }
protected IVR mapCamera(ReflectionHelpers helper) { IVR vrCamera = null; if(_map.interfaceMap.ContainsKey("IVR")) { try { vrCamera = Activator.CreateInstance(helper.GetTypeInAssemblies(_map.interfaceMap["IVR"])) as IVR; } catch(Exception e) { //TODO: find a way to get the real logger! Debug.LogError("ERROR_INITIALIXING_IVR_FROM_MAP:" + e); } } if(vrCamera == null) { if(injectionBinder.GetBinding<IVR>() != null) { vrCamera = injectionBinder.GetInstance<IVR>(); } } if(vrCamera == null) vrCamera = new NullVR(); var ivrbinding = injectionBinder.GetBinding<IVR>(); if (ivrbinding == null) { injectionBinder.Bind<IVR>().ToValue(vrCamera).ToSingleton(); } return vrCamera; }
private CinemachineVirtualCamera[] CreateRigs(CinemachineVirtualCamera[] copyFrom) { // Invalidate the cache mOrbitals = null; float[] softCenterDefaultsV = new float[] { 0.5f, 0.55f, 0.6f }; CinemachineVirtualCamera[] newRigs = new CinemachineVirtualCamera[3]; for (int i = 0; i < RigNames.Length; ++i) { CinemachineVirtualCamera src = null; if (copyFrom != null && copyFrom.Length > i) { src = copyFrom[i]; } if (CreateRigOverride != null) { newRigs[i] = CreateRigOverride(this, RigNames[i], src); } else { // Create a new rig with default components GameObject go = new GameObject(RigNames[i]); go.transform.parent = transform; newRigs[i] = go.AddComponent <CinemachineVirtualCamera>(); if (src != null) { ReflectionHelpers.CopyFields(src, newRigs[i]); } else { go = newRigs[i].GetComponentOwner().gameObject; go.AddComponent <CinemachineOrbitalTransposer>(); go.AddComponent <CinemachineComposer>(); } } // Set up the defaults newRigs[i].InvalidateComponentPipeline(); CinemachineOrbitalTransposer orbital = newRigs[i].GetCinemachineComponent <CinemachineOrbitalTransposer>(); if (orbital == null) { orbital = newRigs[i].AddCinemachineComponent <CinemachineOrbitalTransposer>(); // should not happen } if (src == null) { // Only set defaults if not copying orbital.m_YawDamping = 0; CinemachineComposer composer = newRigs[i].GetCinemachineComponent <CinemachineComposer>(); if (composer != null) { composer.m_HorizontalDamping = composer.m_VerticalDamping = 0; composer.m_ScreenX = 0.5f; composer.m_ScreenY = softCenterDefaultsV[i]; composer.m_DeadZoneWidth = composer.m_DeadZoneHeight = 0.1f; composer.m_SoftZoneWidth = composer.m_SoftZoneHeight = 0.8f; composer.m_BiasX = composer.m_BiasY = 0; } } } return(newRigs); }
protected void SetupLoggers(ReflectionHelpers helper) { var mappedLoggers = false; if(_map.namedInterfaceBindings != null) { foreach(var namedInterfaceBinding in _map.namedInterfaceBindings) { if(namedInterfaceBinding.InterfaceToMap == typeof(ILogger).ToString()) { mappedLoggers = true; injectionBinder.Bind<ILogger>() .To(helper.GetTypeInAssemblies(namedInterfaceBinding.TargetType)) .ToName(namedInterfaceBinding.nameToMapTo); //injectionBinder.Bind<ILogger>().To<RemoteLogger>().ToName(namedInterfaceBinding.nameToMapTo); } } } if(!mappedLoggers) { injectionBinder.Bind<ILogger>().To<RemoteLogger>().ToName(LogManager.NamedLogger.PRIMARY); injectionBinder.Bind<ILogger>().To<UnityLogger>().ToName(LogManager.NamedLogger.SECONDARY); injectionBinder.Bind<ILogger>().To<NullDebugLog>().ToName(LogManager.NamedLogger.TERTIARY); } injectionBinder.Bind<ILogger>().To<LogManager>().ToSingleton().CrossContext(); //injectionBinder.Bind<>() }
public static DungeonFlow DuplicateDungeonFlow(DungeonFlow flow) { DungeonFlow dungeonFlow = ScriptableObject.CreateInstance <DungeonFlow>(); dungeonFlow.name = flow.name; dungeonFlow.fallbackRoomTable = flow.fallbackRoomTable; dungeonFlow.phantomRoomTable = flow.phantomRoomTable; dungeonFlow.subtypeRestrictions = flow.subtypeRestrictions; dungeonFlow.evolvedRoomTable = flow.evolvedRoomTable; ReflectionHelpers.ReflectSetField(typeof(DungeonFlow), "m_firstNodeGuid", ReflectionHelpers.ReflectGetField <string>(typeof(DungeonFlow), "m_firstNodeGuid", flow), dungeonFlow); dungeonFlow.flowInjectionData = flow.flowInjectionData; dungeonFlow.sharedInjectionData = flow.sharedInjectionData; ReflectionHelpers.ReflectSetField(typeof(DungeonFlow), "m_nodeGuids", new List <string>(ReflectionHelpers.ReflectGetField <List <string> >(typeof(DungeonFlow), "m_nodeGuids", flow)), dungeonFlow); List <DungeonFlowNode> list = new List <DungeonFlowNode>(); ReflectionHelpers.ReflectSetField(typeof(DungeonFlow), "m_nodes", list, dungeonFlow); foreach (DungeonFlowNode node in flow.AllNodes) { DungeonFlowNode dungeonFlowNode = DuplicateDungeonFlowNode(node); dungeonFlowNode.flow = dungeonFlow; list.Add(dungeonFlowNode); } return(dungeonFlow); }