Esempio n. 1
0
 public void AddInnerMessageToLast(
     Diagnostics.MessageKind kind, Diagnostics.MessageCode code,
     string text, params Diagnostics.Span[] spans)
 {
     var msg = Diagnostics.Message.Make(code, text, kind, spans);
     this.messages[this.messages.Count - 1].SetInner(msg);
 }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the ServerLink class.
        /// </summary>
        protected ServerLink(string name)
            : base(name)
        {
            sessions = new SortedList<int, LinkSession>();

            Diag = new Diagnostics();
        }
    /// <summary>
    /// Processes the specified arguments.
    /// </summary>
    /// <param name="args">The arguments.</param>
    public virtual void Process(PipelineArgs args)
    {
      Assert.ArgumentNotNull(args, "args");

      Order order = args.CustomData["order"] as Order;

      if (order == null)
      {
        return;
      }

      BusinessCatalogSettings businnesCatalogSettings = Context.Entity.GetConfiguration<BusinessCatalogSettings>();
      Item companyMasterData = Sitecore.Context.Database.SelectSingleItem(businnesCatalogSettings.CompanyMasterDataLink);
      if (companyMasterData == null)
      {
        return;
      }

      string queryString = string.Format("orderid={0}&mode=mail", order.OrderNumber);
      Item saleDepartment = companyMasterData.Children["Sale"];
      var saleParams = new { Recipient = saleDepartment["Email"] };

      IMail mailProvider = Context.Entity.Resolve<IMail>();
      mailProvider.SendMail("Order Mail To Admin", saleParams, queryString);
    }
Esempio n. 4
0
 public void AddMessage(
     Diagnostics.MessageKind kind, Diagnostics.MessageCode code,
     string text, params Diagnostics.Span[] spans)
 {
     var msg = Diagnostics.Message.Make(code, text, kind, spans);
     msg.SetContext(this.contextStack);
     this.messages.Add(msg);
 }
Esempio n. 5
0
 public int CreateBinding(Core.Name name, int registerIndex, Diagnostics.Span span)
 {
     var binding = new LocalBinding();
     binding.name = name;
     binding.registerIndex = registerIndex;
     binding.declSpan = span;
     this.localBindings.Add(binding);
     return this.localBindings.Count - 1;
 }
Esempio n. 6
0
 public bool HasMessagesWithCode(Diagnostics.MessageCode code)
 {
     foreach (var message in this.messages)
     {
         if (message.GetCode() == code)
             return true;
     }
     return false;
 }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the ServerLink class.
        /// </summary>
        protected ServerLink(string name)
            : base(name)
        {
            sessions = new SortedList<int, LinkSession>();

            recoverable = new Dictionary<string, LinkSession>();
            recoveryTokens = new Dictionary<int, Binder.Token>();

            Diag = new Diagnostics();
        }
Esempio n. 8
0
 public static InstructionMoveLiteralStruct Of(
     Diagnostics.Span span, DataAccess destination, int structIndex,
     DataAccess[] fieldSources, Diagnostics.Span[] fieldDestSpans)
 {
     return new InstructionMoveLiteralStruct
     {
         span = span,
         destination = destination,
         structIndex = structIndex,
         fieldSources = fieldSources,
         fieldDestSpans = fieldDestSpans
     };
 }
Esempio n. 9
0
 public static InstructionMoveCallResult For(
     Diagnostics.Span span,
     DataAccess destination,
     DataAccess callTarget,
     DataAccess[] arguments)
 {
     return new InstructionMoveCallResult
     {
         span = span,
         destination = destination,
         callTargetSource = callTarget,
         argumentSources = arguments
     };
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the LinkSession class.
        /// </summary>
        protected LinkSession(SessionBasedLink link)
        {
            handle = handlePool.Acquire();
            this.link = link;

            rxBuffer = new Buffer();
            rxBufferList = new List<ArraySegment<byte>>();
            txBufferList = new List<ArraySegment<byte>>();

            eventsSending = new List<Event>();
            eventsToSend = new List<Event>();
            buffersSending = new List<SendBuffer>();

            Diag = new Diagnostics(this);
        }
Esempio n. 11
0
 public AmqpSession(AmqpConnection connection, AmqpSessionSettings settings, ILinkFactory linkFactory)
 {
     Fx.Assert(connection != null, "connection must not be null");
     Fx.Assert(settings != null, "settings must not be null");
     this.connection = connection;
     this.settings = settings;
     this.linkFactory = linkFactory;
     this.State = AmqpObjectState.Start;
     this.links = new Dictionary<string, AmqpLink>();
     this.linksByLocalHandle = new HandleTable<AmqpLink>(uint.MaxValue);
     this.linksByRemoteHandle = new HandleTable<AmqpLink>(uint.MaxValue);
     this.outgoingChannel = new OutgoingSessionChannel(this);
     this.incomingChannel = new IncomingSessionChannel(this);
     this.diagnostics = new Diagnostics();
 }
Esempio n. 12
0
        protected Socket socket; // underlying socket

        #endregion Fields

        #region Constructors

        protected SocketLinkSession(SocketLink link, Socket socket)
            : base(socket.Handle)
        {
            this.link = link;
            this.socket = socket;

            sendQueue = new Queue<Event>();

            recvBuffer = new Buffer(12);
            sendBuffer = new Buffer(12);

            recvBufferList = new List<ArraySegment<byte>>();
            sendBufferList = new List<ArraySegment<byte>>();

            Diag = new Diagnostics(this);
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the AbsractUdpLink class.
        /// </summary>
        protected AbstractUdpLink(string name)
            : base(name)
        {
            map = new SortedList<int, EndPoint>();
            reverseMap = new Dictionary<EndPoint, int>();

            socket = new Socket(IPAddress.Any.AddressFamily,
                SocketType.Dgram, ProtocolType.Udp);

            rxBuffer = new Buffer();
            txBuffer = new Buffer();

            txQueue = new Queue<Event>();

            rwlock = new ReaderWriterLockSlim();

            Diag = new Diagnostics();
        }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the LinkSession class.
        /// </summary>
        protected LinkSession(SessionBasedLink link)
        {
            this.link = link;

            rxBuffer = new Buffer();
            rxBufferList = new List<ArraySegment<byte>>();
            txBufferList = new List<ArraySegment<byte>>();

            eventsSending = new List<Event>();
            eventsToSend = new List<Event>();
            buffersSending = new List<SendBuffer>();
            buffersSent = new List<SendBuffer>();

            if (link.SessionRecoveryEnabled)
            {
                preConnectionQueue = new List<Event>();
            }

            Diag = new Diagnostics(this);
        }
Esempio n. 15
0
    /// <summary>
    /// Processes the specified arguments.
    /// </summary>
    /// <param name="args">The arguments.</param>
    public virtual void Process(PipelineArgs args)
    {
      Assert.ArgumentNotNull(args, "args");

      Order order = args.CustomData["order"] as Order;

      if (order == null)
      {
        return;
      }

      IMail mailProvider = Context.Entity.Resolve<IMail>();
      string queryString = string.Format("orderid={0}&mode=mail", order.OrderNumber);

      var param = new
      {
        Recipient = order.CustomerInfo.Email
      };

      mailProvider.SendMail("Order Mail To Customer", param, queryString);
    }
Esempio n. 16
0
 public bool ValidateSingleDecl(List<DeclReference> decls, Name origName, Diagnostics.Span span)
 {
     if (decls.Count == 0)
     {
         this.AddMessage(
             Diagnostics.MessageKind.Error,
             Diagnostics.MessageCode.Unknown,
             "unknown '" + origName.GetString() + "'",
             span);
         return false;
     }
     else if (decls.Count > 1)
     {
         this.AddMessage(
             Diagnostics.MessageKind.Error,
             Diagnostics.MessageCode.AmbiguousDeclaration,
             "ambiguous '" + origName.GetString() + "' between " +
             "'" + this.GetDeclName(decls[0]).GetString() + "'" +
             (decls.Count == 2 ? " and " : ", ") +
             "'" + this.GetDeclName(decls[1]).GetString() + "'" +
             (decls.Count > 2 ? ", and other " + (decls.Count - 2) : ""),
             span);
         return false;
     }
     else
         return true;
 }
        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,
                new Type[] { },
                null);

            if (constructor != null)
            {
                returnValue._graphicalHostHelperObject = constructor.Invoke(new object[] { });
                Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything");
            }

            return(returnValue);
        }
Esempio n. 18
0
 public int GetColumnAtSpanEnd(Diagnostics.Span span)
 {
     return this.GetColumnAtPos(span.end);
 }
