protected override void MapInternal(Reflection.InitContext initContext, IMapDataSource source, object sourceObject, IMapDataDestination dest, object destObject, params object[] parameters) { FullObjectMapper mapper = (FullObjectMapper)initContext.ObjectMapper; IDataReader dataReader = (IDataReader)sourceObject; //int[] index = GetIndex(source, dest); //IValueMapper[] mappers = GetValueMappers(source, dest, index); //foreach (var valueMapper in mappers) //{ //} InitSchema(dataReader); if (mapper.ColParent) { FillObject(mapper, dataReader, destObject); while (dataReader.Read()) { destObject = FillObject(destObject, mapper, dataReader); } } else FillObject(mapper, dataReader, destObject); }
public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, Reflection.MemberInfo member) { if (reflectedType == null) throw new ArgumentNullException("reflectedType"); if (member == null) throw new ArgumentNullException("member"); if (!(member is TypeInfo) && member.DeclaringType != reflectedType) return EmptyArray<Attribute>.Value; return member.GetCustomAttributes(false); }
public FormMember(Reflection.IClassMember member) : base(member) { this._Label = new Element("label"); this._Restrictions = new Restrictions.RestrictionList(member.MemberInfo, true); this._Interceptors = new Interceptors.InterceptorList(member.MemberInfo, true); LabelAttribute label = member.GetAttribute<LabelAttribute>(true); if (label != null) this._Label.Children.AddLast(new Text(label.Text)); else this._Label.Children.AddLast(new Text(member.MemberName)); }
public void TestGetsShouldBeCamelCased() { var subject = new TestSubject(); var reflection = new Reflection(subject).AdaptToNaturalLanguage(); subject.ComplexArray = new TestSubject[3]; subject.ComplexArray[0] = new TestSubject(); subject.ComplexArray[1] = new TestSubject(); subject.ComplexArray[2] = new TestSubject(); subject.ComplexArray[0].SimpleString = "first"; subject.ComplexArray[1].SimpleString = "second"; subject.ComplexArray[2].SimpleString = "third"; Assert.That(reflection.Get("complex array.0.simple string").Result, Is.EqualTo("first")); Assert.That(reflection.Get("complex array.1.simple string").Result, Is.EqualTo("second")); Assert.That(reflection.Get("complex array.2.simple string").Result, Is.EqualTo("third")); }
public void TestSetsByIndexerShouldBeCamelCased() { var subject = new TestSubject(); var reflection = new Reflection(subject).AdaptToNaturalLanguage(); subject.ComplexArray = new TestSubject[3]; subject.ComplexArray[0] = new TestSubject(); subject.ComplexArray[1] = new TestSubject(); subject.ComplexArray[2] = new TestSubject(); subject.ComplexArray[0].SimpleString = "first"; subject.ComplexArray[1].SimpleString = "second"; subject.ComplexArray[2].SimpleString = "third"; reflection["complex array.0.simple string"] = "1 CHANGED"; reflection["complex array.1.simple string"] = "2 CHANGED"; reflection["complex array.2.simple string"] = "3 CHANGED"; Assert.That(subject.ComplexArray[0].SimpleString, Is.EqualTo("1 CHANGED")); Assert.That(subject.ComplexArray[1].SimpleString, Is.EqualTo("2 CHANGED")); Assert.That(subject.ComplexArray[2].SimpleString, Is.EqualTo("3 CHANGED")); }
private void RegisterMember(Type type, Reflection.MemberInfo m, Type mType, Func<object, object> get, Action<object, object> set) { if (mType.IsSubclassOf(typeof(Delegate))) return; // struct that holds access method for property/field MemberInfo accessor = new MemberInfo(); accessor.Type = mType; accessor.Get = get; accessor.Set = set; if(set!=null){ // writeable ? accessor.SerializeMethod = YamlSerializeMethod.Assign; } else { accessor.SerializeMethod = YamlSerializeMethod.Never; if ( mType.IsClass ) accessor.SerializeMethod = YamlSerializeMethod.Content; } var field = m as FieldInfo; var prop = m as PropertyInfo; var attr1 = m.GetAttribute<YamlSerializeAttribute>(); if ( attr1 != null ) { // specified if ( set == null ) { // read only member if ( attr1.SerializeMethod == YamlSerializeMethod.Assign || ( mType.IsValueType && accessor.SerializeMethod == YamlSerializeMethod.Content ) ) throw new ArgumentException("{0} {1} is not writeable by {2}." .DoFormat(mType.FullName, m.Name, attr1.SerializeMethod.ToString())); } accessor.SerializeMethod = attr1.SerializeMethod; } else { //if there are no attributes, and the field/property is private, internal, or protected, set it to not serialize if (field != null) { if (field.IsFamilyOrAssembly || field.IsPrivate) accessor.SerializeMethod = YamlSerializeMethod.Never; } else if (prop != null) { if (accessor.Get.Method.IsFamilyOrAssembly || accessor.Get.Method.IsPrivate) accessor.SerializeMethod = YamlSerializeMethod.Never; } } if ( accessor.SerializeMethod == YamlSerializeMethod.Never ) return; // no need to register if ( accessor.SerializeMethod == YamlSerializeMethod.Binary ) { if ( !mType.IsArray ) throw new InvalidOperationException("{0} {1} of {2} is not an array. Can not be serialized as binary." .DoFormat(mType.FullName, m.Name, type.FullName)); if ( !TypeUtils.IsPureValueType(mType.GetElementType()) ) throw new InvalidOperationException( "{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary." .DoFormat(mType.GetElementType(), mType.FullName, m.Name, type.FullName)); } // ShouldSerialize // YamlSerializeAttribute(Never) => false // ShouldSerializeSomeProperty => call it // DefaultValueAttribute(default) => compare to it // otherwise => true var shouldSerialize = type.GetMethod("ShouldSerialize" + m.Name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, Type.EmptyTypes, new System.Reflection.ParameterModifier[0]); if ( shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && accessor.ShouldSeriealize == null ) accessor.ShouldSeriealize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray); var attr2 = m.GetAttribute<DefaultValueAttribute>(); if ( attr2 != null && accessor.ShouldSeriealize == null ) { var defaultValue = attr2.Value; if ( TypeUtils.IsNumeric(defaultValue) && defaultValue.GetType() != mType ) defaultValue = TypeUtils.CastToNumericType(defaultValue, mType); accessor.ShouldSeriealize = obj => !TypeUtils.AreEqual(defaultValue, accessor.Get(obj)); } if ( accessor.ShouldSeriealize == null ) accessor.ShouldSeriealize = obj => true; Accessors.Add(m.Name, accessor); }
public static Type GetHiddenType(this CustomPropertyDrawer prop) { return(Reflection.GetField <Type>("m_Type", typeof(CustomPropertyDrawer), false, prop)); }
public void GetTypesWithAttribute() { Assert.AreEqual(4, Reflection.GetTypesWith <KRPCServiceAttribute> ().Count()); Assert.AreEqual(5, Reflection.GetTypesWith <KRPCClassAttribute> ().Count()); Assert.AreEqual(0, Reflection.GetTypesWith <KRPCPropertyAttribute> ().Count()); }
/// <summary> /// Creates an enumerator used in foreach statement. /// </summary> /// <param name="keyed">Whether the foreach statement uses keys.</param> /// <param name="aliasedValues">Whether the values returned by enumerator are assigned by reference.</param> /// <param name="caller">Type <see cref="Reflection.DTypeDesc"/> of the caller (ignored).</param> /// <returns>The dictionary enumerator.</returns> /// <remarks>Used for internal purposes only!</remarks> public virtual IDictionaryEnumerator GetForeachEnumerator(bool keyed, bool aliasedValues, Reflection.DTypeDesc caller) { if (aliasedValues) return new ForeachEnumeratorAliased(this, keyed); else return new ForeachEnumeratorValues(this/*, keyed*/); }
/// <summary> /// Sets up the fields needed to store the data for lazy loading /// </summary> /// <param name="TypeBuilder"></param> private void SetupFields(Reflection.Emit.TypeBuilder TypeBuilder) { if (ClassMappings.ContainsKey(TypeBuilder.BaseClass)) { foreach (IMapping Mapping in ClassMappings[TypeBuilder.BaseClass]) { foreach (IProperty Property in Mapping.Properties) { if (Property is IManyToOne || Property is IMap) { if (Fields.FirstOrDefault(x => x.Name == Property.DerivedFieldName) == null) Fields.Add(TypeBuilder.CreateField(Property.DerivedFieldName, Property.Type)); } else if (Property is IIEnumerableManyToOne || Property is IManyToMany) { if (Fields.FirstOrDefault(x => x.Name == Property.DerivedFieldName) == null) Fields.Add(TypeBuilder.CreateField(Property.DerivedFieldName, typeof(IEnumerable<>).MakeGenericType(Property.Type))); } else if (Property is IListManyToOne || Property is IListManyToMany) { if (Fields.FirstOrDefault(x => x.Name == Property.DerivedFieldName) == null) Fields.Add(TypeBuilder.CreateField(Property.DerivedFieldName, typeof(List<>).MakeGenericType(Property.Type))); } } } } }
public static async Task SetAssetBundleFileInfo(string exportPath, AssetInfoManifest assetInfoManifest, BuildResult buildResult) { var assetInfos = Reflection.GetPrivateField <AssetInfoManifest, AssetInfo[]>(assetInfoManifest, "assetInfos"); var assetBundleGroups = assetInfos .Where(x => x.IsAssetBundle) .GroupBy(x => x.AssetBundle.AssetBundleName); var tasks = new Dictionary <string, Task>(); foreach (var assetBundleGroup in assetBundleGroups) { var assetBundleName = assetBundleGroup.Key; if (tasks.ContainsKey(assetBundleName)) { continue; } var assetInfo = assetBundleGroup.First(); var detail = buildResult.GetDetails(assetBundleName); if (!detail.HasValue) { throw new InvalidDataException("AssetBundle build info not found. : " + assetBundleName); } var filePath = PathUtility.Combine(exportPath, assetBundleName); // CRC. assetInfo.AssetBundle.SetCRC(detail.Value.Crc); // Hash. var assetBundleHash = detail.Value.Hash.ToString(); // ファイルハッシュ・ファイルサイズ設定. var packageFilePath = Path.ChangeExtension(filePath, AssetBundleManager.PackageExtension); var task = Task.Run(() => { if (!File.Exists(packageFilePath)) { throw new InvalidDataException("Package file not found. : " + packageFilePath); } var fileInfo = new FileInfo(packageFilePath); var size = fileInfo.Exists ? fileInfo.Length : -1; var crc = FileUtility.GetCRC(packageFilePath); // 同じアセットバンドル名の全アセット情報を更新. foreach (var item in assetBundleGroup) { item.SetFileInfo(size, crc, assetBundleHash); } }); tasks.Add(assetBundleName, task); } await Task.WhenAll(tasks.Values); Reflection.SetPrivateField(assetInfoManifest, "assetInfos", assetInfos); UnityEditorUtility.SaveAsset(assetInfoManifest); assetInfoManifest.BuildCache(true); EditorUtility.ClearProgressBar(); }
internal AssemblyBuilder DefineDynamicAssembly(Reflection.AssemblyName name, AssemblyBuilderAccess access) { return AssemblyBuilder.DefineDynamicAssembly(name, access); }
/// <summary> /// Set up interfaces /// </summary> /// <param name="TypeBuilder">Type builder to use</param> public void SetupInterfaces(Reflection.Emit.TypeBuilder TypeBuilder) { Fields = new List<Reflection.Emit.FieldBuilder>(); SessionField = CreateProperty(TypeBuilder, "Session0", typeof(Session)); CreateConstructor(TypeBuilder); SetupFields(TypeBuilder); }
public static void SetAttribute(this DecoratorDrawer drawer, PropertyAttribute attrib) { Reflection.SetField("m_Attribute", typeof(DecoratorDrawer), attrib, false, drawer); }
protected override object MapInternal(Reflection.InitContext initContext) { FbDataReader dr = initContext.SourceObject as FbDataReader; // Fb's SP returns single row with nulls if selected object doesn't exists // so for all DBNull's (null) should be returned, instead of object instance // if (dr != null) { int i = dr.FieldCount; while (--i >= 0) if (!dr.IsDBNull(i)) break; // All field are DBNull. // if (i < 0) return null; } return base.MapInternal(initContext); }
public static void SetFieldInfo(this PropertyDrawer drawer, FieldInfo info) { Reflection.SetField("m_FieldInfo", typeof(PropertyDrawer), info, false, drawer); }
public static void OnGUISafe(this PropertyDrawer drawer, Rect position, SerializedProperty property, GUIContent label) { Reflection.GetReflectedMethod("OnGUISafe", typeof(UnityEditor.PropertyDrawer), false, drawer).Invoke(drawer, new object[] { position, property, label }); }
public static float GetPropertyHeightSafe(this PropertyDrawer drawer, SerializedProperty property, GUIContent label) { return((float)Reflection.GetReflectedMethod("GetPropertyHeightSafe", typeof(UnityEditor.PropertyDrawer), false, drawer).Invoke(drawer, new object[] { property, label })); }
public void HasAttribute() { Assert.IsTrue(Reflection.HasAttribute <KRPCServiceAttribute> (typeof(TestService3))); Assert.IsFalse(Reflection.HasAttribute <KRPCServiceAttribute> (typeof(TestService.TestClass))); }
public void GetPropertiesWithAttribute() { Assert.AreEqual(3, Reflection.GetPropertiesWith <KRPCPropertyAttribute> (typeof(TestService)).Count()); Assert.AreEqual(2, Reflection.GetPropertiesWith <KRPCPropertyAttribute> (typeof(TestService.TestClass)).Count()); Assert.AreEqual(0, Reflection.GetPropertiesWith <KRPCPropertyAttribute> (typeof(string)).Count()); }
public static Stream LoadEmbeddedResource(Reflection.Assembly thisAsm, string assemblyName, string resourceName) { string name = assemblyName + "." + resourceName; if (new List<string>(thisAsm.GetManifestResourceNames()).IndexOf(name) != -1) return thisAsm.GetManifestResourceStream(name); else return null; }
public static bool GetUseForChildren(this CustomPropertyDrawer prop) { return(Reflection.GetField <bool>("m_UseForChildren", typeof(CustomPropertyDrawer), false, prop)); }
private void UpdateCardTooltip() { var pos = User32.GetMousePos(); var relativePlayerDeckPos = ViewBoxPlayer.PointFromScreen(new Point(pos.X, pos.Y)); var relativeOpponentDeckPos = ViewBoxOpponent.PointFromScreen(new Point(pos.X, pos.Y)); var relativeSecretsPos = StackPanelSecrets.PointFromScreen(new Point(pos.X, pos.Y)); var relativeCardMark = _cardMarks.Select(x => new { Label = x, Pos = x.PointFromScreen(new Point(pos.X, pos.Y)) }); var visibility = (Config.Instance.OverlayCardToolTips && !Config.Instance.OverlaySecretToolTipsOnly) ? Visible : Hidden; ToolTipCard.CardSetToolTip.Visibility = Config.Instance.OverlaySetToolTips ? Visible : Collapsed; ToolTipCard.CreatedByVisibility = Collapsed; var cardMark = relativeCardMark.FirstOrDefault( x => x.Label.IsVisible && PointInsideControl(x.Pos, x.Label.ActualWidth, x.Label.ActualHeight, new Thickness(3, 1, 7, 1))); if (!Config.Instance.HideOpponentCardMarks && cardMark != null) { var index = _cardMarks.IndexOf(cardMark.Label); var card = _game.Opponent.Hand.FirstOrDefault(x => x.GetTag(GameTag.ZONE_POSITION) == index + 1 && x.HasCardId && !x.Info.Hidden)?.Card; var creatorCard = _cardMarks[index].SourceCard; if (card != null || creatorCard != null) { ToolTipCard.SetValue(DataContextProperty, card ?? creatorCard); var offset = _cardMarks[index].ActualHeight * 1.25; var topOffset = Canvas.GetTop(_cardMarks[index]) + offset; var leftOffset = Canvas.GetLeft(_cardMarks[index]) + offset; Canvas.SetTop(ToolTipCard, topOffset); Canvas.SetLeft(ToolTipCard, leftOffset); ToolTipCard.Visibility = Config.Instance.OverlayCardMarkToolTips ? Visible : Hidden; ToolTipCard.CreatedByVisibility = card != null ? Collapsed : Visible; } else { ToolTipCard.Visibility = Hidden; ToolTipCard.CreatedByVisibility = Collapsed; } } //player card tooltips else if (ListViewPlayer.Visibility == Visible && StackPanelPlayer.Visibility == Visible && PointInsideControl(relativePlayerDeckPos, ListViewPlayer.ActualWidth, ListViewPlayer.ActualHeight)) { //card size = card list height / amount of cards var cardSize = ViewBoxPlayer.ActualHeight / ListViewPlayer.Items.Count; var cardIndex = (int)(relativePlayerDeckPos.Y / cardSize); if (cardIndex < 0 || cardIndex >= ListViewPlayer.Items.Count) { return; } ToolTipCard.SetValue(DataContextProperty, ListViewPlayer.Items.Cast <AnimatedCard>().ElementAt(cardIndex).Card); var centeredListOffset = Config.Instance.OverlayCenterPlayerStackPanel ? (BorderStackPanelPlayer.ActualHeight - StackPanelPlayer.ActualHeight) / 2 : 0; //offset is affected by scaling var topOffset = Canvas.GetTop(BorderStackPanelPlayer) + centeredListOffset + GetListViewOffset(StackPanelPlayer) + cardIndex * cardSize * Config.Instance.OverlayPlayerScaling / 100; //prevent tooltip from going outside of the overlay if (topOffset + ToolTipCard.ActualHeight > Height) { topOffset = Height - ToolTipCard.ActualHeight; } SetTooltipPosition(topOffset, BorderStackPanelPlayer); ToolTipCard.Visibility = visibility; } //opponent card tooltips else if (ListViewOpponent.Visibility == Visible && StackPanelOpponent.Visibility == Visible && PointInsideControl(relativeOpponentDeckPos, ListViewOpponent.ActualWidth, ListViewOpponent.ActualHeight)) { //card size = card list height / amount of cards var cardSize = ViewBoxOpponent.ActualHeight / ListViewOpponent.Items.Count; var cardIndex = (int)(relativeOpponentDeckPos.Y / cardSize); if (cardIndex < 0 || cardIndex >= ListViewOpponent.Items.Count) { return; } ToolTipCard.SetValue(DataContextProperty, ListViewOpponent.Items.Cast <AnimatedCard>().ElementAt(cardIndex).Card); var centeredListOffset = Config.Instance.OverlayCenterOpponentStackPanel ? (BorderStackPanelOpponent.ActualHeight - StackPanelOpponent.ActualHeight) / 2 : 0; //offset is affected by scaling var topOffset = Canvas.GetTop(BorderStackPanelOpponent) + centeredListOffset + GetListViewOffset(StackPanelOpponent) + cardIndex * cardSize * Config.Instance.OverlayOpponentScaling / 100; //prevent tooltip from going outside of the overlay if (topOffset + ToolTipCard.ActualHeight > Height) { topOffset = Height - ToolTipCard.ActualHeight; } SetTooltipPosition(topOffset, BorderStackPanelOpponent); ToolTipCard.Visibility = visibility; } else if (StackPanelSecrets.Visibility == Visible && PointInsideControl(relativeSecretsPos, StackPanelSecrets.ActualWidth, StackPanelSecrets.ActualHeight)) { //card size = card list height / amount of cards var cardSize = StackPanelSecrets.ActualHeight / StackPanelSecrets.Children.Count; var cardIndex = (int)(relativeSecretsPos.Y / cardSize); if (cardIndex < 0 || cardIndex >= StackPanelSecrets.Children.Count) { return; } ToolTipCard.SetValue(DataContextProperty, StackPanelSecrets.Children[cardIndex].GetValue(DataContextProperty)); //offset is affected by scaling var topOffset = Canvas.GetTop(StackPanelSecrets) + cardIndex * cardSize * Config.Instance.OverlayOpponentScaling / 100; //prevent tooltip from going outside of the overlay if (topOffset + ToolTipCard.ActualHeight > Height) { topOffset = Height - ToolTipCard.ActualHeight; } SetTooltipPosition(topOffset, StackPanelSecrets); ToolTipCard.Visibility = Config.Instance.OverlaySecretToolTipsOnly ? Visible : visibility; } else if (BgsTopBar.Visibility == Visible && BattlegroundsMinionsPanel.Visibility == Visible && BattlegroundsMinionsPanel.ActiveTier > 0) { var found = false; foreach (var group in BattlegroundsMinionsPanel.Groups) { var cardList = group.Cards; if (!group.IsVisible || !cardList.IsVisible) { continue; } var relativePos = cardList.PointFromScreen(new Point(pos.X, pos.Y)); if (PointInsideControl(relativePos, cardList.ActualWidth, cardList.ActualHeight)) { var cards = cardList.ItemsControl.Items; var cardSize = cardList.ActualHeight / cards.Count; var cardIndex = (int)(relativePos.Y / cardSize); if (cardIndex < 0 || cardIndex >= cards.Count) { return; } var card = cards.GetItemAt(cardIndex) as AnimatedCard; if (card == null) { return; } ToolTipCard.SetValue(DataContextProperty, card.GetValue(DataContextProperty)); //offset is affected by scaling var cardListPos = cardList.TransformToAncestor(CanvasInfo).Transform(new Point(0, 0)); var topOffset = cardListPos.Y + cardIndex * cardSize * AutoScaling; //prevent tooltip from going outside of the overlay if (topOffset + ToolTipCard.ActualHeight > Height) { topOffset = Height - ToolTipCard.ActualHeight; } Canvas.SetTop(ToolTipCard, topOffset); Canvas.SetLeft(ToolTipCard, cardListPos.X - ToolTipCard.ActualWidth + 22); ToolTipCard.Visibility = visibility; found = true; } } if (!found) { ToolTipCard.Visibility = Hidden; HideAdditionalToolTips(); } } else { ToolTipCard.Visibility = Hidden; HideAdditionalToolTips(); } if (ToolTipCard.Visibility == Visible) { if (ToolTipCard.GetValue(DataContextProperty) is Card card) { if (_lastToolTipCardId != card.Id) { _lastToolTipCardId = card.Id; ShowAdditionalToolTips(); } } else { HideAdditionalToolTips(); } } else { HideAdditionalToolTips(); _lastToolTipCardId = string.Empty; } if (!Config.Instance.ForceMouseHook) { if (Config.Instance.ExtraFeatures) { var relativePos = PointFromScreen(new Point(pos.X, pos.Y)); if ((StackPanelSecrets.IsVisible && (PointInsideControl(StackPanelSecrets.PointFromScreen(new Point(pos.X, pos.Y)), StackPanelSecrets.ActualWidth, StackPanelSecrets.ActualHeight, new Thickness(20))) || relativePos.X < 170 && relativePos.Y > Height - 120)) { if (_mouseInput == null) { HookMouse(); } } else if (_mouseInput != null && !((_isFriendsListOpen.HasValue && _isFriendsListOpen.Value) || Reflection.IsFriendsListVisible())) { UnHookMouse(); } } else if (_mouseInput != null) { UnHookMouse(); } } if (!Config.Instance.AlwaysShowGoldProgress) { if (_game.IsInMenu && PointInsideControl(RectGoldDisplay.PointFromScreen(new Point(pos.X, pos.Y)), RectGoldDisplay.ActualWidth, RectGoldDisplay.ActualHeight)) { UpdateGoldProgress(); GoldProgressGrid.Visibility = Visible; } else { GoldProgressGrid.Visibility = Hidden; } } }
/// <summary> /// 获取描述,使用System.ComponentModel.Description特性设置描述 /// </summary> /// <typeparam name="T">枚举</typeparam> /// <param name="member">成员名、值、实例均可,范例:Enum1枚举有成员A=0,可传入"A"、0、Enum1.A,获取值0</param> /// <returns></returns> public static string GetDescription <T>(object member) { return(Reflection.GetDescription <T>(GetName <T>(member))); }
/// <summary> /// Creates the default constructor /// </summary> /// <param name="TypeBuilder">Type builder</param> private static void CreateConstructor(Reflection.Emit.TypeBuilder TypeBuilder) { IMethodBuilder Constructor = TypeBuilder.CreateConstructor(); { Constructor.SetCurrentMethod(); Constructor.This.Call(TypeBuilder.BaseClass.GetConstructor(Type.EmptyTypes)); Constructor.Return(); } }
/// <summary> /// 获取描述,使用System.ComponentModel.Description特性设置描述 /// </summary> /// <param name="type">枚举类型</param> /// <param name="member">成员名、值、实例均可,范例:Enum1枚举有成员A=0,可传入"A"、0、Enum1.A,获取值0</param> /// <returns></returns> public static string GetDescription(Type type, object member) { return(Reflection.GetDescription(type, GetName(type, member))); }
/// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { Controls.Clear(); ddlFilterType = new RockDropDownList(); Controls.Add(ddlFilterType); ddlFilterType.ID = this.ID + "_ddlFilter"; var component = Rock.Reporting.DataFilterContainer.GetComponent(FilterEntityTypeName); if (component != null) { component.Options = FilterOptions; filterControls = component.CreateChildControls(FilteredEntityType, this); } else { filterControls = new Control[0]; } ddlFilterType.AutoPostBack = true; ddlFilterType.SelectedIndexChanged += ddlFilterType_SelectedIndexChanged; ddlFilterType.Items.Clear(); foreach (var section in AuthorizedComponents) { foreach (var item in section.Value) { if (!this.ExcludedFilterTypes.Any(a => a == item.Key)) { ListItem li = new ListItem(item.Value, item.Key); if (!string.IsNullOrWhiteSpace(section.Key)) { li.Attributes.Add("optiongroup", section.Key); } var filterComponent = Rock.Reporting.DataFilterContainer.GetComponent(item.Key); if (filterComponent != null) { string description = Reflection.GetDescription(filterComponent.GetType()); if (!string.IsNullOrWhiteSpace(description)) { li.Attributes.Add("title", description); } } li.Selected = item.Key == FilterEntityTypeName; ddlFilterType.Items.Add(li); } } } hfExpanded = new HiddenField(); Controls.Add(hfExpanded); hfExpanded.ID = this.ID + "_hfExpanded"; hfExpanded.Value = "True"; lbDelete = new LinkButton(); Controls.Add(lbDelete); lbDelete.ID = this.ID + "_lbDelete"; lbDelete.CssClass = "btn btn-xs btn-danger "; lbDelete.Click += lbDelete_Click; lbDelete.CausesValidation = false; var iDelete = new HtmlGenericControl("i"); lbDelete.Controls.Add(iDelete); iDelete.AddCssClass("fa fa-times"); }
/// <summary> /// private static cstor that is used to init an /// instance of this class as a singleton /// </summary> static DataProvider() { instance = (DataProvider)Reflection.CreateObject("data", "GIBS.FBFoodInventory.Components", ""); }
public void GetTypeByName() { Assert.AreEqual(typeof(ReflectionTest), Reflection.GetType("KRPC.Test.Utils.ReflectionTest")); }
private async void HideCardsWhenFriendsListOpen(Point clickPos) { var panels = new List <Border>(); if (Canvas.GetLeft(BorderStackPanelPlayer) - 200 < 500) { panels.Add(BorderStackPanelPlayer); } if (Canvas.GetLeft(BorderStackPanelOpponent) < 500) { panels.Add(BorderStackPanelOpponent); } _isFriendsListOpen = null; if (Config.Instance.HideDecksInOverlay) { return; } foreach (var panel in panels) { //if panel visible, only continue of click was in the button left corner if (!(clickPos.X < 150 && clickPos.Y > Height - 100) && panel.Visibility == Visibility.Visible) { continue; } var checkForFriendsList = true; if (panel.Equals(BorderStackPanelPlayer) && Config.Instance.HidePlayerCards) { checkForFriendsList = false; } else if (panel.Equals(BorderStackPanelOpponent) && Config.Instance.HideOpponentCards) { checkForFriendsList = false; } if (!checkForFriendsList) { continue; } if (_isFriendsListOpen == null) { await Task.Delay(500); _isFriendsListOpen = Reflection.IsFriendsListVisible(); } if (_isFriendsListOpen.Value) { var childPanel = Helper.FindVisualChildren <StackPanel>(panel).FirstOrDefault(); if (childPanel == null) { continue; } var panelHeight = Canvas.GetTop(panel) + childPanel.ActualHeight; if (childPanel.VerticalAlignment == VerticalAlignment.Center) { panelHeight += panel.ActualHeight / 2 - childPanel.ActualHeight / 2; } var needToHide = panelHeight > Height * 0.3; if (needToHide) { var isPlayerPanel = panel.Equals(BorderStackPanelPlayer); Log.Info("Friendslist is open! Hiding " + (isPlayerPanel ? "player" : "opponent") + " panel."); panel.Visibility = Visibility.Collapsed; if (isPlayerPanel) { _playerCardsHidden = true; } else { _opponentCardsHidden = true; } } } else if (panel.Visibility == Visibility.Collapsed) { if (!(_game.IsInMenu && Config.Instance.HideInMenu)) { panel.Visibility = Visibility.Visible; if (panel.Equals(BorderStackPanelPlayer)) { _playerCardsHidden = false; } else { _opponentCardsHidden = false; } } } } }
/// <summary> /// Resolves whether given instance <paramref name="value"/> is of given type <paramref name="tinfo"/>. /// </summary> /// <param name="value">Value to be checked.</param> /// <param name="tinfo">Type descriptor.</param> /// <returns>Whether <paramref name="value"/> is of type <paramref name="tinfo"/>.</returns> public static bool IsInstanceOf(object value, Reflection.PhpTypeInfo tinfo) { if (tinfo == null) { throw new ArgumentNullException(nameof(tinfo)); } return tinfo.Type.GetTypeInfo().IsInstanceOfType(value); }
// ReSharper disable once UnusedMember.Global public void ConfigureServices(IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddLogging(options => { options.SetMinimumLevel(LogLevel.Debug); options.AddFilter("Microsoft", LogLevel.Warning); options.AddConsole(); }); var mvcBuilder = services.AddMvc(o => { o.Filters.Add(new DefaultExceptionFilterAttribute()); }); mvcBuilder.AddNewtonsoftJson(o => { o.SerializerSettings.Converters.Add(new StringEnumConverter()); }); //}).AddJsonOptions(o => //{ // o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); //}); mvcBuilder.ConfigureApplicationPartManager(manager => { manager.FeatureProviders.Remove(manager.FeatureProviders.First(f => f.GetType() == typeof(ControllerFeatureProvider))); manager.FeatureProviders.Add(new WirehomeControllerFeatureProvider(typeof(ComponentsController).Namespace)); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Wirehome.Core API", Version = "v1", Description = "The public API for the Wirehome.Core service.", License = new OpenApiLicense { Name = "Apache-2.0", Url = new Uri("https://github.com/chkr1011/Wirehome.Core/blob/master/LICENSE") }, Contact = new OpenApiContact { Name = "Wirehome.Core", Email = string.Empty, Url = new Uri("https://github.com/chkr1011/Wirehome.Core") }, }); c.OperationFilter <BinaryContentFilter>(); }); var serviceImplementations = Reflection.GetClassesAssignableFrom <WirehomeCoreService>(); foreach (var singletonService in serviceImplementations) { if (singletonService == typeof(WirehomeCoreService)) { continue; } Console.WriteLine($"Registering service {singletonService}"); services.AddSingleton(singletonService); } var pythonProxyImplementations = Reflection.GetClassesAssignableFrom <IInjectedPythonProxy>(); foreach (var pythonProxy in pythonProxyImplementations) { Console.WriteLine($"Registering Python proxy {pythonProxy}"); services.AddSingleton(typeof(IPythonProxy), pythonProxy); } services.AddSingleton <PythonProxyFactory>(); services.AddCors(); services.AddResponseCompression(options => { options.Providers.Add <GzipCompressionProvider>(); }); }
private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollection<AttributeAst> attributeAsts, bool isHidden, Reflection.MethodAttributes methodAttributes, Type[] parameterTypes) { bool isStatic = (methodAttributes & Reflection.MethodAttributes.Static) != 0; var ctor = isStatic ? _typeBuilder.DefineTypeInitializer() : _typeBuilder.DefineConstructor(methodAttributes, CallingConventions.Standard, parameterTypes); DefineCustomAttributes(ctor, attributeAsts, _parser, AttributeTargets.Constructor); if (isHidden) { ctor.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } var ilGenerator = ctor.GetILGenerator(); if (!isStatic) { ilGenerator.Emit(OpCodes.Ldarg_0); // load 'this' on stack for Stfld call ilGenerator.Emit(OpCodes.Ldnull); ilGenerator.Emit(OpCodes.Ldfld, _sessionStateKeeperField); ilGenerator.EmitCall(OpCodes.Call, s_sessionStateKeeper_GetSessionState, null); // load 'sessionState' on stack for Stfld call ilGenerator.Emit(OpCodes.Stfld, _sessionStateField); } DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Count()), isStatic, parameterTypes, typeof(void), (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n)); }
// dynamically create provider private static void CreateProvider() { objProvider = (DataProvider)Reflection.CreateObject("data", "Affine.Dnn.Modules.ATI_Comps", ""); }
public static ComponentInstallerBase GetInstaller(string installerType) { ComponentInstallerBase installer = null; switch (installerType) { case "File": installer = new FileInstaller(); break; case "Assembly": installer = new AssemblyInstaller(); break; case "ResourceFile": installer = new ResourceFileInstaller(); break; case "AuthenticationSystem": case "Auth_System": installer = new AuthenticationInstaller(); break; case "DashboardControl": installer = new DashboardInstaller(); break; case "Script": installer = new ScriptInstaller(); break; case "Config": installer = new ConfigInstaller(); break; case "Cleanup": installer = new CleanupInstaller(); break; case "Skin": installer = new SkinInstaller(); break; case "Container": installer = new ContainerInstaller(); break; case "Module": installer = new ModuleInstaller(); break; case "CoreLanguage": installer = new LanguageInstaller(LanguagePackType.Core); break; case "ExtensionLanguage": installer = new LanguageInstaller(LanguagePackType.Extension); break; case "Provider": installer = new ProviderInstaller(); break; case "SkinObject": installer = new SkinControlInstaller(); break; case "Widget": installer = new WidgetInstaller(); break; default: ListController listController = new ListController(); ListEntryInfo entry = listController.GetListEntryInfo("Installer", installerType); if (entry != null && !string.IsNullOrEmpty(entry.Text)) { installer = (ComponentInstallerBase)Reflection.CreateObject(entry.Text, "Installer_" + entry.Value); } break; } return(installer); }
new public static bool ReflectionUnitTest( ) { try { Type type = InternalType; if (type == null) { throw new Exception("Could not find internal type for CubeBlockEntity"); } bool result = true; result &= Reflection.HasMethod(type, CubeBlockGetObjectBuilderMethod); result &= Reflection.HasMethod(type, CubeBlockGetActualBlockMethod); result &= Reflection.HasMethod(type, CubeBlockDamageBlockMethod); result &= Reflection.HasMethod(type, CubeBlockGetBuildValueMethod); result &= Reflection.HasMethod(type, CubeBlockGetBuildPercentMethod); result &= Reflection.HasMethod(type, CubeBlockGetIntegrityValueMethod); result &= Reflection.HasMethod(type, CubeBlockGetMaxIntegrityValueMethod); result &= Reflection.HasMethod(type, CubeBlockUpdateWeldProgressMethod); result &= Reflection.HasField(type, CubeBlockParentCubeGridField); result &= Reflection.HasField(type, CubeBlockColorMaskHSVField); result &= Reflection.HasField(type, CubeBlockConstructionManagerField); result &= Reflection.HasField(type, CubeBlockCubeBlockDefinitionField); type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(ActualCubeBlockNamespace, ActualCubeBlockClass); if (type == null) { throw new Exception("Could not find actual type for CubeBlockEntity"); } result &= Reflection.HasMethod(type, ActualCubeBlockGetObjectBuilderMethod); result &= Reflection.HasMethod(type, ActualCubeBlockGetFactionsObjectMethod); result &= Reflection.HasMethod(type, ActualCubeBlockSetFactionsDataMethod); result &= Reflection.HasMethod(type, ActualCubeBlockGetMatrixMethod); result &= Reflection.HasMethod(type, ActualCubeBlockGetOwnerMethod); type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(FactionsDataNamespace, FactionsDataClass); if (type == null) { throw new Exception("Could not find factions data type for CubeBlockEntity"); } result &= Reflection.HasField(type, FactionsDataOwnerField); result &= Reflection.HasField(type, FactionsDataShareModeField); type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(ConstructionManagerNamespace, ConstructionManagerClass); if (type == null) { throw new Exception("Could not find construction manager type for CubeBlockEntity"); } result &= Reflection.HasMethod(type, ConstructionManagerSetIntegrityBuildValuesMethod); result &= Reflection.HasMethod(type, ConstructionManagerGetBuildValueMethod); result &= Reflection.HasMethod(type, ConstructionManagerGetIntegrityValueMethod); result &= Reflection.HasMethod(type, ConstructionManagerGetMaxIntegrityMethod); result &= Reflection.HasMethod(type, ConstructionManagerGetBuildPercentMethod); result &= Reflection.HasMethod(type, ConstructionManagerGetIntegrityPercentMethod); result &= Reflection.HasField(type, ConstructionManagerIntegrityValueField); result &= Reflection.HasField(type, ConstructionManagerBuildValueField); return(result); } catch (Exception ex) { ApplicationLog.BaseLog.Error(ex); return(false); } }
/// <summary> /// Creates an enumerator used in foreach statement. /// </summary> /// <param name="keyed">Whether the foreach statement uses keys.</param> /// <param name="aliasedValues">Whether the values returned by enumerator are assigned by reference.</param> /// <param name="caller">Type <see cref="Reflection.DTypeDesc"/> of the caller (ignored).</param> /// <returns>The dictionary enumerator.</returns> /// <remarks>Used for internal purposes only!</remarks> public virtual IDictionaryEnumerator GetForeachEnumerator(bool keyed, bool aliasedValues, Reflection.DTypeDesc caller) { if (this.Count == 0) return OrderedDictionary.EmptyEnumerator.SingletonInstance; if (aliasedValues) return new ForeachEnumeratorAliased(this, keyed); else return new ForeachEnumeratorValues(this/*, keyed*/); }
public override void OnInspectorGUI() { var instance = target as LocalizeAtlasRequest; Initialize(); var update = false; var folderGuids = instance.FolderGuids.ToList(); var removeTarget = new List <string>(); using (new EditorGUILayout.HorizontalScope()) { GUILayout.Space(8f); if (GUILayout.Button(toolbarPlusIcon, GUILayout.Width(30f), GUILayout.Height(16f))) { folderGuids.Add(null); update = true; } } var scrollViewLayoutOption = new List <GUILayoutOption>(); if (5 < folderGuids.Count) { scrollViewLayoutOption.Add(GUILayout.MaxHeight(120f)); } using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPosition, scrollViewLayoutOption.ToArray())) { for (var i = 0; i < folderGuids.Count; i++) { var folderGuid = folderGuids[i]; UnityEngine.Object folder = null; if (!string.IsNullOrEmpty(folderGuid)) { var assetPath = AssetDatabase.GUIDToAssetPath(folderGuid); folder = AssetDatabase.LoadMainAssetAtPath(assetPath); } using (new EditorGUILayout.HorizontalScope()) { var layoutOption = new GUILayoutOption[] { GUILayout.Height(16f), GUILayout.ExpandWidth(true), }; EditorGUI.BeginChangeCheck(); folder = EditorGUILayout.ObjectField(folder, typeof(UnityEngine.Object), false, layoutOption); if (EditorGUI.EndChangeCheck()) { // フォルダだけ登録可能. if (UnityEditorUtility.IsFolder(folder) || folder == null) { folderGuids[i] = folder == null ? string.Empty : UnityEditorUtility.GetAssetGUID(folder); update = true; } } if (GUILayout.Button(toolbarMinusIcon, EditorStyles.miniButton, GUILayout.Width(25f))) { removeTarget.Add(folderGuid); } } GUILayout.Space(2f); } scrollPosition = scrollView.scrollPosition; } if (removeTarget.Any()) { foreach (var info in removeTarget) { folderGuids.Remove(info); } update = true; } if (update) { Reflection.SetPrivateField(instance, "folderGuids", folderGuids.ToArray()); } }
/// <summary> /// Sets up a property (IEnumerable) /// </summary> /// <param name="Method">Method builder</param> /// <param name="BaseType">Base type for the object</param> /// <param name="ReturnValue">Return value</param> /// <param name="Property">Property info</param> /// <param name="Mapping">Mapping info</param> private void SetupIEnumerableProperty(IMethodBuilder Method, Type BaseType, Reflection.Emit.BaseClasses.VariableBase ReturnValue, IProperty Property, IMapping Mapping) { Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Property.DerivedFieldName); Utilities.Reflection.Emit.FieldBuilder FieldLoaded = Fields.Find(x => x.Name == Property.DerivedFieldName + "_Loaded"); Utilities.Reflection.Emit.Commands.If If1 = Method.If((VariableBase)SessionField, Comparison.NotEqual, null); { Utilities.Reflection.Emit.Commands.If If2 = Method.If(Field, Comparison.Equal, null); { Utilities.Reflection.Emit.Commands.If If3 = Method.If(FieldLoaded, Comparison.Equal, Method.CreateConstant(false)); { //Load data VariableBase IDValue = Method.This.Call(BaseType.GetProperty(Mapping.IDProperty.Name).GetGetMethod()); VariableBase IDParameter = Method.NewObj(typeof(EqualParameter<>).MakeGenericType(Mapping.IDProperty.Type), new object[] { IDValue, "ID", "@" }); VariableBase PropertyList = Method.NewObj(typeof(List<IParameter>)); PropertyList.Call("Add", new object[] { IDParameter }); MethodInfo LoadPropertiesMethod = typeof(Session).GetMethod("LoadProperties"); LoadPropertiesMethod = LoadPropertiesMethod.MakeGenericMethod(new Type[] { BaseType, Field.DataType.GetGenericArguments()[0] }); VariableBase ReturnVal = ((VariableBase)SessionField).Call(LoadPropertiesMethod, new object[] { Method.This, Property.Name, PropertyList.Call("ToArray") }); Field.Assign(ReturnVal); FieldLoaded.Assign(true); } If3.EndIf(); } If2.EndIf(); Utilities.Reflection.Emit.Commands.If If4 = Method.If(Field, Comparison.Equal, null); { Field.Assign(Method.NewObj(typeof(List<>).MakeGenericType(Property.Type).GetConstructor(Type.EmptyTypes))); } If4.EndIf(); } If1.EndIf(); ReturnValue.Assign(Field); }
public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter) { if (reflectedType == null) throw new ArgumentNullException("reflectedType"); if (parameter == null) throw new ArgumentNullException("parameter"); return parameter.GetCustomAttributes(false); }
public XmlMessageSerializer() { reflection = new Reflection(); }
public void SetupEndMethod(Reflection.Emit.Interfaces.IMethodBuilder Method, Type BaseType, Reflection.Emit.BaseClasses.VariableBase ReturnValue) { Method.SetCurrentMethod(); if (ClassMappings.ContainsKey(BaseType) && Method.Name.StartsWith("get_", StringComparison.InvariantCulture)) { foreach (IMapping Mapping in ClassMappings[BaseType]) { string PropertyName = Method.Name.Replace("get_", ""); IProperty Property = Mapping.Properties.FirstOrDefault(x => x.Name == PropertyName); if (Property != null) { if (Property is IManyToOne || Property is IMap) SetupSingleProperty(Method, BaseType, ReturnValue, Property, Mapping); else if (Property is IIEnumerableManyToOne || Property is IManyToMany) SetupIEnumerableProperty(Method, BaseType, ReturnValue, Property, Mapping); else if (Property is IListManyToMany || Property is IListManyToOne) SetupListProperty(Method, BaseType, ReturnValue, Property, Mapping); return; } } } }
private string ExportModule(int moduleID, string fileName, string folder) { var strMessage = ""; if (Module != null) { if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) { try { var objObject = Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass); //Double-check if (objObject is IPortable) { var content = Convert.ToString(((IPortable)objObject).ExportModule(moduleID)); if (!String.IsNullOrEmpty(content)) { //remove invalid chars in content content = Regex.Replace(content, _invalidCharsRegex, string.Empty); //add attributes to XML document content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<content type=\"" + CleanName(Module.DesktopModule.ModuleName) + "\" version=\"" + Module.DesktopModule.Version + "\">" + content + "</content>"; //First check the Portal limits will not be exceeded (this is approximate) var objPortalController = new PortalController(); var strFile = PortalSettings.HomeDirectoryMapPath + folder + fileName; if (objPortalController.HasSpaceAvailable(PortalId, content.Length)) { //save the file var objStream = File.CreateText(strFile); objStream.WriteLine(content); objStream.Close(); //add file to Files table #pragma warning disable 612,618 FileSystemUtils.AddFile(fileName, PortalId, folder, PortalSettings.HomeDirectoryMapPath, "application/octet-stream"); #pragma warning restore 612,618 } else { strMessage += "<br>" + string.Format(Localization.GetString("DiskSpaceExceeded"), strFile); } } else { strMessage = Localization.GetString("NoContent", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } catch { strMessage = Localization.GetString("Error", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } return(strMessage); }
private static void CreateProvider() { objProvider = (DataProvider)Reflection.CreateObject("data", "VNPT.Modules.HealthCare", ""); }
private string ExportModule(int moduleID, string fileName, IFolderInfo folder) { var strMessage = ""; if (Module != null) { if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) { try { var objObject = Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass); //Double-check if (objObject is IPortable) { XmlDocument moduleXml = new XmlDocument(); XmlNode moduleNode = ModuleController.SerializeModule(moduleXml, Module, true); //add attributes to XML document XmlAttribute typeAttribute = moduleXml.CreateAttribute("type"); typeAttribute.Value = CleanName(Module.DesktopModule.ModuleName); moduleNode.Attributes.Append(typeAttribute); XmlAttribute versionAttribute = moduleXml.CreateAttribute("version"); versionAttribute.Value = Module.DesktopModule.Version; moduleNode.Attributes.Append(versionAttribute); // Create content from XmlNode StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); moduleNode.WriteTo(xw); var content = sw.ToString(); if (!String.IsNullOrEmpty(content)) { //remove invalid chars in content -> DNN 26810: Handled by ModuleController.SerializeModule //content = Regex.Replace(content, _invalidCharsRegex, string.Empty); //add attributes to XML document //content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<content type=\"" + CleanName(Module.DesktopModule.ModuleName) + "\" version=\"" + // Module.DesktopModule.Version + "\">" + content + "</content>"; //First check the Portal limits will not be exceeded (this is approximate) if (PortalController.Instance.HasSpaceAvailable(PortalId, content.Length)) { //add file to Files table using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(content))) { FileManager.Instance.AddFile(folder, fileName, fileContent, true, true, "application/octet-stream"); } } else { strMessage += "<br>" + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); } } else { strMessage = Localization.GetString("NoContent", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } catch { strMessage = Localization.GetString("Error", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } return(strMessage); }
private void CopyModulesFromSourceTab(TabInfo tab, TabInfo sourceTab) { foreach (var module in sourceTab.ChildModules.Values) { if (module.IsDeleted || module.AllTabs) { continue; } var newModule = module.Clone(); newModule.TabID = tab.TabID; newModule.DefaultLanguageGuid = Null.NullGuid; newModule.CultureCode = tab.CultureCode; newModule.VersionGuid = Guid.NewGuid(); newModule.LocalizedVersionGuid = Guid.NewGuid(); newModule.ModuleID = Null.NullInteger; _moduleController.InitialModulePermission(newModule, newModule.TabID, 0); newModule.InheritViewPermissions = module.InheritViewPermissions; newModule.ModuleID = _moduleController.AddModule(newModule); //Copy each setting to the new TabModule instance foreach (DictionaryEntry setting in module.ModuleSettings) { _moduleController.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); } foreach (DictionaryEntry setting in module.TabModuleSettings) { _moduleController.UpdateTabModuleSetting(newModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); } //copy permissions from source module foreach (ModulePermissionInfo permission in module.ModulePermissions) { newModule.ModulePermissions.Add(new ModulePermissionInfo { ModuleID = newModule.ModuleID, PermissionID = permission.PermissionID, RoleID = permission.RoleID, UserID = permission.UserID, PermissionKey = permission.PermissionKey, AllowAccess = permission.AllowAccess }, true); } ModulePermissionController.SaveModulePermissions(newModule); if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) { var moduleBizClass = Reflection.CreateObject(newModule.DesktopModule.BusinessControllerClass, newModule.DesktopModule.BusinessControllerClass) as IPortable; if (moduleBizClass != null) { var content = Convert.ToString(moduleBizClass.ExportModule(module.ModuleID)); if (!string.IsNullOrEmpty(content)) { content = XmlUtils.RemoveInvalidXmlCharacters(content); moduleBizClass.ImportModule(newModule.ModuleID, content, newModule.DesktopModule.Version, UserController.Instance.GetCurrentUserInfo().UserID); } } } } }
/// <summary> /// Sets up the exception method /// </summary> /// <param name="Method">Method builder</param> /// <param name="BaseType">Base type</param> public void SetupExceptionMethod(Reflection.Emit.Interfaces.IMethodBuilder Method, Type BaseType) { }
public static NavigationProvider Instance(string FriendlyName) { return((NavigationProvider)Reflection.CreateObject("navigationControl", FriendlyName, "", "")); }
public void SetupStartMethod(Reflection.Emit.Interfaces.IMethodBuilder Method, Type BaseType) { Method.SetCurrentMethod(); if (ClassMappings.ContainsKey(BaseType) && Method.Name.StartsWith("set_", StringComparison.InvariantCulture)) { foreach (IMapping Mapping in ClassMappings[BaseType]) { string PropertyName = Method.Name.Replace("set_", ""); IProperty Property = Mapping.Properties.FirstOrDefault(x => x.Name == PropertyName); if (Property != null) { Company.Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Property.DerivedFieldName); if (Field != null) Field.Assign(Method.Parameters.ElementAt(1)); return; } } } }
private static List <HearthMirror.Objects.Deck> GetConstructedDecks() => Reflection.GetDecks().Where(x => x.Cards.Sum(c => c.Count) == 30 && x.Type != BrawlDeckType).ToList();
/// <summary> /// Creates a default property /// </summary> /// <param name="TypeBuilder">Type builder</param> /// <param name="Name">Name of the property</param> /// <param name="PropertyType">Property type</param> /// <returns>The property builder</returns> private static IPropertyBuilder CreateProperty(Reflection.Emit.TypeBuilder TypeBuilder, string Name, Type PropertyType) { return TypeBuilder.CreateDefaultProperty(Name, PropertyType, PropertyAttributes.SpecialName, MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public, MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public); }
private static List <HearthMirror.Objects.Deck> GetBrawlDecks() => Reflection.GetDecks().Where(x => x.Type == BrawlDeckType).ToList();
/// <summary> /// Sets up a property (non IEnumerable) /// </summary> /// <param name="Method">Method builder</param> /// <param name="BaseType">Base type for the object</param> /// <param name="ReturnValue">Return value</param> /// <param name="Property">Property info</param> /// <param name="Mapping">Mapping info</param> private void SetupSingleProperty(IMethodBuilder Method, Type BaseType, Reflection.Emit.BaseClasses.VariableBase ReturnValue, IProperty Property, IMapping Mapping) { Company.Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Property.DerivedFieldName); Company.Utilities.Reflection.Emit.Commands.If If1 = Method.If((VariableBase)SessionField, Comparison.NotEqual, null); { Company.Utilities.Reflection.Emit.Commands.If If2 = Method.If(Field, Comparison.Equal, null); { //Load Data VariableBase IDValue = Method.This.Call(BaseType.GetProperty(Mapping.IDProperty.Name).GetGetMethod()); VariableBase IDParameter = Method.NewObj(typeof(EqualParameter<>).MakeGenericType(Mapping.IDProperty.Type), new object[] { IDValue, "ID", "@" }); VariableBase PropertyList = Method.NewObj(typeof(List<IParameter>)); PropertyList.Call("Add", new object[] { IDParameter }); MethodInfo LoadPropertyMethod = typeof(Session).GetMethod("LoadProperty"); LoadPropertyMethod = LoadPropertyMethod.MakeGenericMethod(new Type[] { BaseType, Field.DataType }); VariableBase ReturnVal = ((VariableBase)SessionField).Call(LoadPropertyMethod, new object[] { Method.This, Property.Name, PropertyList.Call("ToArray") }); Field.Assign(ReturnVal); } If2.EndIf(); } If1.EndIf(); ReturnValue.Assign(Field); }
/// <summary> /// Renders the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="result">The result.</param> /// <exception cref="System.Exception">Your Lava command must contain at least one valid filter. If you configured a filter it's possible that the property or attribute you provided does not exist.</exception> public override void Render(Context context, TextWriter result) { // first ensure that entity commands are allowed in the context if (!this.IsAuthorized(context)) { result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name)); base.Render(context, result); return; } bool hasFilter = false; // get a service for the entity based off it's friendly name var entityTypes = EntityTypeCache.All(); var model = string.Empty; if (_entityName == "business") { model = "Rock.Model.Person"; } else { model = "Rock.Model." + _entityName; } // Check first to see if this is a core model var entityTypeCache = entityTypes.Where(e => String.Equals(e.Name, model, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); // If not, look for first plug-in model that has same friendly name if (entityTypeCache == null) { entityTypeCache = entityTypes .Where(e => e.IsEntity && !e.Name.StartsWith("Rock.Model") && e.FriendlyName != null && e.FriendlyName.RemoveSpaces().ToLower() == _entityName) .OrderBy(e => e.Id) .FirstOrDefault(); } // If still null check to see if this was a duplicate class and full class name was used as entity name if (entityTypeCache == null) { model = _entityName.Replace('_', '.'); entityTypeCache = entityTypes.Where(e => String.Equals(e.Name, model, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); } if (entityTypeCache != null) { Type entityType = entityTypeCache.GetEntityType(); if (entityType != null) { // Get the database context var dbContext = Reflection.GetDbContextForEntityType(entityType); // create an instance of the entity's service Rock.Data.IService serviceInstance = Reflection.GetServiceForEntityType(entityType, dbContext); ParameterExpression paramExpression = Expression.Parameter(entityType, "x"); Expression queryExpression = null; // the base expression we'll use to build our query from // parse markup var parms = ParseMarkup(_markup, context); if (parms.Any(p => p.Key == "id")) { string propertyName = "Id"; List <string> selectionParms = new List <string>(); selectionParms.Add(PropertyComparisonConversion("==").ToString()); selectionParms.Add(parms["id"].ToString()); selectionParms.Add(propertyName); var entityProperty = entityType.GetProperty(propertyName); queryExpression = ExpressionHelper.PropertyFilterExpression(selectionParms, paramExpression, propertyName, entityProperty.PropertyType); hasFilter = true; } else { // where clause expression if (parms.Any(p => p.Key == "where")) { queryExpression = ParseWhere(parms["where"], entityType, serviceInstance, paramExpression, entityType, entityTypeCache); if (queryExpression != null) { hasFilter = true; } } // DataView expression if (parms.Any(p => p.Key == "dataview")) { var dataViewId = parms["dataview"].AsIntegerOrNull(); if (dataViewId.HasValue) { var dataViewExpression = GetDataViewExpression(dataViewId.Value, serviceInstance, paramExpression, entityTypeCache); if (queryExpression == null) { queryExpression = dataViewExpression; hasFilter = true; } else { queryExpression = Expression.AndAlso(queryExpression, dataViewExpression); } } } // process dynamic filter expressions (from the query string) if (parms.Any(p => p.Key == "dynamicparameters")) { var dynamicFilters = parms["dynamicparameters"].Split(',') .Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList(); foreach (var dynamicFilter in dynamicFilters) { var dynamicFilterValue = HttpContext.Current.Request[dynamicFilter]; var dynamicFilterExpression = GetDynamicFilterExpression(dynamicFilter, dynamicFilterValue, entityType, serviceInstance, paramExpression); if (dynamicFilterExpression != null) { if (queryExpression == null) { queryExpression = dynamicFilterExpression; hasFilter = true; } else { queryExpression = Expression.AndAlso(queryExpression, dynamicFilterExpression); } } } } } // make the query from the expression MethodInfo getMethod = serviceInstance.GetType().GetMethod("Get", new Type[] { typeof(ParameterExpression), typeof(Expression), typeof(Rock.Web.UI.Controls.SortProperty), typeof(int?) }); if (getMethod != null) { var queryResult = getMethod.Invoke(serviceInstance, new object[] { paramExpression, queryExpression, null, null }) as IQueryable <IEntity>; // process entity specific filters switch (_entityName) { case "person": { queryResult = PersonFilters((IQueryable <Person>)queryResult, parms); break; } case "business": { queryResult = BusinessFilters((IQueryable <Person>)queryResult, parms); break; } } // if there was a dynamic expression add it now if (parms.Any(p => p.Key == "expression")) { queryResult = queryResult.Where(parms["expression"]); hasFilter = true; } // get a listing of ids if (parms.Any(p => p.Key == "ids")) { var value = parms["ids"].ToString().Split(',').Select(int.Parse).ToList(); queryResult = queryResult.Where(x => value.Contains(x.Id)); hasFilter = true; } var queryResultExpression = queryResult.Expression; // add sort expressions if (parms.Any(p => p.Key == "sort")) { string orderByMethod = "OrderBy"; foreach (var column in parms["sort"].Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToList()) { string propertyName; var direction = SortDirection.Ascending; if (column.EndsWith(" desc", StringComparison.OrdinalIgnoreCase)) { direction = SortDirection.Descending; propertyName = column.Left(column.Length - 5); } else { propertyName = column; } string methodName = direction == SortDirection.Descending ? orderByMethod + "Descending" : orderByMethod; if (entityType.GetProperty(propertyName) != null) { // sorting a entity property var memberExpression = Expression.Property(paramExpression, propertyName); LambdaExpression sortSelector = Expression.Lambda(memberExpression, paramExpression); queryResultExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { queryResult.ElementType, sortSelector.ReturnType }, queryResultExpression, sortSelector); } else { // sorting on an attribute // get attribute id int?attributeId = null; foreach (var id in AttributeCache.GetByEntity(entityTypeCache.Id).SelectMany(a => a.AttributeIds)) { var attribute = AttributeCache.Get(id); if (attribute.Key == propertyName) { attributeId = id; break; } } if (attributeId.HasValue) { // get AttributeValue queryable and parameter if (dbContext is RockContext) { var attributeValues = new AttributeValueService(dbContext as RockContext).Queryable(); ParameterExpression attributeValueParameter = Expression.Parameter(typeof(AttributeValue), "v"); MemberExpression idExpression = Expression.Property(paramExpression, "Id"); var attributeExpression = Attribute.Helper.GetAttributeValueExpression(attributeValues, attributeValueParameter, idExpression, attributeId.Value); LambdaExpression sortSelector = Expression.Lambda(attributeExpression, paramExpression); queryResultExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { queryResult.ElementType, sortSelector.ReturnType }, queryResultExpression, sortSelector); } else { throw new Exception(string.Format("The database context for type {0} does not support RockContext attribute value queries.", entityTypeCache.FriendlyName)); } } } orderByMethod = "ThenBy"; } } // reassemble the queryable with the sort expressions queryResult = queryResult.Provider.CreateQuery(queryResultExpression) as IQueryable <IEntity>; if (parms.GetValueOrNull("count").AsBoolean()) { int countResult = queryResult.Count(); context.Scopes.Last()["count"] = countResult; } else { // run security check on each result var items = queryResult.ToList(); var itemsSecured = new List <IEntity>(); Person person = GetCurrentPerson(context); foreach (IEntity item in items) { ISecured itemSecured = item as ISecured; if (itemSecured == null || itemSecured.IsAuthorized(Authorization.VIEW, person)) { itemsSecured.Add(item); } } queryResult = itemsSecured.AsQueryable(); // offset if (parms.Any(p => p.Key == "offset")) { queryResult = queryResult.Skip(parms["offset"].AsInteger()); } // limit, default to 1000 if (parms.Any(p => p.Key == "limit")) { queryResult = queryResult.Take(parms["limit"].AsInteger()); } else { queryResult = queryResult.Take(1000); } // check to ensure we had some form of filter (otherwise we'll return all results in the table) if (!hasFilter) { throw new Exception("Your Lava command must contain at least one valid filter. If you configured a filter it's possible that the property or attribute you provided does not exist."); } var resultList = queryResult.ToList(); // if there is only one item to return set an alternative non-array based variable if (resultList.Count == 1) { context.Scopes.Last()[_entityName] = resultList.FirstOrDefault(); } context.Scopes.Last()[parms["iterator"]] = resultList; } } } } else { result.Write(string.Format("Could not find a model for {0}.", _entityName)); base.Render(context, result); } base.Render(context, result); }