Пример #1
0
        /// <summary>
        /// Send messages from the session (message) queue in a FIFO fashion.
        /// </summary>
        /// <returns></returns>
        internal bool TryDrainSessionSendQueue()
        {
            bool barrierOpen;
            var  messageExists        = true;
            var  sessionQuotaExceeded = false;
            var  driverDisposed       = false;

            // if we got through the barrier and exited because we found no message but the sessionQueue is not empty then there was a race that
            // a Send operation lost so we circle back and try sending the message that the Send operation would have tried to send
            do
            {
                // low impact lock - while sending a message to ensure we process sends synchronously in FIFO
                var value = Interlocked.CompareExchange(ref this.drainQueueBarrier, 1, 0);
                barrierOpen = value == 0;

                if (barrierOpen)
                {
                    try
                    {
                        while (!sessionQuotaExceeded && !driverDisposed && messageExists)
                        {
                            IOperationData nextMessage = null;
                            messageExists = this.sessionQueue.TryPeek(out nextMessage);

                            // IMPORTANT: This try-catch code relies on the fact that the COM-interop layer SYNCHRONOUSLY THROWS A FAULT from the BeginFunc OF SendAsync
                            // TODO: find a way to push handling of this transient fault down into the managed wrapper for sessions
                            // TODO: what happens if there is a session Abort? Or a failure of the partner?
                            if (messageExists)
                            {
                                try
                                {
                                    // drop the Task returned since the only possible exceptions in the task results reflect session abort
                                    // we will get a notification for session abort through the registered interface and deal with it there
                                    this.outboundSession.SendAsync(nextMessage, CancellationToken.None).ContinueWith(this.SendContinuation);
                                }
                                catch (FabricException fabricException)
                                {
                                    var errorCode = fabricException.ErrorCode;

                                    if (errorCode == FabricErrorCode.ReliableSessionQuotaExceeded)
                                    {
                                        FabricEvents.Events.SessionSendFailure("QuotaExceeded@" + this.streamManager.TraceType, this.SessionId.ToString());
                                        sessionQuotaExceeded = true;
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (e is InvalidOperationException || e is OperationCanceledException)
                                    {
                                        FabricEvents.Events.SessionSendFailure("SessionAborted@" + this.streamManager.TraceType, this.SessionId.ToString());

                                        // the driver was Disposed usually due to partner reset, this driver is no longer valid: confirm that
                                        var snapshot = this.outboundSession.GetDataSnapshot();
                                        Diagnostics.Assert(
                                            !snapshot.IsOpenForSend,
                                            "{0} InvalidOperationException when outboundSession is open for Send in TryDrainSessionSendQueue",
                                            this.tracer);
                                        driverDisposed = true;
                                    }
                                    else
                                    {
                                        Tracing.WriteExceptionAsError(
                                            "SendAsync.Failure",
                                            e,
                                            "{0} OutboundSessionDriver.SendContinuation encountered unexpected exception",
                                            this.tracer);
                                        Diagnostics.Assert(
                                            false,
                                            "{0} Unexpected exception {1} in OutboundSessionDriver.SendContinuation",
                                            this.tracer,
                                            e.GetType());
                                    }
                                }
                                // dequeue the message only if the message was successfully handed out to the session for send proc.
                                if (!sessionQuotaExceeded && !driverDisposed)
                                {
                                    var popSuccess = this.sessionQueue.TryDequeue(out nextMessage);
                                    Diagnostics.Assert(
                                        popSuccess,
                                        "{0} Unexpected missing message in OutboundSessionDriver.TryDrainSessionSendQueue",
                                        this.tracer);
                                }
                            }
                        }
                    }
                    finally
                    {
                        value = Interlocked.CompareExchange(ref this.drainQueueBarrier, 0, 1);
                        Diagnostics.Assert(
                            value == 1,
                            "drainQueueBarrier was reset to 0 while inside critical section in OutboundSessionDriver.TryDrainSessionSendQueue");
                    }
                }
            } // Finally check if messages got added to the queue while we were busy processing the earlier message.
            while (barrierOpen && !driverDisposed && !messageExists && this.sessionQueue.Count > 0);

            return(sessionQuotaExceeded);
        }
Пример #2
0
        /// <summary>
        /// Remove breakpoints.
        /// </summary>
        protected override void ProcessRecord()
        {
            List <Breakpoint> breakpoints = Context.Debugger.GetBreakpoints();

            //
            // Filter by parameter set
            //
            if (this.ParameterSetName.Equals("Script", StringComparison.OrdinalIgnoreCase))
            {
                // no filter
            }
            else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase))
            {
                breakpoints = Filter(
                    breakpoints,
                    _id,
                    delegate(Breakpoint breakpoint, int id)
                {
                    return(breakpoint.Id == id);
                }
                    );
            }
            else if (this.ParameterSetName.Equals("Command", StringComparison.OrdinalIgnoreCase))
            {
                breakpoints = Filter(
                    breakpoints,
                    _command,
                    delegate(Breakpoint breakpoint, string command)
                {
                    CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint;

                    if (commandBreakpoint == null)
                    {
                        return(false);
                    }

                    return(commandBreakpoint.Command.Equals(command, StringComparison.OrdinalIgnoreCase));
                });
            }
            else if (this.ParameterSetName.Equals("Variable", StringComparison.OrdinalIgnoreCase))
            {
                breakpoints = Filter(
                    breakpoints,
                    _variable,
                    delegate(Breakpoint breakpoint, string variable)
                {
                    VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint;

                    if (variableBreakpoint == null)
                    {
                        return(false);
                    }

                    return(variableBreakpoint.Variable.Equals(variable, StringComparison.OrdinalIgnoreCase));
                });
            }
            else if (this.ParameterSetName.Equals("Type", StringComparison.OrdinalIgnoreCase))
            {
                breakpoints = Filter(
                    breakpoints,
                    _type,
                    delegate(Breakpoint breakpoint, BreakpointType type)
                {
                    switch (type)
                    {
                    case BreakpointType.Line:
                        if (breakpoint is LineBreakpoint)
                        {
                            return(true);
                        }

                        break;

                    case BreakpointType.Command:
                        if (breakpoint is CommandBreakpoint)
                        {
                            return(true);
                        }

                        break;

                    case BreakpointType.Variable:
                        if (breakpoint is VariableBreakpoint)
                        {
                            return(true);
                        }

                        break;
                    }

                    return(false);
                });
            }
            else
            {
                Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName);
            }

            //
            // Filter by script
            //
            if (_script != null)
            {
                breakpoints = Filter(
                    breakpoints,
                    _script,
                    delegate(Breakpoint breakpoint, string script)
                {
                    if (breakpoint.Script == null)
                    {
                        return(false);
                    }

                    return(string.Compare(
                               SessionState.Path.GetUnresolvedProviderPathFromPSPath(breakpoint.Script),
                               SessionState.Path.GetUnresolvedProviderPathFromPSPath(script),
                               StringComparison.OrdinalIgnoreCase
                               ) == 0);
                });
            }

            //
            // Output results
            //
            foreach (Breakpoint b in breakpoints)
            {
                WriteObject(b);
            }
        }