Esempio n. 19
0
    private bool AreAllTargetEnemyDead(QuestBehaviour questBehaviour, EventEncounterStateChange e)
    {
        if (this.EnemyArmyGUIDs != null)
        {
            if (questBehaviour.Quest.QuestDefinition.Category != "GlobalQuest" && !this.IgnoreDisbandedArmies)
            {
                for (int i = 0; i < this.EnemyArmyGUIDs.Length; i++)
                {
                    IGameEntity gameEntity;
                    this.gameEntityRepositoryService.TryGetValue(this.EnemyArmyGUIDs[i], out gameEntity);
                    if (gameEntity != null)
                    {
                        break;
                    }
                    if (gameEntity == null && i == this.EnemyArmyGUIDs.Length - 1)
                    {
                        return(true);
                    }
                }
            }
            bool flag = true;
            for (int j = 0; j < this.EnemyArmyGUIDs.Length; j++)
            {
                ulong enemyArmyGUID = this.EnemyArmyGUIDs[j];
                if (enemyArmyGUID == 0UL)
                {
                    Diagnostics.LogError("Enemy contender corresponding to quest variable (varname: '{0}') isn't valid in quest definition (name: '{1}')", new object[]
                    {
                        this.EnemyArmyGUIDs[j],
                        questBehaviour.Quest.QuestDefinition.Name
                    });
                }
                else
                {
                    Func <ContenderSnapShot, bool> < > 9__2;
                    Contender contender = e.EventArgs.Encounter.Contenders.FirstOrDefault(delegate(Contender match)
                    {
                        IEnumerable <ContenderSnapShot> contenderSnapShots = match.ContenderSnapShots;
                        Func <ContenderSnapShot, bool> predicate;
                        if ((predicate = < > 9__2) == null)
                        {
                            predicate = (< > 9__2 = ((ContenderSnapShot snapshot) => snapshot.ContenderGUID == enemyArmyGUID));
                        }
                        return(contenderSnapShots.Any(predicate));
                    });
                    if (contender == null)
                    {
                        return(false);
                    }
                    if (contender.Empire != e.Empire)
                    {
                        if (contender.ContenderState != ContenderState.Defeated)
                        {
                            return(false);
                        }
                        flag = false;
                    }
                }
            }
            return(!flag);
        }
        IEnumerable <Contender> enemiesContenderFromEmpire = e.EventArgs.Encounter.GetEnemiesContenderFromEmpire(e.Empire as global::Empire);

        if (enemiesContenderFromEmpire == null)
        {
            return(false);
        }
        return(enemiesContenderFromEmpire.All((Contender match) => match.ContenderState == ContenderState.Defeated));
    }
Esempio n. 20
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);
            }
        }
Esempio n. 21
0
        public bool LoadListen()
        {
            // Don't allocate anything if we have no phrases to hook.

            if (App.ActiveProfile == null)
            {
                return(false);
            }

            if (App.ActiveProfile.ProfileTriggers != null &&
                App.ActiveProfile.ProfileTriggers.Count == 0)
            {
                Diagnostics.Log("LoadListen() called without a trigger added.");
                MessageBox.Show("At least one Trigger must be added!");

                return(false);
            }

            _synthesizer = App.ActiveProfile.Synthesizer;
            _synthesizer.SelectVoice(App.Settings.VoiceInfo);
            _speechRecognitionEngine = new SpeechRecognitionEngine(App.Settings.RecognizerInfo);

            GrammarBuilder grammarPhrases = new GrammarBuilder {
                Culture = App.Settings.RecognizerInfo
            };

            // Grammar must match speech recognition language localization

            List <string> glossary = new List <string>();

            // Add trigger phrases to glossary of voice recognition engine.
            if (App.ActiveProfile.ProfileTriggers != null)
            {
                glossary.AddRange(from trigger in App.ActiveProfile.ProfileTriggers
                                  let phrase = (Phrase)trigger
                                               select trigger.Value);
            }

            grammarPhrases.Append(new Choices(glossary.ToArray()));
            _speechRecognitionEngine.LoadGrammar(new Grammar(grammarPhrases));

            // event function hook
            _speechRecognitionEngine.SpeechRecognized          += PhraseRecognized;
            _speechRecognitionEngine.SpeechRecognitionRejected += Recognizer_SpeechRecognitionRejected;

            try
            {
                _speechRecognitionEngine.SetInputToDefaultAudioDevice();
            }

            catch (InvalidOperationException e)
            {
                Diagnostics.Log(e, "No microphone was detected.");
                MessageBox.Show("No microphone was detected!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            catch (Exception e)
            {
                Diagnostics.Log(e, "An Unknown error occured when attempting to set default input device.");

                MessageBox.Show("An unknown error has occured, contact support if the problem persists.", "Error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            _speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);

            // subscribe to Push-to-Talk key hooks.
            KeyboardHook.KeyDown += _pushToTalkKeyDownHook;
            KeyboardHook.KeyUp   += _pushToTalkKeyUpHook;
            KeyboardHook.InstallHook();

            if (App.Settings.PushToTalkMode != "Hold" && App.Settings.PushToTalkMode != "Toggle" &&
                App.Settings.PushToTalkMode != "Single")
            {
                _pushToTalkActive = true;
            }

            //  successfully established an instance of SAPI engine with well-formed grammar.

            IsListening = true;

            return(true);
        }
Esempio n. 22
0
    protected override State Execute(AIBehaviorTree aiBehaviorTree, params object[] parameters)
    {
        IGameService service = Services.GetService <IGameService>();

        Diagnostics.Assert(service != null);
        if (this.orderTicket != null)
        {
            if (!this.orderTicket.Raised)
            {
                return(State.Running);
            }
            if (this.orderTicket.PostOrderResponse != PostOrderResponse.Processed)
            {
                aiBehaviorTree.ErrorCode = 36;
                return(State.Failure);
            }
            this.orderTicket = null;
            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
        {
            Army army;
            if (base.GetArmyUnlessLocked(aiBehaviorTree, "$Army", out army) != AIArmyMission.AIArmyMissionErrorCode.None)
            {
                return(State.Failure);
            }
            if (army.IsPrivateers)
            {
                return(State.Success);
            }
            using (IEnumerator <Unit> enumerator = army.StandardUnits.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    if (!enumerator.Current.UnitDesign.Tags.Contains(TradableUnit.ReadOnlyMercenary))
                    {
                        return(State.Failure);
                    }
                }
            }
            if (army.Hero != null)
            {
                OrderChangeHeroAssignment orderChangeHeroAssignment = new OrderChangeHeroAssignment(aiBehaviorTree.AICommander.Empire.Index, army.Hero.GUID, GameEntityGUID.Zero);
                orderChangeHeroAssignment.IgnoreCooldown = true;
                aiBehaviorTree.AICommander.Empire.PlayerControllers.AI.PostOrder(orderChangeHeroAssignment, out this.heroTicket, null);
                return(State.Running);
            }
            Region region = service.Game.Services.GetService <IWorldPositionningService>().GetRegion(army.WorldPosition);
            if (region != null && region.City != null && region.City.Empire == army.Empire)
            {
                OrderTogglePrivateers order = new OrderTogglePrivateers(army.Empire.Index, army.GUID, true);
                aiBehaviorTree.AICommander.Empire.PlayerControllers.AI.PostOrder(order, out this.orderTicket, null);
                return(State.Running);
            }
            aiBehaviorTree.ErrorCode = 36;
            return(State.Failure);
        }
    }
Esempio n. 23
0
 private void diagnostics_Click(object sender, EventArgs e)
 {
     var diagnostics = new Diagnostics(new WinFormsWindowMessageHook(this));
 }
Esempio n. 24
0
        // Hides the base SetResult method which we need to override
        // This method is called when the message is actually delivered to a ReceiveAsync call
        // The update to the CloseMessageSequenceNumber property of Inbound is transactional
        internal async Task SetResult(InboundBaseStreamWireMessage message)
        {
            var closeSeqNumber = this.stream.CloseMessageSequenceNumber;

            if (message.Kind == StreamWireProtocolMessageKind.CloseStream)
            {
                // The close message can be a repeat in recovery cases, but the close sequence number must be unique
                // It is also possible that the transaction surrounding this ReceiveAsync will abort and the message
                // will not in fact be consumed -- and will be received again, but the close sequence number must be unique
                Diagnostics.Assert(
                    closeSeqNumber == StreamConstants.InitialValueOfLastSequenceNumberInStream || closeSeqNumber == message.MessageSequenceNumber,
                    "{0} TraceId::{1} encountered multiple close sequence number values {2} and {3}",
                    this.stream.Tracer,
                    this.traceId,
                    closeSeqNumber,
                    message.MessageSequenceNumber);

                try
                {
                    // this method is idempotent; the close sequence number for a stream is invariant
                    await this.stream.SetCloseMessageSequenceNumber(message.MessageSequenceNumber, this.transactionContext);

                    await this.stream.CloseInboundStream(this.transactionContext);
                }
                catch (Exception e)
                {
                    if (e is FabricObjectClosedException)
                    {
                        FabricEvents.Events.DataMessageDelivery(
                            string.Format(CultureInfo.InvariantCulture, "ObjectClosed@{0}{1}", this.traceId, this.stream.TraceType),
                            this.stream.StreamIdentity.ToString(),
                            message.MessageSequenceNumber,
                            this.transactionContext.Id.ToString());

                        this.TrySetException(e);
                        return;
                    }
                    if (e is FabricNotPrimaryException)
                    {
                        FabricEvents.Events.DataMessageDelivery(
                            string.Format(CultureInfo.InvariantCulture, "NotPrimary@{0}{1}", this.traceId, this.stream.TraceType),
                            this.stream.StreamIdentity.ToString(),
                            message.MessageSequenceNumber,
                            this.transactionContext.Id.ToString());

                        this.TrySetException(e);
                        return;
                    }
                    if (e is FabricNotReadableException)
                    {
                        FabricEvents.Events.DataMessageDelivery(
                            string.Format(CultureInfo.InvariantCulture, "NotReadable@{0}{1}", this.traceId, this.stream.TraceType),
                            this.stream.StreamIdentity.ToString(),
                            message.MessageSequenceNumber,
                            this.transactionContext.Id.ToString());

                        this.TrySetException(e);
                        return;
                    }

                    Tracing.WriteExceptionAsError(
                        "DataMessageDelivery.Failure",
                        e,
                        "Partition::Replica {0} TraceId: {1} MessageNumber: {2} TransactionId: {3}",
                        this.stream.TraceType,
                        this.traceId,
                        message.MessageSequenceNumber,
                        this.transactionContext.Id);
                    Diagnostics.Assert(
                        false,
                        "Unexpected Exception In {0} TraceId: {1} MessageNumber: {2} TransactionId: {3}",
                        this.stream.TraceType,
                        this.traceId,
                        message.MessageSequenceNumber,
                        this.transactionContext.Id);
                }
            }
            else
            {
                Diagnostics.Assert(
                    closeSeqNumber == StreamConstants.InitialValueOfLastSequenceNumberInStream || closeSeqNumber > message.MessageSequenceNumber,
                    "{0} received payload message with sequence number {1} which is greater than the close sequence number {2}",
                    this.stream.Tracer,
                    message.MessageSequenceNumber,
                    closeSeqNumber);
            }

            var setResultSuccess = this.TrySetResult(message);

            if (setResultSuccess)
            {
                FabricEvents.Events.DataMessageDelivery(
                    "Success::" + this.traceId + "@" + this.stream.TraceType,
                    this.stream.StreamIdentity.ToString(),
                    message.MessageSequenceNumber,
                    this.transactionContext.Id.ToString());
            }
            else
            {
                FabricEvents.Events.DataMessageDelivery(
                    "Failure::" + this.traceId + "@" + this.stream.TraceType,
                    this.stream.StreamIdentity.ToString(),
                    message.MessageSequenceNumber,
                    this.transactionContext.Id.ToString());
            }
        }
Esempio n. 25
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);
                }
            }
            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",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        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);
        }
