コード例 #1
0
ファイル: BattleNetClient.cs プロジェクト: wjlafrance/jinxbot
        private void CreateAccountNLS()
        {
            BncsPacket pck = new BncsPacket((byte)BncsPacketId.AuthAccountCreate);

            m_nls = new NLS(m_settings.Username, m_settings.Password);
            m_nls.CreateAccount(pck);

            Send(pck);
        }
コード例 #2
0
        /// <inheritdoc />
        protected override void OnInitialize()
        {
            IConfigurationElement[] configurationElements = ExtensionService.Instance.GetConfigurationElements(DataViewExtensionPointId);
            if (configurationElements.Length == 0)
            {
                _log.Warning("No data view has been contributed by any extension point!");
                return;
            }

            _log.Debug($"{configurationElements.Length} data view contributions has been found");
            for (int i = -1; ++i != configurationElements.Length;)
            {
                IConfigurationElement configurationElement = configurationElements[i];

                string id    = configurationElement["id"];
                string cls   = configurationElement["class"];
                string label = configurationElement["label"];

                if (string.IsNullOrEmpty(label))
                {
                    label = id;
                }

                _log.Debug($"Registering contribution {{id: '{id}', cls: '{cls}', label: '{label}'}}");

                if (string.IsNullOrWhiteSpace(id))
                {
                    _log.Error("Id attribute of data view extension contribution is null or empty!");
                    continue;
                }

                if (string.IsNullOrWhiteSpace(cls))
                {
                    _log.Error($"Class attribute of data view extension contribution is null or empty!. Contribution id: '{id}'");
                    continue;
                }

                IBundle providingBundle = ExtensionService.Instance.GetProvidingBundle(configurationElement);
                try {
                    Type dataViewType = TypeLoader.TypeForName(providingBundle, cls);

                    // NLS support
                    label = NLS.Localize(label, dataViewType);

                    DataViewContribution dataViewContribution = new DataViewContribution {
                        DataViewId    = id,
                        DataViewType  = dataViewType,
                        DataViewLabel = label
                    };

                    iRegisteredDataViews.Add(dataViewContribution);
                    _log.Info($"Data view contribution '{id}' registered.");
                } catch (Exception ex) {
                    _log.Error($"Error loading type '{cls}'.", ex);
                }
            }
        }
コード例 #3
0
ファイル: BattleNetClient.cs プロジェクト: wjlafrance/jinxbot
        private void LoginAccountNLS()
        {
            m_nls = new NLS(m_settings.Username, m_settings.Password);

            BncsPacket pck0x53 = new BncsPacket((byte)BncsPacketId.AuthAccountLogon);

            m_nls.LoginAccount(pck0x53);
            Send(pck0x53);
        }
コード例 #4
0
        private async void LoginAccountNLS()
        {
            _nls = new NLS(_settings.Username, _settings.Password);

            BncsPacket pck0x53 = new BncsPacket(BncsPacketId.AuthAccountLogon, _storage.Acquire());

            _nls.LoginAccount(pck0x53);
            await pck0x53.SendAsync(_connection);
        }
コード例 #5
0
        private async void CreateAccountNLS()
        {
            BncsPacket pck = new BncsPacket(BncsPacketId.AuthAccountCreate, _storage.Acquire());

            _nls = new NLS(_settings.Username, _settings.Password);
            _nls.CreateAccount(pck);

            await pck.SendAsync(_connection);
        }
コード例 #6
0
ファイル: QueryNodeImpl.cs プロジェクト: wow64bb/YAFNET
        public void Add(IQueryNode child)
        {
            if (IsLeaf || this.clauses == null || child == null)
            {
                throw new ArgumentException(NLS
                                            .GetLocalizedMessage(QueryParserMessages.NODE_ACTION_NOT_SUPPORTED));
            }

            this.clauses.Add(child);
            ((QueryNode)child).SetParent(this);
        }
コード例 #7
0
ファイル: QueryNodeImpl.cs プロジェクト: wow64bb/YAFNET
        public void Add(IList <IQueryNode> children)
        {
            if (IsLeaf || this.clauses == null)
            {
                throw new ArgumentException(NLS
                                            .GetLocalizedMessage(QueryParserMessages.NODE_ACTION_NOT_SUPPORTED));
            }

            foreach (IQueryNode child in children)
            {
                Add(child);
            }
        }
