public void ShouldReturnNullIfNoItemFound(ResolvePathCommand sut, string path)
 {
     sut.Initialize(path);
     ReflectionUtil.CallMethod(sut, "DoExecute").Should().BeNull();
 }
示例#2
0
        public override IEnumerable <Processor> CreateProcessors(ProcessorArgs args)
        {
            var hive = (ProcessorHive)ReflectionUtil.CreateObject(this.Type);

            return(hive.CreateProcessors(args));
        }
示例#3
0
        public ActionResult RunAgent(string type)
        {
            try
            {
                Job.Total = 1;

                if (string.IsNullOrEmpty(type))
                {
                    return
                        (base.Json(
                             new
                    {
                        Status = "Error",
                        Success = false,
                        Message = Translate.Text("Oops! System error, please try again")
                    },
                             JsonRequestBehavior.AllowGet));
                }
                XmlNode agentNode = GetAgentNode(type);
                if (agentNode == null)
                {
                    return
                        (base.Json(
                             new
                    {
                        Status = "Error",
                        Success = false,
                        Message = Translate.Text("Oops! System error, please try again")
                    },
                             JsonRequestBehavior.AllowGet));
                }
                Job.AddMessage("Running {0}", new object[] { agentNode.Attributes["type"] });
                object obj2       = ReflectionUtil.CreateObject(agentNode);
                string methodName = agentNode.Attributes["method"].Value;
                if (obj2 != null)
                {
                    MethodInfo method = ReflectionUtil.GetMethod(obj2.GetType(), methodName, true, true, true,
                                                                 new object[0]);
                    if (method != null)
                    {
                        ReflectionUtil.InvokeMethod(method, new object[0], obj2);
                    }
                }
                Job.Processed += 1;
                return(Json(
                           new { Status = "Success", Success = true, Message = Translate.Text("Sucessfully executed!") },
                           JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Log.Error("could not run agent", ex, this);
                return
                    (base.Json(
                         new
                {
                    Status = "Error",
                    Success = false,
                    Message = Translate.Text("Oops! System error, please try again")
                },
                         JsonRequestBehavior.AllowGet));
            }
        }
        void Init()
        {
            GameObject textObj = new GameObject("MultiGMPDisplayText");

            chargeText           = textObj.AddComponent <TextMeshPro>();
            chargeText.text      = "Charging...";
            chargeText.alignment = TextAlignmentOptions.Center;
            chargeText.fontSize  = 3;
            chargeText.color     = Color.white;
            chargeText.font      = Resources.Load <TMP_FontAsset>("Teko-Medium SDF No Glow");
            chargeText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 2f);
            chargeText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 2f);
            if (Plugin.ChatConfig.uiOnTop)
            {
                chargeText.rectTransform.position = new Vector3(0f, 3f, 7f);
                textObj.transform.localScale     *= 1.5f;
            }

            else
            {
                chargeText.rectTransform.position = new Vector3(0f, -1f, 7f);
                textObj.transform.localScale     *= 2.0f;
            }


            var counterImage = ReflectionUtil.GetPrivateField <Image>(
                Resources.FindObjectsOfTypeAll <ScoreMultiplierUIController>().First(), "_multiplierProgressImage");

            GameObject canvasobj = new GameObject("MultiGMPDisplayCanvas");
            Canvas     canvas    = canvasobj.AddComponent <Canvas>();

            canvas.renderMode = RenderMode.WorldSpace;
            CanvasScaler cs = canvasobj.AddComponent <CanvasScaler>();

            cs.scaleFactor          = 10.0f;
            cs.dynamicPixelsPerUnit = 10f;
            GraphicRaycaster gr = canvasobj.AddComponent <GraphicRaycaster>();

            canvasobj.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 1f);
            canvasobj.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 1f);

            GameObject counter = new GameObject("MultiGMPDisplayCounter");

            chargeCounter            = counter.AddComponent <Image>();
            counter.transform.parent = canvasobj.transform;
            counter.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 0.5f);
            counter.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0.5f);
            counter.transform.localScale = new Vector3(1f, 1f, 1f);

            chargeCounter.sprite        = counterImage.sprite;
            chargeCounter.type          = Image.Type.Filled;
            chargeCounter.fillMethod    = Image.FillMethod.Radial360;
            chargeCounter.fillOrigin    = (int)Image.Origin360.Top;
            chargeCounter.fillClockwise = true;
            chargeCounter.fillAmount    = Plugin.charges / MultiMain.Config.maxCharges;
            chargeCounter.color         = Color.green;

            GameObject background = new GameObject("MultiGMPDisplayBackGround");
            var        bg         = background.AddComponent <Image>();

            background.transform.parent = canvasobj.transform;
            background.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 0.5f);
            background.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0.5f);
            background.transform.localScale = new Vector3(1f, 1f, 1f);

            bg.sprite = counterImage.sprite;
            bg.CrossFadeAlpha(0.05f, 1f, false);

            canvasobj.GetComponent <RectTransform>().SetParent(textObj.transform, false);
            canvasobj.transform.localPosition = new Vector3(0f, -.4f, 0f);

            chargeCountText           = new GameObject("MultiGMPDisplayChargeCount").AddComponent <TextMeshPro>();
            chargeCountText.text      = Plugin.charges.ToString();
            chargeCountText.alignment = TextAlignmentOptions.Center;
            chargeCountText.fontSize  = 2.5f;
            chargeCountText.color     = Color.white;
            chargeCountText.font      = Resources.Load <TMP_FontAsset>("Teko-Medium SDF No Glow");
            chargeCountText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 1f);
            chargeCountText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 1f);
            chargeCountText.GetComponent <RectTransform>().SetParent(textObj.transform, false);
            chargeCountText.transform.localPosition = new Vector3(0f, -.43f, 0f);

            cooldownText           = new GameObject("MultiGMPDisplayCoolDown").AddComponent <TextMeshPro>();
            cooldownText.text      = "";
            cooldownText.alignment = TextAlignmentOptions.MidlineRight;
            cooldownText.fontSize  = 2.5f;
            cooldownText.color     = Color.red;
            cooldownText.font      = Resources.Load <TMP_FontAsset>("Teko-Medium SDF No Glow");
            cooldownText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 10f);
            cooldownText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 1f);
            cooldownText.GetComponent <RectTransform>().SetParent(textObj.transform, false);
            cooldownText.transform.localPosition = new Vector3(-5.4f, -.43f, 0f);

            activeCommandText           = new GameObject("MultiGMPDisplayActiveCommands").AddComponent <TextMeshPro>();
            activeCommandText.text      = "";
            activeCommandText.alignment = TextAlignmentOptions.MidlineLeft;
            activeCommandText.fontSize  = 2.5f;
            activeCommandText.color     = Color.yellow;
            activeCommandText.font      = Resources.Load <TMP_FontAsset>("Teko-Medium SDF No Glow");
            activeCommandText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 10f);
            activeCommandText.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 1f);
            activeCommandText.GetComponent <RectTransform>().SetParent(textObj.transform, false);
            activeCommandText.transform.localPosition = new Vector3(5.4f, -.43f, 0f);
        }