Esempio n. 26
0
        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);
        }
Esempio n. 27
0
 public int GetLineIndexAtSpanEnd(Diagnostics.Span span)
 {
     return this.GetLineAtPos(span.end);
 }
Esempio n. 28
0
    protected override State Execute(QuestBehaviour questBehaviour, EventEncounterStateChange e, params object[] parameters)
    {
        if (this.UpdateVars)
        {
            this.Initialize(questBehaviour);
            this.UpdateVars = false;
        }
        if (e.EventArgs.EncounterState != EncounterState.BattleHasEnded)
        {
            return(State.Running);
        }
        IEnumerable <Contender> enemiesContenderFromEmpire = e.EventArgs.Encounter.GetEnemiesContenderFromEmpire(e.Empire as global::Empire);

        if (enemiesContenderFromEmpire == null)
        {
            return(State.Running);
        }
        this.SaveEnemyArmyGUIDs(questBehaviour);
        if (this.EnemyArmyGUIDVarName != null && this.EnemyArmyGUIDs == null)
        {
            Diagnostics.LogError("Fail to find all army GUID in '{0}' (for quest {1})", new object[]
            {
                string.Join(", ", this.EnemyArmyGUIDVarName),
                questBehaviour.Quest.Name
            });
            return(State.Running);
        }
        if (this.EnemyArmyGUIDs == null || this.EnemyArmyGUIDs.Length == 0)
        {
            if (this.CountAllDeadEnemyArmiesForStepProgression)
            {
                base.ProgressionIncrement = enemiesContenderFromEmpire.Count((Contender match) => match.ContenderState == ContenderState.Defeated);
            }
            else
            {
                base.ProgressionIncrement = 1;
            }
        }
        else if (this.CountAllDeadEnemyArmiesForStepProgression)
        {
            base.ProgressionIncrement = this.ComputeDeadEnemyTargetCount(questBehaviour, e);
        }
        else
        {
            base.ProgressionIncrement = 1;
        }
        if (!string.IsNullOrEmpty(this.Output_WinnerVarName))
        {
            this.AddWinnerToQuestVariable(questBehaviour, e);
        }
        if (!string.IsNullOrEmpty(this.Output_LooserVarName))
        {
            this.AddLooserToQuestVariable(questBehaviour, e);
        }
        if (!string.IsNullOrEmpty(this.Output_WinnerEmpire))
        {
            this.AddWinnerEmpireToQuestVariable(questBehaviour, e);
        }
        if (!string.IsNullOrEmpty(this.Output_Position))
        {
            this.AddPositionToQuestVariable(questBehaviour, e);
        }
        if (!this.DoesKilledArmyBelongsToTargetedEmpire(questBehaviour, e))
        {
            return(State.Running);
        }
        if ((this.TargetOption == QuestBehaviourTreeNode_Decorator_KillArmy.KillArmyTargetOption.All && this.AreAllTargetEnemyDead(questBehaviour, e)) || (this.TargetOption == QuestBehaviourTreeNode_Decorator_KillArmy.KillArmyTargetOption.Any && this.IsThereOneTargetEnemyDead(questBehaviour, e)))
        {
            return(State.Success);
        }
        return(State.Running);
    }
Esempio n. 29
0
 public static InstructionMoveLiteralTuple Empty(Diagnostics.Span span, DataAccess destination)
 {
     return new InstructionMoveLiteralTuple { span = span, destination = destination };
 }
