Наследование: MonoBehaviour
Пример #1
0
 public float EffectiveMaxDistance(Activator activator)
 {
     if (useActivatorMaxDistance) {
         return activator.maxDistance;
     }
     return maxDistance;
 }
Пример #2
0
 public Form1()
 {
     directory = AppDomain.CurrentDomain.BaseDirectory;
     advisePath = directory + "advise.txt";
     InitializeComponent();
     Application.ApplicationExit += onApplicationExit;
     filter = new Filter(this);
     parser = new Parser();
     decryptor = new Decryptor(filter);
     writer = new Writer(advisePath);
     activator = new Activator(decryptor, parser, writer);
     ReadData();
     checkUpdates(null, null);
     //System.Timers.Timer updateTimer = new System.Timers.Timer(15 * 60 * 60 * 1000);
     //updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(checkUpdates);
     poolNewsListBox.DoubleClick += addActualNews;
     actualNewsListBox.DoubleClick += removeActualNews;
     actualNewsListBox.SelectedIndexChanged += newsListBox_SelectedIndexChanged;
     poolSymbolListBox.DoubleClick += addActualSymbol;
     actualSymbolListBox.DoubleClick += removeActualSymbol;
     highRadioButton.CheckedChanged += radioButton_CheckedChanged;
     midRadioButton.CheckedChanged += radioButton_CheckedChanged;
     lowRadioButton.CheckedChanged += radioButton_CheckedChanged;
     reverse_checkBox.CheckedChanged += reverse_checkBox_CheckedChanged;
     button2.Click += new_terminal_path;
 }
Пример #3
0
 public override void Activate(Activator activator)
 {
     base.Activate(activator);
     if (activator.unit.controller == Player.instance) {
         Player.instance.Possess(target);
     }
 }
Пример #4
0
 static Config()
 {
     // Initialize the menu
     Menu = MainMenu.AddMenu(MenuName, MenuName.ToLower());
     Menu.AddGroupLabel("Welcome to my Sion Addon have fun! :)");
     Menu.AddLabel("To see/change the Settings");
     Menu.AddLabel("Click on Modes :)");
     activator = new Activator(Menu);
     // Initialize the modes
     Modes.Initialize();
 }
        public ActivatorClient(string guid, ProcessDomainSetup setup)
        {
            var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = setup.TypeFilterLevel };
            var clientProvider = new BinaryClientFormatterSinkProvider();

            var properties = new Hashtable();
            properties["portName"] = string.Format(ActivatorHost.ClientChannelName, guid);
            properties["name"] = string.Format(ActivatorHost.ClientChannelName, guid);
            setup.Remoting.ApplyClientProperties(properties);

            _channel = new IpcChannel(properties, clientProvider, serverProvider);
            ChannelServices.RegisterChannel(_channel, false);

            _activator = (Activator)System.Activator.GetObject(typeof(Activator), string.Format("ipc://{0}/{1}", string.Format(ActivatorHost.ServerChannelName, guid), ActivatorHost.ActivatorName));
        }
Пример #6
0
    void Awake()
    {
        activator = GetComponentInChildren<Activator>();
        eye = GetComponentInChildren<Eye>();
        inventory = GetComponentInChildren<Inventory>();
        lastPositionKeeper = GetComponentInChildren<LastPositionKeeper>();
        head = GetComponentInChildren<Head>();
        cameraPlace = GetComponentInChildren<CameraPlace>();
        undo = GetComponentInChildren<Undo>();
        characterController = GetComponentInChildren<CharacterController>();
        rewind = GetComponentInChildren<Rewind>();
        slowmo = GetComponentInChildren<Slowmo>();
        gravity = GetComponentInChildren<Gravity>();

        all.Add(this);
    }
Пример #7
0
		private static void Game_OnGameLoad(EventArgs args)
		{
			//AutoUpdater.InitializeUpdater();
			Chat.Print("Ultimate Carry Version " + LocalVersion + " load ...");
			Helper = new Helper();

			Menu = new Menu("UltimateCarry", "UltimateCarry_" + ObjectManager.Player.ChampionName, true);

			var targetSelectorMenu = new Menu("Target Selector", "TargetSelector");
			SimpleTs.AddToMenu(targetSelectorMenu);
			Menu.AddSubMenu(targetSelectorMenu);
			if (ObjectManager.Player.ChampionName == "Azir")
			{
				var orbwalking = Menu.AddSubMenu(new Menu("AzirWalking", "Orbwalking"));
				Azirwalker = new Azir.Orbwalking.Orbwalker(orbwalking);
				Menu.Item("FarmDelay").SetValue(new Slider(125, 100, 200));
			}
			else
			{
				var orbwalking = Menu.AddSubMenu(new Menu("Orbwalking", "Orbwalking"));
				Orbwalker = new Orbwalking.Orbwalker(orbwalking);
				Menu.Item("FarmDelay").SetValue(new Slider(0, 0, 200));
			}
			var activator = new Activator();
			var potionManager = new PotionManager();
			var baseult = new BaseUlt();
			var bushRevealer = new AutoBushRevealer();
		//var overlay = new Overlay();
		
			try
			{
				// ReSharper disable once AssignNullToNotNullAttribute
				var handle = System.Activator.CreateInstance(null, "UltimateCarry." + ObjectManager.Player.ChampionName);
				Champion = (Champion) handle.Unwrap();
			}
			// ReSharper disable once EmptyGeneralCatchClause
			catch (Exception)
			{
				//Champion = new Champion(); //Champ not supported
			}
					
			Menu.AddToMainMenu();
			Chat.Print("Ultimate Carry loaded!");
		}
		public static IDynamicPromise Create(Type type) =>
			(IDynamicPromise) Activator.CreateInstance(
				typeof(DynamicPromise<>).MakeGenericType(type));
        // works on current assembly!
        private IEnumerable <IMigrationTask <TDatabase> > GetMigratorTasks()
        {
            IEnumerable <IMigrationTask <TDatabase> > tasks = GetType().Assembly.GetTypesDerivedFrom <IMigrationTask <TDatabase> >(true)
                                                              .Select(t => (IMigrationTask <TDatabase>)Activator.CreateInstance(t));

            return(tasks.Where(t => t.SchemaName == DatabaseMigration <TDatabase> .AutomaticMigrationSchemaName));
        }