示例#5
0
        private void SetupTweaks()
        {
            _mainFlowCoordinator = FindObjectOfType <MainFlowCoordinator>();
            _mainFlowCoordinator.GetPrivateField <MainMenuViewController>("_mainMenuViewController").didFinishEvent += SongListTweaks_didFinishEvent;

            RectTransform viewControllersContainer = FindObjectsOfType <RectTransform>().First(x => x.name == "ViewControllers");

            if (initialized || PluginConfig.disableSongListTweaks)
            {
                return;
            }

            Logger.Log("Setting up song list tweaks...");

            try
            {
                var harmony = HarmonyInstance.Create("BeatSaverDownloaderHarmonyInstance");
                harmony.PatchAll(Assembly.GetExecutingAssembly());
            }
            catch (Exception e)
            {
                Logger.Log("Unable to patch level list! Exception: " + e);
            }

            _playlistsFlowCoordinator = new GameObject("PlaylistsFlowCoordinator").AddComponent <PlaylistsFlowCoordinator>();
            _playlistsFlowCoordinator.didFinishEvent += _playlistsFlowCoordinator_didFinishEvent;

            if (SongLoader.AreSongsLoaded)
            {
                _levelCollection = SongLoader.CustomLevelCollectionSO;
            }
            else
            {
                SongLoader.SongsLoadedEvent += (SongLoader sender, List <CustomLevel> levels) =>
                {
                    _levelCollection = SongLoader.CustomLevelCollectionSO;
                };
            }

            _simpleDialog = ReflectionUtil.GetPrivateField <SimpleDialogPromptViewController>(_mainFlowCoordinator, "_simpleDialogPromptViewController");
            _simpleDialog = Instantiate(_simpleDialog.gameObject, _simpleDialog.transform.parent).GetComponent <SimpleDialogPromptViewController>();

            _levelListViewController = viewControllersContainer.GetComponentInChildren <LevelPackLevelsViewController>(true);
            _levelListViewController.didSelectLevelEvent += _levelListViewController_didSelectLevelEvent;

            _levelPacksViewController = viewControllersContainer.GetComponentInChildren <LevelPacksViewController>(true);
            _levelPacksViewController.didSelectPackEvent += _levelPacksViewController_didSelectPackEvent;

            TableView     _songSelectionTableView = _levelListViewController.GetComponentsInChildren <TableView>(true).First();
            RectTransform _tableViewRectTransform = _levelListViewController.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "LevelsTableView");

            _tableViewRectTransform.sizeDelta        = new Vector2(0f, -20.5f);
            _tableViewRectTransform.anchoredPosition = new Vector2(0f, -2.5f);

            Button _pageUp = _tableViewRectTransform.GetComponentsInChildren <Button>(true).First(x => x.name == "PageUpButton");

            (_pageUp.transform as RectTransform).anchoredPosition = new Vector2(0f, -1f);

            Button _pageDown = _tableViewRectTransform.GetComponentsInChildren <Button>(true).First(x => x.name == "PageDownButton");

            (_pageDown.transform as RectTransform).anchoredPosition = new Vector2(0f, 1f);

            _fastPageUpButton = Instantiate(_pageUp, _tableViewRectTransform, false);
            (_fastPageUpButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 1f);
            (_fastPageUpButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 1f);
            (_fastPageUpButton.transform as RectTransform).anchoredPosition = new Vector2(-26f, 1f);
            (_fastPageUpButton.transform as RectTransform).sizeDelta        = new Vector2(8f, 6f);
            _fastPageUpButton.GetComponentsInChildren <RectTransform>().First(x => x.name == "BG").sizeDelta        = new Vector2(8f, 6f);
            _fastPageUpButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Arrow").sprite = Sprites.DoubleArrow;
            _fastPageUpButton.onClick.AddListener(delegate()
            {
                FastScrollUp(_songSelectionTableView, PluginConfig.fastScrollSpeed);
            });

            _fastPageDownButton = Instantiate(_pageDown, _tableViewRectTransform, false);
            (_fastPageDownButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0f);
            (_fastPageDownButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0f);
            (_fastPageDownButton.transform as RectTransform).anchoredPosition = new Vector2(-26f, -1f);
            (_fastPageDownButton.transform as RectTransform).sizeDelta        = new Vector2(8f, 6f);
            _fastPageDownButton.GetComponentsInChildren <RectTransform>().First(x => x.name == "BG").sizeDelta        = new Vector2(8f, 6f);
            _fastPageDownButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Arrow").sprite = Sprites.DoubleArrow;
            _fastPageDownButton.onClick.AddListener(delegate()
            {
                FastScrollDown(_songSelectionTableView, PluginConfig.fastScrollSpeed);
            });

            _randomButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), _levelListViewController.rectTransform, false);
            _randomButton.onClick = new Button.ButtonClickedEvent();
            _randomButton.onClick.AddListener(() =>
            {
                int randomRow = UnityEngine.Random.Range(0, _songSelectionTableView.dataSource.NumberOfCells());
                _songSelectionTableView.ScrollToCellWithIdx(randomRow, TableView.ScrollPositionType.Beginning, false);
                _songSelectionTableView.SelectCellWithIdx(randomRow, true);
            });
            _randomButton.name = "CustomUIButton";

            (_randomButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
            (_randomButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
            (_randomButton.transform as RectTransform).anchoredPosition = new Vector2(35f, 36.25f);
            (_randomButton.transform as RectTransform).sizeDelta        = new Vector2(8.8f, 6f);

            _randomButton.SetButtonText("");
            _randomButton.SetButtonIcon(Sprites.RandomIcon);
            _randomButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Stroke").sprite = Resources.FindObjectsOfTypeAll <Sprite>().First(x => x.name == "RoundRectSmallStroke");

            var _randomIconLayout = _randomButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _randomIconLayout.padding = new RectOffset(0, 0, 0, 0);

            _searchButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), SearchPressed, "Search");
            _searchButton.SetButtonTextSize(3f);
            _searchButton.ToggleWordWrapping(false);

            _sortByButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.SortBy);
            }, "Sort By");
            _sortByButton.SetButtonTextSize(3f);
            _sortByButton.ToggleWordWrapping(false);

            _playlistsButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), PlaylistsButtonPressed, "Playlists");
            _playlistsButton.SetButtonTextSize(3f);
            _playlistsButton.ToggleWordWrapping(false);

            _defButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Default, "");
            },
                                                                 "Default");

            _defButton.SetButtonTextSize(3f);
            _defButton.ToggleWordWrapping(false);
            _defButton.gameObject.SetActive(false);

            _newButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Newest, "");
            }, "Newest");

            _newButton.SetButtonTextSize(3f);
            _newButton.ToggleWordWrapping(false);
            _newButton.gameObject.SetActive(false);


            _difficultyButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Difficulty, "");
            }, "Difficulty");

            _difficultyButton.SetButtonTextSize(3f);
            _difficultyButton.ToggleWordWrapping(false);
            _difficultyButton.gameObject.SetActive(false);

            _detailViewController = viewControllersContainer.GetComponentsInChildren <StandardLevelDetailViewController>(true).First(x => x.name == "LevelDetailViewController");
            _detailViewController.didChangeDifficultyBeatmapEvent += _difficultyViewController_didSelectDifficultyEvent;

            RectTransform buttonsRect = _detailViewController.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PlayButtons");

            _favoriteButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), buttonsRect, false);
            _favoriteButton.onClick = new Button.ButtonClickedEvent();
            _favoriteButton.onClick.AddListener(() =>
            {
                if (PluginConfig.favoriteSongs.Any(x => x.Contains(_detailViewController.selectedDifficultyBeatmap.level.levelID)))
                {
                    PluginConfig.favoriteSongs.Remove(_detailViewController.selectedDifficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Sprites.AddToFavorites);
                    PlaylistsCollection.RemoveLevelFromPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), _detailViewController.selectedDifficultyBeatmap.level.levelID);
                }
                else
                {
                    PluginConfig.favoriteSongs.Add(_detailViewController.selectedDifficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Sprites.RemoveFromFavorites);
                    PlaylistsCollection.AddSongToPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), new PlaylistSong()
                    {
                        levelId = _detailViewController.selectedDifficultyBeatmap.level.levelID, songName = _detailViewController.selectedDifficultyBeatmap.level.songName, level = SongDownloader.GetLevel(_detailViewController.selectedDifficultyBeatmap.level.levelID)
                    });
                }
            });
            _favoriteButton.name = "CustomUIButton";
            _favoriteButton.SetButtonIcon(Sprites.AddToFavorites);
            (_favoriteButton.transform as RectTransform).sizeDelta = new Vector2(12f, 8.8f);
            var _favoriteIconLayout = _favoriteButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _favoriteIconLayout.padding = new RectOffset(3, 3, 0, 0);
            _favoriteButton.transform.SetAsFirstSibling();

            Button practiceButton = buttonsRect.GetComponentsInChildren <Button>().First(x => x.name == "PracticeButton");

            (practiceButton.transform as RectTransform).sizeDelta = new Vector2(12f, 8.8f);
            var _practiceIconLayout = practiceButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _practiceIconLayout.padding = new RectOffset(3, 3, 0, 0);

            _deleteButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), buttonsRect, false);
            _deleteButton.onClick = new Button.ButtonClickedEvent();
            _deleteButton.onClick.AddListener(DeletePressed);
            _deleteButton.name = "CustomUIButton";
            _deleteButton.SetButtonIcon(Sprites.DeleteIcon);
            _deleteButton.interactable = !PluginConfig.disableDeleteButton;
            (_deleteButton.transform as RectTransform).sizeDelta = new Vector2(8.8f, 8.8f);
            _deleteButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Stroke").sprite = Resources.FindObjectsOfTypeAll <Sprite>().First(x => x.name == "RoundRectSmallStroke");

            var _deleteIconLayout = _deleteButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _deleteIconLayout.padding = new RectOffset(0, 0, 1, 1);

            _deleteButton.transform.SetAsLastSibling();

            //based on https://github.com/halsafar/BeatSaberSongBrowser/blob/master/SongBrowserPlugin/UI/Browser/SongBrowserUI.cs#L192
            var statsPanel     = _detailViewController.GetComponentsInChildren <LevelParamsPanel>(true).First(x => x.name == "LevelParamsPanel");
            var statTransforms = statsPanel.GetComponentsInChildren <RectTransform>(true);
            var valueTexts     = statsPanel.GetComponentsInChildren <TextMeshProUGUI>(true).Where(x => x.name == "ValueText").ToList();

            foreach (RectTransform r in statTransforms)
            {
                if (r.name == "Separator")
                {
                    continue;
                }
                r.sizeDelta = new Vector2(r.sizeDelta.x * 0.85f, r.sizeDelta.y * 0.85f);
            }

            var _starStatTransform = Instantiate(statTransforms[1], statsPanel.transform, false);

            _starStatText = _starStatTransform.GetComponentInChildren <TextMeshProUGUI>(true);
            _starStatTransform.GetComponentInChildren <UnityEngine.UI.Image>(true).sprite = Sprites.StarFull;
            _starStatText.text = "--";

            ResultsViewController _standardLevelResultsViewController = viewControllersContainer.GetComponentsInChildren <ResultsViewController>(true).First(x => x.name == "StandardLevelResultsViewController");

            _standardLevelResultsViewController.continueButtonPressedEvent += _standardLevelResultsViewController_continueButtonPressedEvent;

            initialized = true;
        }