Esempio n. 30
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            //_trailerTransform.Rotation = new float3(0,0,0);

            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            if (Mouse.RightButton == true)
            {
                _camAngle += Mouse.Velocity.x * 0.00001f * DeltaTime / 20 * 10000;
            }



            // Setup the camera
            //RC.View = float4x4.CreateTranslation(0,-5,40) * float4x4.CreateRotationY(pBalt.y);

            //RC.View = float4x4.CreateTranslation(pBneu) * float4x4.CreateRotationY(_camAngle);
            RC.View = float4x4.CreateRotationX(-M.Pi / 7.3f) * float4x4.CreateRotationY(M.Pi - _trailerTransform.Rotation.y) * float4x4.CreateTranslation(-_trailerTransform.Translation.x, -6, -_trailerTransform.Translation.z);
            //ToDO If Bedingung eingefügt

            if (Mouse.LeftButton)
            {
                float2 pickPosClip = Mouse.Position * new float2(2.0f / Width, -2.0f / Height) + new float2(-1, 1);
                _scenePicker.View       = RC.View;
                _scenePicker.Projection = RC.Projection;
                List <PickResult> pickResults = _scenePicker.Pick(pickPosClip).ToList();
                if (pickResults.Count > 0)
                {
                    Diagnostics.Log(pickResults[0].Node.Name);

                    PickResult newPick = null;
                    if (pickResults.Count > 0)
                    {
                        pickResults.Sort((a, b) => Sign(a.ClipPos.z - b.ClipPos.z));
                        newPick = pickResults[0];
                    }
                    if (newPick?.Node != _currentPick?.Node)
                    {
                        if (_currentPick != null)
                        {
                            _currentPick.Node.GetMaterial().Diffuse.Color = _oldColor;
                        }
                        if (newPick != null)
                        {
                            var mat = newPick.Node.GetMaterial();
                            _oldColor         = mat.Diffuse.Color;
                            mat.Diffuse.Color = new float3(1, 0.4f, 0.4f);

                            _Pallete = newPick.Node.GetTransform().Translation.y - 2.5f;
                        }
                        _currentPick = newPick;
                    }
                }
            }


            if (_currentPick != null)
            {
                if (_currentPick.Node.Name == "Rad_R_01")
                {
                    float RadR01 = _RadR01Transform.Rotation.x;
                    RadR01 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR01Transform.Rotation = new float3(RadR01, 0, 0);
                }
                else if (_currentPick.Node.Name == "Rad_L_01")
                {
                    float RadR02 = _RadR02Transform.Rotation.x;
                    RadR02 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR02Transform.Rotation = new float3(RadR02, 0, 0);
                }
                else if (_currentPick.Node.Name == "Rad_02_R")
                {
                    float RadR03 = _RadR03Transform.Rotation.x;
                    RadR03 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR03Transform.Rotation = new float3(RadR03, 0, 0);
                }
                else if (_currentPick.Node.Name == "Rad_02_L")
                {
                    float RadR04 = _RadR04Transform.Rotation.x;
                    RadR04 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR04Transform.Rotation = new float3(RadR04, 0, 0);
                }
                else if (_currentPick.Node.Name == "Rad_03_L")
                {
                    float RadR05 = _RadR05Transform.Rotation.x;
                    RadR05 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR05Transform.Rotation = new float3(RadR05, 0, 0);
                }
                else if (_currentPick.Node.Name == "Rad_03_R")
                {
                    float RadR06 = _RadR06Transform.Rotation.x;
                    RadR06 += Keyboard.ADAxis * 2.0f * (DeltaTime);
                    _RadR06Transform.Rotation = new float3(RadR06, 0, 0);
                }
                else if (_currentPick.Node.Name == "Pallete")
                {
                }



                if (_currentPick.Node.Name == "pfeiler_gewinde_arm_nicht_drehbar")
                {
                    float ogd = _oberesGewTransform.Rotation.y;
                    ogd += Keyboard.LeftRightAxis * 0.005f;
                    _oberesGewTransform.Rotation = new float3(0, ogd, 0);
                }
                else if (_currentPick.Node.Name == "unterer_arm")
                {
                    float unter = _unterarmTransform.Rotation.x;
                    if (Keyboard.GetKey(KeyCodes.Up) == true)
                    {
                        if (unter <= 0.35f)
                        {
                            unter += DeltaTime * 0.1f;
                            _unterarmTransform.Rotation = new float3(unter, 0, 0);
                        }
                    }
                    if (Keyboard.GetKey(KeyCodes.Down) == true)
                    {
                        if (unter >= 0.0f)
                        {
                            unter -= DeltaTime * 0.1f;
                            _unterarmTransform.Rotation = new float3(unter, 0, 0);
                        }
                    }
                }

                /*case "Oberer_arm":
                 *  float obArmx = _oberarmTransform.Translation.z;
                 *  obArmx += Keyboard.UpDownAxis * 0.1f;
                 *  /*float obArmy = _oberarmTransform.Translation.z;
                 *  obArmy += Keyboard.UpDownAxis * 0.1f;*/
                /*_oberarmTransform.Translation = new float3(0, 0, obArmx);
                 * break;*/
                else if (_currentPick.Node.Name == "verbindung_arm_greifer")
                {
                    float ver = _verbagTransform.Translation.y;
                    if (Keyboard.GetKey(KeyCodes.Up) == true)
                    {
                        if (ver <= -0.5f)
                        {
                            ver += DeltaTime * 2f;
                            _verbagTransform.Translation = new float3(0, ver, 0);
                        }
                    }
                    if (Keyboard.GetKey(KeyCodes.Down) == true)
                    {
                        if (ver >= -10.0f)
                        {
                            ver -= DeltaTime * 2f;
                            _verbagTransform.Translation = new float3(0, ver, 0);
                        }
                    }
                }
            }
            float Rad_03 = _RadR03Transform.Rotation.x;

            Rad_03 += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            _RadR03Transform.Rotation = new float3(Rad_03, 0, 0);

            float Rad_04 = _RadR04Transform.Rotation.x;

            Rad_04 += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            _RadR04Transform.Rotation = new float3(Rad_04, 0, 0);

            float Rad_05 = _RadR05Transform.Rotation.x;

            Rad_05 += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            _RadR05Transform.Rotation = new float3(Rad_05, 0, 0);

            float Rad_06 = _RadR06Transform.Rotation.x;

            Rad_06 += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            _RadR06Transform.Rotation = new float3(Rad_06, 0, 0);

            float Rad_01x = _RadR01Transform.Rotation.x;
            float Rad_01y = _RadR01Transform.Rotation.y;

            Rad_01x += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            Rad_01y  = -Keyboard.ADAxis * -0.35f;
            _RadR01Transform.Rotation = new float3(Rad_01x, Rad_01y, 0);

            float Rad_02x = _RadR02Transform.Rotation.x;
            float Rad_02y = _RadR02Transform.Rotation.y;

            Rad_02x += Keyboard.WSAxis * 0.15f * (DeltaTime / 16 * 1000);
            Rad_02y  = -Keyboard.ADAxis * -.35f;
            _RadR02Transform.Rotation = new float3(Rad_02x, Rad_02y, 0);

            float xArm    = _unterarmTransform.Rotation.x;
            float yVerbag = _verbagTransform.Translation.y;

            if (_Pallete < yVerbag)
            {
                yVerbag -= DeltaTime;
                if (_Pallete > yVerbag)
                {
                    yVerbag = _Pallete;
                }
            }

            if (_Pallete > yVerbag)
            {
                //xArm -= DeltaTime;
                yVerbag += DeltaTime;
                if (_Pallete < yVerbag)
                {
                    //xArm = _Pallete;
                    yVerbag = _Pallete;
                }
            }



            _verbagTransform.Translation = new float3(_verbagTransform.Translation.x, yVerbag, _verbagTransform.Translation.z);


            float3 pAalt = _carTransform.Translation;
            float3 pBalt = _trailerTransform.Translation;

            float posVel = -Keyboard.WSAxis * Time.DeltaTime;
            float rotVel = Keyboard.ADAxis * Time.DeltaTime;

            float newRot = _carTransform.Rotation.y + (rotVel * Keyboard.WSAxis * Time.DeltaTime * 30);

            _carTransform.Rotation = new float3(0, newRot, 0);

            float3 pAneu = _carTransform.Translation + new float3(posVel * M.Sin(newRot) * 10, 0, posVel * M.Cos(newRot) * 10);

            _carTransform.Translation = pAneu;

            float3 pBneu = pAneu + (float3.Normalize(pBalt - pAneu) * _d);

            _trailerTransform.Translation = pBneu;

            _trailerTransform.Rotation = new float3(0, (float)System.Math.Atan2(float3.Normalize(pBalt - pAneu).x, float3.Normalize(pBalt - pAneu).z), 0);

            // Render the scene on the current render context
            _sceneRenderer.Render(RC);

            // Swap buffers: Show the contents of the backbuffer (containing the currently rendered farame) on the front buffer.
            Present();
        }
Esempio n. 31
0
 private void AndroidLogger_Info(string task, string message)
 {
     Diagnostics.Debug(message);
 }
Esempio n. 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlobStateRepositoryFactory"/> class
 /// </summary>
 /// <param name="cloudStorageProviderFactory">The cloud storage provider factory</param>
 /// <param name="tracer">The tracer</param>
 public BlobStateRepositoryFactory(ICloudStorageProviderFactory cloudStorageProviderFactory, ITracer tracer)
 {
     this.cloudStorageProviderFactory = Diagnostics.EnsureArgumentNotNull(() => cloudStorageProviderFactory);
     this.tracer = tracer;
 }
Esempio n. 33
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (Containers == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "Containers");
     }
     if (OsType == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "OsType");
     }
     if (Containers != null)
     {
         foreach (var element in Containers)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
     if (ImageRegistryCredentials != null)
     {
         foreach (var element1 in ImageRegistryCredentials)
         {
             if (element1 != null)
             {
                 element1.Validate();
             }
         }
     }
     if (IpAddress != null)
     {
         IpAddress.Validate();
     }
     if (Volumes != null)
     {
         foreach (var element2 in Volumes)
         {
             if (element2 != null)
             {
                 element2.Validate();
             }
         }
     }
     if (Diagnostics != null)
     {
         Diagnostics.Validate();
     }
     if (SubnetIds != null)
     {
         foreach (var element3 in SubnetIds)
         {
             if (element3 != null)
             {
                 element3.Validate();
             }
         }
     }
     if (DnsConfig != null)
     {
         DnsConfig.Validate();
     }
     if (EncryptionProperties != null)
     {
         EncryptionProperties.Validate();
     }
     if (InitContainers != null)
     {
         foreach (var element4 in InitContainers)
         {
             if (element4 != null)
             {
                 element4.Validate();
             }
         }
     }
 }
