protected override void OnDraw(Rect bounds)
        {
            LastAction action = Historian.Instance.LastAction;

            TokenizedText = actionMessages[action];
            base.OnDraw(bounds);
        }
        public void MoveForward( )
        {
            if (CurrentAction == LastAction.Idling && Stamina > 0 && !WillColide( ))
            {
                _d5a8c937f540473f9d5f40269401f254--;
                switch (Orientation)
                {
                case Orientation.North:
                    _08389405491042dd89325d46355263d1--;
                    _fd832498b5c4470bb4ac626ee3b3952d = LastAction.MovingForward;
                    //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMovingNorth);
                    break;

                case Orientation.East:
                    _a269ff57246b40fcb2d16fc97f5dea6c++;
                    _fd832498b5c4470bb4ac626ee3b3952d = LastAction.MovingForward;
                    //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMovingEast);
                    break;

                case Orientation.South:
                    _08389405491042dd89325d46355263d1++;
                    _fd832498b5c4470bb4ac626ee3b3952d = LastAction.MovingForward;
                    //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMovingSouth);
                    break;

                case Orientation.West:
                    _a269ff57246b40fcb2d16fc97f5dea6c--;
                    _fd832498b5c4470bb4ac626ee3b3952d = LastAction.MovingForward;
                    //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMovingWest);
                    break;
                }
            }
        }
 public void MeleeAttack( )
 {
     if (CurrentAction == LastAction.Idling)
     {
         _fd832498b5c4470bb4ac626ee3b3952d = LastAction.MeleeAttack;
         var botInMelee = FindBotInRange( );
         if (botInMelee != null)
         {
             var bot = FindBot(botInMelee);
             _lastAttackBotId    = bot.Id;
             _lastAttackLocation = new Position {
                 X = bot.LocationX, Y = bot.LocationY
             };
             if (botInMelee.Orientation == Orientation)
             {
                 DamageBot(bot, MELEE_BACKSTAB_DAMAGE);
                 _673add7aa39b4601ba69f8713deffc8e += MELEE_BACKSTAB_DAMAGE;
                 //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMeleeBackstabAttack);
             }
             else
             {
                 DamageBot(bot, MELEE_DAMAGE);
                 _673add7aa39b4601ba69f8713deffc8e += MELEE_DAMAGE;
                 //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotMeleeAttack);
             }
         }
     }
 }
Exemple #4
0
        internal bool UndoLastAction()
        {
            Main.DebugMessage("Undoing last action type {1} for state {0}", State, LastAction.ToString());
            switch (LastAction)
            {
            case LastActionType.restore:
                Main.DebugMessage("Restoring {0} active mods", ModData.activeMods.Count);
                SetActiveMods(ModData.activeMods);
                return(true);

            case LastActionType.backup:
                if (ModData != null)
                {
                    Main.DebugMessage("Restored {0}'s last state", State);
                    DirectXmlSaver.SaveDataObject((object)ModData, PathHandler.GenBackupModListFile(State));
                }
                else
                {
                    File.Delete(PathHandler.GenBackupModListFile(State));
                }
                return(true);

            case LastActionType.none:
            default:
                Main.Log.Warning("Last Undo Action was not set with a type, cannot undo last action");
                return(false);
            }
        }
        private bool TryCreateReplyActivity(CoreItem item, out Activity activity)
        {
            activity = null;
            if (item.Id == null)
            {
                return(false);
            }
            if (!item.PropertyBag.IsPropertyDirty(MessageItemSchema.LastVerbExecuted))
            {
                return(false);
            }
            LastAction valueOrDefault = item.PropertyBag.GetValueOrDefault <LastAction>(MessageItemSchema.LastVerbExecuted);
            ActivityId id;

            if (valueOrDefault == LastAction.ReplyToSender || (valueOrDefault >= LastAction.VotingOptionMin && valueOrDefault <= LastAction.VotingOptionMax))
            {
                id = ActivityId.Reply;
            }
            else if (valueOrDefault == LastAction.ReplyToAll)
            {
                id = ActivityId.ReplyAll;
            }
            else
            {
                if (valueOrDefault != LastAction.Forward)
                {
                    return(false);
                }
                id = ActivityId.Forward;
            }
            activity = new Activity(id, this.clientInfo.Id, ExDateTime.UtcNow, this.clientSessionId, this.clientInfo.Version, Interlocked.Increment(ref this.sequenceNumber), this.session, item.Id.ObjectId, null, null);
            return(true);
        }
Exemple #6
0
        protected virtual void LogLastAction(object o, ContentAction action)
        {
            Thread thread = new Thread(() =>
            {
                try
                {
                    if (o is TextContent)
                    {
                        var textContent       = (TextContent)o;
                        var repository        = textContent.GetRepository();
                        var folderName        = textContent.FolderName;
                        var contentSummary    = textContent.GetSummary();
                        LastAction lastAction = new LastAction()
                        {
                            Repository     = repository,
                            FolderName     = folderName,
                            ContentSummary = contentSummary,
                            Action         = action,
                            UtcActionDate  = DateTime.UtcNow
                        };
                        EngineContext.Current.Resolve <Kooboo.CMS.Search.Persistence.ILastActionProvider>().Add(lastAction);
                    }
                }
                catch (Exception e)
                {
                    Kooboo.HealthMonitoring.Log.LogException(e);
                }
            });

            thread.Start();
        }
Exemple #7
0
        public async Task ThenCountsShouldBeCorrectWhenEmployerHasASingleCommitmentThats(
            int expectedDraftCount, int expectedReadyForReviewCount, int expectedWithProviderCount, int expectedTransferFundedCohortsCount, int expectedRejectedTransferFundedCohortsCount,
            long?transferSenderId, TransferApprovalStatus transferApprovalStatus,
            AgreementStatus agreementStatus, EditStatus editStatus, LastAction lastAction, int apprenticeshipCount)
        {
            //Arrange
            MockMediator.Setup(x => x.SendAsync(It.IsAny <GetCommitmentsQuery>()))
            .ReturnsAsync(new GetCommitmentsResponse
            {
                Commitments = new List <CommitmentListItem>
                {
                    new CommitmentListItem
                    {
                        TransferSenderId       = transferSenderId,
                        TransferApprovalStatus = transferApprovalStatus,
                        AgreementStatus        = agreementStatus,
                        EditStatus             = editStatus,
                        LastAction             = lastAction,
                        ApprenticeshipCount    = apprenticeshipCount
                    }
                }
            });

            //Act
            var result = await EmployerCommitmentOrchestrator.GetYourCohorts("ABC123", "ABC321");

            //Assert
            Assert.AreEqual(expectedDraftCount, result.Data.DraftCount, "Incorrect DraftCount");
            Assert.AreEqual(expectedReadyForReviewCount, result.Data.ReadyForReviewCount, "Incorrect ReadyForReviewCount");
            Assert.AreEqual(expectedWithProviderCount, result.Data.WithProviderCount, "Incorrect WithProviderCount");
            Assert.AreEqual(expectedTransferFundedCohortsCount, result.Data.TransferFundedCohortsCount, "IncorrectTransferFundedCohortsCount");
            Assert.AreEqual(expectedRejectedTransferFundedCohortsCount, result.Data.RejectedTransferFundedCohortsCount, "IncorrectRejectedTransferFundedCohortsCount");
        }
Exemple #8
0
        public ListViewItem ToListViewItem()
        {
            ListViewItem lvi = new ListViewItem();

            lvi.Text = ID.ToString();

            if (CoinQuantity == 0)
            {
                lvi.SubItems.Add(CoinOriginalQuantity.ToString());
            }
            else
            {
                lvi.SubItems.Add(CoinQuantity.ToString());
            }

            lvi.SubItems.Add(CoinPair.ToString());
            lvi.SubItems.Add(LastAction.ToString());

            if (LastAction == OrderSide.Buy)
            {
                lvi.SubItems.Add(BuyPriceAfterFees.ToString());
            }
            else
            {
                lvi.SubItems.Add(SellPriceAfterFees.ToString());
            }

            lvi.SubItems.Add(Cost.ToString());
            lvi.SubItems.Add(Price.ToString());
            lvi.SubItems.Add(PriceChangePercentage.ToString());
            lvi.ForeColor = PriceChangePercentage > 0m ? Color.Green : Color.Red;
            return(lvi);
        }