Пример #3
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(uriToLaunch != null, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            // we use this test hook is to avoid actually calling out to another process
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                this.WriteObject(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                return;
            }

            Exception exception           = null;
            bool      wrapCaughtException = true;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();

                if (Platform.IsNanoServer || Platform.IsIoT)
                {
                    // We cannot open the URL in browser on headless SKUs.
                    wrapCaughtException = false;
                    exception           = PSTraceSource.NewInvalidOperationException(HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    browserProcess.StartInfo.FileName        = uriToLaunch.OriginalString;
                    browserProcess.StartInfo.UseShellExecute = true;
                    browserProcess.Start();
                }
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (exception != null)
            {
                if (wrapCaughtException)
                {
                    throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    throw exception;
                }
            }
        }
Пример #4
0
 internal void LeaveScope()
 {
     Diagnostics.Assert(_scopes.Count > 0, "Scope stack can't be empty when leaving a scope");
     _scopes.RemoveAt(_scopes.Count - 1);
 }
Пример #5
0
    public State CheckConditions(QuestBehaviour questBehaviour, GameEvent gameEvent, params object[] parameters)
    {
        if (this.ConditionChecks == null)
        {
            return(State.Success);
        }
        if (this.InterpretedVarsToUpdate != null && this.InterpretedVarsToUpdate.Length != 0)
        {
            Dictionary <StaticString, IEnumerable <SimulationObjectWrapper> > dictionary = new Dictionary <StaticString, IEnumerable <SimulationObjectWrapper> >();
            dictionary.Add("$(Empire)", new SimulationObjectWrapper[]
            {
                questBehaviour.Initiator
            });
            IGameService service = Services.GetService <IGameService>();
            Diagnostics.Assert(service != null && service.Game != null);
            dictionary.Add("$(Empires)", (from emp in (service.Game as global::Game).Empires
                                          where emp is MajorEmpire && !(emp as MajorEmpire).IsEliminated
                                          select emp).ToArray <global::Empire>());
            string[] interpretedVarsToUpdate = this.InterpretedVarsToUpdate;
            for (int i = 0; i < interpretedVarsToUpdate.Length; i++)
            {
                string variable = interpretedVarsToUpdate[i];
                QuestVariableDefinition questVariableDefinition = questBehaviour.Quest.QuestDefinition.Variables.FirstOrDefault((QuestVariableDefinition varDefinition) => varDefinition is QuestInterpretedVariableDefinition && varDefinition.VarName == variable);
                if (questVariableDefinition != null)
                {
                    QuestVariable questVariable = questBehaviour.QuestVariables.FirstOrDefault((QuestVariable questVar) => questVar.Name == variable);
                    if (questVariable != null)
                    {
                        questVariable.Object = (questVariableDefinition as QuestInterpretedVariableDefinition).Evaluate(dictionary, questBehaviour.QuestVariables);
                        if (global::GameManager.Preferences.QuestVerboseMode)
                        {
                            Diagnostics.Log("[Quest] Updated value of '{0}' to '{1}' in quest '{2}'", new object[]
                            {
                                variable,
                                questVariable.Object,
                                questBehaviour.Quest.QuestDefinition.Name
                            });
                        }
                    }
                    else
                    {
                        Diagnostics.LogError("[Quest] InterpretedVarToUpdate '{0}' is not registered in quest behaviour '{1}'", new object[]
                        {
                            variable,
                            questBehaviour.Quest.QuestDefinition.Name
                        });
                    }
                }
                else
                {
                    Diagnostics.LogError("[Quest] Could not find InterpretedVarToUpdate '{0}' in quest '{1}'", new object[]
                    {
                        variable,
                        questBehaviour.Quest.QuestDefinition.Name
                    });
                }
            }
        }
        bool flag = false;

        for (int j = 0; j < this.ConditionChecks.Length; j++)
        {
            QuestBehaviourTreeNode_ConditionCheck questBehaviourTreeNode_ConditionCheck = this.ConditionChecks[j];
            State state = questBehaviourTreeNode_ConditionCheck.CheckCondition(questBehaviour, gameEvent, parameters);
            if (questBehaviourTreeNode_ConditionCheck.Inverted)
            {
                state = base.Inverse(state);
            }
            if (state == State.Failure)
            {
                if (questBehaviourTreeNode_ConditionCheck.IsFailureCondition)
                {
                    return(State.Failure);
                }
                flag = true;
            }
        }
        if (flag)
        {
            return(State.Running);
        }
        return(State.Success);
    }
Пример #6
0
 internal void SetCommandLineParameters(FormattingCommandLineParameters commandLineParameters)
 {
     Diagnostics.Assert(commandLineParameters != null, "the caller has to pass a valid instance");
     _parameters = commandLineParameters;
 }
Пример #7
0
    public void RefreshContent()
    {
        if (this.City == null)
        {
            return;
        }
        if (this.City.Empire == null)
        {
            return;
        }
        if (this.GuiEmpire.Index != this.City.Empire.Index)
        {
            if (this.guiEmpire == null)
            {
                this.Unbind();
                return;
            }
            this.GuiEmpire = new GuiEmpire(this.City.Empire);
            DepartmentOfIndustry agency = this.City.Empire.GetAgency <DepartmentOfIndustry>();
            this.ConstructionQueue = agency.GetConstructionQueue(this.City);
        }
        if (this.GuiEmpire != null)
        {
            this.FactionBackground.TintColor = this.GuiEmpire.Color;
            this.PopulationSymbol.TintColor  = this.GuiEmpire.Color;
            this.FactionSymbol.TintColor     = this.GuiEmpire.Color;
            this.PinLine.TintColor           = this.GuiEmpire.Color;
            this.PopulationNumber.Text       = GuiFormater.FormatGui(this.City.GetPropertyValue(SimulationProperties.Population), false, false, false, 1);
            this.FactionSymbol.Image         = this.GuiEmpire.GuiFaction.GetImageTexture(global::GuiPanel.IconSize.LogoSmall, true);
        }
        string content = "%CityCurrentConstructionDescription";

        if (this.City.IsInfected)
        {
            this.PanelSpying.Visible        = false;
            this.PanelOvergrownCity.Visible = true;
            this.AgeTransform.Height        = this.ModifierPosition.EndHeight;
            if (this.GuiPreviousEmpire == null)
            {
                this.GuiPreviousEmpire = new GuiEmpire(this.City.LastNonInfectedOwner);
            }
            if (this.GuiPreviousEmpire != null)
            {
                this.PreviousEmpireFactionIcon.TintColor     = this.GuiPreviousEmpire.Color;
                this.PreviousEmpireFactionIcon.Image         = this.GuiPreviousEmpire.GuiFaction.GetImageTexture(global::GuiPanel.IconSize.LogoSmall, true);
                this.PreviousEmpireFactionTooltip.Class      = "Descriptor";
                this.PreviousEmpireFactionTooltip.ClientData = this.GuiEmpire.Empire;
                Faction faction = this.GuiPreviousEmpire.Empire.Faction;
                if (faction != null)
                {
                    new List <string>();
                    foreach (SimulationDescriptor simulationDescriptor in faction.GetIntegrationDescriptors())
                    {
                        this.PreviousEmpireFactionTooltip.Content = simulationDescriptor.Name;
                    }
                }
            }
            if (this.ConstructionQueue.PendingConstructions.Count > 0)
            {
                Construction construction = this.ConstructionQueue.Peek();
                if (construction.ConstructibleElement.SubCategory == "SubCategoryAssimilation" && construction.ConstructibleElement.Name != "CityConstructibleActionInfectedRaze")
                {
                    content = "%IntegratingFactionUnderConstructionDescription";
                }
            }
        }
        this.ConstructionGroup.AgeTooltip.Content = content;
        this.RefreshCityName();
        DepartmentOfIntelligence agency2 = this.playerControllerRepository.ActivePlayerController.Empire.GetAgency <DepartmentOfIntelligence>();
        bool flag = this.playerControllerRepository.ActivePlayerController.Empire.SimulationObject.Tags.Contains(global::Empire.TagEmpireEliminated);

        if (flag && ELCPUtilities.SpectatorSpyFocus >= 0)
        {
            agency2 = this.game.Empires[ELCPUtilities.SpectatorSpyFocus].GetAgency <DepartmentOfIntelligence>();
        }
        Unit hero = null;

        InfiltrationProcessus.InfiltrationState infiltrationState = InfiltrationProcessus.InfiltrationState.None;
        bool flag2 = false;

        if (this.playerControllerRepository != null)
        {
            if (this.City.Empire == this.playerControllerRepository.ActivePlayerController.Empire)
            {
                flag2 = true;
            }
            else if (this.PanelSpying.Visible && agency2 != null && agency2.TryGetSpyOnGarrison(this.City, out hero, out infiltrationState) && infiltrationState == InfiltrationProcessus.InfiltrationState.Infiltrated)
            {
                flag2 = true;
            }
            else if (flag)
            {
                flag2 = true;
            }
        }
        if (!flag2)
        {
            if (this.City.Empire == null)
            {
                this.CompetitorTitle.Text = string.Empty;
            }
            else
            {
                DiplomaticRelation diplomaticRelation = this.playerControllerRepository.ActivePlayerController.Empire.GetAgency <DepartmentOfForeignAffairs>().GetDiplomaticRelation(this.City.Empire);
                Diagnostics.Assert(diplomaticRelation != null);
                if (diplomaticRelation.State != null && diplomaticRelation.State.Name == DiplomaticRelationState.Names.Alliance)
                {
                    AgeUtils.TruncateString(AgeLocalizer.Instance.LocalizeString("%CityLabelAlliedTitle"), this.CompetitorTitle, out this.temp, '.');
                    this.CompetitorTitle.Text = this.temp;
                }
                else if (diplomaticRelation.State != null && diplomaticRelation.State.Name == DiplomaticRelationState.Names.Peace)
                {
                    AgeUtils.TruncateString(AgeLocalizer.Instance.LocalizeString("%CityLabelFriendlyTitle"), this.CompetitorTitle, out this.temp, '.');
                    this.CompetitorTitle.Text = this.temp;
                }
                else
                {
                    AgeUtils.TruncateString(AgeLocalizer.Instance.LocalizeString("%CityLabelEnemyTitle"), this.CompetitorTitle, out this.temp, '.');
                    this.CompetitorTitle.Text = this.temp;
                }
            }
        }
        this.SelectionButton.AgeTransform.Enable = flag2;
        this.PlayerSpecificGroup.Visible         = flag2;
        this.CompetitorSpecificGroup.Visible     = !flag2;
        float propertyValue  = this.City.GetPropertyValue(SimulationProperties.CityDefensePoint);
        float propertyValue2 = this.City.GetPropertyValue(SimulationProperties.MaximumCityDefensePoint);
        float propertyValue3 = this.City.GetPropertyValue(SimulationProperties.CityDefensePointRecoveryPerTurn);
        float propertyValue4 = this.City.GetPropertyValue(SimulationProperties.Ownership);

        Diagnostics.Assert(this.UnitNumber != null);
        Diagnostics.Assert(this.City.StandardUnits != null);
        int num = (this.City.Militia == null) ? 0 : this.City.Militia.StandardUnits.Count;

        this.UnitNumber.Text    = GuiFormater.FormatGui(this.City.StandardUnits.Count + num);
        this.DefenseNumber.Text = GuiFormater.FormatStock(propertyValue, SimulationProperties.CityDefensePoint, 0, true);
        float propertyValue5 = this.City.GetPropertyValue(SimulationProperties.DefensivePower);

        this.DefenseGroup.AgeTooltip.Content = AgeLocalizer.Instance.LocalizeString("%CityDefenseDescription");
        this.DefenseIcon.Image = AgeManager.Instance.FindDynamicTexture("fortificationCityLabel", false);
        if (propertyValue5 > 0f)
        {
            this.DefenseGroup.AgeTooltip.Content = AgeLocalizer.Instance.LocalizeString("%CityDefenseWithDefensivePowerDescription").Replace("$DefensivePowerValue", GuiFormater.FormatGui(propertyValue5, false, true, false, 1));
            this.DefenseIcon.Image = AgeManager.Instance.FindDynamicTexture("retaliationCityLabel", false);
        }
        this.DefenseGroup.AgeTooltip.Content = this.DefenseGroup.AgeTooltip.Content.Replace("$CityDefenseValue", GuiFormater.FormatGui(propertyValue, false, true, false, 1));
        if (propertyValue4 < 1f && !this.City.IsInfected)
        {
            this.OwnershipPercentage.AgeTransform.Visible = true;
            this.OwnershipPercentage.Text = GuiFormater.FormatGui(propertyValue4, true, false, false, 1);
        }
        else
        {
            this.OwnershipPercentage.AgeTransform.Visible = false;
        }
        if (this.City.BesiegingEmpire != null || this.City.BesiegingSeafaringArmies.Count != 0 || this.City.IsUnderEarthquake)
        {
            float num2 = DepartmentOfTheInterior.GetBesiegingPower(this.City, true);
            num2 += DepartmentOfTheInterior.GetCityPointEarthquakeDamage(this.City);
            this.DefenseTendency.Text = "(" + GuiFormater.FormatGui(-num2, false, true, true, 1) + ")";
        }
        else if (propertyValue < propertyValue2)
        {
            this.DefenseTendency.Text = "(" + GuiFormater.FormatGui(propertyValue3, false, true, true, 1) + ")";
        }
        else
        {
            this.DefenseTendency.Text = string.Empty;
        }
        if (flag2)
        {
            Construction construction2 = null;
            if (this.ConstructionQueue != null)
            {
                construction2 = this.ConstructionQueue.Peek();
            }
            if (this.City.IsInfected && construction2 == null)
            {
                this.PlayerSpecificGroup.Visible = false;
            }
            if (construction2 != null)
            {
                IImageFeatureProvider imageFeatureProvider = construction2.ConstructibleElement as IImageFeatureProvider;
                GuiElement            guiElement;
                if (imageFeatureProvider != null)
                {
                    Texture2D image;
                    if (imageFeatureProvider.TryGetTextureFromIcon(global::GuiPanel.IconSize.Small, out image))
                    {
                        this.ConstructionImage.Image = image;
                    }
                }
                else if (this.guiPanelHelper.TryGetGuiElement(construction2.ConstructibleElement.Name, out guiElement))
                {
                    Texture2D image2;
                    if (this.guiPanelHelper.TryGetTextureFromIcon(guiElement, global::GuiPanel.IconSize.Small, out image2))
                    {
                        this.ConstructionImage.Image = image2;
                    }
                }
                else
                {
                    this.ConstructionImage.Image = null;
                }
                CityLabel.emptyList.Clear();
                int   b;
                float num3;
                float num4;
                bool  flag3;
                QueueGuiItem.GetConstructionTurnInfos(this.City, construction2, CityLabel.emptyList, out b, out num3, out num4, out flag3);
                int numberOfTurn = Mathf.Max(1, b);
                this.ConstructionTurns.Text = QueueGuiItem.FormatNumberOfTurns(numberOfTurn);
            }
            else
            {
                this.ConstructionImage.Image = this.NoConstructionTexture;
                this.ConstructionTurns.Text  = "%EmptyConstructionTitle";
            }
        }
        if (this.PanelSpying.Visible && this.playerControllerRepository != null && agency2 != null)
        {
            float value = this.City.GetPropertyValue(SimulationProperties.CityAntiSpy) * 0.01f;
            this.AntiSpyValue.Text                    = GuiFormater.FormatGui(value, true, true, false, 0);
            this.HeroGroup.Visible                    = false;
            this.SpyingEffectsGroup.Visible           = false;
            this.AssignSpyButton.AgeTransform.Visible = false;
            if (this.City.Empire != this.playerControllerRepository.ActivePlayerController.Empire)
            {
                if (infiltrationState != InfiltrationProcessus.InfiltrationState.None)
                {
                    this.HeroGroup.Visible = true;
                    this.HeroCard.Bind(hero, this.playerControllerRepository.ActivePlayerController.Empire as global::Empire, null);
                    this.HeroCard.RefreshContent(false, false);
                    if (this.HeroCard.GuiHero != null)
                    {
                        AgeTooltip ageTooltip = this.HeroCard.HeroPortrait.AgeTransform.AgeTooltip;
                        if (ageTooltip != null)
                        {
                            ageTooltip.Class      = "Unit";
                            ageTooltip.ClientData = this.HeroCard.GuiHero;
                            ageTooltip.Content    = this.HeroCard.GuiHero.Title;
                        }
                    }
                    if (infiltrationState == InfiltrationProcessus.InfiltrationState.Infiltrated)
                    {
                        this.InfiltrationTurnSymbol.AgeTransform.Visible = false;
                        this.InfiltrationTurnValue.AgeTransform.Visible  = false;
                        this.HeroCard.AgeTransform.Alpha = 1f;
                        this.SpyingEffectsGroup.Visible  = true;
                    }
                    else
                    {
                        this.HeroCard.AgeTransform.Alpha = 0.75f;
                        this.InfiltrationTurnSymbol.AgeTransform.Visible = true;
                        this.InfiltrationTurnValue.AgeTransform.Visible  = true;
                        int value2 = DepartmentOfIntelligence.InfiltrationRemainingTurns(hero);
                        this.InfiltrationTurnValue.Text = GuiFormater.FormatGui(value2);
                    }
                }
                else if (!flag)
                {
                    this.AssignSpyButton.AgeTransform.Visible = true;
                    float value3 = 0f;
                    this.failures.Clear();
                    bool flag4 = agency2.CanBeInfiltrate(this.City, out value3, this.failures);
                    bool flag5 = agency2.Empire.GetAgency <DepartmentOfEducation>().Heroes.Count < 1;
                    if (flag5)
                    {
                        flag4 = false;
                    }
                    this.AssignSpyButton.AgeTransform.Enable = flag4;
                    global::IGuiService service = Services.GetService <global::IGuiService>();
                    string str = string.Empty;
                    if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureNotAffordable))
                    {
                        str = "#c52222#";
                    }
                    string arg    = str + GuiFormater.FormatGui(value3, false, true, false, 0) + service.FormatSymbol(this.infiltrationCostResourceName);
                    string format = AgeLocalizer.Instance.LocalizeString("%EspionageLabelAssignSpyTitle");
                    this.AssignTitle.Text = string.Format(format, arg);
                    AgeTooltip ageTooltip2 = this.AssignSpyButton.AgeTransform.AgeTooltip;
                    if (ageTooltip2)
                    {
                        if (flag4)
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyDescription";
                        }
                        else if (flag5)
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyNoHeroesDescription";
                        }
                        else if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureNotVisible))
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyNoVisibilityDescription";
                        }
                        else if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureSiege))
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyUnderSiegeDescription";
                        }
                        else if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureNotAffordable))
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyNotAffordableDescription";
                        }
                        else if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureAlreadyInfiltrated))
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyAlreadyInfiltratedDescription";
                        }
                        else if (this.failures.Contains(DepartmentOfIntelligence.InfiltrationTargetFailureCityInfected))
                        {
                            ageTooltip2.Content = "%EspionageLabelAssignSpyCityInfectedDescription";
                        }
                    }
                }
            }
        }
        bool         flag6 = false;
        List <Kaiju> list  = new List <Kaiju>();

        foreach (RegionalEffect regionalEffect in this.city.GetRegionalEffects())
        {
            IRegionalEffectsProviderGameEntity regionalEffectsProviderGameEntity = null;
            if (this.regionalEffectsService.TryGetEffectOwner(regionalEffect.GUID, out regionalEffectsProviderGameEntity) && regionalEffectsProviderGameEntity.GetRegionalEffectsProviderContext().SimulationObject.Tags.Contains("ClassKaiju"))
            {
                flag6 = true;
                if (regionalEffectsProviderGameEntity is Kaiju)
                {
                    Kaiju item = regionalEffectsProviderGameEntity as Kaiju;
                    if (!list.Contains(item))
                    {
                        list.Add(item);
                    }
                }
            }
        }
        if (flag6)
        {
            AgeTransform ageTransform = this.KaijuIcon.AgeTransform;
            ageTransform.Visible = true;
            ageTransform.Enable  = true;
            this.PopulationGroup.PercentBottom = 100f - (ageTransform.Height + ageTransform.PixelMarginBottom) / ageTransform.GetParent().Height * 100f;
            KaijuInfluenceInCityTooltipData clientData = new KaijuInfluenceInCityTooltipData(this.City, list);
            this.KaijuIcon.AgeTransform.AgeTooltip.Content    = "%CityKaijuAffectedDescription";
            this.KaijuIcon.AgeTransform.AgeTooltip.Class      = "Kaijus";
            this.KaijuIcon.AgeTransform.AgeTooltip.ClientData = clientData;
            return;
        }
        this.KaijuIcon.AgeTransform.Visible = false;
        this.KaijuIcon.AgeTransform.Enable  = false;
        this.PopulationGroup.PercentBottom  = 100f;
    }