Пример #10
0
        private void CollectNewProcessorsByComponentType(TypeInfo componentType)
        {
            if (componentTypes.Contains(componentType))
            {
                return;
            }

            componentTypes.Add(componentType);
            OnComponentTypeAdded(componentType);

            // Automatically collect processors that are used by this component
            var processorAttributes = componentType.GetCustomAttributes<DefaultEntityComponentProcessorAttribute>();
            foreach (var processorAttributeType in processorAttributes)
            {
                var processorType = AssemblyRegistry.GetType(processorAttributeType.TypeName);
                if (processorType == null || !typeof(EntityProcessor).GetTypeInfo().IsAssignableFrom(processorType.GetTypeInfo()))
                {
                    // TODO: log an error if type is not of EntityProcessor
                    continue;
                }

                // Filter using ExecutionMode
                if ((ExecutionMode & processorAttributeType.ExecutionMode) != ExecutionMode.None)
                {
                    // Make sure that we are adding a processor of the specified type only if it is not already in the list or pending

                    // 1) Check in the list of existing processors
                    var addNewProcessor = true;
                    for (int i = 0; i < processors.Count; i++)
                    {
                        if (processorType == processors[i].GetType())
                        {
                            addNewProcessor = false;
                            break;
                        }
                    }
                    if (addNewProcessor)
                    {
                        // 2) Check in the list of pending processors
                        for (int i = 0; i < pendingProcessors.Count; i++)
                        {
                            if (processorType == pendingProcessors[i].GetType())
                            {
                                addNewProcessor = false;
                                break;
                            }
                        }
                        
                        // If not found, we can add this processor
                        if (addNewProcessor)
                        {
                            var processor = (EntityProcessor)Activator.CreateInstance(processorType);
                            pendingProcessors.Add(processor);

                            // Collect dependencies
                            foreach (var subComponentType in processor.RequiredTypes)
                            {
                                CollectNewProcessorsByComponentType(subComponentType);
                            }
                        }
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// 把一个实体数据拷贝到另一个实体
        /// </summary>
        /// <param name="dataEntity"></param>
        /// <param name="newEntity"></param>
        /// <param name="copyHandler"></param>
        /// <param name="clearPrimaryKeyValue"></param>
        /// <param name="onlyDbProperty"></param>
        /// <param name="onlyDirtyProperty"></param>
        public static void CopyData(this IDataEntityBase dataEntity, IDataEntityBase newEntity, Func <string, string, bool> copyHandler = null, bool clearPrimaryKeyValue = false, bool onlyDbProperty = false, bool onlyDirtyProperty = false)
        {
            IDataEntityType dataEntityType = dataEntity.GetDataEntityType();
            IDataEntityType type2          = newEntity.GetDataEntityType();

            if (copyHandler == null)
            {
                copyHandler = (dtName, propName) => true;
            }
            IEnumerable <IDataEntityProperty> dirtyProperties = dataEntityType.GetDirtyProperties(dataEntity);

            foreach (ISimpleProperty property in type2.Properties.GetSimpleProperties(onlyDbProperty))
            {
                if (copyHandler(type2.Name, property.Name))
                {
                    IDataEntityProperty dpOldProperty = null;
                    TryGetOldProperty(property, dataEntityType, out dpOldProperty);
                    if ((!onlyDirtyProperty || dirtyProperties.Contains <IDataEntityProperty>(dpOldProperty)) && !(property.IsReadOnly || (dpOldProperty == null)))
                    {
                        property.SetValue(newEntity, dpOldProperty.GetValue(dataEntity));
                    }
                }
            }
            if (clearPrimaryKeyValue)
            {
                ISimpleProperty primaryKey = type2.PrimaryKey;
                if (primaryKey != null)
                {
                    primaryKey.ResetValue(newEntity);
                }
                type2.SetDirty(newEntity, true);
            }
            foreach (IComplexProperty property4 in type2.Properties.GetComplexProperties(onlyDbProperty))
            {
                IDataEntityProperty property5 = null;
                TryGetOldProperty(property4, dataEntityType, out property5);
                IDataEntityBase base2 = property5.GetValue(dataEntity) as IDataEntityBase;
                if (base2 != null)
                {
                    IDataEntityBase base3;
                    if (property4.IsReadOnly)
                    {
                        base3 = property4.GetValue(newEntity) as IDataEntityBase;
                        if (base3 == null)
                        {
                            throw new ORMDesignException("??????", ResManager.LoadKDString("哦,真不幸,只读的属性却返回了NULL值。", "014009000001633", SubSystemType.SL, new object[0]));
                        }
                        base2.CopyData(base3, copyHandler, false, onlyDbProperty, false);
                    }
                    else
                    {
                        base3 = property4.ComplexPropertyType.CreateInstance() as IDataEntityBase;
                        base2.CopyData(base3, copyHandler, clearPrimaryKeyValue, onlyDbProperty, false);
                        property4.SetValue(newEntity, base3);
                    }
                }
            }
            foreach (ICollectionProperty property6 in type2.Properties.GetCollectionProperties(onlyDbProperty))
            {
                IDataEntityProperty property7 = null;
                TryGetOldProperty(property6, dataEntityType, out property7);
                object obj2 = property7.GetValue(dataEntity);
                if (obj2 != null)
                {
                    IEnumerable enumerable2 = obj2 as IEnumerable;
                    if (enumerable2 == null)
                    {
                        throw new ORMDesignException("??????", ResManager.LoadKDString("哦,真不幸,集合的属性返回值不支持枚举。", "014009000001634", SubSystemType.SL, new object[0]));
                    }
                    object obj3 = property6.GetValue(newEntity);
                    if (obj3 == null)
                    {
                        if (property6.IsReadOnly)
                        {
                            throw new ORMDesignException("??????", ResManager.LoadKDString("哦,真不幸,集合的属性返回值为null。", "014009000001635", SubSystemType.SL, new object[0]));
                        }
                        obj3 = Activator.CreateInstance(property6.PropertyType);
                        property6.SetValue(newEntity, obj3);
                    }
                    IList list = obj3 as IList;
                    if (list == null)
                    {
                        throw new ORMDesignException("??????", ResManager.LoadKDString("哦,真不幸,集合的属性返回值不支持IList。", "014009000001636", SubSystemType.SL, new object[0]));
                    }
                    list.Clear();
                    foreach (IDataEntityBase base4 in enumerable2)
                    {
                        IDataEntityBase base5 = property6.CollectionItemPropertyType.CreateInstance() as IDataEntityBase;
                        base4.CopyData(base5, copyHandler, clearPrimaryKeyValue, onlyDbProperty, false);
                        list.Add(base5);
                    }
                }
            }
        }
Пример #12
0
 /// <summary>
 /// Returns an instance of the <paramref name="type"/> on which the method is invoked.
 /// </summary>
 /// <param name="type">The type on which the method was invoked.</param>
 /// <returns>An instance of the <paramref name="type"/>.</returns>
 public static object GetInstance(this Type type)
 {
     // This is about as quick as it gets.
     return(Activator.CreateInstance(type));
 }
Пример #13
0
 public static DataAccessor CreateInstance(Type type)
 {
     return((DataAccessor)Activator.CreateInstance(TypeFactory.GetType(type)));
 }
Пример #14
0
 public virtual void Activate(Activator activator)
 {
     if (DebugManager.debug) {
         Debug.Log(string.Format("Activated: {0}", this));
     }
 }
Пример #15
0
        public virtual void LoadFromObject(JObject jsonObject)
        {
            IEnumerator itr = jsonObject.Properties().GetEnumerator();
            FieldInfo   field;

            while (itr.MoveNext())
            {
                var key = ((JProperty)itr.Current).Name;
                field = GetType().GetField(key);
                // Si el campo no existe, omitir
                if (field == null)
                {
                    continue;
                }
                Object obj = jsonObject[key];
                try
                {
                    var isConektaObject = (field.FieldType.Namespace ?? "").Equals("ConektaCSharp");

                    var objStr = obj.ToString();

                    if (!String.IsNullOrWhiteSpace(objStr))
                    {
                        switch ((int)objStr[0])
                        {
                        // {
                        case 123:
                            var o = JObject.Parse(objStr);
                            if (o["object"] != null)
                            {
                                var conektaObject = ConektaObjectFromJSONFactory.ConektaObjectFactory(o,
                                                                                                      o["object"].ToString());
                                field.SetValue(this, conektaObject);
                                SetVal(key, conektaObject);
                            }
                            else
                            {
                                if (isConektaObject)
                                {
                                    var handle = Activator.CreateInstance(null, field.FieldType.FullName);
                                    var attr   = (ConektaObject)handle.Unwrap();

                                    attr.LoadFromObject((JObject)obj);
                                    field.SetValue(this, attr);
                                    SetVal(key, attr);
                                }
                                else
                                {
                                    var tipoCampo       = Type.GetType(field.FieldType.FullName);
                                    var valorConvertido = Convert.ChangeType(obj, tipoCampo);
                                    field.SetValue(this, valorConvertido);
                                    SetVal(key, valorConvertido);
                                }
                            }

                            break;

                        // [
                        case 91:
                            var jsonArray = JArray.Parse(objStr);
                            if (jsonArray.Count > 0)
                            {
                                var conektaObject = new ConektaObject();
                                if (isConektaObject)
                                {
                                    var handle = Activator.CreateInstance(null, field.FieldType.FullName);
                                    conektaObject = (ConektaObject)handle.Unwrap();
                                }

                                foreach (var jItem in jsonArray)
                                {
                                    if (jsonArray[0]["object"] != null)
                                    {
                                        conektaObject.Add(
                                            ConektaObjectFromJSONFactory.ConektaObjectFactory(
                                                jItem.ToObject <JObject>(),
                                                jItem["object"].ToString()));
                                    }
                                    else
                                    {
                                        conektaObject.Add(
                                            ConektaObjectFromJSONFactory.ConektaObjectFactory(
                                                jItem.ToObject <JObject>(), key));
                                    }
                                }
                                field.SetValue(this, conektaObject);
                                SetVal(key, conektaObject);
                            }
                            break;

                        default:
                            if (isConektaObject)
                            {
                                var handle = Activator.CreateInstance(null, field.FieldType.FullName);
                                var attr   = (ConektaObject)handle.Unwrap();

                                attr.LoadFromObject((JObject)obj);
                                field.SetValue(this, attr);
                                SetVal(key, attr);
                            }
                            else
                            {
                                var tipoCampo       = Type.GetType(field.FieldType.FullName);
                                var valorConvertido = Convert.ChangeType(obj, tipoCampo);
                                field.SetValue(this, valorConvertido);
                                SetVal(key, valorConvertido);
                            }
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    // No field found
                    //System.out.println(e.toString());
                    throw new Error(e.Message);
                }
            }
        }
Пример #16
0
 protected static T Create <T>(IBlock parent, By @by)
 {
     return((T)Activator.CreateInstance(typeof(T), parent, @by));
 }
        /// <summary>
        /// Get the object from a path node
        /// </summary>
        /// <param name="root">Root dictionary</param>
        /// <param name="path">Path node</param>
        /// <returns>Item at the given path</returns>
        public static object GetPathNode(Dictionary <string, object> root, object[] path)
        {
            Dictionary <string, object> currentDictionary = root;
            List <object> currentList = null;

            for (int i = 0; i < path.Length - 1; i++)
            {
                object pathItem = path[i];
                if (pathItem is string pathString)
                {
                    if (currentDictionary.TryGetValue(pathString, out object child))
                    {
                        if (child is Dictionary <string, object> childDictionary)
                        {
                            currentList       = null;
                            currentDictionary = childDictionary;
                        }
                        else if (child is List <object> childList)
                        {
                            currentList       = childList;
                            currentDictionary = null;
                        }
                        else
                        {
                            // Stop here if the node type is unsupported
                            return(null);
                        }
                    }
                    else
                    {
                        Dictionary <string, object> newNode = new Dictionary <string, object>();
                        currentDictionary.Add(pathString, newNode);
                        currentDictionary = newNode;
                    }
                }
                else if (pathItem is ItemPathNode pathNode)
                {
                    if (currentDictionary.TryGetValue(pathNode.Name, out object nodeObject))
                    {
                        if (nodeObject is List <object> nodeList)
                        {
                            currentList = nodeList;
                        }
                        else
                        {
                            // Stop here if the node type is unsupported
                            return(nodeObject);
                        }

                        for (int k = currentList.Count; k > pathNode.List.Count; k--)
                        {
                            currentList.RemoveAt(k - 1);
                        }
                    }
                    else
                    {
                        currentList = new List <object>(pathNode.List.Count);
                        currentDictionary.Add(pathNode.Name, currentList);
                    }

                    Type itemType = (path[i + 1] is string) ? typeof(Dictionary <string, object>) : typeof(List <object>);
                    for (int k = currentList.Count; k < pathNode.List.Count; k++)
                    {
                        if (pathNode.List[k] == null)
                        {
                            currentList.Add(null);
                        }
                        else
                        {
                            object newItem = Activator.CreateInstance(itemType);
                            currentList.Add(newItem);
                        }
                    }

                    object currentItem = currentList[pathNode.Index];
                    if (currentItem is Dictionary <string, object> dictionaryItem)
                    {
                        currentList       = null;
                        currentDictionary = dictionaryItem;
                    }
                    else if (currentItem is List <object> listItem)
                    {
                        currentList       = listItem;
                        currentDictionary = null;
                    }
                    else
                    {
                        // Stop here if the item type is unsupported
                        return(null);
                    }
                }
            }

            if (currentDictionary != null)
            {
                return(currentDictionary);
            }
            return(currentList);
        }
Пример #18
0
 private static void Game_OnGameLoad(EventArgs args)
 {
     Activator = new Activator();
     Game.PrintChat("Nabb<font color=\"#FF0000\">Activator</font> - Loaded!");
     VersionUpdater.UpdateCheck();
 }
Пример #19
0
 // Use this for initialization
 void Awake()
 {
     GameManager.instance.SetGameState(GameState.Loading);
     _activator = FindObjectOfType<Activator>();
 }
Пример #20
0
 public override void Activate(Activator activator)
 {
     base.Activate(activator);
     effects.ForEach((effect) => effect.Run());
 }
Пример #21
0
 public override void Activate(Activator activator) {
     base.Activate(activator);
     activator.unit.inventory.Pick(this);
 }
Пример #22
0
 public override void Activate(Activator activator)
 {
     base.Activate(activator);
     GameManager.instance.CompleteLevel();
 }
Пример #23
0
        public static object GenericListDrawer(object[] objects, InvokeWrapper wrapper)
        {
            var list   = wrapper.Get <System.Collections.IList>(objects[0]);
            var target = objects[0] as Object;

            if (InspectorGUI.Foldout(EditorData.Instance.GetData(target, wrapper.Member.Name),
                                     InspectorGUI.MakeLabel(wrapper.Member)))
            {
                object insertElementBefore = null;
                object insertElementAfter  = null;
                object eraseElement        = null;
                var    skin         = InspectorEditor.Skin;
                var    buttonLayout = new GUILayoutOption[]
                {
                    GUILayout.Width(1.0f * EditorGUIUtility.singleLineHeight),
                    GUILayout.Height(1.0f * EditorGUIUtility.singleLineHeight)
                };
                foreach (var listObject in list)
                {
                    using (InspectorGUI.IndentScope.Single) {
                        GUILayout.BeginHorizontal();
                        {
                            InspectorGUI.Separator(1.0f, EditorGUIUtility.singleLineHeight);

                            if (InspectorGUI.Button(MiscIcon.EntryInsertBefore,
                                                    true,
                                                    "Insert new element before this.",
                                                    buttonLayout))
                            {
                                insertElementBefore = listObject;
                            }
                            if (InspectorGUI.Button(MiscIcon.EntryInsertAfter,
                                                    true,
                                                    "Insert new element after this.",
                                                    buttonLayout))
                            {
                                insertElementAfter = listObject;
                            }
                            if (InspectorGUI.Button(MiscIcon.EntryRemove,
                                                    true,
                                                    "Remove this element.",
                                                    buttonLayout))
                            {
                                eraseElement = listObject;
                            }
                        }
                        GUILayout.EndHorizontal();

                        InspectorEditor.DrawMembersGUI(new Object[] { target }, ignored => listObject);
                    }
                }

                InspectorGUI.Separator(1.0f, 0.5f * EditorGUIUtility.singleLineHeight);

                if (list.Count == 0)
                {
                    GUILayout.Label(GUI.MakeLabel("Empty", true), skin.Label);
                }

                bool addElementToList = false;
                GUILayout.BeginHorizontal();
                {
                    GUILayout.FlexibleSpace();
                    addElementToList = InspectorGUI.Button(MiscIcon.EntryInsertAfter,
                                                           true,
                                                           "Add new element.",
                                                           buttonLayout);
                }
                GUILayout.EndHorizontal();

                object newObject = null;
                if (addElementToList || insertElementBefore != null || insertElementAfter != null)
                {
                    newObject = Activator.CreateInstance(list.GetType().GetGenericArguments()[0], new object[] { });
                }

                if (eraseElement != null)
                {
                    list.Remove(eraseElement);
                }
                else if (newObject != null)
                {
                    if (addElementToList || (list.Count > 0 && insertElementAfter != null && insertElementAfter == list[list.Count - 1]))
                    {
                        list.Add(newObject);
                    }
                    else if (insertElementAfter != null)
                    {
                        list.Insert(list.IndexOf(insertElementAfter) + 1, newObject);
                    }
                    else if (insertElementBefore != null)
                    {
                        list.Insert(list.IndexOf(insertElementBefore), newObject);
                    }
                }

                if (eraseElement != null || newObject != null)
                {
                    EditorUtility.SetDirty(target);
                }
            }

            // A bit of a hack until I figure out how to handle multi-selection
            // of lists, if that should be possible at all. We're handling the
            // list from inside this drawer and by returning null the return
            // value isn't propagated to any targets.
            return(null);
        }
Пример #24
0
        private static void Game_OnGameLoad(EventArgs args)
        {
            Config = new Menu("Godlike Skillz", "Godlike Skillz", true);
            CClass = new Champion();
            AActivator = new Activator();

            var baseType = CClass.GetType();

            var championName = ObjectManager.Player.ChampionName.ToLowerInvariant();

            switch (championName)
            {
                case "yasuo":
                    CClass = new Yasuo();
                    break;/*
                case "ezreal":
                    CClass = new Ezreal();
                    break;
                case "lucian":
                    CClass = new Lucian();
                    break;
                case "corki":
                    CClass = new Corki();
                    break;
                case "quinn":
                    CClass = new Quinn();
                    break;
                case "kennen":
                    CClass = new Kennen();
                    break;
                case "thresh":
                    CClass = new Thresh();
                    break;
                case "evelynn":
                    CClass = new Thresh();
                    break;
                case "leesin":
                    CClass = new Thresh();
                    break;
                case "rengar":
                    CClass = new Thresh();
                    break;
                case "zed":
                    CClass = new Zed();
                    break;
                case "kogmaw":
                    CClass = new Kogmaw();
                    break;
                case "tristana":
                    CClass = new Tristana();
                    break;*/
              }

            CClass.Id = ObjectManager.Player.BaseSkinName;
            CClass.Config = Config;

            var targetSelectorMenu = new Menu("Target Selector", "Target Selector");
            TargetSelector.AddToMenu(targetSelectorMenu);
            Config.AddSubMenu(targetSelectorMenu);

            var orbwalking = Config.AddSubMenu(new Menu("Orbwalking", "Orbwalking"));
            if (CClass.Orbwalk)
            {
                CClass.Orbwalker = new Orbwalking.Orbwalker(orbwalking);
            }

            /* Menu Summoners */
            var summoners = Config.AddSubMenu(new Menu("Summoners", "Summoners"));
            var summonersHeal = summoners.AddSubMenu(new Menu("Heal", "Heal"));
            {
                summonersHeal.AddItem(new MenuItem("SUMHEALENABLE", "Enable").SetValue(true));
                summonersHeal.AddItem(new MenuItem("SUMHEALSLIDER", "Min. Heal Per.").SetValue(new Slider(20, 99, 1)));
            }

            var summonersBarrier = summoners.AddSubMenu(new Menu("Barrier", "Barrier"));
            {
                summonersBarrier.AddItem(new MenuItem("SUMBARRIERENABLE", "Enable").SetValue(true));
                summonersBarrier.AddItem(
                    new MenuItem("SUMBARRIERSLIDER", "Min. Heal Per.").SetValue(new Slider(20, 99, 1)));
            }

            var summonersIgnite = summoners.AddSubMenu(new Menu("Ignite", "Ignite"));
            {
                summonersIgnite.AddItem(new MenuItem("SUMIGNITEENABLE", "Enable").SetValue(true));
            }
            /* Menu Items */
            var items = Config.AddSubMenu(new Menu("Items", "Items"));
            items.AddItem(new MenuItem("BOTRK", "BOTRK").SetValue(true));
            items.AddItem(new MenuItem("GHOSTBLADE", "Ghostblade").SetValue(true));
            items.AddItem(new MenuItem("SWORD", "Sword of the Divine").SetValue(true));
            items.AddItem(new MenuItem("MURAMANA", "Muramana").SetValue(true));
            QuickSilverMenu = new Menu("QSS", "QuickSilverSash");
            items.AddSubMenu(QuickSilverMenu);
            QuickSilverMenu.AddItem(new MenuItem("AnyStun", "Any Stun").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnySlow", "Any Slow").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnySnare", "Any Snare").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnyTaunt", "Any Taunt").SetValue(true));
            foreach (var t in AActivator.BuffList)
            {
                foreach (var enemy in ObjectManager.Get<Obj_AI_Hero>().Where(enemy => enemy.IsEnemy))
                {
                    if (t.ChampionName == enemy.ChampionName)
                        QuickSilverMenu.AddItem(new MenuItem(t.BuffName, t.DisplayName).SetValue(t.DefaultValue));
                }
            }

            var extras = new Menu("Extras", "Extras");
            new PotionManager(extras);
            extras.AddItem(
                new MenuItem("atkmove", "Custom Attack Move").SetValue(true));
            Config.AddSubMenu(extras);

            // If Champion is supported draw the extra menus
            if (baseType != CClass.GetType())
            {
                var combo = new Menu("Combo", "Combo");
                if (CClass.ComboMenu(combo))
                {
                    Config.AddSubMenu(combo);
                }

                var harass = new Menu("Harass", "Harass");
                if (CClass.HarassMenu(harass))
                {
                    harass.AddItem(new MenuItem("HarassMana", "Min. Mana Percent").SetValue(new Slider(50, 100, 0)));
                    Config.AddSubMenu(harass);
                }

                var laneclear = new Menu("LaneClear", "LaneClear");
                if (CClass.LaneClearMenu(laneclear))
                {
                    laneclear.AddItem(
                        new MenuItem("LaneClearMana", "Min. Mana Percent").SetValue(new Slider(50, 100, 0)));
                    Config.AddSubMenu(laneclear);
                }

                var misc = new Menu("Misc", "Misc");
                if (CClass.MiscMenu(misc))
                {
                    Config.AddSubMenu(misc);
                }

                CClass.ExtrasMenu(extras);

                var drawing = new Menu("Drawings", "Drawings");
                if (CClass.DrawingMenu(drawing))
                {
                    Config.AddSubMenu(drawing);
                }

            }

            CClass.MainMenu(Config);
            Config.AddToMainMenu();

            Drawing.OnDraw += Drawing_OnDraw;
            Game.OnUpdate += Game_OnGameUpdate;
            Game.OnWndProc += GameOnOnWndProc;
            Orbwalking.AfterAttack += OrbwalkingAfterAttack;
            Orbwalking.OnAttack += OrbwalkingOnAttack;
            Orbwalking.BeforeAttack += OrbwalkingBeforeAttack;
            //GameObject.OnCreate += ObjSpellMissileOnOnCreate;
            //Obj_AI_Base.OnProcessSpellCast += OnProcessSpell;
        }
Пример #25
0
        private static void OnBeginRequest(object sender, EventArgs e)
        {
            var    app           = (HttpApplication)sender;
            string strCurrentUrl = app.Request.RawUrl.ToLower().Trim();

            app.StaticFile304();
            // Debug go first
            if (UrlService.IsDebugUrl(strCurrentUrl))
            {
                // Nothing here
                // just return
                return;
            }

            // Check cn
            if (AppServiceStartAction.state != DataBaseService.PingDbState.NoError)
            {
                // Nothing here
                // just return
                return;
            }

            // Check original pictures
            if (strCurrentUrl.Contains("/pictures/product/original/"))
            {
                app.Context.RewritePath("~/err404.aspx");
                return;
            }

            // Check price_temp folder
            if (strCurrentUrl.Contains("/price_temp/"))
            {
                var actions = RoleActionService.GetCustomerRoleActionsByCustomerId(CustomerContext.CurrentCustomer.Id);

                if (!(CustomerContext.CurrentCustomer.IsAdmin || TrialService.IsTrialEnabled ||
                      CustomerContext.CurrentCustomer.IsVirtual ||
                      (CustomerContext.CurrentCustomer.IsModerator && actions.Any(item => item.Key == RoleActionKey.DisplayOrders || item.Key == RoleActionKey.DisplayImportExport)))
                    )
                {
                    app.Context.RewritePath("~/err404.aspx");
                    return;
                }
            }

            // Social
            string social = UrlService.Social.Find(strCurrentUrl.Contains);

            if (social != null)
            {
                app.Response.RedirectPermanent("~/social/catalogsocial.aspx?type=" + social.Split('-').Last());
            }

            // Check exportfeed
            //if (strCurrentUrl.Contains("exportfeed.aspx") || strCurrentUrl.Contains("exportfeeddet.aspx"))
            //    return;

            // Payment return url
            if (strCurrentUrl.Contains("/paymentreturnurl/"))
            {
                app.Context.RewritePath("~/PaymentReturnUrl.aspx?PaymentMethodID=" + app.Request.Path.Split(new[] { "/paymentreturnurl/" }, StringSplitOptions.None).LastOrDefault()
                                        + (string.IsNullOrWhiteSpace(app.Request.Url.Query) ? string.Empty : "&" + app.Request.Url.Query.Trim('?')));
                return;
            }
            if (strCurrentUrl.Contains("/paymentnotification/"))
            {
                app.Context.RewritePath("~/HttpHandlers/PaymentNotification.ashx?PaymentMethodID=" + app.Request.Path.Split(new[] { "/paymentnotification/" }, StringSplitOptions.None).LastOrDefault()
                                        + (string.IsNullOrWhiteSpace(app.Request.Url.Query) ? string.Empty : "&" + app.Request.Url.Query.Trim('?')));
                return;
            }

            // Seek in url table
            foreach (var key in UrlService.UrlTable.Keys.Where(strCurrentUrl.Split('?')[0].EndsWith))
            {
                app.Context.RewritePath(UrlService.UrlTable[key] + (string.IsNullOrWhiteSpace(app.Request.Url.Query)
                                                                            ? string.Empty
                                                                            : (UrlService.UrlTable[key].Contains("?") ? "&" : "?") + app.Request.Url.Query.Trim('?')));
                return;
            }

            //// Storage
            //string storage = UrlService.Storages.Find(strCurrentUrl.Contains);
            //if (storage != null)
            //{
            //    var index = strCurrentUrl.IndexOf(storage, StringComparison.Ordinal);
            //    string tail = app.Request.RawUrl.Substring(index + storage.Length);
            //    string pathNew = string.Format("~{0}{1}", storage, tail);
            //    app.Context.RewritePath(pathNew);
            //    return;
            //}

            string path = strCurrentUrl;

            if (app.Request.ApplicationPath != "/")
            {
                if (app.Request.ApplicationPath != null)
                {
                    path = path.Replace(app.Request.ApplicationPath.ToLower(), "");
                }
            }

            // sometimes Path.GetExtension thows exeption "Illegal characters in path"
            try
            {
                string extention = Path.GetExtension(path.Split('?')[0]);
                if (UrlService.ExtentionNotToRedirect.Contains(extention))
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex, false);
            }

            //301 redirect if need
            if (SettingsSEO.Enabled301Redirects && !path.Contains("/admin/"))
            {
                string newUrl = UrlService.GetRedirect301(path.TrimStart('/').Trim('?'), app.Request.Url.AbsoluteUri);
                if (newUrl.IsNotEmpty())
                {
                    app.Response.RedirectPermanent(newUrl);
                    return;
                }
            }

            var modules = AttachedModules.GetModules <IModuleUrlRewrite>();

            foreach (var moduleType in modules)
            {
                var    moduleObject = (IModuleUrlRewrite)Activator.CreateInstance(moduleType, null);
                string newUrl       = path;
                if (moduleObject.RewritePath(path, ref newUrl))
                {
                    app.Context.RewritePath(newUrl);
                    return;
                }
            }

            var param = UrlService.ParseRequest(path);

            if (param != null)
            {
                UrlService.RedirectTo(app, param);
            }
            else if (path.IsNotEmpty() && path != "/" && !path.Contains(".") && !path.Contains("?"))
            {
                Debug.LogError(new HttpException(404, "Can't get url: " + app.Context.Request.RawUrl + "path: '" + path + "'"));
                app.Context.RewritePath("~/err404.aspx");
            }
        }
Пример #26
0
        private static void Game_OnGameLoad(EventArgs args)
        {
            Config = new Menu("Marksman", "Marksman", true);
            CClass = new Champion();
            AActivator = new Activator();
            
            var BaseType = CClass.GetType();

            /* Update this with Activator.CreateInstance or Invoke
               http://stackoverflow.com/questions/801070/dynamically-invoking-any-function-by-passing-function-name-as-string 
               For now stays cancer.
             */
            var championName = ObjectManager.Player.ChampionName.ToLowerInvariant();

            switch (championName)
            {
                case "ashe":
                    CClass = new Ashe();
                    break;
                case "caitlyn":
                    CClass = new Caitlyn();
                    break;
                case "corki":
                    CClass = new Corki();
                    break;
                case "draven":
                    CClass = new Draven();
                    break;
                case "ezreal":
                    CClass = new Ezreal();
                    break;
                case "graves":
                    CClass = new Graves();
                    break;
                case "gnar":
                    CClass = new Gnar();
                    break;
                case "jinx":
                    CClass = new Jinx();
                    break;
                case "kalista":
                    CClass = new Kalista();
                    break;
                case "kogmaw":
                    CClass = new Kogmaw();
                    break;
                case "lucian":
                    CClass = new Lucian();
                    break;
                case "missfortune":
                    CClass = new MissFortune();
                    break;   
                case "quinn":
                    CClass = new Quinn();
                    break;
                case "sivir":
                    CClass = new Sivir();
                    break;
                case "teemo":
                    CClass = new Teemo();
                    break;
                case "tristana":
                    CClass = new Tristana();
                    break;
                case "twitch":
                    CClass = new Twitch();
                    break;
                case "urgot":
                    CClass = new Urgot();
                    break;
                case "vayne":
                    CClass = new Vayne();
                    break;
                case "varus":
                    CClass = new Varus();
                    break;
            }


            CClass.Id = ObjectManager.Player.BaseSkinName;
            CClass.Config = Config;

            var targetSelectorMenu = new Menu("Target Selector", "Target Selector");
            TargetSelector.AddToMenu(targetSelectorMenu);
            Config.AddSubMenu(targetSelectorMenu);

            var orbwalking = Config.AddSubMenu(new Menu("Orbwalking", "Orbwalking"));
            CClass.Orbwalker = new Orbwalking.Orbwalker(orbwalking);

            /* Menu Summoners */
            var summoners = Config.AddSubMenu(new Menu("Summoners", "Summoners"));
            var summonersHeal = summoners.AddSubMenu(new Menu("Heal", "Heal"));
            {
                summonersHeal.AddItem(new MenuItem("SUMHEALENABLE", "Enable").SetValue(true));
                summonersHeal.AddItem(new MenuItem("SUMHEALSLIDER", "Min. Heal Per.").SetValue(new Slider(20, 99, 1)));
            }

            var summonersBarrier = summoners.AddSubMenu(new Menu("Barrier", "Barrier"));
            {
                summonersBarrier.AddItem(new MenuItem("SUMBARRIERENABLE", "Enable").SetValue(true));
                summonersBarrier.AddItem(
                    new MenuItem("SUMBARRIERSLIDER", "Min. Heal Per.").SetValue(new Slider(20, 99, 1)));
            }

            var summonersIgnite = summoners.AddSubMenu(new Menu("Ignite", "Ignite"));
            {
                summonersIgnite.AddItem(new MenuItem("SUMIGNITEENABLE", "Enable").SetValue(true));
            }
            /* Menu Items */            
            var items = Config.AddSubMenu(new Menu("Items", "Items"));
            items.AddItem(new MenuItem("BOTRK", "BOTRK").SetValue(true));
            items.AddItem(new MenuItem("GHOSTBLADE", "Ghostblade").SetValue(true));
            items.AddItem(new MenuItem("SWORD", "Sword of the Divine").SetValue(true));
            items.AddItem(new MenuItem("MURAMANA", "Muramana").SetValue(true));
            QuickSilverMenu = new Menu("QSS", "QuickSilverSash");
            items.AddSubMenu(QuickSilverMenu);
            QuickSilverMenu.AddItem(new MenuItem("AnyStun", "Any Stun").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnySlow", "Any Slow").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnySnare", "Any Snare").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnyTaunt", "Any Taunt").SetValue(true));
            foreach (var t in AActivator.BuffList)
            {
                foreach (var enemy in ObjectManager.Get<Obj_AI_Hero>().Where(enemy => enemy.IsEnemy))
                {
                    if (t.ChampionName == enemy.ChampionName)
                        QuickSilverMenu.AddItem(new MenuItem(t.BuffName, t.DisplayName).SetValue(t.DefaultValue));
                }
            }
            items.AddItem(
                new MenuItem("UseItemsMode", "Use items on").SetValue(
                    new StringList(new[] {"No", "Mixed mode", "Combo mode", "Both"}, 2)));

            
            //var Extras = Config.AddSubMenu(new Menu("Extras", "Extras"));
            //new PotionManager(Extras);

            // If Champion is supported draw the extra menus
            if (BaseType != CClass.GetType())
            {
                var combo = new Menu("Combo", "Combo");
                if (CClass.ComboMenu(combo))
                {
                    Config.AddSubMenu(combo);
                }

                var harass = new Menu("Harass", "Harass");
                if (CClass.HarassMenu(harass))
                {
                    harass.AddItem(new MenuItem("HarassMana", "Min. Mana Percent").SetValue(new Slider(50, 100, 0)));
                    Config.AddSubMenu(harass);
                }

                var laneclear = new Menu("LaneClear", "LaneClear");
                if (CClass.LaneClearMenu(laneclear))
                {
                    laneclear.AddItem(
                        new MenuItem("LaneClearMana", "Min. Mana Percent").SetValue(new Slider(50, 100, 0)));
                    Config.AddSubMenu(laneclear);
                }

                var misc = new Menu("Misc", "Misc");
                if (CClass.MiscMenu(misc))
                {
                    Config.AddSubMenu(misc);
                }
                /*
                if (championName != "caitlyn" || championName != "jinx")
                {
                    MenuInterruptableSpell = new Menu("Interruptable Spell",
                        "Interrupt with " + championName == "caitlyn" ? "Caitlyn's W" : "Jinx's E");

                    MenuInterruptableSpell.AddItem(new MenuItem("InterruptSpells", "Active").SetValue(true));

                    foreach (var xSpell in Interrupter.Spells)
                    {
                        MenuInterruptableSpell.AddItem(
                            new MenuItem("IntNode" + xSpell.BuffName, xSpell.ChampionName + " | " + xSpell.Slot)
                                .SetValue(true));
                    }
                    Config.AddSubMenu(MenuInterruptableSpell);
                }
                */
                var extras = new Menu("Extras", "Extras");
                if (CClass.ExtrasMenu(extras))
                {
                    new PotionManager(extras);
                    Config.AddSubMenu(extras);
                }

                var drawing = new Menu("Drawings", "Drawings");
                if (CClass.DrawingMenu(drawing))
                {
                    drawing.AddItem(
                        new MenuItem("drawMinionLastHit", "Minion Last Hit").SetValue(new Circle(false,
                            System.Drawing.Color.GreenYellow)));
                    drawing.AddItem(
                        new MenuItem("drawMinionNearKill", "Minion Near Kill").SetValue(new Circle(false,
                            System.Drawing.Color.Gray)));
                    drawing.AddItem(new MenuItem("drawJunglePosition", "JunglePosition").SetValue(true));

                    Config.AddSubMenu(drawing);
                }

            }


            CClass.MainMenu(Config);

            Config.AddToMainMenu();

            Drawing.OnDraw += Drawing_OnDraw;
            Game.OnGameUpdate += Game_OnGameUpdate;
            Orbwalking.AfterAttack += Orbwalking_AfterAttack;
            Orbwalking.BeforeAttack += Orbwalking_BeforeAttack;
            //Interrupter.OnPossibleToInterrupt += Interrupter_OnPosibleToInterrupt;
            //Game.OnWndProc += Game_OnWndProc;
        }
Пример #27
0
 protected static T Create <T>(IBlock parent, IWebElement tag)
 {
     return((T)Activator.CreateInstance(typeof(T), parent, tag));
 }
Пример #28
0
        private Type GetModelType()
        {
            T t = Activator.CreateInstance <T>();

            return(t.GetType());
        }
Пример #29
0
 public static TClient CreateClient <TClient>(HttpClient httpClient)
     where TClient : SlackClientBase
 => (TClient)Activator.CreateInstance(typeof(TClient), httpClient);
Пример #30
0
 /// <summary>
 /// Sends an event via the client by raising an event
 /// </summary>
 /// <param name="networkargs">The arguments that are sent. The package's class is initialized via Activator,
 /// so the arguments are the parameters of type T constructor</param>
 public void Send(params object[] networkargs)
 {
     var package = (INetworkPackage)Activator.CreateInstance(typeof(TMessageType), networkargs);
     package.Id = Id;
     OnEvent(package);
 }
Пример #31
0
        public static List <S> SettingWithDialog(Visual owner, IEnumerable <S> presetList = null)
        {
            var dlg = (W)Activator.CreateInstance(typeof(W), owner, presetList ?? new List <S>());

            return(dlg.ShowDialog() == true?dlg.GetPresetList() : null);
        }
Пример #32
0
 private static Func <Graph, Node> FactoryForType(Type t)
 {
     return(g => (Node)Activator.CreateInstance(t, g));
 }
Пример #33
0
 public static DataAccessor CreateInstance(Type type, InitContext context)
 {
     return((DataAccessor)Activator.CreateInstance(TypeFactory.GetType(type), context));
 }
Пример #34
0
 private static Func <Graph, XmlNode, Node> FactoryXmlForType(Type t)
 {
     return((g, x) => (Node)Activator.CreateInstance(t, x, g));
 }
Пример #35
0
        public sealed override Object InvokeMember(
            String name, BindingFlags bindingFlags, Binder binder, Object target,
            Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
        {
            const BindingFlags MemberBindingMask       = (BindingFlags)0x000000FF;
            const BindingFlags InvocationMask          = (BindingFlags)0x0000FF00;
            const BindingFlags BinderGetSetProperty    = BindingFlags.GetProperty | BindingFlags.SetProperty;
            const BindingFlags BinderGetSetField       = BindingFlags.GetField | BindingFlags.SetField;
            const BindingFlags BinderNonFieldGetSet    = (BindingFlags)0x00FFF300;
            const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;

            if (IsGenericParameter)
            {
                throw new InvalidOperationException(SR.Arg_GenericParameter);
            }

            #region Preconditions
            if ((bindingFlags & InvocationMask) == 0)
            {
                // "Must specify binding flags describing the invoke operation required."
                throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));
            }

            // Provide a default binding mask if none is provided
            if ((bindingFlags & MemberBindingMask) == 0)
            {
                bindingFlags |= BindingFlags.Instance | BindingFlags.Public;

                if ((bindingFlags & BindingFlags.CreateInstance) == 0)
                {
                    bindingFlags |= BindingFlags.Static;
                }
            }

            // There must not be more named parameters than provided arguments
            if (namedParams != null)
            {
                if (providedArgs != null)
                {
                    if (namedParams.Length > providedArgs.Length)
                    {
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                    }
                }
                else
                {
                    if (namedParams.Length != 0)
                    {
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                    }
                }
            }
            #endregion

            #region COM Interop
            if (target != null && target.GetType().IsCOMObject)
            {
                throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupportedInvokeMemberCom);
            }
            #endregion

            #region Check that any named paramters are not null
            if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
            {
                // "Named parameter value must not be null."
                throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
            }
            #endregion

            int argCnt = (providedArgs != null) ? providedArgs.Length : 0;

            #region Get a Binder
            if (binder == null)
            {
                binder = DefaultBinder;
            }

            bool bDefaultBinder = (binder == DefaultBinder);
            #endregion

            #region Delegate to Activator.CreateInstance
            if ((bindingFlags & BindingFlags.CreateInstance) != 0)
            {
                if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
                {
                    // "Can not specify both CreateInstance and another access type."
                    throw new ArgumentException(SR.Arg_CreatInstAccess, nameof(bindingFlags));
                }

                return(Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture));
            }
            #endregion

            // PutDispProperty and\or PutRefDispProperty ==> SetProperty.
            if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0)
            {
                bindingFlags |= BindingFlags.SetProperty;
            }

            #region Name
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
            {
                name = GetDefaultMemberName();

                if (name == null)
                {
                    // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
                    name = "ToString";
                }
            }
            #endregion

            #region GetField or SetField
            bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0;
            bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0;

            if (IsGetField || IsSetField)
            {
                #region Preconditions
                if (IsGetField)
                {
                    if (IsSetField)
                    {
                        // "Can not specify both Get and Set on a field."
                        throw new ArgumentException(SR.Arg_FldSetGet, nameof(bindingFlags));
                    }

                    if ((bindingFlags & BindingFlags.SetProperty) != 0)
                    {
                        // "Can not specify both GetField and SetProperty."
                        throw new ArgumentException(SR.Arg_FldGetPropSet, nameof(bindingFlags));
                    }
                }
                else
                {
                    Debug.Assert(IsSetField);

                    if (providedArgs == null)
                    {
                        throw new ArgumentNullException(nameof(providedArgs));
                    }

                    if ((bindingFlags & BindingFlags.GetProperty) != 0)
                    {
                        // "Can not specify both SetField and GetProperty."
                        throw new ArgumentException(SR.Arg_FldSetPropGet, nameof(bindingFlags));
                    }

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                    {
                        // "Can not specify Set on a Field and Invoke on a method."
                        throw new ArgumentException(SR.Arg_FldSetInvoke, nameof(bindingFlags));
                    }
                }
                #endregion

                #region Lookup Field
                FieldInfo   selFld = null;
                FieldInfo[] flds   = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];

                Debug.Assert(flds != null);

                if (flds.Length == 1)
                {
                    selFld = flds[0];
                }
                else if (flds.Length > 0)
                {
                    selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
                }
                #endregion

                if (selFld != null)
                {
                    #region Invocation on a field
                    if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, CommonRuntimeTypes.Array))
                    {
                        #region Invocation of an array Field
                        int idxCnt;

                        if ((bindingFlags & BindingFlags.GetField) != 0)
                        {
                            idxCnt = argCnt;
                        }
                        else
                        {
                            idxCnt = argCnt - 1;
                        }

                        if (idxCnt > 0)
                        {
                            // Verify that all of the index values are ints
                            int[] idx = new int[idxCnt];
                            for (int i = 0; i < idxCnt; i++)
                            {
                                try
                                {
                                    idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
                                }
                                catch (InvalidCastException)
                                {
                                    throw new ArgumentException(SR.Arg_IndexMustBeInt);
                                }
                            }

                            // Set or get the value...
                            Array a = (Array)selFld.GetValue(target);

                            // Set or get the value in the array
                            if ((bindingFlags & BindingFlags.GetField) != 0)
                            {
                                return(a.GetValue(idx));
                            }
                            else
                            {
                                a.SetValue(providedArgs[idxCnt], idx);
                                return(null);
                            }
                        }
                        #endregion
                    }

                    if (IsGetField)
                    {
                        #region Get the field value
                        if (argCnt != 0)
                        {
                            throw new ArgumentException(SR.Arg_FldGetArgErr, nameof(bindingFlags));
                        }

                        return(selFld.GetValue(target));

                        #endregion
                    }
                    else
                    {
                        #region Set the field Value
                        if (argCnt != 1)
                        {
                            throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));
                        }

                        selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);

                        return(null);

                        #endregion
                    }
                    #endregion
                }

                if ((bindingFlags & BinderNonFieldGetSet) == 0)
                {
                    throw new MissingFieldException(FullName, name);
                }
            }
            #endregion

            #region Property PreConditions
            // @Legacy - This is RTM behavior
            bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0;
            bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0;

            if (isGetProperty || isSetProperty)
            {
                #region Preconditions
                if (isGetProperty)
                {
                    Debug.Assert(!IsSetField);

                    if (isSetProperty)
                    {
                        throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
                    }
                }
                else
                {
                    Debug.Assert(isSetProperty);

                    Debug.Assert(!IsGetField);

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                    {
                        throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
                    }
                }
                #endregion
            }
            #endregion

            MethodInfo[] finalists = null;
            MethodInfo   finalist  = null;

            #region BindingFlags.InvokeMethod
            if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
            {
                #region Lookup Methods
                MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
                LowLevelListWithIList <MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = semiFinalists[i];
                    Debug.Assert(semiFinalist != null);

                    if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
                    {
                        continue;
                    }

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new LowLevelListWithIList <MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists, 0);
                }
                #endregion
            }
            #endregion

            Debug.Assert(finalists == null || finalist != null);

            #region BindingFlags.GetProperty or BindingFlags.SetProperty
            if (finalist == null && isGetProperty || isSetProperty)
            {
                #region Lookup Property
                PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
                LowLevelListWithIList <MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = null;

                    if (isSetProperty)
                    {
                        semiFinalist = semiFinalists[i].GetSetMethod(true);
                    }
                    else
                    {
                        semiFinalist = semiFinalists[i].GetGetMethod(true);
                    }

                    if (semiFinalist == null)
                    {
                        continue;
                    }

                    BindingFlags expectedBindingFlags = semiFinalist.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
                    if ((bindingFlags & expectedBindingFlags) != expectedBindingFlags)
                    {
                        continue;
                    }

                    if (!semiFinalist.QualifiesBasedOnParameterCount(bindingFlags, CallingConventions.Any, new Type[argCnt]))
                    {
                        continue;
                    }

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new LowLevelListWithIList <MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists, 0);
                }
                #endregion
            }
            #endregion

            if (finalist != null)
            {
                #region Invoke
                if (finalists == null &&
                    argCnt == 0 &&
                    finalist.GetParametersNoCopy().Length == 0 &&
                    (bindingFlags & BindingFlags.OptionalParamBinding) == 0)
                {
                    //if (useCache && argCnt == props[0].GetParameters().Length)
                    //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]);

                    return(finalist.Invoke(target, bindingFlags, binder, providedArgs, culture));
                }

                if (finalists == null)
                {
                    finalists = new MethodInfo[] { finalist }
                }
                ;

                if (providedArgs == null)
                {
                    providedArgs = Array.Empty <object>();
                }

                Object state = null;


                MethodBase invokeMethod = null;

                try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
                catch (MissingMethodException) { }

                if (invokeMethod == null)
                {
                    throw new MissingMethodException(FullName, name);
                }

                //if (useCache && argCnt == invokeMethod.GetParameters().Length)
                //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod);

                Object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);

                if (state != null)
                {
                    binder.ReorderArgumentArray(ref providedArgs, state);
                }

                return(result);

                #endregion
            }

            throw new MissingMethodException(FullName, name);
        }
    }
		protected virtual Mobile CreateMobile()
		{
			return (Mobile) Activator.CreateInstance( Type );
		}