Exemple #9
0
        public async Task CheckStatusUpdate(SaveStatus input, LastAction expectedLastAction, bool expectedCreateTaskBool)
        {
            _mockHashingService.Setup(m => m.DecodeValue("ABBA99")).Returns(2L);
            _mockMediator.Setup(m => m.Send(It.IsAny <GetProviderAgreementQueryRequest>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new GetProviderAgreementQueryResponse {
                HasAgreement = ProviderAgreementStatus.Agreed
            }));

            _mockMediator.Setup(m => m.Send(It.IsAny <GetCommitmentQueryRequest>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new GetCommitmentQueryResponse
            {
                Commitment = new CommitmentView
                {
                    AgreementStatus = AgreementStatus.NotAgreed,
                    EditStatus      = EditStatus.ProviderOnly
                }
            }));

            await _orchestrator.SubmitCommitment("UserId", 1L, "ABBA99", input, string.Empty, new SignInUserModel());

            _mockMediator.Verify(m => m
                                 .Send(It.Is <SubmitCommitmentCommand>(
                                           p => p.ProviderId == 1L &&
                                           p.CommitmentId == 2L &&
                                           p.Message == string.Empty &&
                                           p.LastAction == expectedLastAction &&
                                           p.CreateTask == expectedCreateTaskBool), It.IsAny <CancellationToken>()));
        }
Exemple #10
0
        /// <summary>
        /// Undoes the last editing change - autocomplete word,
        /// insert punctuation or insert a character
        /// </summary>
        public void UndoLastEditChange()
        {
            try
            {
                Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " +
                          Context.AppAgentMgr.CurrentEditingMode);

                if (Context.AppAgentMgr.CurrentEditingMode != EditingMode.TextEntry)
                {
                    return;
                }

                switch (_lastAction)
                {
                case LastAction.Punctuation:
                    deletePreviousPunctuation();
                    break;

                case LastAction.AutoCompleteWord:
                    DeletePreviousWord();
                    break;

                case LastAction.AlphaNumeric:
                    AgentManager.Instance.Keyboard.Send(Keys.Back);
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            _lastAction = LastAction.Unknown;
        }
Exemple #11
0
        /// <summary>
        /// Handles actuation of a button representing an alphanumeric character
        /// </summary>
        public void HandleAlphaNumericChar(ArrayList modifiers, char inputChar)
        {
            Context.AppAgentMgr.Keyboard.Send((modifiers != null) ? modifiers.Cast <Keys>().ToList() : KeyStateTracker.GetExtendedKeys(), inputChar);

            KeyStateTracker.KeyTriggered(inputChar);

            _lastAction = LastAction.AlphaNumeric;
        }
Exemple #12
0
 /// <summary>
 /// Handler for the event that is raised when the focus in the
 /// application window changes.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void AppAgentMgr_EvtFocusChanged(object sender, FocusChangedEventArgs e)
 {
     _lastAction                 = LastAction.Unknown;
     _autoCompleteCaretPos       = -1;
     _beforeAutoCompleteCaretPos = -1;
     _autocompleteStartOffset    = -1;
     _autoCompletePartialWord    = String.Empty;
 }
Exemple #13
0
 internal static string EncodeReplyForwardStatus(LastAction lastAction, IconIndex iconIndex, VersionedId id)
 {
     if (id == null)
     {
         return(string.Empty);
     }
     return(ReplyForwardUtils.EncodeReplyForwardStatus(lastAction, iconIndex, id.ToBase64String()));
 }
Exemple #14
0
        /// <summary>
        /// Handles actuation of a button representing an alphanumeric character
        /// </summary>
        /// <param name="inputChar">char to send</param>
        public void HandleAlphaNumericChar(char inputChar)
        {
            Context.AppAgentMgr.Keyboard.Send(inputChar);

            KeyStateTracker.KeyTriggered(inputChar);

            _lastAction = LastAction.AlphaNumeric;
        }
 public void TurnAround( )
 {
     if (CurrentAction == LastAction.Idling)
     {
         Turn(+2);
         _fd832498b5c4470bb4ac626ee3b3952d = LastAction.TurningAround;
         //_logLogic_a76ef698d9204527836e30719d971888.LogMessage(null, null, _bot_e55472035b434b1ea185cf32ece2b8bc, HistoryName.BotTurningAround);
     }
 }
Exemple #16
0
        private string GetTimeAgo()
        {
            if (LastAction.Year == 1983)
            {
                return(string.Empty);
            }

            return(LastAction.Humanize(false));
        }
 public override int GetHashCode()
 {
     return HashCode.Combine(
         Uuid.GetHashCode(StringComparison.Ordinal),
         Name.GetHashCode(StringComparison.Ordinal),
         State.GetHashCode(),
         LastAction.GetHashCode(),
         SessionName.GetHashCode(StringComparison.Ordinal)
     );
 }
Exemple #18
0
            public override bool Equals(object obj)
            {
                LastAction other = obj as LastAction;

                if (other == null)
                {
                    return(false);
                }
                return(other.lastActionstring == this.lastActionstring);
            }
Exemple #19
0
        /// <summary>
        /// Create a TestCase by specifying all its components.
        /// </summary>
        public TestCase(LastAction lastAction, ExceptionDescription exception, Collection <string> imports,
                        Collection <string> assemblies, string className, Collection <string> testCode)
        {
            this.lastAction = lastAction ?? throw new ArgumentNullException();
            this.exception  = exception ?? throw new ArgumentNullException();

            // Imports.
            if (imports == null)
            {
                throw new ArgumentNullException();
            }
            this.imports = new Collection <string>();
            foreach (string s in imports)
            {
                if (s == null)
                {
                    throw new ArgumentNullException();
                }
                this.imports.Add(s);
            }

            // Referenced assemblies.
            refAssemblies = new Collection <RefAssembly>();
            foreach (string s in assemblies)
            {
                if (s == null)
                {
                    throw new ArgumentNullException();
                }
                refAssemblies.Add(new RefAssembly(RefAssembly.REFASSEMBLY_MARKER + s));
            }

            // Class name.
            if (className == null)
            {
                throw new ArgumentNullException();
            }
            this.className = className;

            // Test code.
            if (testCode == null)
            {
                throw new ArgumentNullException();
            }
            this.testCode = new Collection <string>();
            foreach (string s in testCode)
            {
                if (s == null)
                {
                    throw new ArgumentNullException();
                }
                this.testCode.Add(s);
            }
        }
        public void VerfiyProviderEmailRequestIsCreatedAndSentCorrectly(LastAction lastAction)
        {
            var actionType = lastAction == LastAction.Approve ? "approval" : "review";

            PasAccountApiClient.Verify(x => x.SendEmailToAllProviderRecipients(GetCohortSummaryQueryResult.ProviderId.Value,
                                                                               It.Is <ProviderEmailRequest>(p =>
                                                                                                            p.TemplateId == "ProviderCommitmentNotification" &&
                                                                                                            p.ExplicitEmailAddresses[0] == GetCohortSummaryQueryResult.LastUpdatedByProviderEmail &&
                                                                                                            p.Tokens["cohort_reference"] == GetCohortSummaryQueryResult.CohortReference &&
                                                                                                            p.Tokens["type"] == actionType), default));
        }
        public void Teleport(Int16 x, Int16 y)
        {
            if (CurrentAction == LastAction.Idling && Stamina > 0 && !WillColide(x, y))
            {
                _d5a8c937f540473f9d5f40269401f254 -= 10;

                _a269ff57246b40fcb2d16fc97f5dea6c = x;
                _08389405491042dd89325d46355263d1 = y;
                _fd832498b5c4470bb4ac626ee3b3952d = LastAction.Teleport;
            }
        }
Exemple #22
0
        public static TestCase Dummy(string className)
        {
            LastAction           lastAction = new LastAction(LastAction.LASTACTION_MARKER + "none");
            ExceptionDescription exception  = ExceptionDescription.NoException();
            Collection <string>  imports    = new Collection <string>();
            Collection <string>  assemblies = new Collection <string>();
            Collection <string>  testCode   = new Collection <string>();

            testCode.Add("/* Source code printing failed. */");
            return(new TestCase(lastAction, exception, imports, assemblies, className, testCode));
        }
Exemple #23
0
        void CheckTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (name == "")
            {
                return;
            }
            SendRaw(Opcode.Ping);
            if (Server.afkminutes <= 0)
            {
                return;
            }
            if (DateTime.UtcNow < AFKCooldown)
            {
                return;
            }

            if (IsAfk)
            {
                int time = Server.afkkick;
                if (AutoAfk)
                {
                    time += Server.afkminutes;
                }

                if (Server.afkkick > 0 && group.Permission < Server.afkkickperm)
                {
                    if (LastAction.AddMinutes(time) < DateTime.UtcNow)
                    {
                        Leave("Auto-kick, AFK for " + Server.afkkick + " minutes");
                    }
                }
                if (Moved())
                {
                    CmdAfk.ToggleAfk(this, "");
                }
            }
            else
            {
                if (Moved())
                {
                    LastAction = DateTime.UtcNow;
                }

                DateTime lastAction = LastAction;
                if (LastAction.AddMinutes(Server.afkminutes) < DateTime.UtcNow &&
                    !String.IsNullOrEmpty(name))
                {
                    CmdAfk.ToggleAfk(this, "auto: Not moved for " + Server.afkminutes + " minutes");
                    AutoAfk    = true;
                    LastAction = lastAction;
                }
            }
        }