Пример #8
0
 public override void Update()
 {
     base.Update();
     this.FiniteStateMachine.Update();
     if (this.ReturnToLobby)
     {
         if (this.GameServer != null)
         {
             this.GameServer.Dispose();
             this.GameServer = null;
         }
         if (this.GameClient != null)
         {
             this.GameClient.Dispose();
             this.GameClient = null;
         }
         Amplitude.Unity.View.IViewService service = Services.GetService <Amplitude.Unity.View.IViewService>();
         Diagnostics.Assert(service != null);
         service.PostViewChange(typeof(OutGameView), new object[]
         {
             typeof(MenuNewGameScreen)
         });
         this.PostStateChange(typeof(SessionState_Opened), new object[0]);
         string text = AgeLocalizer.Instance.LocalizeString("%RichPresenceInLobby" + base.SessionMode);
         text = text.Replace("$Name", base.GetLobbyData <string>("name", null));
         Steamworks.SteamAPI.SteamFriends.SetRichPresence("status", text);
         this.SetLobbyData("_Launching", false, true);
         this.SetLobbyData("_GameInProgress", false, true);
         this.SetLobbyData("_GameIsMigrating", false, true);
         this.SetLobbyData("_GameSyncState", SynchronizationState.Unset.ToString(), true);
         base.SteamIDServer    = null;
         this.LocalPlayerReady = false;
         this.ReturnToLobby    = false;
         return;
     }
     if (this.GameServer != null)
     {
         (this.GameServer as GameServer).Update();
     }
     if (this.GameClient != null)
     {
         (this.GameClient as GameClient).Update();
     }
     if (this.GameServer != null)
     {
         DateTime   utcNow     = DateTime.UtcNow;
         GameServer gameServer = this.GameServer as GameServer;
         int        num        = 0;
         while (num < 10000 && gameServer.HasPendingOrder)
         {
             gameServer.UpdateMessageBoxAndProcessOrders();
             if (this.GameClient != null)
             {
                 (this.GameClient as GameClient).UpdateMessageBoxAndProcessOrders();
             }
             if (num == 0 || (num + 1) % global::Session.LateUpdatePreemption.Frequency == 0)
             {
                 TimeSpan timeSpan = DateTime.UtcNow - utcNow;
                 if (timeSpan.TotalMilliseconds >= global::Session.LateUpdatePreemption.TimeSpanInMilliseconds)
                 {
                     if (global::Session.LateUpdatePreemption.EnableDiagnostics)
                     {
                         Diagnostics.LogWarning("UpdateMessageBoxAndProcessOrders has been preemptively stopped after having processed {0} order(s) in {1} milliseconds.", new object[]
                         {
                             num + 1,
                             timeSpan.TotalMilliseconds
                         });
                     }
                     break;
                 }
             }
             num++;
         }
     }
 }
Пример #9
0
    protected override IEnumerator OnShow(params object[] parameters)
    {
        yield return(base.OnShow(parameters));

        base.GuiService.GetGuiPanel <ControlBanner>().OnShowScreen(GameScreenType.Menu);
        ISessionService service = Services.GetService <ISessionService>();

        Diagnostics.Assert(service != null && service.Session != null);
        SessionMode sessionMode = service.Session.SessionMode;

        if (sessionMode != SessionMode.Single)
        {
            if (sessionMode - SessionMode.Private > 2)
            {
                throw new ArgumentOutOfRangeException();
            }
            this.InviteGroup.Visible = true;
        }
        else
        {
            this.InviteGroup.Visible = false;
        }
        this.MenuBar.Width = 0f;
        this.MenuBar.ArrangeChildren();
        this.MenuBar.PixelOffsetLeft           = -0.5f * this.MenuBar.Width;
        this.InviteButton.AgeTransform.Enable &= !TutorialManager.IsActivated;
        if (this.VersionLabel.AgeTransform.Visible)
        {
            MenuMainScreen.FormatVersionAndModulePlaylist(null, null, this.VersionLabel);
        }
        this.DlcIconEnumerator.Load();
        this.DlcIconEnumerator.AccessibilityMask = DownloadableContentAccessibility.Shared;
        this.DlcIconEnumerator.SubscriptionMask  = DownloadableContentAccessibility.Shared;
        this.DlcIconEnumerator.RefreshContent();
        float num = 0f;

        for (int i = 0; i < this.VersionLabel.TextLines.Count; i++)
        {
            float num2 = this.VersionLabel.Font.ComputeTextWidth(this.VersionLabel.TextLines[i], this.VersionLabel.ForceCaps, false);
            if (num2 > num)
            {
                num = num2;
            }
        }
        AgeTransform parent = this.VersionLabel.AgeTransform.GetParent();

        parent.Width  = num + this.VersionLabel.AgeTransform.PixelMarginLeft + 4f;
        parent.Height = ((!AgeUtils.HighDefinition) ? ((float)this.VersionLabel.TextLines.Count * 17f) : ((float)this.VersionLabel.TextLines.Count * 17f * AgeUtils.HighDefinitionFactor));
        this.DlcIconEnumerator.AgeTransform.PixelMarginBottom = parent.PixelMarginBottom + parent.Height;
        this.RefreshContent();
        if (!TutorialManager.IsActivated)
        {
            this.GameSessionInformationPanel.Visible = true;
            GameSessionInformationSetting[] componentsInChildren = this.GameSessionInformationPanel.GetComponentsInChildren <GameSessionInformationSetting>();
            for (int j = 0; j < componentsInChildren.Length; j++)
            {
                componentsInChildren[j].SetContent();
            }
        }
        else
        {
            this.GameSessionInformationPanel.Visible = false;
        }
        yield break;
    }
 public void Reset()
 {
     Diagnostics.Assert(this.asyncEnumerator != null, ClassName, "async enumerator cannot be null");
     this.asyncEnumerator.Reset();
 }