コード例 #8
0
        public void Set(IList <IQueryNode> children)
        {
            if (IsLeaf || this.clauses == null)
            {
                var             factory = NLS.GetResourceManagerFactory();
                ResourceManager bundle  = factory.Create(typeof(QueryParserMessages));
                string          message;
                try
                {
                    message = bundle.GetString(QueryParserMessages.NODE_ACTION_NOT_SUPPORTED);
                }
                finally
                {
                    factory.Release(bundle);
                }

                throw new ArgumentException(message);
            }

            // reset parent value
            foreach (IQueryNode child in children)
            {
                child.RemoveFromParent();
            }

            // LUCENENET specific: GetChildren already creates a new list, there is
            // no need to do it again here and have another O(n) operation
            IList <IQueryNode> existingChildren = GetChildren();

            foreach (IQueryNode existingChild in existingChildren)
            {
                existingChild.RemoveFromParent();
            }

            // allocate new children list
            Allocate();

            // add new children and set parent
            Add(children);
        }
コード例 #9
0
 /// <returns>an instance of this translation bundle</returns>
 public static JGitText Get()
 {
     return(NLS.GetBundleFor <JGitText>());
 }
コード例 #10
0
ファイル: QueryParserMessages.cs プロジェクト: wow64bb/YAFNET
 static QueryParserMessages()
 {
     // register all string ids with NLS class and initialize static string
     // values
     NLS.InitializeMessages(BUNDLE_NAME, typeof(QueryParserMessages));
 }
コード例 #11
0
 static Messages()
 {
     NLS.initializeMessages("cnatural.eclipse.messages", typeof(Messages));
 }
コード例 #12
0
ファイル: NewWizardRegistry.cs プロジェクト: astorch/motoi
        /// <inheritdoc />
        protected override void OnInitialize()
        {
            IConfigurationElement[] configurationElements = ExtensionService.Instance.GetConfigurationElements(ExtensionPointId);

            IConfigurationElement[] categories = configurationElements.Where(el => el.Prefix == "category").ToArray();
            IConfigurationElement[] wizards    = configurationElements.Where(el => el.Prefix == "wizard").ToArray();
            IDictionary <string, CategoryContribution> idToCategoryMap = new Dictionary <string, CategoryContribution>(categories.Length);

            // Processing categories
            for (int i = -1; ++i < categories.Length;)
            {
                IConfigurationElement category = categories[i];
                string id    = category["id"];
                string label = category["label"];

                // NLS support
                if (label.StartsWith("%"))
                {
                    string nlsKey       = label.Substring(1);
                    string assemblyName = ExtensionService.Instance.GetProvidingBundle(category).Name;
                    // We cannot use the AppDomain here, because the assembly must not have been loaded yet
                    Assembly assembly       = Assembly.Load(assemblyName); // TODO Check if this may be an issue
                    string   localizationId = NLS.GetLocalizationId(assembly);
                    label = NLS.GetText(localizationId, nlsKey);
                }

                CategoryContribution contribution = new CategoryContribution {
                    Id = id, Label = label
                };
                idToCategoryMap.Add(id, contribution);
                _contributions.Add(contribution);
            }

            // Processing wizards
            for (int i = -1; ++i < wizards.Length;)
            {
                IConfigurationElement wizard = wizards[i];
                string id        = wizard["id"];
                string category  = wizard["category"];
                string label     = wizard["label"];
                string className = wizard["class"];
                string imagePath = wizard["image"];

                if (string.IsNullOrEmpty(className))
                {
                    continue;
                }

                IWizard wizardImpl;

                try {
                    IBundle providingBundle = ExtensionService.Instance.GetProvidingBundle(wizard);
                    Type    wizardType      = TypeLoader.TypeForName(providingBundle, className);
                    wizardImpl = wizardType.NewInstance <IWizard>();
                } catch (Exception ex) {
                    _log.Error($"Error on creating wizard of type '{className}'.", ex);
                    continue;
                }

                ImageDescriptor imageDescriptor = null;
                if (!string.IsNullOrEmpty(imagePath))
                {
                    try {
                        imageDescriptor = ImageDescriptor.Create($"image.{id}", wizardImpl.GetType().Assembly, imagePath);
                    } catch (Exception ex) {
                        _log.Error($"Error on resolving image of wizard '{id}'.", ex);
                    }
                }

                // NLS support
                label = NLS.Localize(label, wizardImpl);

                WizardContribution contribution = new WizardContribution {
                    Id = id, Label = label, Category = category, Wizard = wizardImpl, Image = imageDescriptor
                };

                // Is it a categorized item?
                if (!string.IsNullOrEmpty(category))
                {
                    if (idToCategoryMap.TryGetValue(category, out CategoryContribution categoryContr))
                    {
                        categoryContr.Wizards.Add(contribution);
                        continue;
                    }
                }

                _contributions.Add(contribution);
            }
        }