Exemple #24
0
 private static string EncodeReplyForwardStatus(LastAction lastAction, IconIndex iconIndex, string parentMessageItemIdBase64String)
 {
     EnumValidator.AssertValid <IconIndex>(iconIndex);
     return(string.Format("{0}{1}{2}{3}{4}", new object[]
     {
         (int)lastAction,
         ',',
         (int)iconIndex,
         ',',
         parentMessageItemIdBase64String
     }));
 }
Exemple #25
0
        private static RequestStatus GetProviderOnlyStatus(LastAction lastAction)
        {
            if (lastAction == LastAction.Amend)
            {
                return(RequestStatus.SentForReview);
            }

            if (lastAction == LastAction.Approve)
            {
                return(RequestStatus.WithProviderForApproval);
            }

            return(RequestStatus.None);
        }
Exemple #26
0
        public void Skip()
        {
            int i = NextSkipValue();

            if (_query is OrderByExpression)
            {
                _query = ((OrderByExpression)_query).Skip(i) as SkipExpression;
            }

            bSkip     = true;
            _action   = LastAction.Skip;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".Skip(" + i.ToString() + ")");
        }
 public void SelfDestruct( )
 {
     if (CurrentAction == LastAction.Idling)
     {
         _fd832498b5c4470bb4ac626ee3b3952d = LastAction.SelfDestruct;
         var botsInMelee = FindBotsInRange( );
         foreach (var botInMelee in botsInMelee)
         {
             DamageBot(botInMelee, SELF_DESTRUCT_DAMAGE);
             _673add7aa39b4601ba69f8713deffc8e += SELF_DESTRUCT_DAMAGE;
         }
         _3af8f9c91eb24bd0ab4389ed5241f78c = 0;
     }
 }
Exemple #28
0
        public LevelScreen(GraphicsDevice device, ContentManager content)
            : base(device, content, "level")
        {
            text = content.Load<Texture2D>("sb_texture");
            boxes = new List<Box>();
            player = new Player(text);
            aiplayer = new AIPlayer(ref player);
            levels = new LevelList();
            level = new Level(text, player, ref boxes);
            oldKeyboardState = Keyboard.GetState();
            lastAction = new LastAction();

            currentLevel = 0;
            level.LoadLevel(levels.GetLEvel(currentLevel));
        }
Exemple #29
0
        public void WhenThereAreNoApprentices(RequestStatus expectedResult, LastAction lastAction)
        {
            var commitment = new CommitmentListItem
            {
                LastAction = lastAction,

                EditStatus             = EditStatus.Both,
                ApprenticeshipCount    = 2,
                AgreementStatus        = AgreementStatus.BothAgreed,
                ProviderLastUpdateInfo = new LastUpdateInfo()
            };

            var status = commitment.GetStatus();

            status.Should().Be(expectedResult);
        }
        public void ThenTheRequestHasTheCorrectStatus(LastAction lastAction, AgreementStatus agreementStatus, RequestStatus expectRequestStatus)
        {
            var commitment = new CommitmentListItem
            {
                LastAction          = lastAction,
                AgreementStatus     = agreementStatus,
                EditStatus          = EditStatus.ProviderOnly,
                ApprenticeshipCount = 2
            };

            //Act
            var status = commitment.GetStatus();

            //Assert
            Assert.AreEqual(expectRequestStatus, status);
        }
        public override ViewModel Index()
        {
            var menu = new Menu();
            menu.AddMenuItem(
                new MenuItem
                {
                    Text = "Keep moving forward",
                    Id = '1',
                    ActionResult = GetNextEncounter(),
                    OnInputAccepted = () => _lastAction = LastAction.MovedForward
                });
            menu.AddMenuItem(
                new MenuItem
                {
                    Text = "Inventory",
                    Id = '2',
                    ActionResult = Actions.GoTo<InventoryController>,
                    OnInputAccepted = () => _lastAction = LastAction.MenuNavigation
                });
            menu.AddMenuItem(
                new MenuItem
                {
                    Text = "Spell Book",
                    Id = '3',
                    ActionResult = Actions.GoTo<SpellBookController>,
                    OnInputAccepted = () => _lastAction = LastAction.MenuNavigation
                });
            menu.AddMenuItem(
                new MenuItem
                {
                    Text = "Run away back to town",
                    Id = '4',
                    ActionResult = Actions.GoBack
                });

            DungeonViewModel viewModel = ViewModel.CreateWithMenu<DungeonViewModel>(menu);

            viewModel.Stats = StatsViewModel.FromPlayer(_gameWorld.Player);
            viewModel.DungeonName = string.Format("{0} (Level {1})", _gameWorld.GetCurrentDungeonName(), _gameWorld.CurrentDungeonLevel);
            viewModel.Information = _encounterDetails ?? "This is the dungeon - it isn't a very friendly place. Hallways go off in seemingly every direction, with no end in sight. A skeleton sits upright against a wall in the corner. No doubt an adventurer that came before you...";
            viewModel.AsciiArt = _asciiArtRepository.GetDungeonArt(_gameWorld.CurrentDungeonLevel);

            _encounterDetails = null;

            return viewModel;
        }
Exemple #32
0
        public virtual void Where()
        {
            AstoriaTestLog.WriteLineIgnore("Calling Where");

            //Sub model - projections
            PredicateModel model  = new PredicateModel(this.Workspace, this.ResContainer, this.property, this.ParentRelKey, this.ResType);
            ModelEngine    engine = new ModelEngine(this.Engine, model);

            engine.Run();

            ExpNode e = model.Result;

            this.ParentRelKey = e as KeyExpression;
            if (null == _parentKey)
            {
                /* no keys for resource type*/
                this.Reload();
                return;
            }

            int i = this.Engine.Options.Random.Next(0, 10);

            if (i % 7 == 0)
            {
                e       = ((KeyExpression)e).Predicate;
                bFilter = true;
            }

            if (e != null)
            {
                if (_query is ScanExpression)
                {
                    _query = ((ScanExpression)_query).Where(e) as PredicateExpression;
                }
                else if (_query is NavigationExpression)
                {
                    _query = ((NavigationExpression)_query).Where(e) as PredicateExpression;
                }

                bWhere  = true;
                IsKey   = true;
                _action = LastAction.Where;
                AstoriaTestLog.WriteLineIgnore(".Where()");
            }
        }