Пример #11
0
 public AmbiguousTypeException(TypeName typeName, IEnumerable <string> candidates)
 {
     Candidates = candidates.ToArray();
     TypeName   = typeName;
     Diagnostics.Assert(Candidates.Length > 1, "AmbiguousTypeException can be created only when there are more then 1 candidate.");
 }
    protected override State Execute(AIBehaviorTree aiBehaviorTree, params object[] parameters)
    {
        Army army;

        if (base.GetArmyUnlessLocked(aiBehaviorTree, "$Army", out army) != AIArmyMission.AIArmyMissionErrorCode.None)
        {
            return(State.Failure);
        }
        if (this.currentTicket != null)
        {
            if (!this.currentTicket.Raised)
            {
                return(State.Running);
            }
            bool flag = this.currentTicket.PostOrderResponse == PostOrderResponse.PreprocessHasFailed || this.currentTicket.PostOrderResponse == PostOrderResponse.AuthenticationHasFailed;
            this.currentTicket = null;
            if (flag)
            {
                aiBehaviorTree.ErrorCode = 1;
                return(State.Failure);
            }
            return(State.Success);
        }
        else if (this.heroTicket != null)
        {
            if (!this.heroTicket.Raised)
            {
                return(State.Running);
            }
            if (this.heroTicket.PostOrderResponse != PostOrderResponse.Processed)
            {
                aiBehaviorTree.ErrorCode = 36;
                return(State.Failure);
            }
            this.heroTicket = null;
            return(State.Running);
        }
        else
        {
            if (!aiBehaviorTree.Variables.ContainsKey(this.DestinationVarName))
            {
                aiBehaviorTree.LogError("{0} not set", new object[]
                {
                    this.DestinationVarName
                });
                return(State.Failure);
            }
            WorldPosition worldPosition = (WorldPosition)aiBehaviorTree.Variables[this.DestinationVarName];
            if (!worldPosition.IsValid)
            {
                aiBehaviorTree.LogError("Destination is invalid.", new object[0]);
                aiBehaviorTree.ErrorCode = 2;
                return(State.Failure);
            }
            List <GameEntityGUID> list = new List <GameEntityGUID>();
            foreach (Unit unit in army.StandardUnits)
            {
                list.Add(unit.GUID);
            }
            if (list.Count == 0)
            {
                return(State.Success);
            }
            bool         flag2   = army.Hero != null;
            IGameService service = Services.GetService <IGameService>();
            Diagnostics.Assert(service != null);
            IWorldPositionningService service2 = service.Game.Services.GetService <IWorldPositionningService>();
            Diagnostics.Assert(service2 != null);
            IPathfindingService service3 = service.Game.Services.GetService <IPathfindingService>();
            Diagnostics.Assert(service3 != null);
            City city = service2.GetRegion(worldPosition).City;
            if (city != null)
            {
                District district = service2.GetDistrict(worldPosition);
                if (district != null)
                {
                    GameEntityGUID destinationGuid = GameEntityGUID.Zero;
                    if (city.Camp != null && city.Camp.ContainsDistrict(district.GUID))
                    {
                        destinationGuid = city.Camp.GUID;
                    }
                    else if (District.IsACityTile(district))
                    {
                        destinationGuid = city.GUID;
                    }
                    if (destinationGuid.IsValid)
                    {
                        if (flag2)
                        {
                            if (!District.IsACityTile(district) || city.Hero != null)
                            {
                                this.UnassignHero(army);
                                return(State.Running);
                            }
                            list.Add(army.Hero.GUID);
                        }
                        OrderTransferUnits order = new OrderTransferUnits(army.Empire.Index, army.GUID, destinationGuid, list.ToArray(), false);
                        aiBehaviorTree.AICommander.Empire.PlayerControllers.AI.PostOrder(order, out this.currentTicket, null);
                        return(State.Running);
                    }
                }
            }
            Army armyAtPosition = service2.GetArmyAtPosition(worldPosition);
            if (armyAtPosition != null)
            {
                if (flag2)
                {
                    if (armyAtPosition.Hero != null)
                    {
                        this.UnassignHero(army);
                        return(State.Running);
                    }
                    list.Add(army.Hero.GUID);
                }
                OrderTransferUnits order2 = new OrderTransferUnits(army.Empire.Index, army.GUID, armyAtPosition.GUID, list.ToArray(), false);
                aiBehaviorTree.AICommander.Empire.PlayerControllers.AI.PostOrder(order2, out this.currentTicket, null);
                return(State.Running);
            }
            if (service3.IsTileStopable(worldPosition, army, (PathfindingFlags)0, null))
            {
                OrderTransferGarrisonToNewArmy order3 = new OrderTransferGarrisonToNewArmy(army.Empire.Index, army.GUID, list.ToArray(), worldPosition, StaticString.Empty, false, true, true);
                aiBehaviorTree.AICommander.Empire.PlayerControllers.AI.PostOrder(order3, out this.currentTicket, null);
                return(State.Running);
            }
            aiBehaviorTree.LogError("No valid destination found.", new object[0]);
            aiBehaviorTree.ErrorCode = 2;
            return(State.Failure);
        }
    }
Пример #13
0
 /// <summary>
 /// This overload causes output to be
 /// written onto an Collection[PSObject] which is more useful
 /// in many circumstances than arraylist.
 /// </summary>
 /// <param name="resultCollection">The collection to write into.</param>
 internal Pipe(System.Collections.ObjectModel.Collection <PSObject> resultCollection)
 {
     Diagnostics.Assert(resultCollection != null, "resultCollection cannot be null");
     _isRedirected     = true;
     _resultCollection = resultCollection;
 }
Пример #14
0
 /// <summary>
 /// This overload causes output to be written into a List.
 /// </summary>
 /// <param name="resultList"></param>
 internal Pipe(List <object> resultList)
 {
     Diagnostics.Assert(resultList != null, "resultList cannot be null");
     _isRedirected = true;
     _resultList   = resultList;
 }
Пример #15
0
    protected void OnCursorActivate(params object[] parameters)
    {
        Diagnostics.Assert(base.WorldPositionningService != null);
        Diagnostics.Assert(this.PlayerControllerRepositoryService != null);
        Diagnostics.Assert(base.GlobalPositionningService != null);
        if (this.City != null)
        {
            this.City.CityDistrictCollectionChange -= this.City_CityDistrictCollectionChange;
            this.City.Empire.GetAgency <DepartmentOfTheInterior>().CitiesCollectionChanged -= this.DistrictWorldCursor_CitiesCollectionChanged;
            this.City = null;
            this.ResourceRendererService.SetSelectedRegion(-1);
        }
        if (parameters != null)
        {
            this.City = (parameters.FirstOrDefault((object iterator) => iterator != null && iterator.GetType() == typeof(City)) as City);
        }
        if (base.CursorTarget != null)
        {
            this.WorldDistrict = base.CursorTarget.GetComponent <WorldDistrict>();
            if (this.WorldDistrict != null)
            {
                this.City = this.WorldDistrict.District.City;
            }
            else if (this.City == null)
            {
                Diagnostics.LogError("Invalid cursor target (cant find component of type: 'WorldDistrict').");
                return;
            }
        }
        else if (this.City == null)
        {
            Diagnostics.LogError("Cursor target is null.");
            return;
        }
        if (this.City == null)
        {
            base.Back();
            return;
        }
        IAudioEventService service = Services.GetService <IAudioEventService>();

        Diagnostics.Assert(service != null);
        service.Play2DEvent("Gui/Interface/CitySelection");
        if (this.City.Empire != this.PlayerControllerRepositoryService.ActivePlayerController.Empire)
        {
            this.City.CityDistrictCollectionChange += this.City_CityDistrictCollectionChange;
            this.City.Empire.GetAgency <DepartmentOfTheInterior>().CitiesCollectionChanged += this.DistrictWorldCursor_CitiesCollectionChanged;
            return;
        }
        if (this.ResourceRendererService != null)
        {
            this.ResourceRendererService.Clear();
        }
        this.Camp = (parameters.FirstOrDefault((object iterator) => iterator != null && iterator.GetType() == typeof(Camp)) as Camp);
        if (this.Camp != null || (this.District != null && this.City.Camp != null && this.City.Camp.ContainsDistrict(this.District.GUID)))
        {
            if (this.Camp == null)
            {
                this.Camp = this.City.Camp;
            }
            base.Focus(this.City.Camp, true);
            for (int i = 0; i < this.City.Camp.Districts.Count; i++)
            {
                this.ResourceRendererService.Add(this.City.Camp.Districts[i].WorldPosition);
            }
        }
        else
        {
            this.ResourceRendererService.SetSelectedRegion(this.City.Region.Index);
            if (this.ResourceRendererService != null)
            {
                this.City_CityDistrictCollectionChange(this, new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null));
                this.City.CityDistrictCollectionChange += this.City_CityDistrictCollectionChange;
                this.City.Empire.GetAgency <DepartmentOfTheInterior>().CitiesCollectionChanged += this.DistrictWorldCursor_CitiesCollectionChanged;
            }
        }
        this.City.OnCityCampChanged += this.City_OnCityCampChanged;
        this.City.OnCityDisposed    += this.City_OnCityDisposed;
        global::Empire empire = this.PlayerControllerRepositoryService.ActivePlayerController.Empire as global::Empire;

        if (this.City.Empire.Index == empire.Index && empire.SimulationObject.Tags.Contains("FactionTraitMimics1"))
        {
            this.departmentOfCreepingNodes = empire.GetAgency <DepartmentOfCreepingNodes>();
            this.CheckNodes = true;
        }
        this.SelectCreepingNodes(10);
    }
Пример #16
0
        /// <summary>
        /// ArrayToTuple is a helper method used to create a tuple for the supplied input array.
        /// </summary>
        /// <typeparam name="T">The first generic type parameter.</typeparam>
        /// <param name="inputObjects">Input objects used to create a tuple.</param>
        /// <param name="startIndex">Start index of the array from which the objects have to considered for the tuple creation.</param>
        /// <returns>Tuple object.</returns>
        private static object ArrayToTuple <T>(IList <T> inputObjects, int startIndex)
        {
            Diagnostics.Assert(inputObjects != null, "inputObjects is null");
            Diagnostics.Assert(inputObjects.Count > 0, "inputObjects is empty");

            switch (inputObjects.Count - startIndex)
            {
            case 0:
                return(null);

            case 1:
                return(Tuple.Create(inputObjects[startIndex]));

            case 2:
                return(Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1]));

            case 3:
                return(Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2]));

            case 4:
                return(Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3]));

            case 5:
                return(Tuple.Create(
                           inputObjects[startIndex],
                           inputObjects[startIndex + 1],
                           inputObjects[startIndex + 2],
                           inputObjects[startIndex + 3],
                           inputObjects[startIndex + 4]));

            case 6:
                return(Tuple.Create(
                           inputObjects[startIndex],
                           inputObjects[startIndex + 1],
                           inputObjects[startIndex + 2],
                           inputObjects[startIndex + 3],
                           inputObjects[startIndex + 4],
                           inputObjects[startIndex + 5]));

            case 7:
                return(Tuple.Create(
                           inputObjects[startIndex],
                           inputObjects[startIndex + 1],
                           inputObjects[startIndex + 2],
                           inputObjects[startIndex + 3],
                           inputObjects[startIndex + 4],
                           inputObjects[startIndex + 5],
                           inputObjects[startIndex + 6]));

            case 8:
                return(Tuple.Create(
                           inputObjects[startIndex],
                           inputObjects[startIndex + 1],
                           inputObjects[startIndex + 2],
                           inputObjects[startIndex + 3],
                           inputObjects[startIndex + 4],
                           inputObjects[startIndex + 5],
                           inputObjects[startIndex + 6],
                           inputObjects[startIndex + 7]));

            default:
                return(Tuple.Create(
                           inputObjects[startIndex],
                           inputObjects[startIndex + 1],
                           inputObjects[startIndex + 2],
                           inputObjects[startIndex + 3],
                           inputObjects[startIndex + 4],
                           inputObjects[startIndex + 5],
                           inputObjects[startIndex + 6],
                           ArrayToTuple(inputObjects, startIndex + 7)));
            }
        }
Пример #17
0
 /// <summary>
 /// Used for replicator transaction enlistment.
 /// </summary>
 /// <param name="stateOrKey"></param>
 /// <returns></returns>
 protected override bool IsEqual(object stateOrKey)
 {
     // Should never be called.
     Diagnostics.Assert(false, "should never be called");
     return(false);
 }