Esempio n. 34
0
            private void GenerateProperties(IEnumerable <Method> settersToUse, bool readOnly)
            {
                foreach (var setter in settersToUse)
                {
                    var    type      = (Class)setter.Namespace;
                    var    firstWord = GetFirstWord(setter.Name);
                    string property;
                    if ((firstWord == "set" || firstWord == "set_") &&
                        firstWord.Length < setter.Name.Length)
                    {
                        property = setter.Name.Substring(firstWord.Length);
                    }
                    else
                    {
                        property = setter.Name;
                    }
                    var nameBuilder = new StringBuilder(property);
                    if (char.IsLower(setter.Name[0]))
                    {
                        nameBuilder[0] = char.ToLowerInvariant(nameBuilder[0]);
                    }
                    string afterSet = nameBuilder.ToString();
                    var    s        = setter;
                    foreach (var getter in nonSetters.Where(m => m.Namespace == type &&
                                                            m.ExplicitInterfaceImpl == s.ExplicitInterfaceImpl))
                    {
                        var name = GetReadWritePropertyName(getter, afterSet);
                        if (name == afterSet &&
                            GetUnderlyingType(getter.OriginalReturnType).Equals(
                                GetUnderlyingType(setter.Parameters[0].QualifiedType)))
                        {
                            Method g = getter;
                            foreach (var method in type.Methods.Where(m => m != g && m.Name == name))
                            {
                                var oldName = method.Name;
                                method.Name = string.Format("get{0}{1}",
                                                            char.ToUpperInvariant(method.Name[0]), method.Name.Substring(1));
                                Diagnostics.Debug("Method {0}::{1} renamed to {2}", method.Namespace.Name, oldName, method.Name);
                            }
                            foreach (var @event in type.Events.Where(e => e.Name == name))
                            {
                                var oldName = @event.Name;
                                @event.Name = string.Format("on{0}{1}",
                                                            char.ToUpperInvariant(@event.Name[0]), @event.Name.Substring(1));
                                Diagnostics.Debug("Event {0}::{1} renamed to {2}", @event.Namespace.Name, oldName, @event.Name);
                            }
                            GenerateProperty(name, getter.Namespace, getter, readOnly ? null : setter);
                            goto next;
                        }
                    }
                    Property baseProperty = type.GetBaseProperty(new Property {
                        Name = afterSet
                    }, getTopmost: true);
                    if (!type.IsInterface && baseProperty != null && baseProperty.IsVirtual && setter.IsVirtual)
                    {
                        bool isReadOnly = baseProperty.SetMethod == null;
                        var  name       = GetReadWritePropertyName(baseProperty.GetMethod, afterSet);
                        GenerateProperty(name, setter.Namespace, baseProperty.GetMethod,
                                         readOnly || isReadOnly ? null : setter);
                    }
next:
                    ;
                }
                foreach (Method nonSetter in nonSetters)
                {
                    Class    type         = (Class)nonSetter.Namespace;
                    string   name         = GetPropertyName(nonSetter.Name);
                    Property baseProperty = type.GetBaseProperty(new Property {
                        Name = name
                    }, getTopmost: true);
                    if (!type.IsInterface && baseProperty != null && baseProperty.IsVirtual)
                    {
                        bool isReadOnly = baseProperty.SetMethod == null;
                        if (readOnly == isReadOnly)
                        {
                            GenerateProperty(nonSetter.Namespace, nonSetter,
                                             readOnly ? null : baseProperty.SetMethod);
                        }
                    }
                }
            }
Esempio n. 35
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            AddValueFilter();
            PopulateSelection(TaxonomyFilters, _valueSelection, _includeChildren);

            if ((TaxonomyFilters == null || TaxonomyFilters.Count == 0) &&
                MessageBox.Show(
                    "You forgot to tell me which taxonomy you wanted to query!\nLove, Arya\nDo you want to query the entire project?",
                    "Search everywhere?", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            IQueryable <Sku> query = CurrentQuery;

            if (query == null)
            {
                MessageBox.Show("Nothing to search!");
                return;
            }

            lblStatus.Text = "Searching...";
            lblStatus.Refresh();
            DateTime startTime = DateTime.Now;

            IQueryable <SearchResult> taxQuery = from sku in query
                                                 let skuInfo = sku.SkuInfos.First(si => si.Active)
                                                               group skuInfo by new { skuInfo.TaxonomyID, skuInfo.SkuID }
            into taxSkuGrp
            group taxSkuGrp by taxSkuGrp.Key.TaxonomyID
            into taxGrp
            join tax in AryaTools.Instance.InstanceData.Dc.TaxonomyInfos on taxGrp.Key equals
                                      tax.ID
                                      select new SearchResult {
                Taxonomy = tax, SkuCount = taxGrp.Count()
            };

            _taxResults = taxQuery.ToList();
            dgvTaxonomyResults.DataSource = _taxResults;

            for (int i = 0; i < dgvTaxonomyResults.RowCount; i++)
            {
                if (i % 2 != 0)
                {
                    dgvTaxonomyResults.Rows[i].DefaultCellStyle = DisplayStyle.CellStyleOddRow;
                }
                else
                {
                    dgvTaxonomyResults.Rows[i].DefaultCellStyle = DisplayStyle.CellStyleGreyRegular;
                }
            }

            int      skuCount  = _taxResults.Sum(tax => tax.SkuCount);
            TimeSpan timeTaken = DateTime.Now.Subtract(startTime);

            lblStatus.Text = string.Format(
                "{0} SKUs found. Time taken: {1:00}:{2:00}", skuCount, timeTaken.TotalMinutes, timeTaken.Seconds);
            sw.Stop();
            Diagnostics.WriteMessage("Query", "FrmQueryView - btnSearch_Click", sw.Elapsed, skuCount);
            sw.Reset();
        }
Esempio n. 36
0
#pragma warning restore CA1822 // Member can be static

        public DiagnosticScope CreateScope(string name)
        {
            return(Diagnostics.CreateScope(name));
        }
        public override bool VisitFunctionDecl(Function function)
        {
            if (!function.IsGenerated)
            {
                return(false);
            }

            // Check if this function can be converted.
            if (function.Parameters.Count == 0)
            {
                return(false);
            }

            var classParam = function.Parameters[0];

            Class @class;

            if (!GetClassParameter(classParam, out @class))
            {
                return(false);
            }

            // If we reach here, it means the first parameter is of class type.
            // This means we can change the function to be an instance method.

            // Clean up the name of the function now that it will be an instance method.
            if (!function.Name.StartsWith(@class.Name))
            {
                return(false);
            }

            function.Name = function.Name.Substring(@class.Name.Length);
            function.ExplicitlyIgnore();

            // Create a new fake method so it acts as an instance method.
            var method = new Method
            {
                Namespace         = @class,
                OriginalNamespace = function.Namespace,
                Name              = function.Name,
                OriginalName      = function.OriginalName,
                Mangled           = function.Mangled,
                Access            = AccessSpecifier.Public,
                Kind              = CXXMethodKind.Normal,
                ReturnType        = function.ReturnType,
                Parameters        = function.Parameters,
                CallingConvention = function.CallingConvention,
                IsVariadic        = function.IsVariadic,
                IsInline          = function.IsInline,
                Conversion        = MethodConversionKind.FunctionToInstanceMethod
            };

            if (Options.GeneratorKind == GeneratorKind.CSharp)
            {
                method.Parameters = method.Parameters.Skip(1).ToList();
            }

            @class.Methods.Add(method);

            Diagnostics.Debug("Function converted to instance method: {0}::{1}", @class.Name,
                              function.Name);

            return(true);
        }
Esempio n. 38
0
        /// <summary>
        /// Minimax with transpositions.
        ///
        /// Example - search depth 5
        /// 5    4   3   2   1
        /// A1 - B - E - F - G: Transposition added for each move
        /// A2 - C - E: Same transposition encountered at depth 3.
        /// -> No need to search deeper
        ///
        /// General guidelines
        /// * Don't save transposition values near the leaf nodes (depth 0, maybe 1)
        ///
        /// Example
        /// maximizing depth 4    alpha = 5, beta = 10
        ///
        /// minimizing depth 3    alpha = 5, beta = 10
        /// minimizing depth 3    value = 12 ok.
        /// minimizing depth 3    value = 8 ok. beta = 8
        /// minimizing depth 3    value = 4 -> prune and save as lowerbound. this move results to 4 or lower. return 4
        ///
        /// maximizing depth 2    alpha = 5, beta = 8
        /// maximizing depth 2    value = 13 -> prune and save as upperbound. this move results to 13 or higher. return 13
        /// maximizing depth 2    value = 6 ok. alpha = 6
        ///
        /// minimizing depth 1    alpha = 6 beta = 8
        /// transposition found: lowerbound, 4
        /// transposition found: upperbound, 13
        ///
        ///
        /// maximizing depth 4 receives 4 - ignored
        /// minimizing depth 3 receives 13 - ignored
        /// </summary>
        public static double ToDepthWithTranspositions(Board newBoard, int depth, double alpha, double beta, bool maximizingPlayer)
        {
            if (depth == 0)
            {
                return(newBoard.Evaluate(maximizingPlayer, false, false, depth));
            }

            // Check if solution already exists
            var transposition = newBoard.Shared.Transpositions.GetTranspositionForBoard(newBoard.BoardHash);

            if (transposition != null && transposition.Depth >= depth)
            {
                Diagnostics.IncrementTranspositionsFound();
                var transpositionEval = MoveResearch.CheckMateScoreAdjustToDepthFixed(transposition.Evaluation, depth);

                if (transposition.Type == NodeType.Exact)
                {
                    return(transpositionEval);
                }
                else if (transposition.Type == NodeType.UpperBound && transpositionEval < beta)
                {
                    beta = transpositionEval;
                }
                else if (transposition.Type == NodeType.LowerBound && transpositionEval > alpha)
                {
                    alpha = transpositionEval;
                }
                //else if (transposition.Type == NodeType.UpperBound && !maximizingPlayer && transposition.Evaluation <= alpha)
                //{
                //    // No need to search further, as score was worse than alpha
                //    return transposition.Evaluation;
                //}
                //else if (transposition.Type == NodeType.LowerBound && maximizingPlayer && transposition.Evaluation >= beta)
                //{
                //    // No need to search further, as score was worse than beta
                //    return transposition.Evaluation;
                //}
            }

            var allMoves = newBoard.Moves(maximizingPlayer, false);

            if (!allMoves.Any())
            {
                return(newBoard.Evaluate(maximizingPlayer, false, newBoard.IsCheck(!maximizingPlayer), depth));
            }

            if (maximizingPlayer)
            {
                var value = MoveResearch.DefaultAlpha;
                foreach (var move in allMoves)
                {
                    var nextBoard = new Board(newBoard, move);
                    value = ToDepthWithTranspositions(nextBoard, depth - 1, alpha, beta, false);
                    if (value >= beta)
                    {
                        // Eval is at least beta. Fail high
                        // Prune. Alpha is better than previous level beta. Don't want to use moves from this board set.

                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value,
                                                                NodeType.LowerBound, nextBoard.Shared.GameTurnCount);
                        }
                        Diagnostics.IncrementBeta();
                        break;
                    }
                    else if (value > alpha)
                    {
                        // Value between alpha and beta. Save as exact score
                        // Update alpha for rest of iteration
                        alpha = value;
                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value, NodeType.Exact, nextBoard.Shared.GameTurnCount);
                        }
                    }
                }
                return(value);
            }
            else
            {
                var value = MoveResearch.DefaultBeta;
                foreach (var move in allMoves)
                {
                    var nextBoard = new Board(newBoard, move);
                    value = ToDepthWithTranspositions(nextBoard, depth - 1, alpha, beta, true);
                    if (value <= alpha)
                    {
                        // Eval is at most alpha. Fail low
                        // Prune. Beta is smaller than previous level alpha. Don't want to use moves from this board set.

                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value,
                                                                NodeType.UpperBound, nextBoard.Shared.GameTurnCount);
                        }
                        Diagnostics.IncrementAlpha();
                        break;
                    }
                    else if (value < beta)
                    {
                        // Value between alpha and beta. Save as exact score
                        // Update beta for rest of iteration
                        beta = value;
                        if (depth > 1)
                        {
                            // Add new transposition table
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value, NodeType.Exact, nextBoard.Shared.GameTurnCount);
                        }
                    }
                }
                return(value);
            }
        }
        private bool VerifyAnonymousEnums(ASTContext context)
        {
            bool retVal = true;

            foreach (var anonEnum in Configuration.AnonymousEnums)
            {
                var typeDefs = context.FindTypedef(anonEnum.Value).ToList();
                if (typeDefs.Count == 0)
                {
                    retVal = false;
                    Diagnostics.Warning("typedef {0} for anonymous enum not found in source"
                                        , anonEnum.Value
                                        );
                }
                else if (typeDefs.Count > 1)
                {
                    retVal = false;
                    Diagnostics.Warning("Multiple type definitions for Anonymous enum ({0},{1}) found in source"
                                        , anonEnum.Key
                                        , anonEnum.Value
                                        );
                    foreach (var td in typeDefs)
                    {
                        Diagnostics.Warning("\t{0} in {1}@{2}", td.Name, td.TranslationUnit.FileRelativePath, td.LineNumberStart);
                    }
                }

                /*At this point: typdefs.Count == 1 && typedefs[0] is the matching type - so good to go on that front */

                var sourceEnums = (from unit in context.TranslationUnits
                                   let @enum = unit.FindEnumWithItem(anonEnum.Key)
                                               where @enum != null
                                               select @enum
                                   ).ToList();

                if (sourceEnums.Count == 0)
                {
                    retVal = false;
                    Diagnostics.Warning("no enum found in source with first item matching {0}"
                                        , anonEnum.Key
                                        );
                }
                else if (sourceEnums.Count > 1)
                {
                    retVal = false;
                    Diagnostics.Warning("Multiple enums found in source with first item matching {0}"
                                        , anonEnum.Key
                                        );
                    foreach (var e in sourceEnums)
                    {
                        Diagnostics.Warning("\t{1}@{2}", e.TranslationUnit.FileRelativePath, e.LineNumberStart);
                    }
                }
                else if (!string.IsNullOrEmpty(sourceEnums[0].Name))
                {
                    retVal = false;
                    var wrongEnum = sourceEnums[0];
                    Diagnostics.Warning("Found enum {0} in {1}@{2} with value {3} but expected an anonymous enum"
                                        , wrongEnum.Name
                                        , wrongEnum.TranslationUnit.FileRelativePath
                                        , wrongEnum.LineNumberStart
                                        , anonEnum.Key
                                        );
                }
            }

            return(retVal);
        }