Exemple #33
0
 /// <summary>
 /// Invoked when the text in the application window is cleared.
 /// For instance, a talk window is cleared.
 /// </summary>
 public void OnTextCleared()
 {
     _lastAction = LastAction.Unknown;
 }
Exemple #34
0
        /// <summary>
        /// Handles actuation of a button representation a punctuation
        /// </summary>
        /// <param name="modifiers">Any modfiers (shift, alt, ctrl)</param>
        /// <param name="punctuation">the punctuation</param>
        /// <returns>true on success</returns>
        public bool HandlePunctuation(ArrayList modifiers, char punctuation)
        {
            Log.Debug();

            try
            {
                if (!isPunctuation(punctuation))
                {
                    return false;
                }

                // turn off extended keys such as alt, ctrl.  This causes problems when space
                // is inserted after puncuation and alt+space causes the system menu to show up.

                KeyStateTracker.ClearAlt();
                KeyStateTracker.ClearCtrl();
                KeyStateTracker.ClearFunc();

                using (AgentContext context = Context.AppAgentMgr.ActiveContext())
                {
                    int offset;
                    int count;

                    // delete any spaces before the punctuation
                    context.TextAgent().GetPrecedingWhiteSpaces(out offset, out count);
                    Log.Debug("Preceding whitespace count: " + count);
                    if (count > 0)
                    {
                        Log.Debug("Deleting whitespaces from offset " + offset);
                        context.TextAgent().Delete(offset, count);
                    }

                    Log.Debug("Sending punctuation");
                    Context.AppAgentMgr.Keyboard.Send((modifiers != null) ? modifiers.Cast<Keys>().ToList() : KeyStateTracker.GetExtendedKeys(), punctuation);

                    // if this is a sentence terminator, add spaces
                    // after the punctuation.

                    if ("})]".LastIndexOf(punctuation) >= 0)
                    {
                        Context.AppAgentMgr.Keyboard.Send(KeyStateTracker.GetExtendedKeys(), ' ');
                    }
                    else if (TextUtils.IsTerminator(punctuation))
                    {
                        for (int ii = 0; ii < CoreGlobals.AppPreferences.SpacesAfterPunctuation; ii++)
                        {
                            Context.AppAgentMgr.Keyboard.Send(KeyStateTracker.GetExtendedKeys(), ' ');
                        }
                    }

                    // this is important.  The ACAT talk window caretpos doesn't update until this we exit
                    // this function.  DoEvents give a chance to the talk window to update its caret position.
                    //Application.DoEvents();

                    _autoCompleteCaretPos = context.TextAgent().GetCaretPos();
                    Log.Debug("after actuating, caretpos is " + _autoCompleteCaretPos);

                    KeyStateTracker.KeyTriggered(punctuation);

                    _lastAction = LastAction.Punctuation;
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            return true;
        }
Exemple #35
0
        /// <summary>
        /// Handles acutation of a key such as a Function key.
        /// The 'value' parameter must be one of the Keys enum
        /// values.
        /// </summary>
        /// <param name="modifiers"></param>
        /// <param name="value">the key</param>
        public void HandleVirtualKey(ArrayList modifiers, String value)
        {
            _lastAction = LastAction.Unknown;

            try
            {
                Keys virtualKey = MapVirtualKey(value);
                if (virtualKey != Keys.None)
                {
                    Context.AppAgentMgr.Keyboard.Send((modifiers != null) ? modifiers.Cast<Keys>().ToList() : KeyStateTracker.GetExtendedKeys(), virtualKey);
                    //Context.AppAgentMgr.Keyboard.Send(KeyStateTracker.GetExtendedKeys(), virtualKey);
                    KeyStateTracker.KeyTriggered(virtualKey);
                }
            }
            catch
            {
                Log.Error("Invalid virtual key " + value.Substring(1));
            }
        }
Exemple #36
0
        public virtual void AttachObject()
        {
            //if (RunningUnderLinkModel)
            //    {
            //    object detachMe = RandomTrackedResource;
            //    Context.Detach( RandomTrackedResource );
            //    Context.AttachTo( CurrentResourceSet, detachMe );
            //    }
            //else
            {
                ScanModel model = new ScanModel(_workspace);
                ModelEngine engine = new ModelEngine();
                engine.Models.Add(model);
                engine.Run();

                if (!model.CanInsert)
                    return;

                object newResource = Activator.CreateInstance(model.Result.ClientClrType);
                KeyExpression key = Workspace.GetRandomExistingKey(model.ResultContainer, model.Result);

                if (key != null)
                    newResource.GetType().GetProperty(key.Properties[0].Name).SetValue(newResource, key.Values[0].ClrValue, new object[] { });
                else
                    return;

                try
                {
                    Context.AttachTo(model.ResultContainer.Name, newResource);
                }
                catch (InvalidOperationException e)
                {
                    return;
                }

                AstoriaTestLog.WriteLine("Attaching entity " + model.ResultContainer.BaseType.Name);

                _action = LastAction.AttachObject;
                _state = EntityState.Unchanged;
                this.CurrentResource = newResource;
                this.CanInsert = model.CanInsert;
                this.CanDelete = model.CanDelete;
                this.ResContainer = model.ResultContainer;
                this.ResType = model.Result;
            }
        }
Exemple #37
0
        /// <summary>
        /// Handles actuation of a button representing an alphanumeric character
        /// </summary>
        public void HandleAlphaNumericChar(ArrayList modifiers, char inputChar)
        {
            Context.AppAgentMgr.Keyboard.Send((modifiers != null) ? modifiers.Cast<Keys>().ToList() : KeyStateTracker.GetExtendedKeys(), inputChar);

            KeyStateTracker.KeyTriggered(inputChar);

            _lastAction = LastAction.AlphaNumeric;
        }
Exemple #38
0
        /// <summary>
        /// Creates a TestCase given a file.
        /// IMPORTANT: KEEP IN SYNC WITH TestCase.Write().
        /// </summary>
        public TestCase(FileInfo filePath)
        {
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(filePath.FullName);
            }
            catch (Exception e)
            {
                RandoopEnvironment.Instance.Fail("Encountered a problem when attempting to read file "
                    + filePath
                    + ". Exception message: "
                    + e.Message);
            }

            string line;

            try
            {
                // Read lastAction.
                line = reader.ReadLine();
                if (line == null || !line.StartsWith(LastAction.LASTACTION_MARKER)) throw new TestCaseParseException(filePath);
                line = line.Trim();
                this.lastAction = new LastAction(line);

                // Read exception.
                line = reader.ReadLine();
                if (line == null || !line.StartsWith(ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER)) throw new TestCaseParseException(filePath);
                line = line.Trim();
                this.exception = new ExceptionDescription(line);

                // Read imports.
                this.imports = new Collection<string>();
                while (((line = reader.ReadLine()) != null) && line.Trim().StartsWith("using"))
                {
                    this.imports.Add(line.Trim());
                }

                // Read class name.
                if (line == null || !line.Trim().StartsWith("public class")) throw new TestCaseParseException(filePath);
                this.className = line.Trim().Substring("public class".Length);

                // Read open bracket (class).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Main method declaration line.
                line = reader.ReadLine();
                line = line.Trim();
                if (line == null || !line.StartsWith("public static int")) throw new TestCaseParseException(filePath);
                if (line == null || !line.EndsWith("()")) throw new TestCaseParseException(filePath);

                // Read open bracket (method).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Read "try".
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("try")) throw new TestCaseParseException(filePath);

                // Read open bracket (try).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Read testCode.
                this.testCode = new Collection<string>();
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals(BEGIN_TEST_MARKER)) throw new TestCaseParseException(filePath);
                while (((line = reader.ReadLine()) != null) && !line.Trim().Equals(END_TEST_MARKER))
                {
                    this.testCode.Add(line.Trim());
                }
                if (line == null || !line.Trim().Equals(END_TEST_MARKER)) throw new TestCaseParseException(filePath);

                // Everything that remains to read are the assemblies referenced.

                // Read assemblies referenced.
                this.refAssemblies = new Collection<RefAssembly>();
                while (((line = reader.ReadLine()) != null))
                {
                    if (line.Trim().StartsWith(RefAssembly.REFASSEMBLY_MARKER))
                    {
                        this.refAssemblies.Add(new RefAssembly(line.Trim()));
                    }
                }
            }
            finally
            {
                reader.Close();
            }
        }