示例#6
0
 public static void Reset()
 {
     ReflectionUtil.ResetStaticFields(typeof(BPD));
 }
示例#7
0
 public void ShouldCreateInstance(AddVersionCommandProtoype sut, DataStorageSwitcher switcher)
 {
     ReflectionUtil.CallMethod(sut, "CreateInstance").Should().BeOfType <AddVersionCommand>();
 }
示例#8
0
        /// <summary>
        /// 将对象转换成 json 字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
        /// <param name="withQuotation">属性名是否使用引号(默认不启用)</param>
        /// <returns></returns>
        public static String ConvertObject(Object obj, Boolean isBreakline, Boolean withQuotation)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("{ ");
            if (isBreakline)
            {
                builder.AppendLine();
            }

            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            Boolean             isIdFind     = false;
            Boolean             isNameFind   = false;
            Object              idValue      = "";
            Object              nameValue    = "";
            List <PropertyInfo> propertyList = new List <PropertyInfo>();

            foreach (PropertyInfo info in properties)
            {
                if (isSkip(info))
                {
                    continue;
                }

                if (info.Name.Equals("Id"))
                {
                    isIdFind = true;
                    idValue  = ReflectionUtil.GetPropertyValue(obj, "Id");
                }
                else if (info.Name.Equals("Name"))
                {
                    isNameFind = true;
                    nameValue  = ReflectionUtil.GetPropertyValue(obj, "Name");
                }
                else
                {
                    propertyList.Add(info);
                }
            }

            if (withQuotation)
            {
                if (isIdFind)
                {
                    builder.AppendFormat("\"Id\":{0}, ", idValue);
                }
                if (isNameFind)
                {
                    builder.AppendFormat("\"Name\":\"{0}\", ", nameValue);
                }
            }
            else
            {
                if (isIdFind)
                {
                    builder.AppendFormat("Id:{0}, ", idValue);
                }
                if (isNameFind)
                {
                    builder.AppendFormat("Name:\"{0}\", ", nameValue);
                }
            }

            foreach (PropertyInfo info in propertyList)
            {
                if (info.CanRead == false)
                {
                    continue;
                }

                Object propertyValue = ReflectionUtil.GetPropertyValue(obj, info.Name);

                String jsonValue;
                if (info.PropertyType.IsArray)
                {
                    jsonValue = ConvertArray(propertyValue);
                }
                else if (rft.IsInterface(info.PropertyType, typeof(IList)))
                {
                    jsonValue = ConvertList((IList)propertyValue, isBreakline);
                }
                else
                {
                    jsonValue = Convert(propertyValue, isBreakline);
                }

                if (withQuotation)
                {
                    builder.AppendFormat("\"{0}\":{1}", info.Name, jsonValue);
                }
                else
                {
                    builder.AppendFormat("{0}:{1}", info.Name, jsonValue);
                }

                builder.Append(", ");
                if (isBreakline)
                {
                    builder.AppendLine();
                }
            }
            String result = builder.ToString().Trim().TrimEnd(',');

            if (isBreakline)
            {
                result += Environment.NewLine;
            }
            return(result + " }");
        }
示例#9
0
 public override bool Equals(object obj)
 {
     return(ReflectionUtil.ReflectionEquals(this, obj));
 }
        /// <summary>
        /// MethodCallExpression visit method
        /// </summary>
        /// <param name="m">The MethodCallExpression expression to visit</param>
        /// <returns>The visited MethodCallExpression expression </returns>
        internal override Expression VisitMethodCall(MethodCallExpression m)
        {
            string methodName;

            if (TypeSystem.TryGetQueryOptionMethod(m.Method, out methodName))
            {
                this.builder.Append(methodName);
                this.builder.Append(UriHelper.LEFTPAREN);

                // There is a single function, 'contains', which reorders its argument with
                // respect to the CLR method. Thus handling it as a special case rather than
                // using a more general argument reordering mechanism.
                if (methodName == "contains")
                {
                    Debug.Assert(m.Method.Name == "Contains", "m.Method.Name == 'Contains'");
                    Debug.Assert(m.Object != null, "m.Object != null");
                    Debug.Assert(m.Arguments.Count == 1, "m.Arguments.Count == 1");
                    this.Visit(m.Object);
                    this.builder.Append(UriHelper.COMMA);
                    this.Visit(m.Arguments[0]);
                }
                else
                {
                    if (m.Object != null)
                    {
                        this.Visit(m.Object);
                    }

                    if (m.Arguments.Count > 0)
                    {
                        if (m.Object != null)
                        {
                            this.builder.Append(UriHelper.COMMA);
                        }

                        for (int ii = 0; ii < m.Arguments.Count; ii++)
                        {
                            this.Visit(m.Arguments[ii]);
                            if (ii < m.Arguments.Count - 1)
                            {
                                this.builder.Append(UriHelper.COMMA);
                            }
                        }
                    }
                }

                this.builder.Append(UriHelper.RIGHTPAREN);
            }
            else if (m.Method.Name == "HasFlag")
            {
                Debug.Assert(m.Method.Name == "HasFlag", "m.Method.Name == 'HasFlag'");
                Debug.Assert(m.Object != null, "m.Object != null");
                Debug.Assert(m.Arguments.Count == 1, "m.Arguments.Count == 1");
                this.Visit(m.Object);
                this.builder.Append(UriHelper.SPACE);
                this.builder.Append(UriHelper.HAS);
                this.builder.Append(UriHelper.SPACE);
                this.Visit(m.Arguments[0]);
            }
            else
            {
                SequenceMethod sequenceMethod;
                if (ReflectionUtil.TryIdentifySequenceMethod(m.Method, out sequenceMethod))
                {
                    if (ReflectionUtil.IsAnyAllMethod(sequenceMethod))
                    {
                        // Raise the uriVersion each time we write any or all methods to the uri.
                        WebUtil.RaiseVersion(ref this.uriVersion, Util.ODataVersion4);

                        this.Visit(m.Arguments[0]);
                        this.builder.Append(UriHelper.FORWARDSLASH);
                        if (sequenceMethod == SequenceMethod.All)
                        {
                            this.builder.Append(XmlConstants.AllMethodName);
                        }
                        else
                        {
                            this.builder.Append(XmlConstants.AnyMethodName);
                        }

                        this.builder.Append(UriHelper.LEFTPAREN);
                        if (sequenceMethod != SequenceMethod.Any)
                        {
                            // SequenceMethod.Any represents Enumerable.Any(), which has only source argument
                            // AnyPredicate and All has a second parameter which is the predicate lambda.
                            Debug.Assert(m.Arguments.Count() == 2, "m.Arguments.Count() == 2");
                            LambdaExpression le            = (LambdaExpression)m.Arguments[1];
                            string           rangeVariable = le.Parameters[0].Name;
                            this.builder.Append(rangeVariable);
                            this.builder.Append(UriHelper.COLON);
                            this.scopeCount++;
                            this.Visit(le.Body);
                            this.scopeCount--;
                        }

                        this.builder.Append(UriHelper.RIGHTPAREN);
                        return(m);
                    }
                    else if (sequenceMethod == SequenceMethod.OfType && this.parent != null)
                    {
                        // check to see if this is an OfType filter for Any or All.
                        // e.g. ctx.CreateQuery<Movie>("Movies").Where(m=>m.Actors.OfType<MegaStar>().Any())
                        //      which translates to /Movies()?$filter=Actors/MegaStar/any()
                        MethodCallExpression mce = this.parent as MethodCallExpression;
                        if (mce != null &&
                            ReflectionUtil.TryIdentifySequenceMethod(mce.Method, out sequenceMethod) &&
                            ReflectionUtil.IsAnyAllMethod(sequenceMethod))
                        {
                            Type filteredType = mce.Method.GetGenericArguments().SingleOrDefault();
                            if (ClientTypeUtil.TypeOrElementTypeIsEntity(filteredType))
                            {
                                this.Visit(m.Arguments[0]);
                                this.builder.Append(UriHelper.FORWARDSLASH);

                                UriHelper.AppendTypeSegment(this.builder, filteredType, this.context, this.inPath, ref this.uriVersion);

                                return(m);
                            }
                        }
                    }
                }

                this.cantTranslateExpression = true;
            }

            return(m);
        }
 public void ShouldCreateInstance(SetBlobStreamCommandPrototype sut, DataStorageSwitcher switcher)
 {
     ReflectionUtil.CallMethod(sut, "CreateInstance").Should().BeOfType <SetBlobStreamCommand>();
 }