コード例 #13
0
    public void Finished(FinishState FS, Sprite script)
    {
        LevelSelect.lSelect.loadStagedata();
        Sprite keepPlaying = restart;

        //set a boolean to switch off any remaining actions
        itsoverman = true;
        StopCoroutine(dropScore());

        //stop bullets from moving
        gameSpeed = 0;
        scrollbar.onValueChanged.RemoveListener(scrollbarCallBack);
        switch (FS)
        {
        //the player wins!
        case FinishState.ALIVE:

            //Have we already beat this level?
            if (thisLevel.complete == true)
            {
                keepPlaying = restart;
                //did we get a new highscore?
                if (thisLevel.score < levelScore)
                {
                    //set our new level score switch to true
                    NLS.SetActive(true);
                    //calculate the new score
                    int dif = levelScore - thisLevel.score;
                    thisLevel.score = levelScore;
                    if (GameControl.control.stagedata[GameControl.control.Stage].phases[thisLevel.phase].completed)
                    {
                        StartCoroutine(scoreup(dif));
                    }
                    //GameControl.control.stagedata[GameControl.control.Stage].score += dif;
                }

                //make the button click load the same level
                GameControl.control.leveltoLoad = thisLevel;
            }
            //did we beat a new level?
            else
            {
                //set our new level score switch to true
                NLS.SetActive(true);
                //set the save data to load this level as complete
                GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels[thisLevel.number % 5].complete = true;
                //make the button click load the next level
                keepPlaying = nextLevl;

                //are there more levels in the phase?
                if (LevelSelect.lSelect.inactivebuttons.Count != 0)
                {
                    //calculate the new score
                    thisLevel.score = levelScore;
                    //if we decided we are going to genereate the next level


                    GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels[thisLevel.number % 5].complete = true;
                    //set the highest reached level reference to the number of the next level./
                    GameControl.control.stagedata[GameControl.control.Stage].highestReachedLevel = nextLevel().number;
                    //add a button to the phase
                    LevelSelect.lSelect.AddButton(nextLevel());

                    //make the button click load the next level
                    GameControl.control.leveltoLoad = nextLevel();
                }
                //is the phase complete?
                else
                {
                    //calculate the new score
                    thisLevel.score = levelScore;
                    //set the save data to load this phase as complete
                    GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].completed = true;

                    //are there still phases in the stage?
                    if (GameControl.control.phasenum + 1 < LevelSelect.lSelect.phase[GameControl.control.Stage].intArray.Length)
                    {
                        getphasescore();
                        StartCoroutine(scoreup(GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].score));
                        //change the phase num to reference the next phase
                        GameControl.control.phasenum++;
                        //check if achievements were unlocked
                        LevelSelect.lSelect.achUn = true;
                        // LevelSelect.lSelect.unlockAchievement(GameControl.control.stagedata[GameControl.control.Stage].score);

                        //set the next level number as the highest reached level.
                        GameControl.control.stagedata[GameControl.control.Stage].highestReachedLevel++;

                        //add a new instance of a phase to the stage
                        LevelSelect.lSelect.addPhase(GameControl.control.phasenum, GameControl.control.Stage, true);
                        //make the button click load the next level
                        GameControl.control.leveltoLoad = nextLevel();
                        //add a new button to the phase.
                        LevelSelect.lSelect.AddButton(GameControl.control.leveltoLoad);
                    }
                    //did we complete the stage?
                    else
                    {
                        //change the Stage num to reference the next stage.
                        GameControl.control.Stage++;
                        // GameControl.control.leveltoLoad = nextLevel();
                        newstage = true;
                    }
                }
            }
            break;        //end the operation

        //the player died    but still has lives.
        case FinishState.DEAD:
            //set the button to restart button graphic
            keepPlaying = restart;
            //if this was not an old level
            if (!thisLevel.complete)
            {
                // did the player have a key?
                if (GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].keyLevel == thisLevel.number)

                {
                    //well, not anymore.
                    GameControl.control.key = false;
                }
                //lose a life too.
                GameControl.control.lives--;
            }
            else    // if this was an old level
            {
                if (thisLevel.number == GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels[4].number)

                {
                    //make sure the doors unlocked
                    GameControl.control.key = true;
                }
            }
            //make the button click load the same level
            GameControl.control.leveltoLoad = thisLevel;
            break;

        //the player died and has no lives
        case FinishState.GAMEOVER:
            //the player didnt complete this level
            if (!thisLevel.complete)
            {
                //the probelm here is I need to set the Buttons back to the disabled queue
                //take away all the progress of the current stage.
                //make the highest reached level the last level of the previous phase.
                GameControl.control.stagedata[GameControl.control.Stage].highestReachedLevel -= (4 - LevelSelect.lSelect.inactivebuttons.Count);
                // erase all memory of the current phase
                GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels.Clear();
                //just completely removin the thing. better check into this line of code...................................
                GameControl.control.stagedata[GameControl.control.Stage].phases.RemoveAt(GameControl.control.phasenum);
                //add a new instance of a phase to the stage
                LevelSelect.lSelect.addPhase(GameControl.control.phasenum, GameControl.control.Stage, true);
                //make the button click load the first level if the phase
                GameControl.control.leveltoLoad = GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels[0];
                //add the new levels button
                LevelSelect.lSelect.AddButton(GameControl.control.leveltoLoad);

                Invoke("GameOverCountdown", 3);
            }
            //  the player did complete this level
            else
            {
                GameControl.control.leveltoLoad = thisLevel;
            }
            break;
        }
        //  GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum].levels[thisLevel.number % 5] = thisLevel;
        //save everything for next load session
        GameControl.control.Save();
        //make the  level card appear
        levelCard.gameObject.SetActive(true);
        //calculate how much time has passed
        int min = (int)Time.time / 60;
        int sec = (int)Time.time % 60;

        levelCard.GetComponentInChildren <Text>().text = "Time:  " + min.ToString() + ":" + sec.ToString() + "\n Score: " + levelScore;
        foreach (Image img in levelCard.GetComponentsInChildren <Image>())
        {
            if (img.tag == "stats")
            {
                img.GetComponentInChildren <Text>().text = "Score " + levelScore + "\n + Time: ";
            }
            if (img.tag == "timeStop")
            {
                img.GetComponentInChildren <Text>().text = AdventureBag.aBag.times.ToString();
            }
            if (img.tag == "zoom")
            {
                img.GetComponentInChildren <Text>().text = AdventureBag.aBag.zooms.ToString();
            }
            if (img.tag == "fly")
            {
                img.GetComponentInChildren <Text>().text = AdventureBag.aBag.flys.ToString();
            }

            if (img.tag == "resultText")
            {
                img.GetComponent <Image>().sprite = script;
            }
            if (img.tag == "winloseButton")
            {
                img.GetComponent <Image>().sprite = keepPlaying;
                //Level lv = GameControl.control.stagedata[GameControl.control.Stage].phases[GameControl.control.phasenum]
                img.gameObject.GetComponent <Button>().onClick.AddListener(() => loadLevel(GameControl.control.leveltoLoad));
            }
            if (img.tag == "livesFront")
            {
                if (FS == FinishState.ALIVE)
                {
                    img.GetComponentInChildren <Text>().text      = GameControl.control.lives.ToString();
                    img.GetComponent <Rigidbody2D>().gravityScale = 0;
                }
                else if (FS == FinishState.DEAD)
                {
                    img.GetComponentInChildren <Text>().text = (GameControl.control.lives + 1).ToString();
                    img.GetComponent <Animator>().Play("paper", 0, 0);
                    img.GetComponent <Rigidbody2D>().gravityScale = 1;
                }
                //else if(FS == FinishState.GAMEOVER)
                //{
                //    Invoke ("GameOverCountdown", 3);
                //}
            }
            if (img.tag == "livesBack")
            {
                img.GetComponentInChildren <Text>().text = (GameControl.control.lives).ToString();
            }
        }
        foreach (Text img in levelCard.GetComponentsInChildren <Text>())
        {
            if (img.tag == "LevelScoreText")
            {
                img.GetComponent <Text>().text = ("Level Score: " + thisLevel.score.ToString());
            }
            if (img.tag == "CountdownText")
            {
                int dif = levelScore - thisLevel.score;
                img.GetComponent <Text>().text = ("Stage Score: " + GameControl.control.stagedata[GameControl.control.Stage].score);
            }
        }
    }