Esempio n. 40
0
 public AsyncTcpServer(string name)
     : base(name)
 {
     Diag = new Diagnostics(this);
 }
Esempio n. 41
0
 public virtual IEnumerable <Diagnostic> GetDiagnostics()
 {
     return(Diagnostics.Union(ChildNodes.SelectMany(x => x.GetDiagnostics())));
 }
Esempio n. 42
0
        private void LogLogger(Diagnostics.Logger logs)
        {
            if (logs == null)
                return;

            foreach (var message in logs.Messages)
            {
                if (parseLogMessages)
                    LogParsedMessage(message);
                else
                    LogSimpleMessage(message);
            }
        }
Esempio n. 43
0
        public bool ValidateAsType(DeclReference decl, Name origName, Diagnostics.Span span)
        {
            if (decl.kind != Core.Session.DeclReference.Kind.Struct)
            {
                this.AddMessage(
                    Diagnostics.MessageKind.Error,
                    Diagnostics.MessageCode.WrongDeclarationKind,
                    "'" + this.GetDeclName(decl).GetString() + "' is not a type",
                    span);
                return false;
            }

            return true;
        }
Esempio n. 44
0
 public static DataAccessField Of(Diagnostics.Span span, DataAccess baseAccess, int fieldIndex)
 {
     return new DataAccessField { span = span, baseAccess = baseAccess, fieldIndex = fieldIndex };
 }
Esempio n. 45
0
 public Token(TokenKind kind, Diagnostics.Span span)
 {
     this.kind = kind;
     this.span = span;
 }
        private BoundExpression BindFunctionInvocationExpression(FunctionInvocationExpressionSyntax syntax)
        {
            // Don't try to bind CompileShader function calls, for now.
            if ((syntax.Name.Kind == SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)syntax.Name).Name.ContextualKind == SyntaxKind.CompileShaderKeyword)
            {
                return(new BoundFunctionInvocationExpression(syntax,
                                                             syntax.ArgumentList.Arguments.Select(x => (BoundExpression) new BoundErrorExpression()).ToImmutableArray(),
                                                             OverloadResolutionResult <FunctionSymbolSignature> .None));
            }

            var name           = syntax.Name;
            var boundArguments = BindArgumentList(syntax.ArgumentList);
            var argumentTypes  = boundArguments.Select(a => a.Type).ToImmutableArray();

            var anyErrorsInArguments = argumentTypes.Any(a => a.IsError());

            if (anyErrorsInArguments)
            {
                return(new BoundFunctionInvocationExpression(syntax, boundArguments, OverloadResolutionResult <FunctionSymbolSignature> .None));
            }

            ContainerSymbol containerSymbol;
            SyntaxToken     actualName;

            switch (name.Kind)
            {
            case SyntaxKind.IdentifierName:
                containerSymbol = null;
                actualName      = ((IdentifierNameSyntax)name).Name;
                break;

            case SyntaxKind.QualifiedName:
                containerSymbol = LookupContainer(((QualifiedNameSyntax)syntax.Name).Left);
                actualName      = ((QualifiedNameSyntax)name).Right.Name;
                break;

            default:
                throw new InvalidOperationException();
            }

            var result = (containerSymbol?.Binder ?? this).LookupFunction(actualName, argumentTypes);

            if (result.Best == null)
            {
                if (result.Selected == null)
                {
                    if (result.Candidates.IsEmpty)
                    {
                        Diagnostics.ReportUndeclaredFunction(syntax, argumentTypes);
                        return(new BoundErrorExpression());
                    }
                    else
                    {
                        Diagnostics.ReportOverloadResolutionFailure(syntax, boundArguments.Length);
                    }
                }
                else
                {
                    var symbol1 = result.Selected.Signature.Symbol;
                    var symbol2 = result.Candidates.First(c => !c.Signature.Symbol.Equals(symbol1)).Signature.Symbol;
                    Diagnostics.ReportAmbiguousInvocation(syntax.SourceRange, symbol1, symbol2, argumentTypes);
                }
            }

            var convertedArguments = boundArguments.Select((a, i) => BindArgument(a, result, i, syntax.ArgumentList.Arguments[i].SourceRange)).ToImmutableArray();

            return(new BoundFunctionInvocationExpression(syntax, convertedArguments, result));
        }
Esempio n. 47
0
 public static InstructionMoveAddr Of(Diagnostics.Span span, DataAccess destination, DataAccess source, bool mutable)
 {
     return new InstructionMoveAddr { span = span, destination = destination, source = source, mutable = mutable };
 }