示例#12
0
        /// <summary>
        /// Prepares to register types from an assembly.
        /// </summary>
        /// <param name="assemblyName">The assembly name.</param>
        /// <returns>The corresponding <see cref="FromDescriptor"/></returns>
        public static FromAssemblyDescriptor FromAssemblyNamed(string assemblyName)
        {
            var assembly = ReflectionUtil.GetAssemblyNamed(assemblyName);

            return(FromAssembly(assembly));
        }
        private Block GetSingleBlock()
        {
            Block block = ReflectionUtil.DeserializeFile <Block>("single_block", Block.Deserialize);

            return(block);
        }
 public void ShouldReturnIdIfPathIsId(ResolvePathCommand sut, ID itemId)
 {
     sut.Initialize(itemId.ToString());
     ReflectionUtil.CallMethod(sut, "DoExecute").Should().Be(itemId);
 }
示例#15
0
 //HACK: I was getting dictionary exceptions using the other method
 public bool HasAbility(string abilityName)
 {
     return(GetComponent(ReflectionUtil.GetAbilityTypeFromName(abilityName)));
 }
示例#16
0
 public override string ToString()
 {
     return(ReflectionUtil.ReflectionToString(this));
 }
        private static void ProcessActions(Instance instance, SqlConnectionStringBuilder connectionString,
                                           IPipelineController controller, Product module, Dictionary <string, string> variables,
                                           XmlElement actionsElement)
        {
            // made replacement
            actionsElement.InnerXml = variables.Aggregate(actionsElement.InnerXml,
                                                          (result, variable) => result.Replace(variable.Key, variable.Value)).Replace("{InstanceName}", instance.Name);

            var           actions        = actionsElement.ChildNodes.OfType <XmlElement>();
            var           webRootPath    = instance.WebRootPath;
            List <string> ignoreCommands = new List <string>();

            foreach (XmlElement action in actions.Where(a => a.Name.EqualsIgnoreCase("patch")))
            {
                var commandText = action.GetAttribute("command").EmptyToNull().IsNotNull("The command attribute of <patch /> element must exist and must not be empty");
                var actionText  = action.GetAttribute("action");
                if (actionText == "delete")
                {
                    ignoreCommands.Add(commandText);
                }
            }

            // give extract more priority
            if (actions.Any(xml => xml.Name.EqualsIgnoreCase("extract")) && !ignoreCommands.Contains("extract"))
            {
                FileSystem.FileSystem.Local.Zip.UnpackZip(module.PackagePath, instance.WebRootPath);
            }

            foreach (XmlElement action in actions)
            {
                var    children   = action.ChildNodes.OfType <XmlElement>();
                string actionName = action.Name;
                if (ignoreCommands.Contains(actionName))
                {
                    continue;
                }

                switch (actionName)
                {
                case "extract":
                {
                    // give extract more priority
                    // FileSystem.Instance.UnpackZip(module.PackagePath, instance.GetRootPath(webRootPath));
                    break;
                }

                case "config":
                {
                    string configPath = action.GetAttribute("path");
                    try
                    {
                        XmlDocumentEx config = !string.IsNullOrEmpty(configPath)
                ? XmlDocumentEx.LoadFile(Path.Combine(webRootPath, configPath))
                : instance.GetWebConfig(webRootPath);
                        PerformConfigChanges(instance, children, module, config, variables);
                    }
                    catch (XmlDocumentEx.FileIsMissingException ex)
                    {
                        Log.Warn(
                            "The path attribute is specified (path: {0}) but the file doesn't exist".FormatWith(configPath),
                            typeof(ConfigurationActions), ex);
                    }

                    break;
                }

                case "databases":
                {
                    AddDatabase(instance, children, module, connectionString, controller);
                    break;
                }

                case "editfile":
                {
                    EditFile(action.GetAttribute("path"), children, instance, variables);
                    break;
                }

                case "setRestrictingPlaceholders":
                {
                    InstanceHelper.StartInstance(instance);
                    SetRestrictingPlaceholders(action.GetAttribute("names"), GetWebServiceUrl(instance));
                    break;
                }

                case "custom":
                {
                    var typeName = action.GetAttribute("type").EmptyToNull().IsNotNull("The type attribute is missing in the <custom> install action");
                    var obj      = (IPackageInstallActions)ReflectionUtil.CreateObject(typeName);
                    obj.Execute(instance, module);
                    break;
                }

                case "sql":
                {
                    var db   = action.GetAttribute("database");
                    var file = action.GetAttribute("file").Replace("$(data)", instance.DataFolderPath).Replace("$(website)", instance.WebRootPath);
                    if (!string.IsNullOrEmpty(file))
                    {
                        Assert.IsTrue(File.Exists(file), string.Format("The {0} file does not exist", file));
                    }

                    var sql = string.IsNullOrEmpty(file) ? action.InnerText : FileSystem.FileSystem.Local.File.ReadAllText(file);
                    Assert.IsNotNullOrEmpty(sql.Trim(), "The SQL command is empty");

                    var cstr = instance.Configuration.ConnectionStrings.FirstOrDefault(x => x.Name == db);
                    Assert.IsNotNull(cstr, "The {0} connection string is not found".FormatWith(db));
                    using (var conn = SqlServerManager.Instance.OpenConnection(new SqlConnectionStringBuilder(cstr.Value), false))
                    {
                        foreach (var command in sql.Split("GO"))
                        {
                            SqlServerManager.Instance.Execute(conn, command);
                        }
                    }

                    break;
                }
                }
            }
        }