コード例 #14
0
        private async void HandleAuthInfo(BncsReader dr)
        {
            try
            {
                //DataReader dr = new DataReader(data.Data);
                //if (m_pingPck != null)
                //{
                //    Send(m_pingPck);
                //    m_pingPck = null;
                //}
                _received0x50 = true;

                _loginType          = dr.ReadUInt32();
                _srvToken           = dr.ReadInt32();
                _udpVal             = dr.ReadUInt32();
                _mpqFileTime        = dr.ReadInt64();
                _versioningFilename = dr.ReadCString();
                _usingLockdown      = _versioningFilename.StartsWith("LOCKDOWN", StringComparison.OrdinalIgnoreCase);

                int    crResult = -1, exeVer = -1;
                string exeInfo = null;

                if (!_usingLockdown)
                {
                    _valString = dr.ReadCString();
                    int mpqNum = CheckRevision.ExtractMPQNumber(_versioningFilename);
                    crResult = CheckRevision.DoCheckRevision(_valString, new Stream[] { File.OpenRead(_settings.GameExe), File.OpenRead(_settings.GameFile2), File.OpenRead(_settings.GameFile3) }, mpqNum);
                    exeVer   = CheckRevision.GetExeInfo(_settings.GameExe, out exeInfo);
                }
                else
                {
                    _ldValStr = dr.ReadNullTerminatedByteArray();
                    string dllName = _versioningFilename.Replace(".mpq", ".dll");

                    BnFtpVersion1Request req = new BnFtpVersion1Request(_settings.Client, _versioningFilename, null);
                    req.Gateway       = _settings.Gateway;
                    req.LocalFileName = Path.Combine(Path.GetTempPath(), _versioningFilename);
                    await req.ExecuteRequest();

                    string ldPath = null;
                    using (MpqArchive arch = MpqServices.OpenArchive(req.LocalFileName))
                    {
                        if (arch.ContainsFile(dllName))
                        {
                            ldPath = Path.Combine(Path.GetTempPath(), dllName);
                            arch.SaveToPath(dllName, Path.GetTempPath(), false);
                        }
                    }

                    _ldDigest = CheckRevision.DoLockdownCheckRevision(_ldValStr, new string[] { _settings.GameExe, _settings.GameFile2, _settings.GameFile3 },
                                                                      ldPath, _settings.ImageFile, ref exeVer, ref crResult);
                }

                string prodCode = _settings.Client.ProductCode;

                if (prodCode == "WAR3" || prodCode == "W3XP")
                {
                    _w3srv = dr.ReadByteArray(128);

                    if (!NLS.ValidateServerSignature(_w3srv, _connection.RemoteEP.Address.GetAddressBytes()))
                    {
                        //OnError(new ErrorEventArgs(ErrorType.Warcraft3ServerValidationFailure, Strings.War3ServerValidationFailed, false));
                        //Close();
                        //return;
                    }
                }

                //    BattleNetClientResources.IncomingBufferPool.FreeBuffer(data.Data);

                CdKey key1 = _settings.CdKey1, key2 = _settings.CdKey2;
                _clientToken = new Random().Next();

                byte[] key1Hash = key1.GetHash(_clientToken, _srvToken);
                if (WardenHandler != null)
                {
                    try
                    {
                        if (!WardenHandler.InitWarden(BitConverter.ToInt32(key1Hash, 0)))
                        {
                            WardenHandler.UninitWarden();
                            //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                            WardenHandler = null;
                        }
                    }
                    catch (Win32Exception we)
                    {
                        //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                        //OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, string.Format(CultureInfo.CurrentCulture, "Additional information: {0}", we.Message), false));
                        WardenHandler.UninitWarden();
                        WardenHandler = null;
                    }
                }

                BncsPacket pck0x51 = new BncsPacket(BncsPacketId.AuthCheck, _connection.NetworkBuffers.Acquire());
                pck0x51.InsertInt32(_clientToken);
                pck0x51.InsertInt32(exeVer);
                pck0x51.InsertInt32(crResult);
                if (prodCode == "D2XP" || prodCode == "W3XP")
                {
                    pck0x51.InsertInt32(2);
                }
                else
                {
                    pck0x51.InsertInt32(1);
                }
                pck0x51.InsertBoolean(false);
                pck0x51.InsertInt32(key1.Key.Length);
                pck0x51.InsertInt32(key1.Product);
                pck0x51.InsertInt32(key1.Value1);
                pck0x51.InsertInt32(0);
                pck0x51.InsertByteArray(key1Hash);
                if (key2 != null)
                {
                    pck0x51.InsertInt32(key2.Key.Length);
                    pck0x51.InsertInt32(key2.Product);
                    pck0x51.InsertInt32(key2.Value1);
                    pck0x51.InsertInt32(0);
                    pck0x51.InsertByteArray(key2.GetHash(_clientToken, _srvToken));
                }

                if (_usingLockdown)
                {
                    pck0x51.InsertByteArray(_ldDigest);
                    pck0x51.InsertByte(0);
                }
                else
                {
                    pck0x51.InsertCString(exeInfo);
                }

                pck0x51.InsertCString(_settings.CdKeyOwner);

                await pck0x51.SendAsync(_connection);
            }
            catch (Exception ex)
            {
                //OnError(new ErrorEventArgs(ErrorType.General, "There was an error while initializing your client.  Refer to the exception message for more information.\n" + ex.ToString(), true));
                Disconnect();

                Console.WriteLine(ex.ToString());
            }
        }