Esempio n. 48
0
        } // GetDynamicParameters

        #endregion Parameters

        #region parameter data

        #endregion parameter data

        #region Command code

        /// <summary>
        /// Sets the content of the item at the specified path
        /// </summary>
        protected override void ProcessRecord()
        {
            // Default to the CmdletProviderContext that will direct output to
            // the pipeline.

            CmdletProviderContext currentCommandContext = CmdletProviderContext;

            currentCommandContext.PassThru = PassThru;

            PSObject mshObject = null;

            switch (ParameterSetName)
            {
            case propertyValuePathSet:
            case propertyValueLiteralPathSet:
                mshObject = new PSObject();
                mshObject.Properties.Add(new PSNoteProperty(Name, Value));
                break;

            case propertyPSObjectPathSet:
                mshObject = InputObject;
                break;

            default:
                Diagnostics.Assert(
                    false,
                    "One of the parameter sets should have been resolved or an error should have been thrown by the command processor");
                break;
            } // switch

            foreach (string path in Path)
            {
                try
                {
                    InvokeProvider.Property.Set(path, mshObject, currentCommandContext);
                }
                catch (PSNotSupportedException notSupported)
                {
                    WriteError(
                        new ErrorRecord(
                            notSupported.ErrorRecord,
                            notSupported));
                    continue;
                }
                catch (DriveNotFoundException driveNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            driveNotFound.ErrorRecord,
                            driveNotFound));
                    continue;
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            providerNotFound.ErrorRecord,
                            providerNotFound));
                    continue;
                }
                catch (ItemNotFoundException pathNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            pathNotFound.ErrorRecord,
                            pathNotFound));
                    continue;
                }
            }
        } // ProcessRecord
Esempio n. 49
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.");
 }