Пример #37
0
        // creates a serializer based on static registration (e.g. attributes),
        // generic templates or hardcoded mappings
        private ISerializer <T> CreateSerializer <T>()
        {
            var  type = typeof(T);
            Type serializerType;

            if (this.serializers.TryGetValue(type, out serializerType))
            {
                return((ISerializer <T>)Activator.CreateInstance(serializerType));
            }

            // is this type known as not serializable?
            if (!IsSerializable(type))
            {
                return(new NonSerializer <T>());
            }

            // is there a template for it?
            if (type.IsConstructedGenericType)
            {
                // generic
                // T is an instance of a generic type, such as Nullable<int>
                // and a corresponding generic serializer (template) is registered for the generic type
                var typeParams  = type.GetGenericArguments();
                var genericType = type.GetGenericTypeDefinition();

                if (this.templates.TryGetValue(genericType, out serializerType))
                {
                    // we found a registered generic serializer, specialize it
                    serializerType = serializerType.MakeGenericType(typeParams);
                    return((ISerializer <T>)Activator.CreateInstance(serializerType, nonPublic: true));
                }
            }

            // is the target type annotated with the [Serializer(typeof(MySerializer))] attribute
            var attribute = type.GetCustomAttribute <SerializerAttribute>(inherit: true /*!!!*/);

            if (attribute != null)
            {
                // if the annotation is on a generic type, the serializer is also generic and we need to instantiate the concrete serializer given the generic arguments
                if (type.IsConstructedGenericType && attribute.SerializerType.IsGenericTypeDefinition)
                {
                    var typeParams = type.GetGenericArguments();
                    serializerType = attribute.SerializerType.MakeGenericType(typeParams);
                }
                else
                {
                    serializerType = attribute.SerializerType;
                }

                return((ISerializer <T>)Activator.CreateInstance(serializerType));
            }

            // for arrays, create an array serializer of the right type,
            // which in turn will delegate element serialization to the correct registered serializer
            if (type.IsArray)
            {
                // instantiate the correct array serializer based on the type of elements in the array
                var  itemType        = type.GetElementType();
                Type arraySerializer = Generator.IsSimpleValueType(itemType) ? typeof(SimpleArraySerializer <>) : typeof(ArraySerializer <>);
                serializerType = arraySerializer.MakeGenericType(itemType);
                return((ISerializer <T>)Activator.CreateInstance(serializerType, nonPublic: true));
            }

            return(this.CreateWellKnownSerializer <T>());
        }
		protected virtual Item CreateItem()
		{
			return (Item) Activator.CreateInstance( Type );
		}