Пример #18
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");

            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid language mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid language mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo(string.Empty, scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState,
                                                                         DollarUnderbar);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           nameof(PSLanguageMode.RestrictedLanguage),
                                                           nameof(PSLanguageMode.NoLanguage));
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase = executionContext.CommandDiscovery.LookupCommandProcessor(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            // Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
Пример #19
0
 static CharExtensions()
 {
     Diagnostics.Assert(s_traits.Length == 128, "Extension methods rely on this table size.");
 }
        internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
        {
            GraphicalHostReflectionWrapper returnValue = new GraphicalHostReflectionWrapper();

            if (GraphicalHostReflectionWrapper.IsInputFromRemoting(parentCmdlet))
            {
                ErrorRecord error = new ErrorRecord(
                    new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)),
                    "RemotingNotSupported",
                    ErrorCategory.InvalidOperation,
                    parentCmdlet);

                parentCmdlet.ThrowTerminatingError(error);
            }

            // Prepare the full assembly name.
            AssemblyName graphicalHostAssemblyName = new AssemblyName();

            graphicalHostAssemblyName.Name        = "Microsoft.PowerShell.GraphicalHost";
            graphicalHostAssemblyName.Version     = new Version(3, 0, 0, 0);
            graphicalHostAssemblyName.CultureInfo = new CultureInfo(string.Empty); // Neutral culture
            graphicalHostAssemblyName.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });

            try
            {
                returnValue._graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName);
            }
            catch (FileNotFoundException fileNotFoundEx)
            {
                // This exception is thrown if the Microsoft.PowerShell.GraphicalHost.dll could not be found (was not installed).
                string errorMessage = StringUtil.Format(
                    HelpErrors.GraphicalHostAssemblyIsNotFound,
                    featureName,
                    fileNotFoundEx.Message);

                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new NotSupportedException(errorMessage, fileNotFoundEx),
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }
            catch (Exception e)
            {
                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }

            returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName);

            Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost");
            ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                Array.Empty <Type>(),
                null);

            if (constructor != null)
            {
                returnValue._graphicalHostHelperObject = constructor.Invoke(Array.Empty <object>());
                Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything");
            }

            return(returnValue);
        }
 public override bool Execute(Quest quest)
 {
     Diagnostics.Assert(quest != null);
     if (this.StepNumber >= 0 && this.StepNumber < quest.StepStates.Length)
     {
         quest.StepStates[this.StepNumber] = this.State;
         QuestState state = this.State;
         if (state != QuestState.InProgress)
         {
             if (state != QuestState.Completed || quest.QuestRewards == null)
             {
                 return(true);
             }
             IGameService service = Services.GetService <IGameService>();
             if (service == null || service.Game.Services.GetService <IGameEntityRepositoryService>() == null || service.Game.Services.GetService <IPlayerControllerRepositoryService>() == null)
             {
                 return(true);
             }
             IQuestManagementService service2 = service.Game.Services.GetService <IQuestManagementService>();
             if (service2 == null)
             {
                 return(true);
             }
             List <QuestReward> list = new List <QuestReward>(quest.QuestRewards);
             list.RemoveAll((QuestReward reward) => reward.JustForShow);
             if (quest.QuestDefinition.GlobalWinner == GlobalQuestWinner.Participants)
             {
                 List <QuestReward> list2 = (from reward in list
                                             where reward.StepNumber == this.StepNumber && reward.MinimumRank > 0
                                             select reward).ToList <QuestReward>();
                 if (list2.Count > 0)
                 {
                     int num  = 0;
                     int rank = service2.GetGlobalQuestRank(quest, ref num, quest.QuestDefinition.Steps[this.StepNumber].Name) + 1;
                     list2.RemoveAll((QuestReward reward) => reward.MinimumRank >= rank);
                     for (int i = 0; i < list2.Count; i++)
                     {
                         list.Remove(list2[i]);
                     }
                 }
             }
             service2.AddStepRewards(quest.QuestDefinition, this.StepNumber, list, null, quest);
             Dictionary <StaticString, DroppableResource> dictionary = new Dictionary <StaticString, DroppableResource>();
             for (int j = list.Count - 1; j >= 0; j--)
             {
                 QuestReward questReward = list[j];
                 if (!questReward.Hidden && questReward.StepNumber == this.StepNumber && questReward.Droppables != null)
                 {
                     List <IDroppable> list3 = new List <IDroppable>(questReward.Droppables);
                     for (int k = list3.Count - 1; k >= 0; k--)
                     {
                         DroppableResource droppableResource = list3[k] as DroppableResource;
                         if (droppableResource != null)
                         {
                             if (dictionary.ContainsKey(droppableResource.ResourceName))
                             {
                                 dictionary[droppableResource.ResourceName].Quantity += droppableResource.Quantity;
                             }
                             else
                             {
                                 dictionary.Add(droppableResource.ResourceName, new DroppableResource(droppableResource.ResourceName, droppableResource.Quantity));
                             }
                             list3.RemoveAt(k);
                             if (list3.Count == 0 && string.IsNullOrEmpty(questReward.LocalizationKey))
                             {
                                 list.RemoveAt(j);
                                 break;
                             }
                         }
                     }
                     questReward.Droppables = list3.ToArray();
                 }
             }
             List <QuestReward> list4 = list;
             int          stepNumber  = this.StepNumber;
             bool         hidden      = false;
             IDroppable[] array       = dictionary.Select(delegate(KeyValuePair <StaticString, DroppableResource> kvp)
             {
                 KeyValuePair <StaticString, DroppableResource> keyValuePair = kvp;
                 return(keyValuePair.Value);
             }).ToArray <DroppableResource>();
             list4.Add(new QuestReward(stepNumber, hidden, array, string.Empty, false, -1));
             quest.QuestRewards = list.ToArray();
             using (IEnumerator <QuestReward> enumerator = (from reward in quest.QuestRewards
                                                            where reward.StepNumber == this.StepNumber
                                                            select reward).GetEnumerator())
             {
                 while (enumerator.MoveNext())
                 {
                     QuestReward questReward2 = enumerator.Current;
                     if (questReward2.Droppables == null)
                     {
                         Diagnostics.LogWarning("Quest reward has no droppables.");
                     }
                     else
                     {
                         for (int l = 0; l < questReward2.Droppables.Length; l++)
                         {
                             if (questReward2.Droppables[l] != null)
                             {
                                 IDroppableWithRewardAllocation droppableWithRewardAllocation = questReward2.Droppables[l] as IDroppableWithRewardAllocation;
                                 if (droppableWithRewardAllocation != null)
                                 {
                                     for (int m = 0; m < 32; m++)
                                     {
                                         if ((quest.EmpireBits & 1 << m) != 0)
                                         {
                                             try
                                             {
                                                 global::Empire empire = (service.Game as global::Game).Empires[m];
                                                 if (!empire.SimulationObject.Tags.Contains(global::Empire.TagEmpireEliminated))
                                                 {
                                                     droppableWithRewardAllocation.AllocateRewardTo(empire, new object[0]);
                                                 }
                                             }
                                             catch
                                             {
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 return(true);
             }
         }
         if (quest.QuestRewards != null)
         {
             IGameService service3 = Services.GetService <IGameService>();
             if (service3 != null)
             {
                 IQuestManagementService service4 = service3.Game.Services.GetService <IQuestManagementService>();
                 if (service4 != null)
                 {
                     global::Empire empire2 = null;
                     for (int n = 0; n < 32; n++)
                     {
                         if ((quest.EmpireBits & 1 << n) != 0)
                         {
                             try
                             {
                                 empire2 = (service3.Game as global::Game).Empires[n];
                                 break;
                             }
                             catch
                             {
                             }
                         }
                     }
                     if (empire2 != null)
                     {
                         bool flag = false;
                         List <QuestReward> list5 = new List <QuestReward>(quest.QuestRewards);
                         foreach (QuestReward questReward3 in from reward in quest.QuestRewards
                                  where reward.StepNumber == this.StepNumber
                                  select reward)
                         {
                             questReward3.Hidden = this.HideRewards;
                             if (questReward3.Droppables != null)
                             {
                                 foreach (IDroppable droppable in questReward3.Droppables)
                                 {
                                     if (droppable != null && droppable is DroppableReferenceTechnology)
                                     {
                                         TechnologyDefinition technologyDefinition = (droppable as DroppableReferenceTechnology).ConstructibleElement as TechnologyDefinition;
                                         if (technologyDefinition != null && empire2.GetAgency <DepartmentOfScience>().GetTechnologyState(technologyDefinition.Name) == DepartmentOfScience.ConstructibleElement.State.Researched)
                                         {
                                             list5.Remove(questReward3);
                                             flag = true;
                                         }
                                     }
                                 }
                             }
                         }
                         if (flag)
                         {
                             foreach (QuestReward item in service4.ComputeRewards(quest, quest.QuestDefinition, this.StepNumber, null))
                             {
                                 if (!list5.Contains(item))
                                 {
                                     list5.Add(item);
                                 }
                             }
                             quest.QuestRewards = list5.ToArray();
                         }
                     }
                 }
             }
         }
         return(true);
     }
     return(false);
 }
Пример #22
0
    private void Click()
    {
        if (this.ArmyAction == null)
        {
            return;
        }
        bool flag = false;

        object[] customAttributes = this.ArmyAction.GetType().GetCustomAttributes(typeof(WorldPlacementCursorAttribute), true);
        if (customAttributes != null && customAttributes.Length > 0)
        {
            flag = true;
            if (this.ArmyAction is IArmyActionWithToggle && (this.ArmyAction as IArmyActionWithToggle).IsToggled(this.Army))
            {
                flag = false;
            }
        }
        if (flag)
        {
            if (this.CursorService != null)
            {
                this.CursorService.Backup();
                Diagnostics.Assert(customAttributes.Length == 1);
                WorldPlacementCursorAttribute worldPlacementCursorAttribute = customAttributes[0] as WorldPlacementCursorAttribute;
                Type type = worldPlacementCursorAttribute.Type;
                if (this.ArmyAction is IArmyActionWithUnitSelection)
                {
                    this.CursorService.ChangeCursor(type, new object[]
                    {
                        this.Army,
                        this.ArmyAction,
                        this.unitListPanel.SelectUnits.ToArray()
                    });
                }
                else
                {
                    this.CursorService.ChangeCursor(type, new object[]
                    {
                        this.Army,
                        this.ArmyAction
                    });
                }
            }
        }
        else
        {
            this.failure.Clear();
            if (this.ArmyAction != null)
            {
                if (this.ArmyAction is IArmyActionWithUnitSelection)
                {
                    if (this.ArmyAction.CanExecute(this.Army, ref this.failure, this.unitListPanel.SelectUnits.ToArray()))
                    {
                        Ticket ticket;
                        this.ArmyAction.Execute(this.Army, this.PlayerControllerRepositoryService.ActivePlayerController, out ticket, new EventHandler <TicketRaisedEventArgs>(this.ArmyAction_TicketRaised), this.unitListPanel.SelectUnits.ToArray());
                    }
                }
                else if (this.ArmyAction is IArmyActionWithTargetSelection)
                {
                    this.armyActionTargets.Clear();
                    (this.ArmyAction as IArmyActionWithTargetSelection).FillTargets(this.Army, this.armyActionTargets, ref this.failure);
                    if (this.ArmyAction.CanExecute(this.Army, ref this.failure, new object[]
                    {
                        this.armyActionTargets
                    }))
                    {
                        Ticket ticket2;
                        this.ArmyAction.Execute(this.Army, this.PlayerControllerRepositoryService.ActivePlayerController, out ticket2, new EventHandler <TicketRaisedEventArgs>(this.ArmyAction_TicketRaised), this.armyActionTargets.ToArray());
                    }
                }
                else if (this.ArmyAction.CanExecute(this.Army, ref this.failure, new object[0]))
                {
                    Ticket ticket3;
                    this.ArmyAction.Execute(this.Army, this.PlayerControllerRepositoryService.ActivePlayerController, out ticket3, new EventHandler <TicketRaisedEventArgs>(this.ArmyAction_TicketRaised), new object[0]);
                }
            }
        }
        this.RefreshCanExecute();
    }
    public override void Begin(params object[] parameters)
    {
        base.Begin(parameters);
        IMouseCursorService service = Services.GetService <IMouseCursorService>();

        if (service != null)
        {
            service.AddKey("Loading");
        }
        Diagnostics.Log("GameClientState_GameLaunched.");
        int             num      = 0;
        ISessionService service2 = Services.GetService <ISessionService>();

        Diagnostics.Assert(service2 != null);
        Diagnostics.Assert(service2.Session != null);
        Diagnostics.Assert(service2.Session.IsOpened);
        string text = service2.Session.SteamIDUser.ToString();

        Diagnostics.Assert(service2.Session.SteamIDUser.AccountID == Amplitude.Unity.Framework.Application.UserUniqueID);
        PlayerController playerController = new PlayerController(base.GameClient)
        {
            PlayerID = "player#" + service2.Session.SteamIDUser.AccountID
        };

        for (;;)
        {
            string x         = string.Format("Empire{0}", num);
            string lobbyData = service2.Session.GetLobbyData <string>(x, null);
            if (string.IsNullOrEmpty(lobbyData))
            {
                break;
            }
            if (lobbyData.Contains(text))
            {
                goto IL_113;
            }
            num++;
        }
        Diagnostics.LogError("Player doesn't belong here (SteamUserID: {0}).", new object[]
        {
            text
        });
        goto IL_12C;
IL_113:
        playerController.Empire = base.GameClient.Game.Empires[num];
IL_12C:
        int num2 = 0;

        for (;;)
        {
            string x2         = string.Format("Empire{0}", num2);
            string lobbyData2 = service2.Session.GetLobbyData <string>(x2, null);
            if (string.IsNullOrEmpty(lobbyData2))
            {
                break;
            }
            base.GameClient.Game.Empires[num2].IsControlledByAI = true;
            MajorEmpire majorEmpire = base.GameClient.Game.Empires[num2] as MajorEmpire;
            if (majorEmpire != null)
            {
                if (!lobbyData2.StartsWith("AI"))
                {
                    majorEmpire.IsControlledByAI = false;
                    if (Steamworks.SteamAPI.IsSteamRunning)
                    {
                        string[] array = lobbyData2.Split(Amplitude.String.Separators, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < array.Length; i++)
                        {
                            Steamworks.SteamID steamID = new Steamworks.SteamID(Convert.ToUInt64(array[i], 16));
                            if (!service2.Session.GetLobbyMemberData <bool>(steamID, "Ready", false) && base.GameClient.Session.SessionMode != SessionMode.Single)
                            {
                                majorEmpire.BindPlayer(new Player(majorEmpire)
                                {
                                    Type          = PlayerType.AI,
                                    Location      = ((base.GameClient.Session.GameServer == null) ? PlayerLocation.Remote : PlayerLocation.Local),
                                    LocalizedName = MajorEmpire.GenerateBasicAIName(majorEmpire.Index)
                                });
                            }
                            else
                            {
                                string text2 = Steamworks.SteamAPI.SteamFriends.GetFriendPersonaName(steamID);
                                if (text2 == null)
                                {
                                    text2 = AgeLocalizer.Instance.LocalizeString("%DefaultPlayerName");
                                }
                                majorEmpire.BindPlayer(new Player(majorEmpire)
                                {
                                    Type          = PlayerType.Human,
                                    Location      = ((!(steamID == base.GameClient.SteamIDUser)) ? PlayerLocation.Remote : PlayerLocation.Local),
                                    LocalizedName = text2,
                                    SteamID       = steamID
                                });
                            }
                        }
                    }
                    else
                    {
                        Diagnostics.LogWarning("Steam is not running, cannot get player's name, setting a default one.");
                        majorEmpire.BindPlayer(new Player(majorEmpire)
                        {
                            Type          = PlayerType.Human,
                            Location      = PlayerLocation.Local,
                            LocalizedName = AgeLocalizer.Instance.LocalizeString("%DefaultPlayerName"),
                            SteamID       = Steamworks.SteamID.Zero
                        });
                    }
                }
                else
                {
                    majorEmpire.BindPlayer(new Player(majorEmpire)
                    {
                        Type          = PlayerType.AI,
                        Location      = ((base.GameClient.Session.GameServer == null) ? PlayerLocation.Remote : PlayerLocation.Local),
                        LocalizedName = MajorEmpire.GenerateBasicAIName(majorEmpire.Index)
                    });
                }
            }
            num2++;
        }
        IPlayerControllerRepositoryService service3 = base.GameClient.Game.GetService <IPlayerControllerRepositoryService>();

        if (service3 != null)
        {
            for (int j = 0; j < base.GameClient.Game.Empires.Length; j++)
            {
                PlayerController playerController2 = new PlayerController(base.GameClient)
                {
                    Empire   = base.GameClient.Game.Empires[j],
                    PlayerID = base.GameClient.Game.Empires[j].PlayerID
                };
                service3.Register(playerController2);
                base.GameClient.Game.Empires[j].PlayerController         = playerController2;
                base.GameClient.Game.Empires[j].PlayerControllers.Client = playerController2;
            }
        }
        if (service3 != null)
        {
            service3.Register(playerController);
            service3.SetActivePlayerController(playerController);
        }
        Ticket.ResetCounter(0UL);
        Amplitude.Unity.View.IViewService service4 = Services.GetService <Amplitude.Unity.View.IViewService>();
        if (service4 != null)
        {
            WorldView worldView = (WorldView)service4.FindByType(typeof(WorldView));
            if (worldView != null)
            {
                worldView.WorldViewTechniqueChange += this.WorldView_WorldViewTechniqueChange;
            }
            service4.PostViewChange(typeof(WorldView), new object[0]);
        }
        Amplitude.Unity.Gui.IGuiService service5 = Services.GetService <Amplitude.Unity.Gui.IGuiService>();
        Diagnostics.Assert(service5 != null);
        ConsolePanel guiPanel = service5.GetGuiPanel <ConsolePanel>();

        Diagnostics.Assert(guiPanel != null);
        guiPanel.Load();
        guiPanel.Hide(false);
    }
Пример #24
0
 ushort[] ICadasterService.Connect(City city, PathfindingMovementCapacity movementCapacity, bool proxied)
 {
     if (city == null)
     {
         throw new ArgumentNullException("city");
     }
     if ((movementCapacity & PathfindingMovementCapacity.Water) == PathfindingMovementCapacity.Water)
     {
         StaticString  type  = new StaticString("DistrictImprovement");
         StaticString  y     = new StaticString("DistrictImprovementDocks");
         WorldPosition start = WorldPosition.Invalid;
         for (int i = 0; i < city.Districts.Count; i++)
         {
             District district = city.Districts[i];
             if (district.Type == DistrictType.Improvement && district.GetDescriptorNameFromType(type) == y)
             {
                 start = district.WorldPosition;
                 break;
             }
         }
         if (!start.IsValid)
         {
             return(null);
         }
         DepartmentOfForeignAffairs agency = city.Empire.GetAgency <DepartmentOfForeignAffairs>();
         this.OceanPathfindingWorldContext.RegionIndexList.Clear();
         this.OceanPathfindingWorldContext.RegionIndexList.Add((int)this.WorldPositionningService.GetRegionIndex(city.WorldPosition));
         for (int j = 0; j < city.Region.Borders.Length; j++)
         {
             Region region = this.WorldPositionningService.GetRegion(city.Region.Borders[j].NeighbourRegionIndex);
             if (region.Owner == null || !(region.Owner is MajorEmpire) || region.Owner.Index == city.Empire.Index || agency.GetDiplomaticRelation(region.Owner).HasActiveAbility(DiplomaticAbilityDefinition.TradeRoute))
             {
                 this.OceanPathfindingWorldContext.RegionIndexList.Add(city.Region.Borders[j].NeighbourRegionIndex);
             }
         }
         Diagnostics.Assert(city.CadastralMap != null);
         Diagnostics.Assert((city.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Water) == PathfindingMovementCapacity.Water);
         List <ushort> list  = new List <ushort>();
         List <Region> list2 = new List <Region>();
         List <Region> list3 = new List <Region>();
         list3.Add(city.Region);
         int k = 0;
         int l = 2;
         while (l > 0)
         {
             l--;
             list2.AddRange(list3);
             list3.Clear();
             while (k < list2.Count)
             {
                 Region region2 = list2[k];
                 for (int m = 0; m < region2.Borders.Length; m++)
                 {
                     short  regionIndex = (short)region2.Borders[m].NeighbourRegionIndex;
                     Region region3     = this.WorldPositionningService.GetRegion((int)regionIndex);
                     if (region3 != null && !list2.Contains(region3))
                     {
                         if (region3.City != null)
                         {
                             Diagnostics.Assert(region3.City.CadastralMap != null);
                             if ((region3.City.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Water) == PathfindingMovementCapacity.Water)
                             {
                                 for (int n = 0; n < region3.City.Districts.Count; n++)
                                 {
                                     District district2 = region3.City.Districts[n];
                                     if (district2.Type == DistrictType.Improvement && district2.GetDescriptorNameFromType(type) == y)
                                     {
                                         PathfindingFlags pathfindingFlags = PathfindingFlags.IgnoreAll;
                                         pathfindingFlags &= ~PathfindingFlags.IgnoreMovementCapacities;
                                         pathfindingFlags &= ~PathfindingFlags.IgnorePOI;
                                         PathfindingContext pathfindingContext = new PathfindingContext(GameEntityGUID.Zero, city.Empire, PathfindingMovementCapacity.Water);
                                         pathfindingContext.RefreshProperties(1f, 1f, false, false, 1f, 1f);
                                         bool flag = false;
                                         if (!this.OceanPathfindingWorldContext.RegionIndexList.Contains(region2.Borders[m].NeighbourRegionIndex))
                                         {
                                             flag = true;
                                             this.OceanPathfindingWorldContext.RegionIndexList.Add(region2.Borders[m].NeighbourRegionIndex);
                                         }
                                         PathfindingResult pathfindingResult = this.PathfindingService.FindPath(pathfindingContext, start, district2.WorldPosition, PathfindingManager.RequestMode.Default, this.OceanPathfindingWorldContext, pathfindingFlags, null);
                                         if (flag)
                                         {
                                             this.OceanPathfindingWorldContext.RegionIndexList.Remove(region2.Borders[m].NeighbourRegionIndex);
                                         }
                                         if (pathfindingResult == null)
                                         {
                                             pathfindingResult = this.PathfindingService.FindPath(pathfindingContext, start, district2.WorldPosition, PathfindingManager.RequestMode.Default, null, pathfindingFlags, null);
                                         }
                                         if (pathfindingResult != null)
                                         {
                                             ushort item = this.Reserve(new Road
                                             {
                                                 FromRegion     = (short)city.Region.Index,
                                                 ToRegion       = (short)region3.Index,
                                                 WorldPositions = pathfindingResult.GetCompletePath().ToArray <WorldPosition>(),
                                                 PathfindingMovementCapacity = PathfindingMovementCapacity.Water
                                             });
                                             list.Add(item);
                                         }
                                     }
                                 }
                             }
                         }
                         if (region3.IsOcean)
                         {
                             list3.AddOnce(region3);
                         }
                         else
                         {
                             list2.Insert(k, region3);
                             k++;
                         }
                     }
                 }
                 k++;
             }
         }
         this.OceanPathfindingWorldContext.RegionIndexList.Clear();
         return(list.ToArray());
     }
     else
     {
         if (city.Region.Borders != null)
         {
             List <ushort> list4 = new List <ushort>();
             for (int num = 0; num < city.Region.Borders.Length; num++)
             {
                 short  regionIndex2 = (short)city.Region.Borders[num].NeighbourRegionIndex;
                 Region region4      = this.WorldPositionningService.GetRegion((int)regionIndex2);
                 if (region4 != null && region4.City != null)
                 {
                     if (proxied)
                     {
                         if ((movementCapacity & PathfindingMovementCapacity.Ground) != PathfindingMovementCapacity.Ground)
                         {
                             goto IL_75D;
                         }
                         Diagnostics.Assert(region4.City.CadastralMap != null);
                         if ((region4.City.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Ground) != PathfindingMovementCapacity.Ground)
                         {
                             goto IL_75D;
                         }
                     }
                     bool flag2 = false;
                     if (region4.City.CadastralMap.Roads != null)
                     {
                         for (int num2 = 0; num2 < region4.City.CadastralMap.Roads.Count; num2++)
                         {
                             ushort num3 = region4.City.CadastralMap.Roads[num2];
                             Road   road = this.roads[(int)num3];
                             if (road != null && (city.Region.Index == (int)road.FromRegion || city.Region.Index == (int)road.ToRegion) && (road.PathfindingMovementCapacity & movementCapacity) != PathfindingMovementCapacity.None)
                             {
                                 if (this.RoadModified != null)
                                 {
                                     this.RoadModified(this, new RoadEventArgs(num3, road));
                                 }
                                 flag2 = true;
                                 list4.Add(num3);
                             }
                         }
                     }
                     if (!flag2)
                     {
                         PathfindingFlags pathfindingFlags2 = PathfindingFlags.IgnoreAll;
                         pathfindingFlags2 &= ~PathfindingFlags.IgnoreMovementCapacities;
                         pathfindingFlags2 &= ~PathfindingFlags.IgnorePOI;
                         pathfindingFlags2 &= ~PathfindingFlags.IgnoreRoad;
                         PathfindingContext pathfindingContext2 = new PathfindingContext(GameEntityGUID.Zero, city.Empire, movementCapacity);
                         pathfindingContext2.RefreshProperties(1f, 1f, false, false, 1f, 1f);
                         pathfindingContext2.RemoveMovementCapacity(PathfindingMovementCapacity.FrozenWater);
                         Diagnostics.Assert(this.pathfindingWorldContext != null && this.pathfindingWorldContext.RegionIndexList != null && this.pathfindingWorldContext.RegionIndexList.Count == 2);
                         this.pathfindingWorldContext.RegionIndexList[0] = (int)this.WorldPositionningService.GetRegionIndex(city.WorldPosition);
                         this.pathfindingWorldContext.RegionIndexList[1] = (int)this.WorldPositionningService.GetRegionIndex(region4.City.WorldPosition);
                         PathfindingResult pathfindingResult2 = this.PathfindingService.FindPath(pathfindingContext2, city.WorldPosition, region4.City.WorldPosition, PathfindingManager.RequestMode.Default, this.pathfindingWorldContext, pathfindingFlags2, null);
                         if (pathfindingResult2 == null)
                         {
                             pathfindingFlags2 |= PathfindingFlags.IgnorePOI;
                             pathfindingResult2 = this.PathfindingService.FindPath(pathfindingContext2, city.WorldPosition, region4.City.WorldPosition, PathfindingManager.RequestMode.Default, this.pathfindingWorldContext, pathfindingFlags2, null);
                         }
                         if (pathfindingResult2 != null)
                         {
                             ushort item2 = this.Reserve(new Road
                             {
                                 FromRegion     = (short)city.Region.Index,
                                 ToRegion       = (short)region4.Index,
                                 WorldPositions = pathfindingResult2.GetCompletePath().ToList <WorldPosition>().ToArray(),
                                 PathfindingMovementCapacity = movementCapacity
                             });
                             list4.Add(item2);
                         }
                     }
                 }
                 IL_75D :;
             }
             return(list4.ToArray());
         }
         return(null);
     }
 }
Пример #25
0
        /// <summary>
        /// The following is the matching algorithm:
        /// Retrieve the incoming object (differenceEntry) if any
        /// Retrieve the next reference object (referenceEntry) if any
        /// If differenceEntry matches referenceEntry
        ///   Emit referenceEntry as a match
        ///   Return
        /// If differenceEntry matches any entry in referenceEntryBacklog
        ///   Emit the backlog entry as a match
        ///   Remove the backlog entry from referenceEntryBacklog
        ///   Clear differenceEntry
        /// If referenceEntry (if any) matches any entry in differenceEntryBacklog
        ///   Emit referenceEntry as a match
        ///   Remove the backlog entry from differenceEntryBacklog
        ///   Clear referenceEntry
        /// If differenceEntry is still present
        ///   If SyncWindow is 0
        ///     Emit differenceEntry as unmatched
        ///   Else
        ///     While there is no space in differenceEntryBacklog
        ///       Emit oldest entry in differenceEntryBacklog as unmatched
        ///       Remove oldest entry from differenceEntryBacklog
        ///     Add differenceEntry to differenceEntryBacklog
        /// If referenceEntry is still present
        ///   If SyncWindow is 0
        ///     Emit referenceEntry as unmatched
        ///   Else
        ///     While there is no space in referenceEntryBacklog
        ///       Emit oldest entry in referenceEntryBacklog as unmatched
        ///       Remove oldest entry from referenceEntryBacklog
        ///     Add referenceEntry to referenceEntryBacklog.
        /// </summary>
        /// <param name="differenceEntry"></param>
        private void Process(OrderByPropertyEntry differenceEntry)
        {
            Diagnostics.Assert(_referenceEntries != null, "null referenceEntries");

            // Retrieve the next reference object (referenceEntry) if any
            OrderByPropertyEntry referenceEntry = null;

            if (_referenceObjectIndex < _referenceEntries.Count)
            {
                referenceEntry = _referenceEntries[_referenceObjectIndex++];
            }

            // If differenceEntry matches referenceEntry
            //   Emit referenceEntry as a match
            //   Return
            // 2005/07/19 Switched order of referenceEntry and differenceEntry
            //   so that we cast differenceEntry to the type of referenceEntry.
            if (referenceEntry != null && differenceEntry != null &&
                0 == _comparer.Compare(referenceEntry, differenceEntry))
            {
                EmitMatch(referenceEntry);
                return;
            }

            // If differenceEntry matches any entry in referenceEntryBacklog
            //   Emit the backlog entry as a match
            //   Remove the backlog entry from referenceEntryBacklog
            //   Clear differenceEntry
            OrderByPropertyEntry matchingEntry =
                MatchAndRemove(differenceEntry, _referenceEntryBacklog);

            if (matchingEntry != null)
            {
                EmitMatch(matchingEntry);
                differenceEntry = null;
            }

            // If referenceEntry (if any) matches any entry in differenceEntryBacklog
            //   Emit referenceEntry as a match
            //   Remove the backlog entry from differenceEntryBacklog
            //   Clear referenceEntry
            matchingEntry =
                MatchAndRemove(referenceEntry, _differenceEntryBacklog);
            if (matchingEntry != null)
            {
                EmitMatch(referenceEntry);
                referenceEntry = null;
            }

            // If differenceEntry is still present
            //   If SyncWindow is 0
            //     Emit differenceEntry as unmatched
            //   Else
            //     While there is no space in differenceEntryBacklog
            //       Emit oldest entry in differenceEntryBacklog as unmatched
            //       Remove oldest entry from differenceEntryBacklog
            //     Add differenceEntry to differenceEntryBacklog
            if (differenceEntry != null)
            {
                if (0 < SyncWindow)
                {
                    while (_differenceEntryBacklog.Count >= SyncWindow)
                    {
                        EmitDifferenceOnly(_differenceEntryBacklog[0]);
                        _differenceEntryBacklog.RemoveAt(0);
                    }

                    _differenceEntryBacklog.Add(differenceEntry);
                }
                else
                {
                    EmitDifferenceOnly(differenceEntry);
                }
            }

            // If referenceEntry is still present
            //   If SyncWindow is 0
            //     Emit referenceEntry as unmatched
            //   Else
            //     While there is no space in referenceEntryBacklog
            //       Emit oldest entry in referenceEntryBacklog as unmatched
            //       Remove oldest entry from referenceEntryBacklog
            //     Add referenceEntry to referenceEntryBacklog
            if (referenceEntry != null)
            {
                if (0 < SyncWindow)
                {
                    while (_referenceEntryBacklog.Count >= SyncWindow)
                    {
                        EmitReferenceOnly(_referenceEntryBacklog[0]);
                        _referenceEntryBacklog.RemoveAt(0);
                    }

                    _referenceEntryBacklog.Add(referenceEntry);
                }
                else
                {
                    EmitReferenceOnly(referenceEntry);
                }
            }
        }
Пример #26
0
    void ICadasterService.RefreshCadasterMap()
    {
        Diagnostics.Assert(this.cadasterMap != null && this.cadasterMap.Data != null, "cadasterMap or its Data are null");
        Array.Clear(this.cadasterMap.Data, 0, this.cadasterMap.Data.Length);
        Diagnostics.Assert(this.roads != null, "roads are null");
        List <Region> list = new List <Region>();

        if (this.roads != null)
        {
            for (int i = 0; i < this.roads.Count; i++)
            {
                Road road = this.roads[i];
                if (road != null && (road.PathfindingMovementCapacity & PathfindingMovementCapacity.Ground) == PathfindingMovementCapacity.Ground)
                {
                    Region region  = this.WorldPositionningService.GetRegion((int)road.FromRegion);
                    Region region2 = this.WorldPositionningService.GetRegion((int)road.ToRegion);
                    bool   flag    = false;
                    if (region.City == null)
                    {
                        list.AddOnce(region);
                        flag = true;
                    }
                    if (region2.City == null)
                    {
                        list.AddOnce(region2);
                        flag = true;
                    }
                    if (!flag)
                    {
                        bool flag2 = (region.City.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Ground) == PathfindingMovementCapacity.Ground;
                        Diagnostics.Assert(region.City.Empire != null, "assert3");
                        int  bits  = region.City.Empire.Bits;
                        bool flag3 = (region2.City.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Ground) == PathfindingMovementCapacity.Ground;
                        Diagnostics.Assert(region2.City.Empire != null, "assert5");
                        int bits2 = region2.City.Empire.Bits;
                        Diagnostics.Assert(road.WorldPositions != null, "assert6");
                        for (int j = 0; j < road.WorldPositions.Length; j++)
                        {
                            WorldPosition worldPosition = road.WorldPositions[j];
                            short         regionIndex   = this.WorldPositionningService.GetRegionIndex(worldPosition);
                            if (regionIndex == road.FromRegion && flag2)
                            {
                                byte value = this.cadasterMap.GetValue(worldPosition);
                                this.cadasterMap.SetValue(worldPosition, (byte)((int)value | bits));
                            }
                            else if (regionIndex == road.ToRegion && flag3)
                            {
                                byte value2 = this.cadasterMap.GetValue(worldPosition);
                                this.cadasterMap.SetValue(worldPosition, (byte)((int)value2 | bits2));
                            }
                        }
                    }
                }
            }
        }
        foreach (Region region3 in list)
        {
            this.ELCPDisconnect(region3, PathfindingMovementCapacity.All, true);
            Diagnostics.LogError("ELCP: RefreshCadasterMap detected invalid City in Region {0}, disconnecting ...", new object[]
            {
                region3.LocalizedName
            });
        }
    }
Пример #27
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(null != uriToLaunch, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            // we use this test hook is to avoid actually calling out to another process
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                this.WriteObject(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                return;
            }

            Exception exception           = null;
            bool      wrapCaughtException = true;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();
#if UNIX
                browserProcess.StartInfo.FileName  = Platform.IsLinux ? "xdg-open" : /* OS X */ "open";
                browserProcess.StartInfo.Arguments = uriToLaunch.OriginalString;
                browserProcess.Start();
#elif CORECLR
                // On FullCLR, ProcessStartInfo.UseShellExecute is true by default. This means that the shell will be used when starting the process.
                // On CoreCLR, UseShellExecute is not supported. To work around this, we check if there is a default browser in the system.
                // If there is, we lunch it to open the HelpURI. If there isn't, we error out.
                string webBrowserPath = GetDefaultWebBrowser();
                if (webBrowserPath == null)
                {
                    wrapCaughtException = false;
                    exception           = PSTraceSource.NewInvalidOperationException(HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    browserProcess.StartInfo           = new ProcessStartInfo(webBrowserPath);
                    browserProcess.StartInfo.Arguments = "\"" + uriToLaunch.OriginalString + "\"";
                    browserProcess.Start();
                }
#else
                browserProcess.StartInfo.FileName = uriToLaunch.OriginalString;
                browserProcess.Start();
#endif
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (null != exception)
            {
                if (wrapCaughtException)
                {
                    throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    throw exception;
                }
            }
        }
Пример #28
0
    private void ELCPDisconnect(Region Region, PathfindingMovementCapacity movementCapacity, bool cityAboutToBeDestroyed)
    {
        Diagnostics.Assert(this.roads != null);
        Diagnostics.Assert(Region != null);
        List <ushort> list  = new List <ushort>();
        List <short>  list2 = new List <short>();

        for (int i = 0; i < this.roads.Count; i++)
        {
            if (this.roads[i] != null && (Region.Index == (int)this.roads[i].FromRegion || Region.Index == (int)this.roads[i].ToRegion))
            {
                list2.AddOnce(this.roads[i].FromRegion);
                list2.AddOnce(this.roads[i].ToRegion);
                if (!cityAboutToBeDestroyed && (movementCapacity & PathfindingMovementCapacity.Ground) == PathfindingMovementCapacity.Ground)
                {
                    short regionIndex = this.roads[i].ToRegion;
                    if ((int)this.roads[i].ToRegion == Region.Index)
                    {
                        regionIndex = this.roads[i].FromRegion;
                    }
                    Region region = this.WorldPositionningService.GetRegion((int)regionIndex);
                    if (region != null)
                    {
                        Diagnostics.Assert(region.City != null);
                        Diagnostics.Assert(region.City.CadastralMap != null);
                        if ((region.City.CadastralMap.ConnectedMovementCapacity & PathfindingMovementCapacity.Ground) == PathfindingMovementCapacity.Ground)
                        {
                            if (this.RoadModified != null)
                            {
                                this.RoadModified(this, new RoadEventArgs((ushort)i, this.roads[i]));
                                goto IL_1AF;
                            }
                            goto IL_1AF;
                        }
                    }
                }
                this.roads[i].PathfindingMovementCapacity &= ~movementCapacity;
                if (this.roads[i].PathfindingMovementCapacity == PathfindingMovementCapacity.None)
                {
                    list.Add((ushort)i);
                    ((ICadasterService)this).Unregister((ushort)i);
                    Diagnostics.Assert(this.roads[i] == null);
                }
            }
            IL_1AF :;
        }
        list2.Remove((short)Region.Index);
        if (list2.Count > 0)
        {
            Diagnostics.Assert(this.WorldPositionningService != null);
            for (int j = 0; j < list2.Count; j++)
            {
                Region region2 = this.WorldPositionningService.GetRegion((int)list2[j]);
                if (region2 != null && region2.City != null && region2.City.CadastralMap.Roads != null)
                {
                    List <ushort> list3 = region2.City.CadastralMap.Roads.Except(list).ToList <ushort>();
                    region2.City.CadastralMap.Roads = list3;
                }
            }
        }
    }
        private string GetStringHelper(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus)
        {
            result        = LoadingResult.AssemblyNotFound;
            bindingStatus = AssemblyBindingStatus.NotFound;

            AssemblyLoadResult loadResult = null;

            // try first to see if we have an assembly reference in the cache
            if (_resourceReferenceToAssemblyCache.Contains(resourceReference))
            {
                loadResult    = _resourceReferenceToAssemblyCache[resourceReference] as AssemblyLoadResult;
                bindingStatus = loadResult.status;
            }
            else
            {
                loadResult = new AssemblyLoadResult();
                // we do not have an assembly, we try to load it
                bool foundInGac;
                loadResult.a = LoadAssemblyFromResourceReference(resourceReference, out foundInGac);
                if (loadResult.a == null)
                {
                    loadResult.status = AssemblyBindingStatus.NotFound;
                }
                else
                {
                    loadResult.status = foundInGac ? AssemblyBindingStatus.FoundInGac : AssemblyBindingStatus.FoundInPath;
                }

                // add to the cache even if null
                _resourceReferenceToAssemblyCache.Add(resourceReference, loadResult);
            }

            bindingStatus = loadResult.status;

            if (loadResult.a == null)
            {
                // we failed the assembly loading
                result = LoadingResult.AssemblyNotFound;
                return(null);
            }
            else
            {
                resourceReference.assemblyLocation = loadResult.a.Location;
            };

            // load now the resource from the resource manager cache
            try
            {
                string val = ResourceManagerCache.GetResourceString(loadResult.a, resourceReference.baseName, resourceReference.resourceId);
                if (val == null)
                {
                    result = LoadingResult.StringNotFound;
                    return(null);
                }
                else
                {
                    result = LoadingResult.NoError;
                    return(val);
                }
            }
            catch (InvalidOperationException)
            {
                result = LoadingResult.ResourceNotFound;
            }
            catch (MissingManifestResourceException)
            {
                result = LoadingResult.ResourceNotFound;
            }
            catch (Exception e) // will rethrow
            {
                Diagnostics.Assert(false, "ResourceManagerCache.GetResourceString unexpected exception " + e.GetType().FullName);
                throw;
            }
            return(null);
        }
Пример #30
0
        /// <summary>
        /// Called to find(or create if one is not found) the appropriate OutboundSessionDriver for a given partition.
        /// This method will ensure that we have a one(targetPartition)-to-one(outBoundSessionDriver) relationship.
        ///
        /// TODO: this layer must catch all exceptions and decide what to do with them -- lower layer functions like ResolveAndNormalizeTargetPartition
        /// will throw in case of unrecoverable errors like FabricObjectClosedException
        /// </summary>
        /// <param name="targetPartition">Find or Create OutBoundSessionDriver for this Partition</param>
        /// <param name="streamManager">Stream manager that manages the reference to the driver</param>
        /// <param name="sessionConnectionManager">Use this session connection manager to create a new session if one if not found</param>
        /// <param name="timeout">Timeout</param>
        /// <returns>Returns OutboundSessionDriver if successfull, null otherwise</returns>
        internal static async Task <OutboundSessionDriver> FindOrCreateDriverAsync(
            PartitionKey targetPartition,
            StreamManager streamManager,
            SessionConnectionManager sessionConnectionManager,
            TimeSpan timeout)
        {
            OutboundSessionDriver streamOutboundSessionDriver = null;
            // Complete the call within this time.
            var remainingTimeout = timeout;

            try
            {
                FabricEvents.Events.FindOrCreateOutboundSessionDriver("Start@" + streamManager.TraceType, targetPartition.ToString());
                var beforeResolve = DateTime.UtcNow;

                // The sync point pattern is used here because lock() pattern is not compatible with await pattern
                var normalizedPartitionKey = await streamManager.SessionConnectionManager.ResolveAndNormalizeTargetPartition(targetPartition, remainingTimeout);

                Diagnostics.Assert(
                    null != normalizedPartitionKey,
                    "normalizedPartitionKey is not expected to be null in OutboundSessionDriver.FindOrCreateDriverAsync().");

                // Update remaining time for timeout
                var afterResolve = DateTime.UtcNow;
                remainingTimeout = TimeoutHandler.UpdateTimeout(remainingTimeout, beforeResolve, afterResolve);

                var syncPoint
                    = new SyncPoint <PartitionKey>(
                          streamManager,
                          normalizedPartitionKey,
                          streamManager.RuntimeResources.OutboundSessionDriverSyncpoints);

                try
                {
                    // this is entering an await compatible critical section -- syncPoint.Dispose will leave it
                    await syncPoint.EnterAsync(remainingTimeout);

                    var afterEnter = DateTime.UtcNow;
                    remainingTimeout = TimeoutHandler.UpdateTimeout(remainingTimeout, afterResolve, afterEnter);

                    // Check if the driver already exists
                    var exists = streamManager.RuntimeResources.OutboundSessionDrivers.TryGetValue(normalizedPartitionKey, out streamOutboundSessionDriver);

                    // TODO: should we refcount how many streams depend on this session?

                    // create a new driver if if it does not exist already
                    if (!exists)
                    {
                        FabricEvents.Events.FindOrCreateOutboundSessionDriver("Creating@" + streamManager.TraceType, normalizedPartitionKey.ToString());

                        // we are actually the first stream attaching to this partition on start or recovery or all previous ones closed

                        // Find or create a new reliable messaging session
                        var session = await sessionConnectionManager.FindOrCreateOutboundSessionAsync(normalizedPartitionKey, remainingTimeout);

                        Diagnostics.Assert(null != session, "Session is not expected to be null in OutboundSessionDriver.FindOrCreateDriverAsync().");

                        // Create a new outbound session driver
                        streamOutboundSessionDriver = new OutboundSessionDriver(normalizedPartitionKey, streamManager, sessionConnectionManager, session);
                        Diagnostics.Assert(
                            null != streamOutboundSessionDriver,
                            "Stream OutboundSessionDriver is not expected to be null in OutboundSessionDriver.FindOrCreateDriverAsync().");

                        // Add ref. to stream manager active runtime resources
                        var addSuccess = streamManager.RuntimeResources.OutboundSessionDrivers.TryAdd(normalizedPartitionKey, streamOutboundSessionDriver);
                        Diagnostics.Assert(
                            addSuccess,
                            "{0} Unexpected failure to add newSessionDriver in OutboundSessionDriver.FindOrCreateDriverAsync",
                            streamManager.Tracer);
                    }
                    else
                    {
                        FabricEvents.Events.FindOrCreateOutboundSessionDriver("Found@" + streamManager.TraceType, normalizedPartitionKey.ToString());
                    }
                }
                finally
                {
                    syncPoint.Dispose();
                }
                FabricEvents.Events.FindOrCreateOutboundSessionDriver("Finish@" + streamManager.TraceType, normalizedPartitionKey.ToString());
            }
            catch (TimeoutException)
            {
                FabricEvents.Events.FindOrCreateOutboundSessionDriver("Timeout@" + streamManager.TraceType, targetPartition.ToString());
                throw;
            }
            catch (Exception e)
            {
                Tracing.WriteExceptionAsWarning("FindOrCreateDriverAsync.Failure", e, "{0}", streamManager.Tracer);
                throw;
            }

            return(streamOutboundSessionDriver);
        }