示例#18
0
        public override TKTProcDesc SearchProc(TKTProcDesc procDesc)
        {
            var methodArray = this.SharpType.GetMethods();

            foreach (var method in methodArray)
            {
                if (!ReflectionUtil.IsDeclare(SharpType, method))
                {
                    continue;
                }
                /* 映射类可能有多个同义的方法对应同一个实际方法 */
                ZCodeAttribute[] attrs = AttributeUtil.GetAttributes <ZCodeAttribute>(method);
                /* 编译器生成的类可能没有标注,没有标注的方法必定在ZMappingType上 */
                if (attrs.Length == 0)
                {
                    ExMethodInfo exMethod     = ZTypeUtil.CreatExMethodInfo(method, this.SharpType);
                    TKTProcDesc  typeProcDesc = ProcDescHelper.CreateProcDesc(exMethod);
                    if (typeProcDesc.Eq(procDesc))
                    {
                        TKTProcDesc rdesc = ProcDescHelper.CreateProcDesc(exMethod);
                        return(rdesc);
                    }
                }
                else if (attrs.Length > 0)
                {
                    ParameterInfo[] paramArray = method.GetParameters();
                    parser.InitType(SharpType, method);
                    foreach (ZCodeAttribute attr in attrs)
                    {
                        ZCodeAttribute zCodeAttribute = attr as ZCodeAttribute;
                        TKTProcDesc    typeProcDesc   = parser.Parser(zCodeAttribute.Code);
                        if (method.IsStatic && !method.IsAbstract && typeProcDesc.HasSubject() &&
                            typeProcDesc.GetSubjectArg().ArgType == this.SharpType)
                        {
                            typeProcDesc = typeProcDesc.CreateTail();
                        }
                        if (typeProcDesc.Eq(procDesc))
                        {
                            ExMethodInfo exMethod = null;// getExMethod(method);
                            /* 非 Abstract 的方法肯定从被映射的类中搜索 */
                            if (method.IsAbstract)
                            {
                                var method2 = searchMethodFromSharp(method);
                                exMethod = ZTypeUtil.CreatExMethodInfo(method2, this.SharpType);
                                //return exMethod;
                            }
                            else
                            {
                                exMethod = ZTypeUtil.CreatExMethodInfo(method, this.ZMappingType);
                                //return exMethod;
                            }
                            typeProcDesc.ExMethod = exMethod;
                            return(typeProcDesc);
                        }
                    }
                }
            }
            if (ParentMapping != null && !isRoot())
            {
                var epi = ParentMapping.SearchProc(procDesc);
                if (epi != null)
                {
                    //epi.IsSelf = false;
                    return(epi);
                }
            }
            return(null);
        }
示例#19
0
 public static bool IsSupportedAttributeType(Type clazz)
 {
     return(ATTR_SUPPORTED_TYPES.Contains(clazz) || null != ReflectionUtil.FindInHierarchyOf
                (typeof(IDictionary <,>), clazz));
 }
示例#20
0
        /// <summary>
        /// 하나의 명령을 생성하여 삽입합니다.
        /// </summary>
        /// <param name="aKey"></param>
        /// <param name="aOperator"></param>
        /// <param name="aValue"></param>
        /// <param name="aSearchType"></param>
        /// <returns></returns>
        public IQuery <T> Command(Expression <Func <T, object> > aColName, Operator aOperator, object aValue, SearchType aSearchType)
        {
            //명령 생성시 Value 값이 없는 경우
            if (aValue == null)
            {
                //명령목록이 비어있지 않고, 마지막 명령이 논리연산자인 경우
                if (!IsEmptyQuery() && mCommands.Last().Type == CommandType.LogicalOperator)
                {
                    //마지막 논리 연산자 제거
                    RemoveLastCommand();
                }
                return(this);
            }

            if (aValue is string[] && !(aValue as string[]).Any())
            {
                //명령목록이 비어있지 않고, 마지막 명령이 논리연산자인 경우
                if (!IsEmptyQuery() && mCommands.Last().Type == CommandType.LogicalOperator)
                {
                    //마지막 논리 연산자 제거
                    RemoveLastCommand();
                }
                return(this);
            }

            if (aValue is string && string.IsNullOrEmpty(aValue as string))
            {
                //명령목록이 비어있지 않고, 마지막 명령이 논리연산자인 경우
                if (!IsEmptyQuery() && mCommands.Last().Type == CommandType.LogicalOperator)
                {
                    //마지막 논리 연산자 제거
                    RemoveLastCommand();
                }
                return(this);
            }

            switch (aOperator)
            {
            case Operator.Equals:
            case Operator.LessThan:
            case Operator.LessThanEqualTo:
            case Operator.GreaterThan:
            case Operator.GreaterThanEqualTo:
            case Operator.NotEquals:
            case Operator.Like:
            case Operator.NotLike:
                double lNumber;
                if (!double.TryParse(Convert.ToString(aValue), out lNumber))
                {
                    aValue = "'" + aValue + "'";
                }
                break;

            case Operator.In:

                if (aValue is string[])
                {
                    aValue = string.Join(",", aValue as string[]);
                }

                if (aValue is string)
                {
                    string lValue = (string)aValue;
                    lValue = lValue.Trim();
                    if (!(lValue.StartsWith("{") || lValue.EndsWith("}")))
                    {
                        aValue = "{" + aValue + "}";
                    }
                }
                break;

            case Operator.NotIn:

                if (aValue is string[])
                {
                    aValue = string.Join(",", aValue as string[]);
                }

                if (aValue is string)
                {
                    string lValue = (string)aValue;
                    lValue = lValue.Trim();
                    if (!(lValue.StartsWith("{") || lValue.EndsWith("}")))
                    {
                        aValue = "{" + aValue + "}";
                    }
                }
                break;

            default:
                break;
            }
            if (aSearchType == SearchType.None)
            {
                mCommands.Add(new Command
                {
                    Type  = CommandType.Command,
                    Value = string.Format("{0} {1} {2}", ReflectionUtil.GetMemberName(aColName), getOperator(aOperator), aValue)
                });
            }
            else
            {
                mCommands.Add(new Command
                {
                    Type  = CommandType.Command,
                    Value = string.Format("{0} {1} {2} {3}", ReflectionUtil.GetMemberName(aColName), getOperator(aOperator), aValue, getSearchType(aSearchType))
                });
            }
            return(this);
        }