コード例 #15
0
ファイル: ToolbarItemProvider.cs プロジェクト: astorch/motoi
        /// <summary> Resolves all registered menus and items and tells the main window to handle it. </summary>
        /// <param name="mainWindow">Main window</param>
        public static void AddExtensionPointToolbarItems(IMainWindow mainWindow)
        {
            IConfigurationElement[] configurationElements = ExtensionService.Instance.GetConfigurationElements(ExtensionPointId);

            IConfigurationElement[] groupElements     = configurationElements.Where(x => x.Prefix == "toolbarGroup").ToArray();
            IConfigurationElement[] groupItemElements = configurationElements.Where(x => x.Prefix == "toolbarItem").ToArray();

            for (int i = -1; ++i < groupElements.Length;)
            {
                IConfigurationElement element = groupElements[i];
                string id = element["id"];
                ToolbarGroupContribution menu = new ToolbarGroupContribution(id);
                _idToMenuMap.Add(id, menu);
            }

            // Collection of all opened streams
            List <Stream> streamList = new List <Stream>(20);

            for (int i = -1; ++i < groupItemElements.Length;)
            {
                IConfigurationElement element = groupItemElements[i];
                string id      = element["id"];
                string group   = element["group"];
                string handler = element["handler"];
                string image   = element["image"];
                string label   = element["label"];

                IBundle providingBundle = ExtensionService.Instance.GetProvidingBundle(element);

                IActionHandler actionHandler = null;
                if (!string.IsNullOrEmpty(handler))
                {
                    Type handlerType = TypeLoader.TypeForName(providingBundle, handler);
                    actionHandler = handlerType.NewInstance <IActionHandler>();
                }

                Stream imageStream = null;
                if (!string.IsNullOrEmpty(image))
                {
                    imageStream = providingBundle.GetAssemblyResourceAsStream(image);
                    streamList.Add(imageStream);
                }

                // NLS support
                label = NLS.Localize(label, actionHandler);

                ToolbarItemContribution  menuItem = new ToolbarItemContribution(id, group, actionHandler, label, imageStream);
                ToolbarGroupContribution menuInstance;
                if (_idToMenuMap.TryGetValue(group, out menuInstance))
                {
                    menuInstance.GroupItems.Add(menuItem);
                }
            }

            using (IEnumerator <ToolbarGroupContribution> itr = _idToMenuMap.Values.GetEnumerator()) {
                while (itr.MoveNext())
                {
                    ToolbarGroupContribution contribution = itr.Current;
                    mainWindow.AddToolbarGroup(contribution);
                }
            }

            // Disposing all opened streams
            using (IEnumerator <Stream> itr = streamList.GetEnumerator()) {
                while (itr.MoveNext())
                {
                    Stream stream = itr.Current;
                    stream?.Dispose();
                }
            }
        }