Esempio n. 50
0
        /// <summary> Create the object </summary>
        protected override void BeginProcessing()
        {
            Type type = null;
            PSArgumentException mshArgE = null;

            if (string.Equals(ParameterSetName, netSetName, StringComparison.Ordinal))
            {
                object _newObject = null;
                try
                {
                    type = LanguagePrimitives.ConvertTo(TypeName, typeof(Type), CultureInfo.InvariantCulture) as Type;
                }
                catch (Exception e)
                {
                    // these complications in Exception handling are aim to make error messages better.
                    if (e is InvalidCastException || e is ArgumentException)
                    {
                        if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e,
                                    "AmbiguousTypeReference",
                                    ErrorCategory.InvalidType,
                                    targetObject: null));
                        }

                        mshArgE = PSTraceSource.NewArgumentException(
                            "TypeName",
                            NewObjectStrings.TypeNotFound,
                            TypeName);

                        ThrowTerminatingError(
                            new ErrorRecord(
                                mshArgE,
                                "TypeNotFound",
                                ErrorCategory.InvalidType,
                                targetObject: null));
                    }

                    throw;
                }

                Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true");

                if (type.IsByRefLike)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            PSTraceSource.NewInvalidOperationException(
                                NewObjectStrings.CannotInstantiateBoxedByRefLikeType,
                                type),
                            nameof(NewObjectStrings.CannotInstantiateBoxedByRefLikeType),
                            ErrorCategory.InvalidOperation,
                            targetObject: null));
                }

                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    if (!CoreTypes.Contains(type))
                    {
                        ThrowTerminatingError(
                            new ErrorRecord(
                                new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                    }
                }

                // WinRT does not support creating instances of attribute & delegate WinRT types.
                if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type)))
                {
                    ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType),
                                                          "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null));
                }

                if (ArgumentList == null || ArgumentList.Length == 0)
                {
                    ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
                    if (ci != null && ci.IsPublic)
                    {
                        _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, Array.Empty <object>());
                        if (_newObject != null && Property != null)
                        {
                            // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                    else if (type.GetTypeInfo().IsValueType)
                    {
                        // This is for default parameterless struct ctor which is not returned by
                        // Type.GetConstructor(System.Type.EmptyTypes).
                        try
                        {
                            _newObject = Activator.CreateInstance(type);
                            if (_newObject != null && Property != null)
                            {
                                // Win8:649519
                                _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                            }
                        }
                        catch (TargetInvocationException e)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e.InnerException ?? e,
                                    "ConstructorCalledThrowException",
                                    ErrorCategory.InvalidOperation, null));
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }
                else
                {
                    ConstructorInfo[] ctorInfos = type.GetConstructors();

                    if (ctorInfos.Length != 0)
                    {
                        _newObject = CallConstructor(type, ctorInfos, ArgumentList);
                        if (_newObject != null && Property != null)
                        {
                            // Win8:649519
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }

                mshArgE = PSTraceSource.NewArgumentException(
                    "TypeName", NewObjectStrings.CannotFindAppropriateCtor, TypeName);
                ThrowTerminatingError(
                    new ErrorRecord(
                        mshArgE,
                        "CannotFindAppropriateCtor",
                        ErrorCategory.ObjectNotFound, null));
            }
#if !UNIX
            else // Parameterset -Com
            {
                int result = NewObjectNativeMethods.CLSIDFromProgID(ComObject, out _comObjectClsId);

                // If we're in ConstrainedLanguage, do additional restrictions
                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    bool isAllowed = false;

                    // If it's a system-wide lockdown, we may allow additional COM types
                    if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                    {
                        if ((result >= 0) &&
                            SystemPolicy.IsClassInApprovedList(_comObjectClsId))
                        {
                            isAllowed = true;
                        }
                    }

                    if (!isAllowed)
                    {
                        ThrowTerminatingError(
                            new ErrorRecord(
                                new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                        return;
                    }
                }

                object comObject         = CreateComObject();
                string comObjectTypeName = comObject.GetType().FullName;
                if (!comObjectTypeName.Equals("System.__ComObject"))
                {
                    mshArgE = PSTraceSource.NewArgumentException(
                        "TypeName", NewObjectStrings.ComInteropLoaded, comObjectTypeName);
                    WriteVerbose(mshArgE.Message);
                    if (Strict)
                    {
                        WriteError(new ErrorRecord(
                                       mshArgE,
                                       "ComInteropLoaded",
                                       ErrorCategory.InvalidArgument, comObject));
                    }
                }

                if (comObject != null && Property != null)
                {
                    // Win8:649519
                    comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                }

                WriteObject(comObject);
            }
#endif
        }
Esempio n. 51
0
 public static DataAccessDereference Of(Diagnostics.Span span, DataAccess innerAccess)
 {
     return new DataAccessDereference { span = span, innerAccess = innerAccess };
 }
Esempio n. 52
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(null != _referenceEntries, "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 (null != referenceEntry && null != differenceEntry &&
                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 (null != matchingEntry)
            {
                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 (null != matchingEntry)
            {
                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 (null != differenceEntry)
            {
                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 (null != referenceEntry)
            {
                if (0 < SyncWindow)
                {
                    while (_referenceEntryBacklog.Count >= SyncWindow)
                    {
                        EmitReferenceOnly(_referenceEntryBacklog[0]);
                        _referenceEntryBacklog.RemoveAt(0);
                    }
                    _referenceEntryBacklog.Add(referenceEntry);
                }
                else
                {
                    EmitReferenceOnly(referenceEntry);
                }
            }
        }
Esempio n. 53
0
 public static DataAccessRegister ForRegister(Diagnostics.Span span, int registerIndex)
 {
     return new DataAccessRegister { span = span, registerIndex = registerIndex };
 }
Esempio n. 54
0
        public override bool VisitFunctionDecl(Function function)
        {
            if (!VisitDeclaration(function) || function.IsSynthetized ||
                function.IsExplicitlyGenerated)
            {
                return(false);
            }

            if (function.IsDependent && !(function.Namespace is Class))
            {
                function.GenerationKind = GenerationKind.None;
                Diagnostics.Debug("Function '{0}' was ignored due to dependent context",
                                  function.Name);
                return(false);
            }

            var ret = function.OriginalReturnType;

            string msg;

            if (HasInvalidType(ret.Type, function, out msg))
            {
                function.ExplicitlyIgnore();
                Diagnostics.Debug("Function '{0}' was ignored due to {1} return decl",
                                  function.Name, msg);
                return(false);
            }

            foreach (var param in function.Parameters)
            {
                if (HasInvalidDecl(param, out msg))
                {
                    function.ExplicitlyIgnore();
                    Diagnostics.Debug("Function '{0}' was ignored due to {1} param",
                                      function.Name, msg);
                    return(false);
                }

                if (HasInvalidType(param, out msg))
                {
                    function.ExplicitlyIgnore();
                    Diagnostics.Debug("Function '{0}' was ignored due to {1} param",
                                      function.Name, msg);
                    return(false);
                }

                if (CheckDecayedTypes)
                {
                    var decayedType = param.Type.Desugar() as DecayedType;
                    if (decayedType != null)
                    {
                        function.ExplicitlyIgnore();
                        Diagnostics.Debug("Function '{0}' was ignored due to unsupported decayed type param",
                                          function.Name);
                        return(false);
                    }
                }

                if (param.Kind == ParameterKind.IndirectReturnType)
                {
                    Class retClass;
                    param.Type.Desugar().TryGetClass(out retClass);
                    if (retClass == null)
                    {
                        function.ExplicitlyIgnore();
                        Diagnostics.Debug(
                            "Function '{0}' was ignored due to an indirect return param not of a tag type",
                            function.Name);
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 55
0
 public int GetLineIndexAtSpanStart(Diagnostics.Span span)
 {
     return this.GetLineAtPos(span.start);
 }
Esempio n. 56
0
 internal void LeaveScope()
 {
     Diagnostics.Assert(_scopes.Count > 0, "Scope stack can't be empty when leaving a scope");
     _scopes.RemoveAt(_scopes.Count - 1);
 }
Esempio n. 57
0
 public int GetColumnAtSpanStart(Diagnostics.Span span)
 {
     return this.GetColumnAtPos(span.start);
 }
Esempio n. 58
0
        internal CommandExecutionAttemptResult HandleLine(CString8 *input, bool verboseFailure, bool useHelp)
        {
            Diagnostics.Assert(input != null, "Prompter::HandleLine(CString8*): Parameter 'input' is null");
#if Prompter_DebuggingVerbosity
            Diagnostics.Message("Prompter::HandleLine(CString8*): Function started");
#endif

            if (input->Length == 0)
            {
#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): Raw input is blank");
#endif
                if (verboseFailure)
                {
                    HandleEmptyCommandEntry();
                }

#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): RET");
#endif
                return(CommandExecutionAttemptResult.BlankEntry);
            }
            CString8 *trimmedInput = input->Trim();
            if (trimmedInput->Length == 0)
            {
#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): Trimmed input is blank");
#endif
                CString8.DISPOSE(trimmedInput);

                if (verboseFailure)
                {
                    HandleEmptyCommandEntry();
                }

#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): RET");
#endif
                return(CommandExecutionAttemptResult.BlankEntry);
            }

            int       firstSpace = trimmedInput->IndexOf(" ");
            CString8 *commandName;
            CString8 *parameters;
            if (firstSpace < 0)
            {
                commandName = trimmedInput;
                parameters  = CString8.CreateEmpty();
            }
            else
            {
                commandName = trimmedInput->Substring(0, firstSpace);
                parameters  = trimmedInput->Substring(firstSpace + 1);
            }

            CommandTableEntry *command = this.FindCommand(commandName);
            if (command == null)
            {
#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): Command not found");
#endif
                if (verboseFailure)
                {
                    HandleUnrecognizedCommandEntry(commandName);
                }

#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): Freeing contextual stuff");
#endif
                //Free up what we used
                if (commandName != trimmedInput)
                {
                    CString8.DISPOSE(commandName);
                }
                CString8.DISPOSE(trimmedInput);
                CString8.DISPOSE(parameters);
#if Prompter_DebuggingVerbosity
                Diagnostics.Message("Prompter::HandleLine(CString8*): RET");
#endif
                return(CommandExecutionAttemptResult.NotFound);
            }
            CommandExecutionContext *commandExecutionContext = CommandExecutionContext.CREATE();
            commandExecutionContext->parameters = parameters;

#if Prompter_DebuggingVerbosity
            Diagnostics.Message("Prompter::HandleLine(CString8*): Getting ready to call command");
#endif
            if (!useHelp)
            {
                ADC.MemoryUtil.Call(command->func_Execute, (void *)commandExecutionContext);
            }
            else
            {
                ADC.MemoryUtil.Call(command->func_GetHelp, (void *)commandExecutionContext);
            }
#if Prompter_DebuggingVerbosity
            Diagnostics.Message("Prompter::HandleLine(CString8*): Done calling command");
#endif

            //Free up what we used
#if Prompter_DebuggingVerbosity
            Diagnostics.Message("Prompter::HandleLine(CString8*): Freeing contextual stuff");
#endif
            if (commandName != trimmedInput)
            {
                CString8.DISPOSE(commandName);
            }
            CString8.DISPOSE(trimmedInput);
            CString8.DISPOSE(parameters);
            CommandExecutionContext.DISPOSE(commandExecutionContext);
#if Prompter_DebuggingVerbosity
            Diagnostics.Message("Prompter::HandleLine(CString8*): RET");
#endif
            return(CommandExecutionAttemptResult.Success);
        }
Esempio n. 59
0
        public static void AddElectricalDiagnostics(SEGRepository segR, Guid assetId)
        {
            List<Diagnostics> electrical = DiagnosticsHelper.GetElectricalDiagnostics(segR,assetId).ToList();
            int nextIndex = 1;
            if(electrical.Count>0)
            {
                nextIndex = electrical.OrderBy(x => x.Index).Last().Index + 1;
            }

            using (SEGContext seg = segR.GetContext())
            {
                DiagnosticsType dtEle = seg.DiagnosticsTypes.FirstOrDefault(a => a.Name == "Electrical");
                ItemClass icEle = seg.ItemClasses.FirstOrDefault(a => a.Name == "Electrical");
                List<Item> dtEItems = seg.Items.Where(x => x.ItemClassId == icEle.Id).OrderBy(x => x.Index).ToList();

                // Asset info
                AssetInfo ai = new AssetInfo();
                ai.Key = "EDIAG_" + nextIndex + "_INFO1";
                ai.Value = "";
                ai.AssetId = assetId;
                seg.AssetInfos.Add(ai);

                ai = new AssetInfo();
                ai.Key = "EDIAG_" + nextIndex + "_INFO2";
                ai.Value = "";
                ai.AssetId = assetId;
                seg.AssetInfos.Add(ai);

                ai = new AssetInfo();
                ai.Key = "EDIAG_" + nextIndex + "_INFO3";
                ai.Value = "";
                ai.AssetId = assetId;
                seg.AssetInfos.Add(ai);

                ai = new AssetInfo();
                ai.Key = "EDIAG_" + nextIndex + "_INFO4";
                ai.Value = "";
                ai.AssetId = assetId;
                seg.AssetInfos.Add(ai);

                // Mechanical Diagnostics
                Diagnostics d = new Diagnostics();
                d.AreaId = Guid.Empty;
                d.AssetId = assetId;
                d.Index = nextIndex;
                d.DiagnosticsTypeId = dtEle.Id;
                seg.Diagnostics.Add(d);
                seg.SaveChanges();

                foreach (Item i in dtEItems)
                {
                    DiagnosticsDetail dd = new DiagnosticsDetail();
                    dd.Comments = "";
                    dd.DiagnosticsId = d.Id;
                    dd.EntryDate = DateTime.MinValue;
                    dd.ExecutorId = Guid.Empty;
                    dd.ImageId = Guid.Empty;
                    dd.ItemId = i.Id;
                    dd.Status = "_new_";
                    dd.VerifierId = Guid.Empty;
                    dd.VerifyDate = DateTime.MinValue;
                    seg.DiagnosticsDetails.Add(dd);
                }
                seg.SaveChanges();

            }
        }
Esempio n. 60
0
    /// <summary>
    /// Collision detection between the bullet and ai
    /// </summary>
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Bullet"))
        {
            var bullet = other.gameObject.GetComponent <Bullet>();

            //TODO: Ensure the owner is not colliding with their own bullet
            // also make sure that owned AIs can't be hurt by their owners
            // bullets.

            // Also store the owner of the last bullet that hits so the player to add score to is known.
            //Debug.Log("AI player ID: " + Utilities.GetPlayerID(gameObject));
            if (bullet.Owner != Utilities.GetPlayerID(gameObject))
            {
                switch (aiType)
                {
                case NetworkedAI.AIType.ROGUE:
                {
                    m_parentHealth.InflictDamage(bullet.Damage);
                    other.gameObject.GetComponent <Bullet>().DestroyOnImpact();

                    var player = PlayerManager.GetControllablePlayer();
                    if (player != null && bullet.Owner == Utilities.GetPlayerID(player))
                    {
                        player.GetComponent <PlayerScore>().AddScore(1.0f);
                    }

                    break;
                }

                case NetworkedAI.AIType.FLEET:
                {
                    if (bullet.Owner == GetComponentInParent <FleetAI>().OwnerPlayerID)
                    {
                        if (Diagnostics.IsActive())
                        {
                            Debug.Log("It worked");
                        }
                    }
                    else
                    {
                        if (Diagnostics.IsActive())
                        {
                            Debug.Log("Non-player attacked fleet ship");
                        }

                        m_parentHealth.InflictDamage(bullet.Damage);
                        other.gameObject.GetComponent <Bullet>().DestroyOnImpact();

                        var player = PlayerManager.GetControllablePlayer();
                        if (player != null && bullet.Owner == Utilities.GetPlayerID(player))
                        {
                            player.GetComponent <PlayerScore>().AddScore(1.0f);
                        }
                    }
                    break;
                }

                case NetworkedAI.AIType.PATROL:
                    //TODO: Implement patrol hit detection logic.
                    if (bullet.Owner == GetComponentInParent <PatrolAI>().OwnerPlayerID)
                    {
                        if (Diagnostics.IsActive())
                        {
                            Debug.Log("It worked");
                        }
                    }
                    else
                    {
                        if (Diagnostics.IsActive())
                        {
                            Debug.Log("Non-player attacked fleet ship");
                        }

                        m_parentHealth.InflictDamage(bullet.Damage);
                        other.gameObject.GetComponent <Bullet>().DestroyOnImpact();

                        var player = PlayerManager.GetControllablePlayer();
                        if (player != null && bullet.Owner == Utilities.GetPlayerID(player))
                        {
                            player.GetComponent <PlayerScore>().AddScore(1.0f);
                        }
                    }
                    break;
                }
            }
        }
    }