示例#21
0
        protected override void DidActivate(bool firstActivation, ActivationType activationType)
        {
            if (firstActivation && activationType == ActivationType.AddedToHierarchy)
            {
                _downloadListTableCellInstance = Resources.FindObjectsOfTypeAll <LeaderboardTableCell>().First();

                _tabControl = BeatSaberUI.CreateTextSegmentedControl(rectTransform, new Vector2(0f, 31f), new Vector2(100f, 7f), _tabControl_didSelectCellEvent);
                _tabControl.SetTexts(new string[] { "Players", "Modifiers" });

                #region Modifiers tab

                _modifiersTab = new GameObject("ModifiersTab", typeof(RectTransform)).GetComponent <RectTransform>();
                _modifiersTab.SetParent(rectTransform, false);
                _modifiersTab.anchorMin        = new Vector2(0f, 0f);
                _modifiersTab.anchorMax        = new Vector2(1f, 1f);
                _modifiersTab.anchoredPosition = new Vector2(0f, 0f);
                _modifiersTab.sizeDelta        = new Vector2(0f, 0f);

                _modifiersPanel = Instantiate(Resources.FindObjectsOfTypeAll <GameplayModifiersPanelController>().First(), rectTransform, false);
                _modifiersPanel.gameObject.SetActive(true);
                _modifiersPanel.transform.SetParent(_modifiersTab, false);
                (_modifiersPanel.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0f);
                (_modifiersPanel.transform as RectTransform).anchorMax        = new Vector2(0.5f, 1f);
                (_modifiersPanel.transform as RectTransform).anchoredPosition = new Vector2(0f, -23f);
                (_modifiersPanel.transform as RectTransform).sizeDelta        = new Vector2(120f, -23f);

                HoverHintController hoverHintController = Resources.FindObjectsOfTypeAll <HoverHintController>().First();

                foreach (var hint in _modifiersPanel.GetComponentsInChildren <HoverHint>())
                {
                    hint.SetPrivateField("_hoverHintController", hoverHintController);
                }

                _modifiersPanel.Init(GameplayModifiers.defaultModifiers);
                _modifiersPanel.Awake();

                var modifierToggles = _modifiersPanel.GetPrivateField <GameplayModifierToggle[]>("_gameplayModifierToggles");

                foreach (var item in modifierToggles)
                {
                    item.toggle.onValueChanged.AddListener((enabled) => { gameplayModifiersChanged?.Invoke(); });
                }

                _modifiersPanelBlocker = new GameObject("ModifiersPanelBlocker", typeof(RectTransform)).GetComponent <RectTransform>(); //"If it works it's not stupid"
                _modifiersPanelBlocker.SetParent(_modifiersTab, false);
                _modifiersPanelBlocker.gameObject.AddComponent <UnityEngine.UI.Image>().color = new Color(0f, 0f, 0f, 0f);
                _modifiersPanelBlocker.anchorMin        = new Vector2(0f, 0f);
                _modifiersPanelBlocker.anchorMax        = new Vector2(1f, 0f);
                _modifiersPanelBlocker.pivot            = new Vector2(0.5f, 0f);
                _modifiersPanelBlocker.sizeDelta        = new Vector2(-10f, 62f);
                _modifiersPanelBlocker.anchoredPosition = new Vector2(0f, 0f);

                #endregion

                #region Players tab

                _playersTab = new GameObject("PlayersTab", typeof(RectTransform)).GetComponent <RectTransform>();
                _playersTab.SetParent(rectTransform, false);
                _playersTab.anchorMin        = new Vector2(0f, 0f);
                _playersTab.anchorMax        = new Vector2(1f, 1f);
                _playersTab.anchoredPosition = new Vector2(0f, 0f);
                _playersTab.sizeDelta        = new Vector2(0f, 0f);

                _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageUpButton")), _playersTab, false);
                (_pageUpButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 1f);
                (_pageUpButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 1f);
                (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -18.5f);
                (_pageUpButton.transform as RectTransform).sizeDelta        = new Vector2(40f, 6f);
                _pageUpButton.interactable = true;
                _pageUpButton.onClick.AddListener(delegate()
                {
                    _playersTableView.PageScrollUp();
                });
                _pageUpButton.interactable = false;

                _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageDownButton")), _playersTab, false);
                (_pageDownButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0f);
                (_pageDownButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0f);
                (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, 7f);
                (_pageDownButton.transform as RectTransform).sizeDelta        = new Vector2(40f, 6f);
                _pageDownButton.interactable = true;
                _pageDownButton.onClick.AddListener(delegate()
                {
                    _playersTableView.PageScrollDown();
                });
                _pageDownButton.interactable = false;

                RectTransform container = new GameObject("Content", typeof(RectTransform)).transform as RectTransform;
                container.SetParent(_playersTab, false);
                container.anchorMin        = new Vector2(0.15f, 0.5f);
                container.anchorMax        = new Vector2(0.85f, 0.5f);
                container.sizeDelta        = new Vector2(0f, 49f);
                container.anchoredPosition = new Vector2(0f, -3f);

                var tableGameObject = new GameObject("CustomTableView");
                tableGameObject.SetActive(false);
                _playersTableView = tableGameObject.AddComponent <TableView>();
                _playersTableView.gameObject.AddComponent <RectMask2D>();
                _playersTableView.transform.SetParent(container, false);

                _playersTableView.SetPrivateField("_isInitialized", false);
                _playersTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]);
                tableGameObject.SetActive(true);

                (_playersTableView.transform as RectTransform).anchorMin        = new Vector2(0f, 0f);
                (_playersTableView.transform as RectTransform).anchorMax        = new Vector2(1f, 1f);
                (_playersTableView.transform as RectTransform).sizeDelta        = new Vector2(0f, 0f);
                (_playersTableView.transform as RectTransform).anchoredPosition = new Vector3(0f, 0f);

                ReflectionUtil.SetPrivateField(_playersTableView, "_pageUpButton", _pageUpButton);
                ReflectionUtil.SetPrivateField(_playersTableView, "_pageDownButton", _pageDownButton);

                _playersTableView.dataSource = this;
                #endregion

                _pingText           = this.CreateText("PING: 0", new Vector2(75f, 22.5f));
                _pingText.alignment = TextAlignmentOptions.Left;

                _tabControl_didSelectCellEvent(0);
            }
            else
            {
                for (int i = 0; i < _tableCells.Count; i++)
                {
                    Destroy(_tableCells[i].gameObject);
                }
                _tableCells.Clear();
                _playersList.Clear();
                _playersTableView.ReloadData();
            }

            if (activationType == ActivationType.AddedToHierarchy)
            {
                SetGameplayModifiers(GameplayModifiers.defaultModifiers);
            }
        }
示例#22
0
 /// <summary>
 /// 컬럼명에 따라 내림차순으로 다시 정렬합니다.
 /// OrderBy, OrderByDescending을 사용한 이후에 사용할 수 있습니다.
 /// </summary>
 /// <param name="aColName"></param>
 /// <returns></returns>
 public IOrderedQuery <T> ThenByDescending(Expression <Func <T, object> > aColName)
 {
     mOrderByParams.Add(string.Format("{0} {1}", ReflectionUtil.GetMemberName(aColName), "desc"));
     return(this);
 }
        public override void Instantiate()
        {
            var volumeSettings = Resources.FindObjectsOfTypeAll <FormattedFloatListSettingsController>().FirstOrDefault();

            gameObject      = UnityEngine.Object.Instantiate(volumeSettings.gameObject, Container);
            gameObject.name = optionName;
            gameObject.GetComponentInChildren <TMP_Text>().text = optionName;

            // Add a separator for this menu option
            AddSeparator(Container);

            //This magical nonsense is courtesy of Taz and his SettingsUI class
            ListSettingsController volume = gameObject.GetComponent <ListSettingsController>();

            multiSelectController = (ListViewController)ReflectionUtil.CopyComponent(volume, typeof(ListSettingsController), typeof(ListViewController), gameObject, false);
            UnityEngine.Object.DestroyImmediate(volume);

            multiSelectController.applyImmediately = true;
            multiSelectController.values           = _options.Keys.ToList();
            multiSelectController.SetValue         = OnChange;
            multiSelectController.GetValue         = () =>
            {
                if (GetValue != null)
                {
                    return(GetValue.Invoke());
                }
                return(_options.Keys.ElementAt(0));
            };
            multiSelectController.GetTextForValue = (v) =>
            {
                if (_options.ContainsKey(v))
                {
                    return(_options[v] != null ? _options[v] : v.ToString());
                }
                return("UNKNOWN");
            };
            //Initialize the controller, as if we had just opened the settings menu
            multiSelectController.Init();
            var      value           = multiSelectController.gameObject.transform.Find("Value");
            var      valueText       = value.Find("ValueText");
            TMP_Text valueTextObject = valueText.GetComponent <TMP_Text>();

            valueTextObject.lineSpacing = -50;
            valueTextObject.alignment   = TextAlignmentOptions.CenterGeoAligned;

            var nameText = multiSelectController.gameObject.transform.Find("NameText");

            nameText.localScale = new Vector3(0.85f, 0.85f, 0.85f);
            value.localScale    = new Vector3(0.7f, 0.7f, 0.7f);
            if (hintText != String.Empty)
            {
                BeatSaberUI.AddHintText(nameText as RectTransform, hintText);
            }

            var dec = value.Find("DecButton");

            dec.transform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
            var inc = value.Find("IncButton");

            inc.transform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
            value.localPosition     -= new Vector3(8, 0.3f);

            gameObject.SetActive(false);
            initialized = true;
        }
示例#24
0
        public dynamic GetChildPropertyValues(string tableName)
        {
            PropertyInfo property = GetChildProperty(tableName);

            return(ReflectionUtil.GetPropertyValue(this, property));
        }
示例#25
0
        public IObservableWithTask <DocumentChangeNotification> ForDocumentsOfType <TEntity>()
        {
            var typeName = ReflectionUtil.GetFullNameWithoutVersionInformation(typeof(TEntity));

            return(ForDocumentsOfType(typeName));
        }