Exemple #39
0
        /// <summary>
        /// Create a TestCase by specifying all its components.
        /// </summary>
        public TestCase(LastAction lastAction, ExceptionDescription exception, Collection<string> imports,
            Collection<string> assemblies, string className, Collection<string> testCode)
        {
            // Last action.
            if (lastAction == null) throw new ArgumentNullException();
            this.lastAction = lastAction;

            // Exception.
            if (exception == null) throw new ArgumentNullException();
            this.exception = exception;

            // Imports.
            if (imports == null) throw new ArgumentNullException();
            this.imports = new Collection<string>();
            foreach (string s in imports)
            {
                if (s == null) throw new ArgumentNullException();
                this.imports.Add(s);
            }

            // Referenced assemblies.
            this.refAssemblies = new Collection<RefAssembly>();
            foreach (string s in assemblies)
            {
                if (s == null) throw new ArgumentNullException();
                this.refAssemblies.Add(new RefAssembly(RefAssembly.REFASSEMBLY_MARKER + s));
            }

            // Class name.
            if (className == null) throw new ArgumentNullException();
            this.className = className;

            // Test code.
            if (testCode == null) throw new ArgumentNullException();
            this.testCode = new Collection<string>();
            foreach (string s in testCode)
            {
                if (s == null) throw new ArgumentNullException();
                this.testCode.Add(s);
            }
        }
Exemple #40
0
        public void Top()
            {
            int i = NextTopValue();
          
            if (_query is OrderByExpression)
                _query = ((OrderByExpression)_query).Top( i ) as TopExpression;
            else if (_query is CountExpression)
                _query = ((CountExpression)_query).Top(i) as TopExpression;
            else if (_query is ExpandExpression)
                _query = ((ExpandExpression)_query).Top(i) as TopExpression;
            else if (_query is NavigationExpression)
                _query = ((NavigationExpression)_query).Top(i) as TopExpression;
            else if (_query is SkipExpression)
                _query = ((SkipExpression)_query).Top(i) as TopExpression;
            else if (_query is PredicateExpression)
                _query = ((PredicateExpression)_query).Top(i) as TopExpression;
            else if (_query is ScanExpression)
                _query = ((ScanExpression)_query).Top(i) as TopExpression;

            iTop = i;
            bTop = true;
            _action = LastAction.Top;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore( ".Top(" + i.ToString() + ")" );
            }