Пример #39
0
 public EventMachine(Type t)
 {
     m_sm    = (StateManager)Activator.CreateInstance(t);
     m_evman = new EventManager();
     m_sm.SetEventMan(m_evman);
 }
        protected IList CreateList(Type type)
        {
            var listType = typeof(List <>).MakeGenericType(type);

            return((IList)Activator.CreateInstance(listType));
        }
Пример #41
0
		public object ProvideValue(IServiceProvider serviceProvider)
		{
			if (Android == s_notset
				&& GTK == s_notset
				&& iOS == s_notset
				&& macOS == s_notset
				&& MacCatalyst == s_notset
				&& Tizen == s_notset
#pragma warning disable CS0618 // Type or member is obsolete
				&& UWP == s_notset
#pragma warning restore CS0618 // Type or member is obsolete
				&& WPF == s_notset
				&& WinUI == s_notset
				&& Default == s_notset)
			{
				throw new XamlParseException("OnPlatformExtension requires a value to be specified for at least one platform or Default.", serviceProvider);
			}

			var valueProvider = serviceProvider?.GetService<IProvideValueTarget>() ?? throw new ArgumentException();

			BindableProperty bp;
			PropertyInfo pi = null;
			Type propertyType = null;

			if (valueProvider.TargetObject is Setter setter)
				bp = setter.Property;
			else
			{
				bp = valueProvider.TargetProperty as BindableProperty;
				pi = valueProvider.TargetProperty as PropertyInfo;
			}
			propertyType = bp?.ReturnType
						?? pi?.PropertyType
						?? throw new InvalidOperationException("Cannot determine property to provide the value for.");

			if (!TryGetValueForPlatform(out var value))
			{
				if (bp != null)
					return bp.GetDefaultValue(valueProvider.TargetObject as BindableObject);
				if (propertyType.IsValueType)
					return Activator.CreateInstance(propertyType);
				return null;
			}

			if (Converter != null)
				return Converter.Convert(value, propertyType, ConverterParameter, CultureInfo.CurrentUICulture);

			var converterProvider = serviceProvider?.GetService<IValueConverterProvider>();
			if (converterProvider != null)
			{
				MemberInfo minforetriever()
				{
					if (pi != null)
						return pi;

					MemberInfo minfo = null;
					try
					{
						minfo = bp.DeclaringType.GetRuntimeProperty(bp.PropertyName);
					}
					catch (AmbiguousMatchException e)
					{
						throw new XamlParseException($"Multiple properties with name '{bp.DeclaringType}.{bp.PropertyName}' found.", serviceProvider, innerException: e);
					}
					if (minfo != null)
						return minfo;
					try
					{
						return bp.DeclaringType.GetRuntimeMethod("Get" + bp.PropertyName, new[] { typeof(BindableObject) });
					}
					catch (AmbiguousMatchException e)
					{
						throw new XamlParseException($"Multiple methods with name '{bp.DeclaringType}.Get{bp.PropertyName}' found.", serviceProvider, innerException: e);
					}
				}

				return converterProvider.Convert(value, propertyType, minforetriever, serviceProvider);
			}
			var ret = value.ConvertTo(propertyType, () => pi, serviceProvider, out Exception exception);
			if (exception != null)
				throw exception;
			return ret;
		}
        public LuaCSFunction GetConstructorWrap(Type type)
        {
            //UnityEngine.Debug.LogWarning("GetConstructor:" + type);
            if (!constructorCache.ContainsKey(type))
            {
                var constructors = type.GetConstructors();
                if (type.IsAbstract() || constructors == null || constructors.Length == 0)
                {
                    if (type.IsValueType())
                    {
                        constructorCache[type] = (L) =>
                        {
                            translator.PushAny(L, Activator.CreateInstance(type));
                            return(1);
                        };
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    LuaCSFunction ctor = _GenMethodWrap(type, ".ctor", constructors, true).Call;

                    if (type.IsValueType())
                    {
                        bool hasZeroParamsCtor = false;
                        for (int i = 0; i < constructors.Length; i++)
                        {
                            if (constructors[i].GetParameters().Length == 0)
                            {
                                hasZeroParamsCtor = true;
                                break;
                            }
                        }
                        if (hasZeroParamsCtor)
                        {
                            constructorCache[type] = ctor;
                        }
                        else
                        {
                            constructorCache[type] = (L) =>
                            {
                                if (LuaAPI.lua_gettop(L) == 1)
                                {
                                    translator.PushAny(L, Activator.CreateInstance(type));
                                    return(1);
                                }
                                else
                                {
                                    return(ctor(L));
                                }
                            };
                        }
                    }
                    else
                    {
                        constructorCache[type] = ctor;
                    }
                }
            }
            return(constructorCache[type]);
        }
Пример #43
0
        public static string[] IsGenericType(string[] readToEndLines, object dataObject)
        {
            Type dataObjectType = dataObject.GetType();

            PropertyInfo[] propertyInfos = dataObjectType.GetProperties();
            try {
                propertyInfos = dataObjectType.GetProperties().OrderBy(p => p.GetCustomAttributes().OfType <EdiSegmentAttribute>().First().Order).ToArray();
            }
            catch {
                propertyInfos = dataObjectType.GetProperties().OrderBy(p => p.GetCustomAttributes().OfType <EdiValueAttribute>().First().Order).ToArray();
            }

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                Type propertyType = propertyInfo.PropertyType;
                if (propertyType.IsGenericType)
                {
                    EdiSegmentAttribute eEdiSegmentAttribute = (EdiSegmentAttribute)propertyInfo.GetCustomAttribute(typeof(EdiSegmentAttribute));
                    Type            GenericArgument          = propertyInfo.PropertyType.GetGenericArguments()[0];
                    List <string[]> bloks    = new List <string[]>();
                    List <string>   tempBlok = new List <string>();
                    foreach (string readToEndLine in readToEndLines)
                    {
                        if (eEdiSegmentAttribute.SequenceEnd == null)
                        {
                        }
                        else
                        {
                            if ((tempBlok.Count > 0) && (readToEndLine.StartsWith(eEdiSegmentAttribute.SequenceEnd) | readToEndLine.StartsWith(eEdiSegmentAttribute.Path)))
                            {
                                if (eEdiSegmentAttribute.IsWithSequenceEnd)
                                {
                                    tempBlok.Add(readToEndLine);
                                    bloks.Add(tempBlok.ToArray());
                                    tempBlok.Clear();
                                }
                                else
                                {
                                    bloks.Add(tempBlok.ToArray());
                                    //readToEndLines = readToEndLines.Skip(tempBlok.Count).ToArray();
                                    tempBlok.Clear();
                                    tempBlok.Add(readToEndLine);
                                }
                            }
                            else
                            {
                                tempBlok.Add(readToEndLine);
                            }
                        }
                    }
                    if (tempBlok.Count > 0)
                    {
                        bloks.Add(tempBlok.ToArray());
                        tempBlok.Clear();
                    }
                    object instance = Activator.CreateInstance(propertyInfo.PropertyType);
                    IList  list     = (IList)instance;
                    if (bloks.Count == 0)
                    {
                        bool           IsValueType         = true;
                        PropertyInfo[] propertiesForValues = GenericArgument.GetProperties();
                        foreach (PropertyInfo propertiesForValue in propertiesForValues)
                        {
                            IsValueType &= propertiesForValue.GetCustomAttribute <EdiValueAttribute>() != null;
                        }

                        if (!IsValueType)
                        {
                            object newObject = Edi850Deserialize.DeserializeInternal(readToEndLines, GenericArgument);
                            list.Add(newObject);
                        }
                        else
                        {
                            foreach (PropertyInfo propertiesForValue in propertiesForValues)
                            {
                                if (readToEndLines.Length > 0)
                                {
                                    EdiValueAttribute EdiValueAttributeValue = propertiesForValue.GetCustomAttribute <EdiValueAttribute>();
                                    string[]          ValueResults           = readToEndLines.Where(x => x.Contains(EdiValueAttributeValue.Path)).ToArray();
                                    foreach (string ValueResult in ValueResults)
                                    {
                                        object newObject = Edi850Deserialize.DeserializeInternal(new[] { ValueResult }, GenericArgument);
                                        list.Add(newObject);
                                        readToEndLines = readToEndLines.Where(w => w != ValueResult).ToArray();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (string[] items in bloks)
                        {
                            if (items[0].StartsWith(eEdiSegmentAttribute.Path))
                            {
                                object newObject = Edi850Deserialize.DeserializeInternal(items, GenericArgument);
                                list.Add(newObject);
                            }
                        }
                    }
                    propertyInfo.SetValue(dataObject, list, null);
                }
            }
            return(readToEndLines);
        }
        public void Init(ObjectCheckers objCheckers, ObjectCasters objCasters)
        {
            if ((typeof(Delegate) != targetType && typeof(Delegate).IsAssignableFrom(targetType)) ||
                !method.IsStatic || method.IsConstructor)
            {
                luaStackPosStart = 2;
                if (!method.IsConstructor)
                {
                    targetNeeded = true;
                }
            }

            var paramInfos = method.GetParameters();

            refPos = new int[paramInfos.Length];

            List <int> inPosList  = new List <int>();
            List <int> outPosList = new List <int>();

            List <ObjectCheck> paramsChecks     = new List <ObjectCheck>();
            List <ObjectCast>  paramsCasts      = new List <ObjectCast>();
            List <bool>        isOptionalList   = new List <bool>();
            List <object>      defaultValueList = new List <object>();

            for (int i = 0; i < paramInfos.Length; i++)
            {
                refPos[i] = -1;
                if (!paramInfos[i].IsIn && paramInfos[i].IsOut)  // out parameter
                {
                    outPosList.Add(i);
                }
                else
                {
                    if (paramInfos[i].ParameterType.IsByRef)
                    {
                        var ttype = paramInfos[i].ParameterType.GetElementType();
                        if (CopyByValue.IsStruct(ttype) && ttype != typeof(decimal))
                        {
                            refPos[i] = inPosList.Count;
                        }
                        outPosList.Add(i);
                    }

                    inPosList.Add(i);
                    var paramType = paramInfos[i].IsDefined(typeof(ParamArrayAttribute), false) || (!paramInfos[i].ParameterType.IsArray && paramInfos[i].ParameterType.IsByRef) ?
                                    paramInfos[i].ParameterType.GetElementType() : paramInfos[i].ParameterType;
                    paramsChecks.Add(objCheckers.GetChecker(paramType));
                    paramsCasts.Add(objCasters.GetCaster(paramType));
                    isOptionalList.Add(paramInfos[i].IsOptional);
                    var defalutValue = paramInfos[i].DefaultValue;
                    if (paramInfos[i].IsOptional)
                    {
                        if (defalutValue != null && defalutValue.GetType() != paramInfos[i].ParameterType)
                        {
                            defalutValue = defalutValue.GetType() == typeof(Missing) ? (paramInfos[i].ParameterType.IsValueType() ? Activator.CreateInstance(paramInfos[i].ParameterType) : Missing.Value)
                                : Convert.ChangeType(defalutValue, paramInfos[i].ParameterType);
                        }
                        HasDefalutValue = true;
                    }
                    defaultValueList.Add(paramInfos[i].IsOptional ? defalutValue : null);
                }
            }
            checkArray        = paramsChecks.ToArray();
            castArray         = paramsCasts.ToArray();
            inPosArray        = inPosList.ToArray();
            outPosArray       = outPosList.ToArray();
            isOptionalArray   = isOptionalList.ToArray();
            defaultValueArray = defaultValueList.ToArray();

            if (paramInfos.Length > 0 && paramInfos[paramInfos.Length - 1].IsDefined(typeof(ParamArrayAttribute), false))
            {
                paramsType = paramInfos[paramInfos.Length - 1].ParameterType.GetElementType();
            }

            args = new object[paramInfos.Length];

            if (method is MethodInfo) //constructor is not MethodInfo?
            {
                isVoid = (method as MethodInfo).ReturnType == typeof(void);
            }
            else if (method is ConstructorInfo)
            {
                isVoid = false;
            }
        }
Пример #45
0
        private static void Game_OnGameLoad(EventArgs args)
        {
            Config = new Menu("Marksman", "Marksman", true);
            CClass = new Champion();
            AActivator = new Activator();

            var BaseType = CClass.GetType();

            /* Update this with Activator.CreateInstance or Invoke
               http://stackoverflow.com/questions/801070/dynamically-invoking-any-function-by-passing-function-name-as-string
               For now stays cancer.
             */
            var championName = ObjectManager.Player.ChampionName.ToLowerInvariant();

            switch (championName)
            {
                case "ashe":
                    CClass = new Ashe();
                    break;
                case "caitlyn":
                    CClass = new Caitlyn();
                    break;
                case "corki":
                    CClass = new Corki();
                    break;
                case "draven":
                    CClass = new Draven();
                    break;
                case "ezreal":
                    CClass = new Ezreal();
                    break;
                case "graves":
                    CClass = new Graves();
                    break;
                case "jinx":
                    CClass = new Jinx();
                    break;
                case "kogmaw":
                    CClass = new Kogmaw();
                    break;
                case "lucian":
                    CClass = new Lucian();
                    break;
                case "missfortune":
                    CClass = new MissFortune();
                    break;
                case "quinn":
                    CClass = new Quinn();
                    break;
                case "sivir":
                    CClass = new Sivir();
                    break;
                case "teemo":
                    CClass = new Teemo();
                    break;
                case "tristana":
                    CClass = new Tristana();
                    break;
                case "twitch":
                    CClass = new Twitch();
                    break;
                case "vayne":
                    CClass = new Vayne();
                    break;
                case "varus":
                    CClass = new Varus();
                    break;
            }

            CClass.Id = ObjectManager.Player.BaseSkinName;
            CClass.Config = Config;

            var targetSelectorMenu = new Menu("鐩爣閫夋嫨", "Target Selector");
            SimpleTs.AddToMenu(targetSelectorMenu);
            Config.AddSubMenu(targetSelectorMenu);

            var orbwalking = Config.AddSubMenu(new Menu("璧扮爫", "Orbwalking"));
            CClass.Orbwalker = new Orbwalking.Orbwalker(orbwalking);

            var items = Config.AddSubMenu(new Menu("鐗╁搧", "Items"));
            items.AddItem(new MenuItem("BOTRK", "鐮磋触").SetValue(true));
            items.AddItem(new MenuItem("GHOSTBLADE", "灏忓集鍒€").SetValue(true));
            QuickSilverMenu = new Menu("姘撮摱鑵板甫", "QuickSilverSash");
            items.AddSubMenu(QuickSilverMenu);
            QuickSilverMenu.AddItem(new MenuItem("AnyStun", "鐪╂檿").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnySnare", "澶瑰瓙").SetValue(true));
            QuickSilverMenu.AddItem(new MenuItem("AnyTaunt", "鍢茶").SetValue(true));
            foreach (var t in AActivator.BuffList)
            {
                foreach (var enemy in ObjectManager.Get<Obj_AI_Hero>().Where(enemy => enemy.IsEnemy))
                {
                    if (t.ChampionName == enemy.ChampionName)
                        QuickSilverMenu.AddItem(new MenuItem(t.BuffName, t.DisplayName).SetValue(t.DefaultValue));
                }
            }
            items.AddItem(
                new MenuItem("UseItemsMode", "浣跨敤鐗╁搧").SetValue(
                    new StringList(new[] {"no", "娣峰悎", "杩炴嫑", "鍏ㄩ儴"}, 2)));

            //var Extras = Config.AddSubMenu(new Menu("Extras", "Extras"));
            //new PotionManager(Extras);

            // If Champion is supported draw the extra menus
            if (BaseType != CClass.GetType())
            {
                var combo = new Menu("杩炴嫑", "Combo");
                if (CClass.ComboMenu(combo))
                {
                    Config.AddSubMenu(combo);
                }

                var harass = new Menu("楠氭壈", "Harass");
                if (CClass.HarassMenu(harass))
                {
                    harass.AddItem(new MenuItem("HarassMana", "min钃濋噺%").SetValue(new Slider(50, 100, 0)));
                    Config.AddSubMenu(harass);
                }

                var laneclear = new Menu("娓呯嚎", "LaneClear");
                if (CClass.LaneClearMenu(laneclear))
                {
                    Config.AddSubMenu(laneclear);
                }

                var misc = new Menu("鏉傞」", "Misc");
                if (CClass.MiscMenu(misc))
                {
                    Config.AddSubMenu(misc);
                }

                var extras = new Menu("闄勫姞", "Extras");
                if (CClass.ExtrasMenu(extras))
                {
                    new PotionManager(extras);
                    Config.AddSubMenu(extras);
                }

                var drawing = new Menu("鏄剧ず", "Drawings");
                if (CClass.DrawingMenu(drawing))
                {
                    Config.AddSubMenu(drawing);
                }

                Config.AddSubMenu(new Menu("L#涓枃绀惧尯", "guanggao"));
                Config.SubMenu("guanggao").AddItem(new MenuItem("wangzhan", "www.loll35.com"));
                Config.SubMenu("guanggao").AddItem(new MenuItem("qunhao", "姹夊寲缇わ細397983217"));
            }

            CClass.MainMenu(Config);

            Config.AddToMainMenu();

            Drawing.OnDraw += Drawing_OnDraw;
            Game.OnGameUpdate += Game_OnGameUpdate;
            Orbwalking.AfterAttack += Orbwalking_AfterAttack;
            Orbwalking.BeforeAttack += Orbwalking_BeforeAttack;
        }
        public void Execute(GeneratorExecutionContext context)
        {
            var compilation = context.Compilation as CSharpCompilation;
            if (compilation == null)
            {
                context.ReportDiagnostic(
                    Diagnostic.Create(
                        DescriptorParameterError,
                        Location.None,
                        "incompatible language: " + context.Compilation.Language));

                return;
            }

            try
            {
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + "ServiceUrl", out var serviceUrl);
                var isServiceUrlMissing = String.IsNullOrWhiteSpace(serviceUrl);
                var graphQlSchemaFiles = context.AdditionalFiles.Where(f => String.Equals(Path.GetExtension(f.Path), ".json", StringComparison.OrdinalIgnoreCase)).ToList();
                var indexRegexScalarFieldTypeMappingProviderConfigurationFile =
                    graphQlSchemaFiles.FindIndex(f => String.Equals(Path.GetFileName(f.Path), FileNameRegexScalarFieldTypeMappingProviderConfiguration, StringComparison.OrdinalIgnoreCase));

                ICollection<RegexScalarFieldTypeMappingRule> regexScalarFieldTypeMappingProviderRules = null;
                if (indexRegexScalarFieldTypeMappingProviderConfigurationFile != -1)
                {
                    regexScalarFieldTypeMappingProviderRules =
                        JsonConvert.DeserializeObject<ICollection<RegexScalarFieldTypeMappingRule>>(
                            graphQlSchemaFiles[indexRegexScalarFieldTypeMappingProviderConfigurationFile].GetText().ToString());

                    graphQlSchemaFiles.RemoveAt(indexRegexScalarFieldTypeMappingProviderConfigurationFile);
                }

                var isSchemaFileSpecified = graphQlSchemaFiles.Any();
                if (isServiceUrlMissing && !isSchemaFileSpecified)
                {
                    context.ReportDiagnostic(
                        Diagnostic.Create(
                            DescriptorInfo,
                            Location.None,
                            "Neither \"GraphQlClientGenerator_ServiceUrl\" parameter nor GraphQL JSON schema additional file specified; terminating. "));

                    return;
                }

                if (!isServiceUrlMissing && isSchemaFileSpecified)
                {
                    context.ReportDiagnostic(
                        Diagnostic.Create(
                            DescriptorParameterError,
                            Location.None,
                            "\"GraphQlClientGenerator_ServiceUrl\" parameter and GraphQL JSON schema additional file are mutually exclusive. "));

                    return;
                }

                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + "Namespace", out var @namespace);
                if (String.IsNullOrWhiteSpace(@namespace))
                {
                    var root = (CompilationUnitSyntax)compilation.SyntaxTrees.FirstOrDefault()?.GetRoot();
                    var namespaceIdentifier = (IdentifierNameSyntax)root?.Members.OfType<NamespaceDeclarationSyntax>().FirstOrDefault()?.Name;
                    if (namespaceIdentifier == null)
                    {
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                DescriptorParameterError,
                                Location.None,
                                "\"GraphQlClientGenerator_Namespace\" required"));

                        return;
                    }

                    @namespace = namespaceIdentifier.Identifier.ValueText;

                    context.ReportDiagnostic(
                        Diagnostic.Create(
                            DescriptorInfo,
                            Location.None,
                            $"\"GraphQlClientGenerator_Namespace\" not specified; using \"{@namespace}\""));
                }

                var configuration = new GraphQlGeneratorConfiguration { TreatUnknownObjectAsScalar = true };

                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + "ClassPrefix", out var classPrefix);
                configuration.ClassPrefix = classPrefix;

                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + "ClassSuffix", out var classSuffix);
                configuration.ClassSuffix = classSuffix;

                if (compilation.LanguageVersion >= LanguageVersion.CSharp6)
                    configuration.CSharpVersion =
                        compilation.Options.NullableContextOptions == NullableContextOptions.Disable
                            ? CSharpVersion.Newest
                            : CSharpVersion.NewestWithNullableReferences;

                var currentParameterName = "IncludeDeprecatedFields";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var includeDeprecatedFieldsRaw);
                configuration.IncludeDeprecatedFields = !String.IsNullOrWhiteSpace(includeDeprecatedFieldsRaw) && Convert.ToBoolean(includeDeprecatedFieldsRaw);

                currentParameterName = "CommentGeneration";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var commentGenerationRaw);
                configuration.CommentGeneration =
                    String.IsNullOrWhiteSpace(commentGenerationRaw)
                        ? CommentGenerationOption.CodeSummary
                        : (CommentGenerationOption)Enum.Parse(typeof(CommentGenerationOption), commentGenerationRaw, true);

                currentParameterName = "FloatTypeMapping";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var floatTypeMappingRaw);
                configuration.FloatTypeMapping =
                    String.IsNullOrWhiteSpace(floatTypeMappingRaw)
                        ? FloatTypeMapping.Decimal
                        : (FloatTypeMapping)Enum.Parse(typeof(FloatTypeMapping), floatTypeMappingRaw, true);

                currentParameterName = "BooleanTypeMapping";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var booleanTypeMappingRaw);
                configuration.BooleanTypeMapping =
                    String.IsNullOrWhiteSpace(booleanTypeMappingRaw)
                        ? BooleanTypeMapping.Boolean
                        : (BooleanTypeMapping)Enum.Parse(typeof(BooleanTypeMapping), booleanTypeMappingRaw, true);

                currentParameterName = "IdTypeMapping";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var idTypeMappingRaw);
                configuration.IdTypeMapping =
                    String.IsNullOrWhiteSpace(idTypeMappingRaw)
                        ? IdTypeMapping.Guid
                        : (IdTypeMapping)Enum.Parse(typeof(IdTypeMapping), idTypeMappingRaw, true);

                currentParameterName = "JsonPropertyGeneration";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var jsonPropertyGenerationRaw);
                configuration.JsonPropertyGeneration =
                    String.IsNullOrWhiteSpace(jsonPropertyGenerationRaw)
                        ? JsonPropertyGenerationOption.CaseInsensitive
                        : (JsonPropertyGenerationOption)Enum.Parse(typeof(JsonPropertyGenerationOption), jsonPropertyGenerationRaw, true);

                currentParameterName = "CustomClassMapping";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var customClassMappingRaw);
                if (!KeyValueParameterParser.TryGetCustomClassMapping(
                    customClassMappingRaw?.Split(new[] { '|', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries),
                    out var customMapping,
                    out var customMappingParsingErrorMessage))
                {
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorParameterError, Location.None, customMappingParsingErrorMessage));
                    return;
                }

                foreach (var kvp in customMapping)
                    configuration.CustomClassNameMapping.Add(kvp);

                currentParameterName = "Headers";
                context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var headersRaw);
                if (!KeyValueParameterParser.TryGetCustomHeaders(
                    headersRaw?.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries),
                    out var headers,
                    out var headerParsingErrorMessage))
                {
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorParameterError, Location.None, headerParsingErrorMessage));
                    return;
                }

                currentParameterName = "ScalarFieldTypeMappingProvider";
                if (context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(BuildPropertyKeyPrefix + currentParameterName, out var scalarFieldTypeMappingProviderName))
                {
                    if (regexScalarFieldTypeMappingProviderRules != null)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DescriptorParameterError, Location.None, "\"GraphQlClientGenerator_ScalarFieldTypeMappingProvider\" and RegexScalarFieldTypeMappingProviderConfiguration are mutually exclusive"));
                        return;
                    }

                    if (String.IsNullOrWhiteSpace(scalarFieldTypeMappingProviderName))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DescriptorParameterError, Location.None, "\"GraphQlClientGenerator_ScalarFieldTypeMappingProvider\" value missing"));
                        return;
                    }

                    var scalarFieldTypeMappingProviderType = Type.GetType(scalarFieldTypeMappingProviderName);
                    if (scalarFieldTypeMappingProviderType == null)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DescriptorParameterError, Location.None, $"ScalarFieldTypeMappingProvider \"{scalarFieldTypeMappingProviderName}\" not found"));
                        return;
                    }

                    var scalarFieldTypeMappingProvider = (IScalarFieldTypeMappingProvider)Activator.CreateInstance(scalarFieldTypeMappingProviderType);
                    configuration.ScalarFieldTypeMappingProvider = scalarFieldTypeMappingProvider;
                }
                else if (regexScalarFieldTypeMappingProviderRules?.Count > 0)
                    configuration.ScalarFieldTypeMappingProvider = new RegexScalarFieldTypeMappingProvider(regexScalarFieldTypeMappingProviderRules);

                var graphQlSchemas = new List<(string TargetFileName, GraphQlSchema Schema)>();
                if (isSchemaFileSpecified)
                {
                    foreach (var schemaFile in graphQlSchemaFiles)
                    {
                        var targetFileName = Path.GetFileNameWithoutExtension(schemaFile.Path) + ".cs";
                        graphQlSchemas.Add((targetFileName, GraphQlGenerator.DeserializeGraphQlSchema(schemaFile.GetText().ToString())));
                    }
                }
                else
                {
                    graphQlSchemas.Add((FileNameGraphQlClientSource, GraphQlGenerator.RetrieveSchema(serviceUrl, headers).GetAwaiter().GetResult()));
                    context.ReportDiagnostic(
                        Diagnostic.Create(
                            DescriptorInfo,
                            Location.None,
                            "GraphQl schema fetched successfully from " + serviceUrl));
                }

                var generator = new GraphQlGenerator(configuration);

                foreach (var (targetFileName, schema) in graphQlSchemas)
                {
                    var builder = new StringBuilder();
                    using (var writer = new StringWriter(builder))
                        generator.WriteFullClientCSharpFile(schema, @namespace, writer);

                    context.AddSource(targetFileName, SourceText.From(builder.ToString(), Encoding.UTF8));
                }

                context.ReportDiagnostic(
                    Diagnostic.Create(
                        DescriptorInfo,
                        Location.None,
                        "GraphQlClientGenerator task completed successfully. "));
            }
            catch (Exception exception)
            {
                context.ReportDiagnostic(Diagnostic.Create(DescriptorGenerationError, Location.None, exception.Message));
            }
        }
Пример #47
-1
		private static void Game_OnGameLoad(EventArgs args)
		{
			AutoUpdater.InitializeUpdater();

            Helper = new Helper();

			Menu = new Menu("UltimateCarry", "UltimateCarry_" + ObjectManager.Player.ChampionName, true);

			var targetSelectorMenu = new Menu("Target Selector", "TargetSelector");
			SimpleTs.AddToMenu(targetSelectorMenu);
			Menu.AddSubMenu(targetSelectorMenu);
			var orbwalking = Menu.AddSubMenu(new Menu("Orbwalking", "Orbwalking"));
			Orbwalker = new Orbwalking.Orbwalker(orbwalking);

			//var overlay = new Overlay();
			var potionManager = new PotionManager();
			var activator = new Activator();
            var bushRevealer = new AutoBushRevealer();

            new BaseUlt();
		
			try
			{
				var handle = System.Activator.CreateInstance(null, "UltimateCarry." + ObjectManager.Player.ChampionName);
				Champion = (Champion) handle.Unwrap();
			}
			catch (Exception)
			{
				//Champion = new Champion(); //Champ not supported
			}
					
			Menu.AddToMainMenu();
		}