示例#26
0
        /// <summary>
        /// Return static serializers for type
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public SerializerPair GetOrCreate(Type type)
        {
            if (myStaticSerializers.TryGetValue(type, out var pair))
            {
                return(pair);
            }

            if (myBlackListChecker(type))
            {
                Assertion.Fail($"Attempt to create serializer for black-listed type: {type.ToString(true)}");
            }

            var result = CreateSerializer(type);

            myStaticSerializers[type] = result;
            return(result);

            SerializerPair CreateSerializer(Type t)
            {
                var typeInfo = t.GetTypeInfo();

                var intrinsic = Intrinsic.TryGetIntrinsicSerializer(typeInfo, GetInstanceSerializer);

                if (intrinsic != null)
                {
                    myTypesCatalog.AddType(type);
                    return(intrinsic);
                }

                if (IsList(t))
                {
                    var genericTypeArgument        = t.GetGenericArguments()[0];
                    var argumentTypeSerializerPair = GetInstanceSerializer(genericTypeArgument);
                    return((SerializerPair)ReflectionUtil.InvokeStaticGeneric(typeof(CollectionSerializers), nameof(CollectionSerializers.CreateListSerializerPair), genericTypeArgument, argumentTypeSerializerPair));
                }
                else if (IsDictionary(t) || IsReadOnlyDictionary(t))
                {
                    var typeArguments          = t.GetGenericArguments();
                    var tkey                   = typeArguments[0];
                    var tvalue                 = typeArguments[1];
                    var keySerializer          = GetInstanceSerializer(tkey);
                    var valueSerializer        = GetInstanceSerializer(tvalue);
                    var serializersFactoryName = IsReadOnlyDictionary(t) ? nameof(CollectionSerializers.CreateReadOnlyDictionarySerializerPair) : nameof(CollectionSerializers.CreateDictionarySerializerPair);
                    return((SerializerPair)ReflectionUtil.InvokeStaticGeneric2(typeof(CollectionSerializers), serializersFactoryName, tkey, tvalue, keySerializer, valueSerializer));
                }
                else if (t.IsArray)
                {
                    return((SerializerPair)ReflectionUtil.InvokeGenericThis(this, nameof(CreateArraySerializer), t.GetElementType()));
                }
                else if (t.IsEnum)
                {
                    var serializer = ReflectionUtil.InvokeGenericThis(this, nameof(CreateEnumSerializer), t);
                    return((SerializerPair)serializer);
                }
                else if (ReflectionSerializerVerifier.IsValueTuple(typeInfo))
                {
                    return((SerializerPair)ReflectionUtil.InvokeGenericThis(this, nameof(CreateValueTupleSerializer), type));
                }
                else if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    var genericTypeArgument = typeInfo.GetGenericArguments()[0];
                    var nullableSerializer  = (SerializerPair)ReflectionUtil.InvokeGenericThis(this, nameof(RegisterNullable), genericTypeArgument);
                    return(nullableSerializer);
                    // return CreateGenericSerializer(member, typeInfo, implementingType, implementingTypeInfo);
                }
                else
                {
                    myTypesCatalog.AddType(type);
                    var serializer = ReflectionUtil.InvokeGenericThis(this, nameof(CreateCustomScalar), t);
                    return((SerializerPair)serializer);
                }
            }
        }
示例#27
0
        private object ReflectionInitInternal(object instance)
        {
            var typeInfo = instance.GetType().GetTypeInfo();

            if (ReflectionSerializerVerifier.HasRdExtAttribute(instance.GetType().GetTypeInfo()))
            {
                ReflectionSerializerVerifier.AssertValidRdExt(typeInfo);
            }

            foreach (var mi in SerializerReflectionUtil.GetBindableMembers(typeInfo))
            {
                ReflectionSerializerVerifier.AssertMemberDeclaration(mi);
                var currentValue = ReflectionUtil.GetGetter(mi)(instance);
                if (currentValue == null)
                {
                    currentValue = ActivateRdExtMember(mi);

                    var memberSetter = ReflectionUtil.GetSetter(mi);
                    memberSetter(instance, currentValue);
                }
                else
                {
                    var implementingType = ReflectionSerializerVerifier.GetImplementingType(ReflectionUtil.GetReturnType(mi).GetTypeInfo());
                    Assertion.Assert(currentValue.GetType() == implementingType,
                                     "Bindable field {0} was initialized with incompatible type. Expected type {1}, actual {2}",
                                     mi,
                                     implementingType.ToString(true),
                                     currentValue.GetType().ToString(true));
                }
            }

            // Add RdEndpoint for Impl class (counterpart of Proxy)
            var  interfaces   = typeInfo.GetInterfaces();
            bool isProxy      = interfaces.Contains(typeof(IProxyTypeMarker));
            var  rpcInterface = ReflectionSerializersFactory.GetRpcInterface(typeInfo);

            if (!isProxy && rpcInterface != null)
            {
                var bindableChildren = ((IReflectionBindable)instance).BindableChildren;

                var interfaceMap     = typeInfo.GetInterfaceMap(rpcInterface);
                var interfaceMethods = interfaceMap.InterfaceMethods;

                // Dynamic adapters for Properties are not required, so skip them
                var ignoreMethods = new HashSet <string>(StringComparer.Ordinal);
                foreach (var propertyInfo in rpcInterface.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    ignoreMethods.Add(propertyInfo.GetSetMethod()?.Name);
                    ignoreMethods.Add(propertyInfo.GetGetMethod()?.Name);
                }

                foreach (var interfaceMethod in interfaceMethods)
                {
                    if (ignoreMethods.Contains(interfaceMethod.Name))
                    {
                        continue;
                    }

                    var adapter = myProxyGenerator.CreateAdapter(rpcInterface, interfaceMethod);

                    var name        = ProxyGenerator.ProxyFieldName(interfaceMethod);
                    var requestType = ProxyGenerator.GetRequstType(interfaceMethod)[0];
                    EnsureFakeTupleRegistered(requestType);

                    var responseNonTaskType = ProxyGenerator.GetResponseType(interfaceMethod, unwrapTask: true);
                    var responseType        = ProxyGenerator.GetResponseType(interfaceMethod, unwrapTask: false);
                    var endPointType        = typeof(RdCall <,>).MakeGenericType(requestType, responseNonTaskType);
                    var endpoint            = ActivateGenericMember(name, endPointType.GetTypeInfo());
                    SetAsync(interfaceMethod, endpoint);
                    if (endpoint is RdReactiveBase reactiveBase)
                    {
                        reactiveBase.ValueCanBeNull = true;
                    }
                    if (ProxyGenerator.IsSync(interfaceMethod))
                    {
                        var delType    = typeof(Func <, ,>).MakeGenericType(typeof(Lifetime), requestType, typeof(RdTask <>).MakeGenericType(responseNonTaskType));
                        var @delegate  = adapter.CreateDelegate(delType, instance);
                        var methodInfo = typeof(ReflectionRdActivator).GetMethod(nameof(SetHandler)).NotNull().MakeGenericMethod(requestType, responseNonTaskType);
                        methodInfo.Invoke(null, new[] { endpoint, @delegate });
                    }
                    else
                    {
                        if (responseType == typeof(Task))
                        {
                            var delType    = typeof(Func <, ,>).MakeGenericType(typeof(Lifetime), requestType, typeof(Task));
                            var @delegate  = adapter.CreateDelegate(delType, instance);
                            var methodInfo = typeof(ReflectionRdActivator).GetMethod(nameof(SetHandlerTaskVoid)).NotNull().MakeGenericMethod(requestType);
                            methodInfo.Invoke(null, new[] { endpoint, @delegate });
                        }
                        else
                        {
                            var delType    = typeof(Func <, ,>).MakeGenericType(typeof(Lifetime), requestType, typeof(Task <>).MakeGenericType(responseNonTaskType));
                            var @delegate  = adapter.CreateDelegate(delType, instance);
                            var methodInfo = typeof(ReflectionRdActivator).GetMethod(nameof(SetHandlerTask)).NotNull().MakeGenericMethod(requestType, responseNonTaskType);
                            methodInfo.Invoke(null, new[] { endpoint, @delegate });
                        }
                    }

                    bindableChildren.Add(new KeyValuePair <string, object>(name, endpoint));
                }
            }
            else if (rpcInterface != null)
            {
                foreach (var interfaceMethod in rpcInterface.GetMethods())
                {
                    var requestType = ProxyGenerator.GetRequstType(interfaceMethod)[0];
                    EnsureFakeTupleRegistered(requestType);
                }
            }

            // Allow initialize to setup bindings to composite properties.
            if (instance is IReflectionBindable reflectionBindable)
            {
                reflectionBindable.OnActivated();
            }

            return(instance);
        }