Exemple #41
0
        public void Expand()
        {
            string sExpand = String.Empty;
            PropertyExpression[] expandValues = new PropertyExpression[1];

            List<ResourceProperty> properties = new List<ResourceProperty>();
            foreach (ResourceProperty property in from.Properties)
            {
                if (property.IsNavigation && from.Properties.Contains(property) &&
                        !(from.Name == "BugDefectTrackingSet" || from.Name == "BugProjectTrackingSet"))
                    properties.Add(property);
            }

            if (properties.Count > 0)
            {
                expandValues[0] = new PropertyExpression(properties[0]);
                sExpand = expandValues[0].ToString();

                if (_query is TopExpression)
                    _query = ((TopExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is OrderByExpression)
                    _query = ((OrderByExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is ScanExpression)
                    _query = ((ScanExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is NavigationExpression)
                    _query = ((NavigationExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is SkipExpression)
                    _query = ((SkipExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is PredicateExpression)
                    _query = ((PredicateExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is CountExpression)
                    _query = ((CountExpression)_query).Expand(expandValues) as ExpandExpression;
                else if (_query is NavigationExpression)
                    _query = ((NavigationExpression)_query).Expand(expandValues) as ExpandExpression;
              
                bExpand = true;
                _action = LastAction.Expand;
                bIsOption = true;
                AstoriaTestLog.WriteLineIgnore(".Expand(" + sExpand + ")");
            }
        }
Exemple #42
0
        public void Count()
        {
            if (_query is TopExpression)
                _query = ((TopExpression)_query).Count(true) as CountExpression;
            else if (_query is OrderByExpression)
                _query = ((OrderByExpression)_query).Count(true) as CountExpression;
            else if (_query is ScanExpression)
                _query = ((ScanExpression)_query).Count(true) as CountExpression;
            else if (_query is NavigationExpression)
                _query = ((NavigationExpression)_query).Count(true) as CountExpression;
            else if (_query is SkipExpression)
                _query = ((SkipExpression)_query).Count(true) as CountExpression;
            else if (_query is NavigationExpression)
                _query = ((NavigationExpression)_query).Count(true) as CountExpression;
            else if (_query is ExpandExpression)
                _query = ((ExpandExpression)_query).Count(true) as CountExpression;
            else if (_query is PredicateExpression)
                _query = ((PredicateExpression)_query).Count(true) as CountExpression;


            IsCount = true;
            _action = LastAction.Count;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".Count");
        }
Exemple #43
0
        /// <summary>
        /// Creates a TestCase given a file.
        /// IMPORTANT: KEEP IN SYNC WITH TestCase.Write().
        /// </summary>
        public TestCase(FileInfo filePath)
        {
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(filePath.FullName);
            }
            catch (Exception e)
            {
                Common.Enviroment.Fail("Encountered a problem when attempting to read file "
                    + filePath
                    + ". Exception message: "
                    + e.Message);
            }

            string line;

            try
            {
                // Read lastAction.
                line = reader.ReadLine();
                if (line == null || !line.StartsWith(LastAction.LASTACTION_MARKER)) throw new TestCaseParseException(filePath);
                line = line.Trim();
                this.lastAction = new LastAction(line);

                // Read exception.
                line = reader.ReadLine();
                if (line == null || !line.StartsWith(ExceptionDescription.EXCEPTION_DESCRIPTION_MARKER)) throw new TestCaseParseException(filePath);
                line = line.Trim();
                this.exception = new ExceptionDescription(line);

                // Read imports.
                this.imports = new Collection<string>();
                while (((line = reader.ReadLine()) != null) && line.Trim().StartsWith("using"))
                {
                    this.imports.Add(line.Trim());
                }

                // Read class name.
                if (line == null || !line.Trim().StartsWith("public class")) throw new TestCaseParseException(filePath);
                this.className = line.Trim().Substring("public class".Length);

                // Read open bracket (class).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Main method declaration line.
                line = reader.ReadLine();
                line = line.Trim();
                if (line == null || !line.StartsWith("public static int")) throw new TestCaseParseException(filePath);
                if (line == null || !line.EndsWith("()")) throw new TestCaseParseException(filePath);

                // Read open bracket (method).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Read "try".
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("try")) throw new TestCaseParseException(filePath);

                // Read open bracket (try).
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals("{")) throw new TestCaseParseException(filePath);

                // Read testCode.
                this.testCode = new Collection<string>();
                line = reader.ReadLine();
                if (line == null || !line.Trim().Equals(BEGIN_TEST_MARKER)) throw new TestCaseParseException(filePath);
                while (((line = reader.ReadLine()) != null) && !line.Trim().Equals(END_TEST_MARKER))
                {
                    this.testCode.Add(line.Trim());
                }
                if (line == null || !line.Trim().Equals(END_TEST_MARKER)) throw new TestCaseParseException(filePath);

                // Read test plan collections from testCode. --- [email protected] adds for sequence-based reducer
                this.testPlanCollection = new Collection<string>();
                bool planStart = false;
                foreach (string testline in testCode)
                {
                    if (testline.Trim().StartsWith("/*"))
                    {
                        planStart = true;
                        continue; //skip to the next line, the beginning of plans
                    }

                    if ((planStart == true) && !(testline.Trim().StartsWith("*/")))
                    {
                        if ((testline == null) || !testline.Trim().StartsWith("plan")) throw new TestCaseParseException(filePath);
                        this.testPlanCollection.Add(testline.Trim());
                    }

                    if (testline.Trim().StartsWith("*/")) break;

                }

                // Everything that remains to read are the assemblies referenced.

                // Read assemblies referenced.
                this.refAssemblies = new Collection<RefAssembly>();
                while (((line = reader.ReadLine()) != null))
                {
                    if (line.Trim().StartsWith(RefAssembly.REFASSEMBLY_MARKER))
                    {
                        this.refAssemblies.Add(new RefAssembly(line.Trim()));
                    }
                }
            }
            finally
            {
                reader.Close();
            }
        }
Exemple #44
0
        public virtual void SaveChanges(SaveChangesOptions so, string sync)
        {
            AstoriaTestLog.WriteLineIgnore("Entities tracked:" + Context.Resources.Count);
            this.Entities.Clear();
            foreach (EntityDescriptorWrapper ed in Context.Resources)
            {
                Uri _uri = null;
                bool bURI = Context.TryGetUri(ed.Entity, out _uri);
                Entities.Add(ed.Entity, new string[] { ed.State.ToString(), _uri == null ? "" : _uri.OriginalString });
            }

            AstoriaTestLog.WriteLineIgnore("Save changes");

            if (Context.Resources.Count > 1)
                so = SaveChangesOptions.BatchWithSingleChangeset;

            DataServiceResponseWrapper response = null;

            try
            {
                switch (sync)
                {
                    case "sync":
                        response = this.Context.SaveChanges(so);
                        break;
                    case "async":
                        IAsyncResult async = this.Context.BeginSaveChanges(null, null);
                        response = this.Context.EndSaveChanges(async);
                        break;
                }
                //Save info on entities
                EntitiesAfter.Clear();
                foreach (EntityDescriptorWrapper ed in Context.Resources)
                {
                    Uri _uri = null;
                    bool bURI = Context.TryGetUri(ed.Entity, out _uri);
                    EntitiesAfter.Add(ed.Entity, new string[] { ed.State.ToString(), _uri == null ? "" : _uri.OriginalString });
                }

                //Verification
                VerifySaveChanges(response);
                VerifyData(this.Workspace, this.Entities, this.EntitiesAfter);
                //RaiseCompleted(true);
                //  AstoriaTestLog.WriteVariationResult(true);
            }
            catch (Exception e)
            {
                AstoriaTestLog.WriteLine(e);
                // AstoriaTestLog.WriteVariationResult(false);
                //RaiseCompleted(false);
            }
            finally
            {
                // AstoriaTestLog.WriteVariationEnd();
                // AstoriaTestLog.WriteVariationStart("Model Variation: " + ClientModelBase.variationID, ClientModelBase.variationID++);
                _action = LastAction.SaveChanges;
                _state = EntityState.Unchanged;
                CurrentResource = null;
                this.CreateContext();

            }


        }
Exemple #45
0
        public virtual void Detach()
        {
            AstoriaTestLog.WriteLine("Detaching entity " + CurrentResource.GetType().Name);
            object resourceToBeDetached = RandomTrackedResource;
            Context.Detach(resourceToBeDetached);

            _action = LastAction.Detach;
            CurrentResource = null;
            _state = EntityState.Unchanged;
        }
Exemple #46
0
        public virtual void DeleteObject()
        {

            object resourceToBeDeleted = RandomTrackedResource;
            AstoriaTestLog.WriteLine("Deleting entity " + resourceToBeDeleted.GetType().Name);
            Context.DeleteObject(resourceToBeDeleted);

            _action = LastAction.DeleteObject;
            _state = EntityState.Deleted;
        }
Exemple #47
0
        /// <summary>
        /// Deletes the previous word.  Depends on the last editing action.
        /// If a punctuation was the last thing that was entered, it deletes
        /// the punctuations.  If word auto-completion was the last action,
        /// it undoes the auto-completion and restores the previously entered
        /// partial word.  Otherwise, it just deletes the previous word.
        /// </summary>
        public void UndoLastAction()
        {
            try
            {
                Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " +
                          Context.AppAgentMgr.CurrentEditingMode);

                using (var context = Context.AppAgentMgr.ActiveContext())
                {
                    if (context.TextAgent().IsTextSelected())
                    {
                        context.TextAgent().Keyboard.Send(Keys.Back);
                        _lastAction = LastAction.Unknown;
                        return;
                    }
                }

                switch (_lastAction)
                {
                    case LastAction.Punctuation:
                        deletePreviousPunctuation();
                        break;

                    case LastAction.AutoCompleteWord:
                        DeletePreviousWord();
                        break;

                    default:
                        DeletePreviousWord();
                        break;
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            _lastAction = LastAction.Unknown;
        }
        /// <summary>
        /// Processing of code element deleted
        /// </summary>
        /// <param name="Parent"></param>
        /// <param name="element"></param>
        void events_ElementDeleted(object Parent, CodeElement element)
        {
            // Protection agains multi call with same parameters
            if ((lastAction == LastAction.Delete) && (lastParent == Parent) && (lastElement == element))
                return;
            else
            {
                lastParent = Parent;
                lastElement = element;
                lastAction = LastAction.Delete;
            }

            if (element.IsCodeType)
            {
                CodeType codeType = element as CodeType;
                CodeElement parent = Parent as CodeElement;

                // Get full name
                string fullname;
                if (parent == null)
                    fullname = codeType.Name;
                else fullname = parent.FullName + "." + codeType.Name;
                if (typesByFullName.ContainsKey(fullname))
                {
                    typesByFullName.Remove(fullname);
                    typesByName.Remove(codeType.Name, codeType);
                    if (OnTypeRemoved != null)
                        OnTypeRemoved(fullname);
                }
            }
            else if (element is CodeVariable)
            {
                CodeVariable field = element as CodeVariable;
                CodeType parent = Parent as CodeType;
                if ((OnFieldRemoved != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnFieldRemoved(parent, element.Name);
            }
            else if (element is CodeProperty)
            {
                CodeProperty property = element as CodeProperty;
                CodeType parent = Parent as CodeType;
                if ((OnPropertyRemoved != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnPropertyRemoved(parent, element.Name);
            }
            else if (element is CodeFunction2)
            {
                CodeFunction2 m = element as CodeFunction2;
                CodeType parent = Parent as CodeType;
                if ((OnMethodRemoved != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnMethodRemoved(parent, m.get_Prototype((int)(vsCMPrototype.vsCMPrototypeUniqueSignature)));
            }
            else if (element is CodeParameter)
            {
                CodeParameter p = element as CodeParameter;
                CodeFunction2 m = Parent as CodeFunction2;
                CodeType parent = m.Parent as CodeType;
                if ((OnParameterRemoved != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnParameterRemoved(m, element.Name);
            }
            else if (element is CodeNamespace)
            {
                string fullname;
                if ((Parent as CodeElement) != null)
                    fullname = (Parent as CodeElement).FullName + "." + element.Name + ".";
                else
                    fullname = element.Name + ".";
                List<string> toRemove = new List<string>();
                foreach (string typeFullName in typesByFullName.Keys)
                    if (typeFullName.StartsWith(fullname))
                        toRemove.Add(typeFullName);

                foreach (string typeFullName in toRemove)
                {
                    CodeType codeType = typesByFullName[typeFullName];
                    string name = GetTypeName(typeFullName);
                    typesByFullName.Remove(typeFullName);
                    typesByName.Remove(name, codeType);
                    if (OnTypeRemoved != null)
                        OnTypeRemoved(typeFullName);
                }
            }
            else if (element is CodeAttribute2)
            {
                if (OnAttributeRemoved != null)
                    OnAttributeRemoved(Parent as CodeElement, element.Name);
            }

            RemoveObsoleteTypes();
        }
Exemple #49
0
 /// <summary>
 /// Handler for the event that is raised when the focus in the
 /// application window changes.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void AppAgentMgr_EvtFocusChanged(object sender, FocusChangedEventArgs e)
 {
     _lastAction = LastAction.Unknown;
     _autoCompleteCaretPos = -1;
     _beforeAutoCompleteCaretPos = -1;
     _autocompleteStartOffset = -1;
     _autoCompletePartialWord = String.Empty;
 }
Exemple #50
0
 public void Skip()
     {
     int i = NextSkipValue();
     if (_query is OrderByExpression)
         _query = ((OrderByExpression)_query).Skip( i ) as SkipExpression;
  
     bSkip = true;
     _action = LastAction.Skip;
     bIsOption = true;
     AstoriaTestLog.WriteLineIgnore(".Skip(" + i.ToString() + ")");
     }
Exemple #51
0
 public static TestCase Dummy(string className)
 {
     LastAction lastAction = new LastAction(LastAction.LASTACTION_MARKER + "none");
     ExceptionDescription exception = ExceptionDescription.NoException();
     Collection<string> imports = new Collection<string>();
     Collection<string> assemblies = new Collection<string>();
     Collection<string> testCode = new Collection<string>();
     testCode.Add("/* Source code printing failed. */");
     return new TestCase(lastAction, exception, imports, assemblies, className, testCode);
 }
Exemple #52
0
        /// <summary>
        /// Auto-completes a partially entered with with the 'wordselected'. The
        /// 'wordSelected' is typically one that the word prediction engine suggests
        /// and the one that the user selects
        /// </summary>
        /// <param name="wordSelected">the autocomplete word.</param>
        public void AutoCompleteWord(String wordSelected)
        {
            bool isCapitalizedWordToReplace = false;

            try
            {
                using (AgentContext context = Context.AppAgentMgr.ActiveContext())
                {
                    Context.AppAgentMgr.TextChangedNotifications.Hold();

                    int caretPos = context.TextAgent().GetCaretPos();

                    _beforeAutoCompleteCaretPos = caretPos;
                    _autocompleteStartOffset = -1;

                    int offset;
                    int count;
                    context.TextAgent().GetPrevWordOffset(out offset, out count);
                    Log.Debug("PrevWord offset: " + offset + ", count: " + count);

                    // check if we are just completing the current word or inserting a new word
                    int insertOrReplaceOffset;
                    String wordToReplace;
                    bool checkInsert = context.TextAgent().CheckInsertOrReplaceWord(out insertOrReplaceOffset, out wordToReplace);
                    Log.Debug("checkInsert: " + checkInsert + ", insertorreplaceoffset: " + insertOrReplaceOffset +
                              ", caret: " + caretPos + ", caretPos-delprev: " + (caretPos - count));

                    _autoCompletePartialWord = wordToReplace;

                    int wordToReplaceLength = wordToReplace.Length;
                    if (wordToReplaceLength > 0)
                    {
                        isCapitalizedWordToReplace = Char.IsUpper(wordToReplace[0]);
                    }

                    Log.Debug("checkInsert: " + checkInsert + ". inserRepOff: " + insertOrReplaceOffset +
                              ". wordTORep: " + wordToReplace);

                    if (KeyStateTracker.IsStickyShiftOn())
                    {
                        wordSelected = wordSelected.ToUpper();
                    }
                    else if (KeyStateTracker.IsShiftOn())
                    {
                        wordSelected = capitalizeWord(wordSelected);
                        KeyStateTracker.KeyTriggered(wordSelected[0]);
                    }

                    if (checkInsert)
                    {
                        Log.Debug("Inserting [" + wordSelected + "] at offset " + insertOrReplaceOffset);
                        context.TextAgent().Insert(insertOrReplaceOffset, wordSelected);
                    }
                    else
                    {
                        if (count > 0)
                        {
                            wordToReplaceLength = count;
                        }

                        if (wordToReplaceLength > 0 && isCapitalizedWordToReplace &&
                            Char.ToUpper(wordToReplace[0]) == Char.ToUpper(wordSelected[0]))
                        {
                            wordSelected = capitalizeWord(wordSelected);
                        }

                        Log.Debug("Replacing word at offset " + insertOrReplaceOffset + ". Length: " +
                                  wordToReplaceLength + ". with [" + wordSelected + "]");

                        context.TextAgent().Replace(insertOrReplaceOffset, wordToReplaceLength, wordSelected);
                    }

                    _autocompleteStartOffset = insertOrReplaceOffset;

                    _lastAction = LastAction.AutoCompleteWord;

                    postAutoCompleteWord();

                    _autoCompleteCaretPos = context.TextAgent().GetCaretPos();
                    Log.Debug("_autocompleteCursorPos is " + _autoCompleteCaretPos);
                }
            }
            catch (InvalidAgentContextException iace)
            {
                Log.Debug("Agent Context is invalid " + iace);
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
            }
            finally
            {
                uint threadId = GetCurrentThreadId();
                Log.Debug("Calling TextChangedNotifications.Release AFTER Autocompeting word " + threadId + ", caretPos: " + Context.AppAgentMgr.ActiveContext().TextAgent().GetCaretPos());
                Context.AppAgentMgr.TextChangedNotifications.Release();
                Log.Debug("Returned from TextChangedNotifications.Release AFTER Autocompeting word " + threadId);
            }
        }
Exemple #53
0
        public void Navigation()
            {
            bool bfound = false;
            int j = 0;
            ResourceType _navType = null;

            while (!bfound && j < from.Properties.Count)
                {
                int i = this.Engine.Options.Random.Next( 0, from.Properties.Count );

                ResourceProperty _property = (ResourceProperty)from.Properties[i];
                if (_property.IsNavigation && _property.Type is CollectionType && this.ResContainer.BaseType.Properties.Contains( _property ))
                    {
                    if (_query is PredicateExpression)
                        {
                        _query = ((PredicateExpression)_query).Nav( _property.Property() ) as NavigationExpression;
                        if (_property.Type is CollectionType)
                            {
                            _navType = (ResourceType)((ResourceCollection)_property.Type).SubType;
                            _pType = _navType.ClientClrType;
                            }
                        else if (_property.Type is ResourceType)
                            {
                            _navType = (ResourceType)_property.Type;
                            _pType = _property.Type.ClrType;
                            }

                        this.ResType = _navType;

                        bNav = true;
                        bfound = true;
                        _action = LastAction.Nav;
                        property = _property;
                        this.ResType = _navType; //update the resourceType

                        AstoriaTestLog.WriteLineIgnore( ".Nav(" + _property.Property().Name + ")" );
                        IsKey = false;
                        }
                    }

                j++;
                }
            }
Exemple #54
0
        public virtual void AddObject()
        {

            object newResource = CurrentResource;

            try
            {
                Context.AddObject(CurrentResourceSet, newResource);
                ModelExtensions.EnsureInsert(Context.UnderlyingContext, newResource, CurrentResourceSet, Workspace, CurrentResourceSet);
            }
            catch (InvalidOperationException e)
            {
                return;
            }

            AstoriaTestLog.WriteLine("Adding entity " + CurrentResourceSet);

            //Resolve the client type
            Type resType = CurrentResourceType;
            ResolveClientType(this.Workspace, this.Context, resType);
            _action = LastAction.AddObject;
            _state = EntityState.Added;
            //this.CanInsert = model.CanInsert;
            //this.CanDelete = model.CanDelete;
            //this.ResContainer = model.ResultContainer;
            //this.ResType = model.Result;
            //this.CurrentResource = newResource;
        }
Exemple #55
0
        public virtual void Select()
            {
           
            PropertyExpression ordervalues = new PropertyExpression( this.ResType.Properties.Choose() );

            if (_query is ScanExpression)
                _query = ((ScanExpression)_query).Select() as ProjectExpression;
            if (_query is NavigationExpression)
                _query = ((NavigationExpression)_query).Select() as ProjectExpression;
            if (_query is TopExpression)
                _query = ((TopExpression)_query).Select() as ProjectExpression;
            if (_query is SkipExpression)
                _query = ((SkipExpression)_query).Select() as ProjectExpression;
            if (_query is CountExpression)
                _query = ((CountExpression)_query).Select() as ProjectExpression;
            if (_query is ExpandExpression)
                _query = ((ExpandExpression)_query).Select() as ProjectExpression;

            if (_query is PredicateExpression)
                {
                int i = this.Engine.Options.Random.Next( 0, 2 );

                if (bFilter) { i = 0; }

                switch (i)
                    {
                    case 0:
                        _query = ((PredicateExpression)_query).Select() as ProjectExpression;
                        break;
                    case 1:

                        if (ordervalues.Type is CollectionType)
                            {
                            this.ResType = (ResourceType)((ResourceCollection)ordervalues.Type).SubType;
                            _pType = this.ResType.ClientClrType;
                            }
                        else if (ordervalues.Type is ResourceType)
                            {
                            this.ResType = (ResourceType)ordervalues.Type;
                            _pType = ordervalues.Type.ClrType;
                            }
                        else
                            _pType = ordervalues.Type.ClrType;

                        _query = ((PredicateExpression)_query).Select( ordervalues ) as ProjectExpression;

                        break;
                    }

                }

            if (_query != null)
                {
                bSelect = true;
                _action = LastAction.Select;
                _isValid = isValid.Yes;
                AstoriaTestLog.WriteLineIgnore( ".Select()" );
                this.Disabled = true;
                }
            }
Exemple #56
0
        public virtual void From()
            {
            if (RunningUnderScenarioModel)
                {
                _query = Query.From( Exp.Variable( ResContainer ) );
                _pType = ResContainer.BaseType.ClientClrType;
                AstoriaTestLog.WriteLineIgnore( "Query.From(" + ResContainer.Name + ")" );
                }
            else
                {
                ScanModel model = new ScanModel( _workspace );
                ModelEngine engine = new ModelEngine( this.Engine, model );
                engine.Run();

                this.ResContainer = model.ResultContainer;
                _query = Query.From( Exp.Variable( model.ResultContainer ) );
                _pType = model.ResultContainer.BaseType.ClientClrType;
                AstoriaTestLog.WriteLineIgnore( "Query.From(" + model.ResultContainer.Name + ")" );
                }


            _action = LastAction.From;
            IsCount = false;

            }
Exemple #57
0
        public virtual void Where()
            {

                AstoriaTestLog.WriteLineIgnore("Calling Where");

            //Sub model - projections
            PredicateModel model = new PredicateModel( this.Workspace, this.ResContainer, this.property, this.ParentRelKey, this.ResType );
            ModelEngine engine = new ModelEngine( this.Engine, model );
            engine.Run();

            ExpNode e = model.Result;

            this.ParentRelKey = e as KeyExpression;
            if (null == _parentKey)
                {
                /* no keys for resource type*/
                this.Reload();
                return;
                }

            int i = this.Engine.Options.Random.Next( 0, 10 );
            if (i % 7 == 0)
                {
                e = ((KeyExpression)e).Predicate;
                bFilter = true;
                }

            if (e != null)
                {
                if (_query is ScanExpression)
                    _query = ((ScanExpression)_query).Where( e ) as PredicateExpression;
                else if (_query is NavigationExpression)
                    _query = ((NavigationExpression)_query).Where( e ) as PredicateExpression;
                
                bWhere = true;
                IsKey = true;
                _action = LastAction.Where;
                AstoriaTestLog.WriteLineIgnore( ".Where()" );
                }
            }
        /// <summary>
        /// Processes code element added
        /// </summary>
        /// <param name="element"></param>
        void events_ElementAdded(CodeElement element)
        {
            if ((lastAction == LastAction.Add) && (lastElement == element))
                return;
            else
            {
                lastAction = LastAction.Add;
                lastElement = element;
            }

            if (element is CodeType)
            {
                CodeType codeType = element as CodeType;
                if (!typesByFullName.ContainsKey(codeType.FullName))
                {
                    typesByFullName.Add(codeType.FullName, codeType);
                    typesByName.Add(codeType.Name, codeType);
                    if (codeType.Parent is CodeNamespace)
                    {
                        if (OnTypeAdded != null)
                            OnTypeAdded(codeType);
                    }
                    else if (codeType.Parent is CodeClass)
                    {
                        if (OnNestedTypeAdded != null)
                            OnNestedTypeAdded(codeType.Parent as CodeClass, codeType);
                    }
                }
            }
            else if (element is CodeVariable)
            {
                CodeVariable field = element as CodeVariable;
                CodeType parent = field.Parent as CodeType;
                if ((OnFieldAdded != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnFieldAdded(parent, field);
            }
            else if (element is CodeProperty)
            {
                CodeProperty property = element as CodeProperty;
                CodeType parent = property.Parent as CodeType;
                if ((OnPropertyAdded != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnPropertyAdded(parent, property);
            }
            else if (element is CodeFunction2)
            {
                CodeFunction2 m = element as CodeFunction2;
                CodeType parent = m.Parent as CodeType;
                if ((OnMethodAdded != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnMethodAdded(parent, m);
            }
            else if (element is CodeParameter)
            {
                CodeParameter p = element as CodeParameter;
                CodeFunction2 m = p.Parent as CodeFunction2;
                CodeType parent = m.Parent as CodeType;
                if ((OnParameterAdded != null) && (typesByFullName.ContainsKey(parent.FullName)))
                    OnParameterAdded(m, p);
                else if (OnElementPropertiesChanged != null)
                    OnElementPropertiesChanged(m as CodeElement);
            }
            else if (element is CodeNamespace)
                TakeIntoAccount(element as CodeNamespace, true);
            else if (element is CodeAttribute2)
            {
                CodeAttribute2 attribute = element as CodeAttribute2;
                if (OnAttributeAdded != null)
                    OnAttributeAdded(attribute);
            }
        }
Exemple #59
0
 private void ResetLastActionAndPlayerPosition()
 {
     lastAction = new LastAction();
     oldPlayerPosition = player.Position;
 }
Exemple #60
0
        public void Sort(bool bAsc)
        {
            //Sub model - sort
            SortModel model = new SortModel(this._workspace, _fromContainer.BaseType);
            ModelEngine engine = new ModelEngine(this.Engine, model);
            engine.Run();

            PropertyExpression[] ordervalues = model.SortResult;

           if (_query is TopExpression)
                _query = ((TopExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            else if (_query is SkipExpression)
                _query = ((SkipExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            else if (_query is CountExpression)
                _query = ((CountExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            else if (_query is ExpandExpression)
                _query = ((ExpandExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            else if (_query is NavigationExpression)
                _query = ((NavigationExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
           else if (_query is PredicateExpression)
               _query = ((PredicateExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
           else if (_query is ScanExpression)
               _query = ((ScanExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;

            bSort = true;
            _action = LastAction.OrderBy;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".OrderBy(" + ordervalues.ToString() + ")");
        }