コード例 #16
0
        /// <summary> Resolves all registered menus and items and tells the main window to handle it. </summary>
        /// <param name="mainWindow">Main window</param>
        public static void AddExtensionPointMenuItems(IMainWindow mainWindow)
        {
            IConfigurationElement[] configurationElements = ExtensionService.Instance.GetConfigurationElements(ExtensionPointIdMenuItems);

            List <IConfigurationElement> menuElementCollection        = new List <IConfigurationElement>(30);
            List <IConfigurationElement> menuItemElementsCollection   = new List <IConfigurationElement>(30);
            List <IConfigurationElement> menuItemSeparatorsCollection = new List <IConfigurationElement>(30);

            Func <string, ICollection <IConfigurationElement> > getCollection = prefix => {
                if (prefix == "menu")
                {
                    return(menuElementCollection);
                }
                if (prefix == "menuItem")
                {
                    return(menuItemElementsCollection);
                }
                if (prefix == "separator")
                {
                    return(menuItemSeparatorsCollection);
                }
                return(null);
            };

            // Sort elements into corresponding collections
            for (int i = -1; ++i != configurationElements.Length;)
            {
                IConfigurationElement element = configurationElements[i];
                string prefix = element.Prefix;
                ICollection <IConfigurationElement> collection = getCollection(prefix);
                collection?.Add(element);
            }

            // Process registered menus
            using (IEnumerator <IConfigurationElement> itr = menuElementCollection.GetEnumerator()) {
                while (itr.MoveNext())
                {
                    IConfigurationElement element = itr.Current;
                    string id    = element["id"];
                    string label = element["label"];

                    // NLS support
                    if (label.StartsWith("%"))
                    {
                        string nlsKey       = label.Substring(1);
                        string assemblyName = ExtensionService.Instance.GetProvidingBundle(element).Name;
                        // We cannot use the AppDomain here, because the assembly must not have been loaded yet
                        Assembly assembly       = Assembly.Load(assemblyName); // TODO Check if this may be an issue
                        string   localizationId = NLS.GetLocalizationId(assembly);
                        label = NLS.GetText(localizationId, nlsKey);
                    }

                    MenuContribution menu = new MenuContribution(id, label);
                    _idToMenuMap.Add(id, menu);
                }
            }

            // Collection of all opened streams
            LinkedList <Stream> streamList = new LinkedList <Stream>();

            // Process registered menu items
            using (IEnumerator <IConfigurationElement> itr = menuItemElementsCollection.GetEnumerator()) {
                while (itr.MoveNext())
                {
                    IConfigurationElement element = itr.Current;
                    string id       = element["id"];
                    string menu     = element["menu"];
                    string label    = element["label"];
                    string handler  = element["handler"];
                    string shortcut = element["shortcut"];
                    string image    = element["image"];

                    IBundle providingBundle = ExtensionService.Instance.GetProvidingBundle(element);

                    IActionHandler actionHandler = null;
                    if (!string.IsNullOrEmpty(handler))
                    {
                        Type handlerType = TypeLoader.TypeForName(providingBundle, handler);
                        actionHandler = handlerType.NewInstance <IActionHandler>();
                    }

                    Stream imageStream = null;
                    if (!string.IsNullOrEmpty(image))
                    {
                        imageStream = providingBundle.GetAssemblyResourceAsStream(image);
                        streamList.AddLast(imageStream);
                    }

                    // NLS support
                    label = NLS.Localize(label, actionHandler);

                    MenuItemContribution menuItem = new MenuItemContribution(id, label, menu, actionHandler, shortcut, imageStream);
                    if (_idToMenuMap.TryGetValue(menu, out MenuContribution menuInstance))
                    {
                        menuInstance.MenuItems.Add(menuItem);
                    }
                }
            }

            int findIndex(IList <MenuItemContribution> set, string itemRef)
            {
                for (int i = -1; ++i != set.Count;)
                {
                    MenuItemContribution mic = set[i];
                    if (mic.Id == itemRef)
                    {
                        return(i);
                    }
                }

                return(-1);
            }

            // Process registered separators
            using (IEnumerator <IConfigurationElement> itr = menuItemSeparatorsCollection.GetEnumerator()) {
                while (itr.MoveNext())
                {
                    IConfigurationElement element = itr.Current;
                    string id           = element["id"];
                    string menu         = element["menu"];
                    string insertBefore = element["insertBefore"];
                    string insertAfter  = element["insertAfter"];

                    MenuItemContribution menuItem = new MenuItemContribution(id, string.Empty, menu, null, null, null)
                    {
                        IsSeparator = true
                    };
                    if (!_idToMenuMap.TryGetValue(menu, out MenuContribution menuContribution))
                    {
                        continue;
                    }

                    bool   useInsertBefore = !string.IsNullOrEmpty(insertBefore);
                    string itemReference   = useInsertBefore ? insertBefore : insertAfter;
                    IList <MenuItemContribution> menuItemCollection = menuContribution.MenuItems;
                    int referenceIndex = findIndex(menuItemCollection, itemReference);
                    if (referenceIndex == -1)
                    {
                        continue;
                    }

                    int insertIndex = useInsertBefore ? referenceIndex : referenceIndex + 1;
                    menuItemCollection.Insert(insertIndex, menuItem);
                }
            }

            // Support custom menu configurer
            ICustomMenuConfigurer customMenuConfigurer = GetCustomMenuConfigurer();

            MenuContribution[] menuContributions       = _idToMenuMap.Values.ToArray();
            MenuContribution[] customMenuContributions = customMenuConfigurer != null
                ? customMenuConfigurer.Configure(menuContributions)
                : menuContributions;

            // Add each contributed menu to the main window
            Array.ForEach(customMenuContributions, mainWindow.AddMenu);

            // Disposing all opened streams
            using (LinkedList <Stream> .Enumerator enmtor = streamList.GetEnumerator()) {
                while (enmtor.MoveNext())
                {
                    Stream stream = enmtor.Current;
                    stream?.Dispose();
                }
            }
        }