示例#28
0
        public bool LoadGame(string seBinPath, string userDataPath, string savePath)
        {
            if (!Directory.Exists(seBinPath))
            {
                return(false);
            }

            if (!Directory.Exists(savePath))
            {
                return(false);
            }

            if (!savePath.StartsWith(userDataPath, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            string contentPath = Path.GetFullPath(Path.Combine(seBinPath, @"..\Content"));

            MyFileSystem.Reset();
            MyFileSystem.Init(contentPath, userDataPath);

            MyLog.Default        = MySandboxGame.Log;
            MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME.
            MySandboxGame.Config.Load();

            MyFileSystem.InitUserSpecific(null);

            SpaceEngineersGame.SetupPerGameSettings();

            VRageRender.MyRenderProxy.Initialize(new MyNullRender());
            // We create a whole instance of MySandboxGame!
            // If this is causing an exception, then there is a missing dependency.
            MySandboxGame gameTemp = new MySandboxGame(null);

            #region Game Localization

            // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it.
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode);

            var culture          = System.Threading.Thread.CurrentThread.CurrentUICulture;
            var languageTag      = culture.IetfLanguageTag;
            var localizationPath = Path.Combine(contentPath, @"Data\Localization");
            var codes            = languageTag.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            var maincode         = codes.Length > 0 ? codes[0] : null;
            var subcode          = codes.Length > 1 ? codes[1] : null;
            MyTexts.Clear();
            MyTexts.LoadTexts(localizationPath, maincode, subcode);

            #endregion

            MyStorageBase.UseStorageCache = false;

            #region MySession creation

            // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies.
            var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
            var ourStart  = typeof(EconomyConfigurationEditor.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
            ReflectionUtil.ReplaceMethod(ourStart, keenStart);

            // Create an empty instance of MySession for use by low level code.
            Sandbox.Game.World.MySession mySession = ReflectionUtil.ConstructPrivateClass <Sandbox.Game.World.MySession>(new Type[0], new object[0]);
            ReflectionUtil.ConstructField(mySession, "m_sessionComponents"); // Required as the above code doesn't populate it during ctor of MySession.
            mySession.Settings = new MyObjectBuilder_SessionSettings {
                EnableVoxelDestruction = true
            };

            // Assign the instance back to the static.
            Sandbox.Game.World.MySession.Static = mySession;

            Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem();
            Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData();

            #endregion

            #region Load Sandbox

            var filename = Path.Combine(savePath, SpaceEngineersConsts.SandBoxCheckpointFilename);

            MyObjectBuilder_Checkpoint checkpoint;
            string errorInformation;
            bool   compressedCheckpointFormat;
            bool   snapshot = false;
            bool   retVal   = SpaceEngineersApi.TryReadSpaceEngineersFile <MyObjectBuilder_Checkpoint>(filename, out checkpoint, out compressedCheckpointFormat, out errorInformation, snapshot);

            if (!retVal)
            {
                return(false);
            }

            #endregion

            MyDefinitionManager.Static.PrepareBaseDefinitions();
            MyDefinitionManager.Static.LoadData(checkpoint.Mods);
            var MaterialIndex = new Dictionary <string, byte>();

            return(true);
        }
示例#29
0
 public IEnumerable <IIdentityVersion> GetAllVersions(IServiceProvider serviceProvider)
 {
     return(ReflectionUtil.GetAllInstances <IIdentityVersion>(Assembly.GetExecutingAssembly(), serviceProvider));
 }
示例#30
0
        /// <summary>
        /// Parses the specified string in an object of the specified type
        /// </summary>
        /// <param name="reader">The input reader</param>
        /// <param name="t">The type of the object that needs to be parsed</param>
        /// <returns>The parsed object</returns>
        public object Parse(TextReader reader, Type t)
        {
            object ret = null;

            List <KeyValuePair <string, string> > singleValues = new List <KeyValuePair <string, string> >();
            Dictionary <string, List <List <KeyValuePair <string, string> > > > arrayValues =
                new Dictionary <string, List <List <KeyValuePair <string, string> > > >();
            List <List <KeyValuePair <string, string> > > curArrayList;

            // parse properties into single keyvalue pairs and the indexed properties into
            // the array Values
            #region Parse properties
            string curLine = reader.ReadLine();
            int    idxSeparator, idxIndex1, idxIndex2;
            string key, val, keyIndex, keyIndexBase, keyIndexProp;
            int    curIndex;
            while (curLine != null)
            {
                curLine = curLine.Trim();
                if (!string.IsNullOrEmpty(curLine) && curLine[0] != COMMENT_CHAR)
                {
                    idxSeparator = curLine.IndexOf(SEPARATOR_CHAR);
                    if (idxSeparator != -1)
                    {
                        key = curLine.Substring(0, idxSeparator);
                        val = curLine.Substring(idxSeparator + 1);

                        // check if the key is indexed/array
                        idxIndex1 = key.IndexOf(INDEX_START_CHAR);
                        if (idxIndex1 == -1)
                        {
                            singleValues.Add(new KeyValuePair <string, string>(key, val));
                        }
                        else
                        {
                            idxIndex2 = key.IndexOf(INDEX_END_CHAR);
                            if (idxIndex2 < idxIndex1)
                            {
                                throw new InvalidDataException("Cannot read index for property: " + key);
                            }
                            else
                            {
                                keyIndex = key.Substring(idxIndex1 + 1, idxIndex2 - idxIndex1 - 1);
                                if (int.TryParse(keyIndex, out curIndex))
                                {
                                    keyIndexBase = key.Substring(0, idxIndex1);
                                    keyIndexProp = key.Substring(idxIndex2 + 2);

                                    if (!arrayValues.ContainsKey(keyIndexBase))
                                    {
                                        arrayValues[keyIndexBase] = new List <List <KeyValuePair <string, string> > >();
                                    }
                                    curArrayList = arrayValues[keyIndexBase];
                                    if (curArrayList == null || curArrayList.Count <= curIndex)
                                    {
                                        curArrayList.Add(new List <KeyValuePair <string, string> >());
                                    }
                                    curArrayList[curIndex].Add(new KeyValuePair <string, string>(keyIndexProp, val));
                                }
                                else
                                {
                                    throw new InvalidDataException("Not a valid indexed property: " + key);
                                }
                            }
                        }
                    }
                }
                curLine = reader.ReadLine();
            }
            #endregion

            // create a new object for type
            ret = ReflectionUtil.CreateInstance(t);

            ReflectionCache typeCache   = ReflectionUtil.GetCache(t);
            PropertyInfo    piSpecified = null;

            // now reflect through the specified type and set parsed values
            foreach (KeyValuePair <string, string> kvp in singleValues)
            {
                ReflectionUtil.SetPropertyPathValue(ret, kvp.Key, kvp.Value);

                // also set the "Specified"-flag, if any
                piSpecified = typeCache.GetProperty(kvp.Key + "Specified", false);
                if (piSpecified != null)
                {
                    piSpecified.SetValue(ret, true, null);
                }
            }

            object curRootObject;
            List <KeyValuePair <string, string> > curRootObjectProperties;
            PropertyInfo    pi;
            ConstructorInfo ci;

            foreach (string arrayPropertyName in arrayValues.Keys)
            {
                curArrayList = arrayValues[arrayPropertyName];

                pi = ReflectionUtil.GetProperty(t, arrayPropertyName);
                ci = pi.PropertyType.GetConstructor(new Type[] { typeof(int) });
                object[] o = (object[])ci.Invoke(new object[] { curArrayList.Count });

                Type elementType = pi.PropertyType.Assembly.GetType(pi.PropertyType.FullName.Replace("[]", string.Empty), false);

                for (int i = 0; i < curArrayList.Count; i++)
                {
                    curRootObject           = ReflectionUtil.CreateInstance(elementType);
                    curRootObjectProperties = curArrayList[i];

                    typeCache = ReflectionUtil.GetCache(elementType);

                    foreach (KeyValuePair <string, string> kvp in curRootObjectProperties)
                    {
                        ReflectionUtil.SetPropertyPathValue(curRootObject, kvp.Key, kvp.Value);

                        // also set the "Specified"-flag, if any
                        piSpecified = typeCache.GetProperty(kvp.Key + "Specified", false);
                        if (piSpecified != null)
                        {
                            piSpecified.SetValue(curRootObject, true, null);
                        }
                    }

                    o[i] = curRootObject;
                }

                ReflectionUtil.SetPropertyPathValue(ret, arrayPropertyName, o);
            }

            return(ret);
        }