コード例 #17
0
        private void HandleAuthInfo(ParseData data)
        {
            try
            {
                DataReader dr = new DataReader(data.Data);
                if (m_pingPck != null)
                {
                    Send(m_pingPck);
                    m_pingPck = null;
                }
                m_received0x50 = true;

                m_loginType          = dr.ReadUInt32();
                m_srvToken           = dr.ReadUInt32();
                m_udpVal             = dr.ReadUInt32();
                m_mpqFiletime        = dr.ReadInt64();
                m_versioningFilename = dr.ReadCString();
                m_usingLockdown      = m_versioningFilename.StartsWith("LOCKDOWN", StringComparison.OrdinalIgnoreCase);

                int    crResult = -1, exeVer = -1;
                string exeInfo = null;

                if (!m_usingLockdown)
                {
                    m_valString = dr.ReadCString();
                    int mpqNum = CheckRevision.ExtractMPQNumber(m_versioningFilename);
                    crResult = CheckRevision.DoCheckRevision(m_valString, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 }, mpqNum);
                    exeVer   = CheckRevision.GetExeInfo(m_settings.GameExe, out exeInfo);
                }
                else
                {
                    m_ldValStr = dr.ReadNullTerminatedByteArray();
                    string dllName = m_versioningFilename.Replace(".mpq", ".dll");

                    BnFtpVersion1Request req = new BnFtpVersion1Request(m_settings.Client, m_versioningFilename, null);
                    req.Server        = m_settings.Gateway.ServerHost;
                    req.LocalFileName = Path.Combine(Path.GetTempPath(), m_versioningFilename);
                    req.ExecuteRequest();

                    string ldPath = null;
                    using (MpqArchive arch = MpqServices.OpenArchive(req.LocalFileName))
                    {
                        if (arch.ContainsFile(dllName))
                        {
                            ldPath = Path.Combine(Path.GetTempPath(), dllName);
                            arch.SaveToPath(dllName, Path.GetTempPath(), false);
                        }
                    }

                    m_ldDigest = CheckRevision.DoLockdownCheckRevision(m_ldValStr, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 },
                                                                       ldPath, m_settings.ImageFile, ref exeVer, ref crResult);
                }

                m_prodCode = m_settings.Client;

                if (m_prodCode == "WAR3" ||
                    m_prodCode == "W3XP")
                {
                    m_w3srv = dr.ReadByteArray(128);

                    if (!NLS.ValidateServerSignature(m_w3srv, RemoteEP.Address.GetAddressBytes()))
                    {
                        OnError(new ErrorEventArgs(ErrorType.Warcraft3ServerValidationFailure, Strings.War3ServerValidationFailed, false));
                        //Close();
                        //return;
                    }
                }

                BattleNetClientResources.IncomingBufferPool.FreeBuffer(data.Data);

                CdKey key1, key2 = null;
                key1 = new CdKey(m_settings.CdKey1);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    key2 = new CdKey(m_settings.CdKey2);
                }

                m_clientToken = unchecked ((uint)new Random().Next());

                byte[] key1Hash = key1.GetHash(m_clientToken, m_srvToken);
                if (m_warden != null)
                {
                    try
                    {
                        if (!m_warden.InitWarden(BitConverter.ToInt32(key1Hash, 0)))
                        {
                            m_warden.UninitWarden();
                            OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                            m_warden = null;
                        }
                    }
                    catch (Win32Exception we)
                    {
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, string.Format(CultureInfo.CurrentCulture, "Additional information: {0}", we.Message), false));
                        m_warden.UninitWarden();
                        m_warden = null;
                    }
                }

                BncsPacket pck0x51 = new BncsPacket((byte)BncsPacketId.AuthCheck);
                pck0x51.Insert(m_clientToken);
                pck0x51.Insert(exeVer);
                pck0x51.Insert(crResult);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    pck0x51.Insert(2);
                }
                else
                {
                    pck0x51.Insert(1);
                }
                pck0x51.Insert(false);
                pck0x51.Insert(key1.Key.Length);
                pck0x51.Insert(key1.Product);
                pck0x51.Insert(key1.Value1);
                pck0x51.Insert(0);
                pck0x51.Insert(key1Hash);
                if (key2 != null)
                {
                    pck0x51.Insert(key2.Key.Length);
                    pck0x51.Insert(key2.Product);
                    pck0x51.Insert(key2.Value1);
                    pck0x51.Insert(0);
                    pck0x51.Insert(key2.GetHash(m_clientToken, m_srvToken));
                }

                if (m_usingLockdown)
                {
                    pck0x51.InsertByteArray(m_ldDigest);
                    pck0x51.InsertByte(0);
                }
                else
                {
                    pck0x51.InsertCString(exeInfo);
                }

                pck0x51.InsertCString(m_settings.CdKeyOwner);

                Send(pck0x51);
            }
            catch (Exception ex)
            {
                OnError(new ErrorEventArgs(ErrorType.General, "There was an error while initializing your client.  Refer to the exception message for more information.\n" + ex.ToString(), true));
                Close();
            }
        }