Example #1
0
        // Start is called before the first frame update
        void Start()
        {
            inventory = GetComponent <ResourceInventory>().backingInventory;

            timeTracker      = GetComponent <ITimeTracker>();
            optimizer        = new GatherBehaviorOptimizer();
            gatheringWeights = optimizer.generateInitialWeights();

            stateMachine = new AsyncStateMachine <GathererState, GathererBehavior>(GathererState.Gathering);

            stateMachine.registerStateTransitionHandler(GathererState.All, GathererState.All, (x) =>
            {
                objectSeeker.ClearCurrentTarget();
                lastTargetCheckTime = 0;
            }, StateChangeExecutionOrder.StateExit);

            var sellingStateHandler = new SellingStateHandler();

            sellingStateHandler.InstantiateOnObject(this);

            stateMachine.registerGenericHandler(new GatheringStateHandler());
            stateMachine.registerGenericHandler(new GoingHomeStateHandler());
            stateMachine.registerGenericHandler(new WaitTillMarketStateHandler());
            stateMachine.registerGenericHandler(sellingStateHandler);
            stateMachine.registerGenericHandler(new GoingToConsumeHandler());
            stateMachine.registerGenericHandler(new ConsumingStateHandler());
            stateMachine.registerGenericHandler(new DieStateHandler());
            stateMachine.registerGenericHandler(new SleepStateHandler());

            stateMachine.LockStateHandlers();
        }
Example #2
0
 void BackgroundInitialize()
 {
     timer = Counters.TargetRuntimesLoading.BeginTiming("Initializing Runtime " + Id);
     lock (initLock) {
         try {
             RunInitialization();
         } catch (Exception ex) {
             LoggingService.LogFatalError("Unhandled exception in SystemAssemblyService background initialisation thread.", ex);
         } finally {
             lock (initEventLock) {
                 initializing = false;
                 initialized  = true;
                 try {
                     if (initializedEvent != null && !ShuttingDown)
                     {
                         initializedEvent(this, EventArgs.Empty);
                     }
                 } catch (Exception ex) {
                     LoggingService.LogError("Error while initializing the runtime: " + Id, ex);
                 }
             }
             timer.End();
         }
     }
 }
Example #3
0
		internal bool Close (bool saveWorkspacePreferencies, bool closeProjectFiles)
		{
			if (Items.Count > 0) {
				ITimeTracker timer = Counters.CloseWorkspaceTimer.BeginTiming ();
				try {
					// Request permission for unloading the items
					foreach (WorkspaceItem it in new List<WorkspaceItem> (Items)) {
						if (!RequestItemUnload (it))
							return false;
					}

					if (saveWorkspacePreferencies)
						SavePreferences ();

					if (closeProjectFiles) {
						foreach (Document doc in IdeApp.Workbench.Documents.ToArray ()) {
							if (!doc.Close ())
								return false;
						}
					}

					foreach (WorkspaceItem it in new List<WorkspaceItem> (Items)) {
						try {
							Items.Remove (it);
							it.Dispose ();
						} catch (Exception ex) {
							MessageService.ShowError (GettextCatalog.GetString ("Could not close solution '{0}'.", it.Name), ex);
						}
					}
				} finally {
					timer.End ();
				}
			}
			return true;
		}
Example #4
0
    public void CopyTimeTrackerState(ITimeTracker other)
    {
        TimeMachineController otherTM = other as TimeMachineController;

        if (otherTM != null)
        {
            Activated.Copy(otherTM.Activated);
            Occupied.Copy(otherTM.Occupied);
            ActivatedTimeStep.Copy(otherTM.ActivatedTimeStep);
            Countdown.Copy(otherTM.Countdown);

            Position.Copy(otherTM.Position);
            ItemForm = otherTM.ItemForm;

            playerID.Copy(otherTM.playerID);
            doneTimeTravelPlayerID = otherTM.doneTimeTravelPlayerID;
            IsAnimatingOpenClose   = otherTM.IsAnimatingOpenClose;
            IsAnimatingFold        = otherTM.IsAnimatingFold;
            IsAnimatingUnfold      = otherTM.IsAnimatingUnfold;

            isFoldable = otherTM.isFoldable;
        }
        else
        {
            gameController.LogError($"Cannot copy state from {other.GetType()} to {nameof(TimeMachineController)}");
        }
    }
 public MemorizationPageViewModel(IDeck deck, ITimeTracker timeTracker, ICardAssociationRepository repo)
     : this()
 {
     _timeTracker = timeTracker;
     _deck        = deck;
     _cardAssociationRepository = repo;
 }
Example #6
0
        /// <summary>
        /// Cleans the files produced by this solution item
        /// </summary>
        /// <param name='monitor'>
        /// A progress monitor
        /// </param>
        /// <param name='configuration'>
        /// Configuration to use to clean the project
        /// </param>
        public void Clean(IProgressMonitor monitor, ConfigurationSelector configuration)
        {
            ITimeTracker tt = Counters.CleanProjectTimer.BeginTiming("Cleaning " + Name, GetProjectEventMetadata(configuration));

            try {
                //SolutionFolder handles the begin/end task itself, don't duplicate
                if (this is SolutionFolder)
                {
                    RunTarget(monitor, ProjectService.CleanTarget, configuration);
                    return;
                }

                try {
                    SolutionEntityItem        it    = this as SolutionEntityItem;
                    SolutionItemConfiguration iconf = it != null?it.GetConfiguration(configuration) : null;

                    string confName = iconf != null ? iconf.Id : configuration.ToString();
                    monitor.BeginTask(GettextCatalog.GetString("Cleaning: {0} ({1})", Name, confName), 1);
                    RunTarget(monitor, ProjectService.CleanTarget, configuration);
                } finally {
                    monitor.EndTask();
                }
            }
            finally {
                tt.End();
            }
        }
Example #7
0
 public MoreTimeRequestController(
     MoreTimeRequestContext context,
     ITimeRequestData timeRequestData,
     ITimeTravelClock timeTravelClock,
     ITimeTracker timeTracker)
 {
     _dbContext       = context;
     _timeRequestData = timeRequestData;
     _clock           = timeTravelClock;
     _timeTracker     = timeTracker;
     if (_timeRequestData.NumTimeRequests(_dbContext) == 0)
     {
         // Create a new MoreTimeRequest if collection is empty,
         // which means you can't delete all MoreTimeRequests.
         _timeRequestData.AddTimeRequest(
             _dbContext,
             new MoreTimeRequest {
             RequestTimeStamp             = _clock.Now,
             Expired                      = true,
             Alerted                      = true,
             LengthInMinutes              = 0,
             MinutesToAdjustClockBy       = 0,
             TimeAdjustmentAtCreationTime = 0
         });
         _timeRequestData.SaveChanges(_dbContext);
     }
 }
Example #8
0
		async Task<bool> OpenWorkspaceItemInternal (FilePath file, bool closeCurrent, bool loadPreferences, IDictionary<string, string> metadata)
		{
			var item = GetAllItems<WorkspaceItem> ().FirstOrDefault (w => w.FileName == file.FullPath);
			if (item != null) {
				IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem = item;
				IdeApp.Workbench.StatusBar.ShowWarning (GettextCatalog.GetString ("{0} is already opened", item.FileName.FileName));
				return true;
			}

			if (closeCurrent) {
				if (!await Close ())
					return false;
			}

			var monitor = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor (true);
			bool reloading = IsReloading;

			monitor = monitor.WithCancellationSource (openingItemCancellationSource);

			IdeApp.Workbench.LockGui ();
			metadata = GetOpenWorkspaceItemMetadata (metadata);
			ITimeTracker timer = Counters.OpenWorkspaceItemTimer.BeginTiming (metadata);
			try {
				var oper = BackgroundLoadWorkspace (monitor, file, loadPreferences, reloading, metadata, timer);
				return await oper;
			} finally {
				timer.End ();
				monitor.Dispose ();
				IdeApp.Workbench.UnlockGui ();
			}
		}
        public virtual async Task TriggerCompletion(CompletionTriggerReason reason)
        {
            if (Editor.SelectionMode == SelectionMode.Block)
            {
                return;
            }

            if (CompletionWindowManager.IsVisible)
            {
                CompletionWindowManager.ToggleCategoryMode();
                return;
            }
            Editor.EnsureCaretIsNotVirtual();
            ICompletionDataList completionList = null;
            int cpos, wlen;

            if (!GetCompletionCommandOffset(out cpos, out wlen))
            {
                cpos = Editor.CaretOffset;
                wlen = 0;
            }

            completionTokenSrc.Cancel();
            completionTokenSrc = new CancellationTokenSource();
            var token = completionTokenSrc.Token;

            CurrentCompletionContext = CompletionWidget.CreateCodeCompletionContext(cpos);
            CurrentCompletionContext.TriggerWordLength = wlen;

            ITimeTracker timer = null;
            bool         failure = false;

            try {
                timer          = Counters.ProcessCodeCompletion.BeginTiming();
                completionList = await DoHandleCodeCompletionAsync(CurrentCompletionContext, new CompletionTriggerInfo (reason), token);

                if (completionList != null && completionList.TriggerWordStart >= 0)
                {
                    CurrentCompletionContext.TriggerOffset     = completionList.TriggerWordStart;
                    CurrentCompletionContext.TriggerWordLength = completionList.TriggerWordLength;
                }
                if (completionList == null || !CompletionWindowManager.ShowWindow(this, (char)0, completionList, CompletionWidget, CurrentCompletionContext))
                {
                    CurrentCompletionContext = null;
                }
            } catch (Exception) {
                failure = true;
                throw;
            } finally {
                Counters.ProcessCodeCompletion.EndTiming();
                if (failure)
                {
                    completionStats.OnFailure(timer.Duration);
                }
                else
                {
                    completionStats.OnSuccess(timer.Duration);
                }
            }
        }
Example #10
0
    public string GetCollisionStateString()
    {
        List <Collider2D> contactColliders = new List <Collider2D>();

        _capsuleCollider.GetContacts(contactColliders);

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

        foreach (var collider in contactColliders)
        {
            if (collider.gameObject == gameController.Player.gameObject || collider.gameObject == this.gameObject)
            {
                continue;
            }

            ITimeTracker timeTracker = GameController.GetTimeTrackerComponent(collider.gameObject);
            if (timeTracker != null)
            {
                colliderStrings.Add(timeTracker.ID.ToString());
            }
            else
            {
                colliderStrings.Add($"U{collider.GetInstanceID().ToString()}");
            }
        }

        colliderStrings.Sort();

        return(string.Join(",", colliderStrings));
    }
Example #11
0
        async private Task stopTimeTrackingTimerAsync()
        {
            if (!isTrackingTime())
            {
                return;
            }

            // Stop timer
            _timeTrackingTimer.Stop();

            // Reset member right now to not send tracked time again on re-entrance
            ITimeTracker timeTracker = _timeTracker;

            _timeTracker      = null;
            _timeTrackingMode = null;

            string convertSpanToText(TimeSpan span) => String.Format("{0}h {1}m {2}s",
                                                                     span.ToString("hh"), span.ToString("mm"), span.ToString("ss"));

            addOperationRecord("Sending tracked time has started");
            try
            {
                TimeSpan span = await timeTracker.Stop();

                string duration = convertSpanToText(span);
                addOperationRecord(String.Format("Tracked time {0} sent successfully", duration));
            }
            catch (ForbiddenTimeTrackerException ex)
            {
                TimeSpan span     = ex.TrackedTime;
                string   duration = convertSpanToText(span);
                string   status   = String.Format(
                    "Cannot report tracked time ({0}).\r\n"
                    + "You don't have permissions to track time in {1} project.\r\n"
                    + "Please contact {2} administrator or SCM team.",
                    duration, timeTracker.MergeRequest.ProjectKey.ProjectName, timeTracker.MergeRequest.ProjectKey.HostName);
                MessageBox.Show(status, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                addOperationRecord(String.Format("Tracked time is not set. Set up permissions and report {0} manually",
                                                 duration));
            }
            catch (TooSmallSpanTimeTrackerException)
            {
                addOperationRecord("Tracked time less than 1 second is ignored");
            }
            catch (TimeTrackerException ex)
            {
                TimeSpan span     = ex.TrackedTime;
                string   duration = convertSpanToText(span);
                string   status   = String.Format("Error occurred. Tracked time {0} is not sent", duration);
                ExceptionHandlers.Handle(status, ex);
                MessageBox.Show(status, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (!isTrackingTime())
            {
                onTimerStopped();
            }
        }
Example #12
0
        public static async Task FindAllReferencesAsync(string documentIdString, Projects.Project hintProject = null)
        {
            if (hintProject == null)
            {
                hintProject = IdeApp.Workbench.ActiveDocument?.Project;
            }
            ITimeTracker timer   = null;
            var          monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true);

            try {
                var metadata = Counters.CreateFindReferencesMetadata();
                timer = Counters.FindReferences.BeginTiming(metadata);
                var tasks = new List <(Task task, FindReferencesProvider provider)> (findReferencesProvider.Count);
                foreach (var provider in findReferencesProvider)
                {
                    try {
                        tasks.Add((provider.FindAllReferences(documentIdString, hintProject, monitor), provider));
                    } catch (OperationCanceledException) {
                        Counters.SetUserCancel(metadata);
                        return;
                    } catch (Exception ex) {
                        Counters.SetFailure(metadata);
                        if (monitor != null)
                        {
                            monitor.ReportError("Error finding references", ex);
                        }
                        LoggingService.LogError("Error finding references", ex);
                        findReferencesProvider = findReferencesProvider.Remove(provider);
                    }
                }
                foreach (var task in tasks)
                {
                    try {
                        await task.task;
                    } catch (OperationCanceledException) {
                        Counters.SetUserCancel(metadata);
                        return;
                    } catch (Exception ex) {
                        Counters.SetFailure(metadata);
                        if (monitor != null)
                        {
                            monitor.ReportError("Error finding references", ex);
                        }
                        LoggingService.LogError("Error finding references", ex);
                        findReferencesProvider = findReferencesProvider.Remove(task.provider);
                    }
                }
            } finally {
                if (monitor != null)
                {
                    monitor.Dispose();
                }
                if (timer != null)
                {
                    timer.Dispose();
                }
            }
        }
Example #13
0
 public MonoDevelopFindUsagesContext()
 {
     monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true);
     monitor.BeginTask(GettextCatalog.GetString("Searching..."), 100);
     CancellationToken = monitor.CancellationToken;
     CancellationToken.Register(Finished);
     metadata = Counters.CreateFindReferencesMetadata();
     timer    = Counters.FindReferences.BeginTiming(metadata);
 }
Example #14
0
    private void DoGrab()
    {
        if (gameController.CurrentPlayerID != ID)
        {
            return;                                       // only current player can initiate grab with this method
        }
        bool isFound = false;

        if (ItemID != -1)                              // not -1 means it is a valid item, so we ARE holding something
        {
            if (gameController.DropItem(this, ItemID)) // check to see if we successfully drop the item
            {
                AudioSource.PlayClipAtPoint(_grabAudio, Camera.main.transform.position, 1f);
                gameController.AddEvent(ID, TimeEvent.EventType.PLAYER_DROP, ItemID);
                gameController.SetItemInUI(-1);
                ItemID = -1;
            }
        }
        else
        {
            List <Collider2D> contacts = new List <Collider2D>();
            GrabCollider.GetContacts(contacts);
            foreach (var contact in contacts)
            {
                if (contact.gameObject == gameObject)
                {
                    continue;
                }

                ITimeTracker timeTracker = GameController.GetTimeTrackerComponent(contact.gameObject, true);
                if (timeTracker != null)
                {
                    if (timeTracker.SetItemState(true))
                    {
                        isFound = true;
                        ItemID  = timeTracker.ID;
                    }
                }

                // break the loop if we found an object bc we can only pick up one object
                if (isFound)
                {
                    break;
                }
            }

            // this is when he grabs a object and it shows up in the screen
            if (isFound == true)
            {
                AudioSource.PlayClipAtPoint(_grabAudio, Camera.main.transform.position, 1f);
                gameController.AddEvent(ID, TimeEvent.EventType.PLAYER_GRAB, ItemID);
                gameController.SetItemInUI(ItemID);
            }
        }
    }
 protected override void OnEndTask(string name, int totalWork, int stepWork)
 {
     if (timers.Count > 0)
     {
         ITimeTracker c = timers.Pop();
         if (c != null)
         {
             c.End();
         }
     }
 }
 public override void EndTask()
 {
     if (timers.Count > 0)
     {
         ITimeTracker c = timers.Pop();
         if (c != null)
         {
             c.End();
         }
     }
     base.EndTask();
 }
        void Finished()
        {
            if (!CancellationToken.IsCancellationRequested)
            {
                monitor?.ReportResults(antiDuplicatesSet.Keys);
            }
            monitor?.Dispose();
            monitor = null;

            timer?.Dispose();
            timer = null;
        }
 protected override void OnBeginTask(string name, int totalWork, int stepWork)
 {
     if (!string.IsNullOrEmpty(name))
     {
         ITimeTracker c = counter.BeginTiming(name);
         c.Trace(name);
         timers.Push(c);
     }
     else
     {
         timers.Push(null);
     }
 }
Example #19
0
        public void OneTimeSetUp()
        {
            _timeRequestData = new FakeTimeRequestData();
            _testClock       = new FakeClock();
            _timeTracker     = new TimeTracker();
            _dbDummyContext  = new MoreTimeRequestContext(new DbContextOptions <MoreTimeRequestContext>());

            _controller = new MoreTimeRequestController(
                _dbDummyContext,
                _timeRequestData,
                _testClock,
                _timeTracker);
        }
            void WriteMefCacheControl(ComposableCatalog catalog, ITimeTracker timer)
            {
                var mefAssemblyNames = new HashSet <string> ();
                var mefAssemblyInfos = new List <MefControlCacheAssemblyInfo> ();

                foreach (var assembly in MefAssemblies)
                {
                    mefAssemblyNames.Add(assembly.GetName().ToString());

                    mefAssemblyInfos.Add(new MefControlCacheAssemblyInfo {
                        Location        = assembly.Location,
                        ModuleVersionId = assembly.ManifestModule.ModuleVersionId,
                    });
                }

                var additionalInputAssemblies = new List <MefControlCacheAssemblyInfo> ();
                var loadedMap = loadedAssemblies.ToDictionary(x => x.FullName, x => x);

                foreach (var asm in catalog.GetInputAssemblies())
                {
                    var assemblyName = asm.ToString();
                    if (mefAssemblyNames.Contains(assemblyName))
                    {
                        continue;
                    }

                    if (!loadedMap.TryGetValue(assemblyName, out var assembly))
                    {
                        throw new InvalidRuntimeCompositionException(assemblyName);
                    }

                    additionalInputAssemblies.Add(new MefControlCacheAssemblyInfo {
                        Location        = assembly.Location,
                        ModuleVersionId = assembly.ManifestModule.ModuleVersionId,
                    });
                }

                // Create cache control data.
                var controlCache = new MefControlCache {
                    MefAssemblyInfos             = mefAssemblyInfos,
                    AdditionalInputAssemblyInfos = additionalInputAssemblies,
                };

                var serializer = new JsonSerializer();

                using (var fs = File.Open(MefCacheControlFile, FileMode.Create))
                    using (var sw = new StreamWriter(fs)) {
                        serializer.Serialize(sw, controlCache);
                    }
                timer.Trace("Composition control file written");
            }
Example #21
0
    public void CopyTimeTrackerState(ITimeTracker other)
    {
        PlayerController otherPlayer = other as PlayerController;

        if (otherPlayer != null)
        {
            Position.Copy(otherPlayer.Position);
            Velocity.Copy(otherPlayer.Velocity);
        }
        else
        {
            gameController.LogError($"Cannot copy state from {other.GetType()} to {nameof(PlayerController)}");
        }
    }
 public override void BeginStepTask(string name, int totalWork, int stepSize)
 {
     if (!string.IsNullOrEmpty(name))
     {
         ITimeTracker c = counter.BeginTiming(name);
         c.Trace(name);
         timers.Push(c);
     }
     else
     {
         timers.Push(null);
     }
     base.BeginStepTask(name, totalWork, stepSize);
 }
        public MemorizationPageViewModel()
        {
            CardsSeen = new ObservableCollection <PlayingCard>();
            DeckBuilder deckBuilder = new DeckBuilder();

            deckBuilder.IncludeSpades();
            deckBuilder.IncludeDiamonds();
            deckBuilder.IncludeClubs();
            deckBuilder.IncludeHearts();
            deckBuilder.Shuffle();
            _deck           = new Deck(deckBuilder.Build());
            TurnCardCommand = new DelegateCommand(ExecuteTurnCard, CanExecuteTurnCard);
            StopCommand     = new DelegateCommand(ExecuteStop, CanExecuteStop);
            _timeTracker    = new TimeTracker();
        }
    public virtual void CopyTimeTrackerState(ITimeTracker other)
    {
        BasicTimeTracker otherTracker = other as BasicTimeTracker;

        if (otherTracker != null)
        {
            Position.Copy(otherTracker.Position);
            ItemForm = otherTracker.ItemForm;

            _shouldPoolObject = otherTracker._shouldPoolObject;
            _isItemable       = otherTracker._isItemable;
        }
        else
        {
            gameController.LogError($"Cannot copy state from {other.GetType()} to {nameof(BasicTimeTracker)}");
        }
    }
Example #25
0
        public void SaveAll()
        {
            ITimeTracker tt = Counters.SaveAllTimer.BeginTiming();

            try {
                // Make a copy of the list, since it may change during save
                Document[] docs = new Document [Documents.Count];
                Documents.CopyTo(docs, 0);

                foreach (Document doc in docs)
                {
                    doc.Save();
                }
            } finally {
                tt.End();
            }
        }
Example #26
0
    public override bool IsEquivalentItem(ITimeTracker other)
    {
        ExplodeBox otherExplode = other as ExplodeBox;

        if (otherExplode == null)
        {
            return(false);                              // incorrect object type
        }
        if (this.spritePath != otherExplode.spritePath)
        {
            return(false);                                                    // different labels matter
        }
        if (this.requiredActivatableIDs.Except(otherExplode.requiredActivatableIDs).Any())
        {
            return(false);                                                                                       // any difference in activatable IDs
        }
        return(base.IsEquivalentItem(other));
    }
            void WriteMefCacheControl(ITimeTracker timer)
            {
                // Create cache control data.
                var controlCache = new MefControlCache {
                    AssemblyInfos = Assemblies.Select(asm => new MefControlCacheAssemblyInfo {
                        Location         = asm.Location,
                        LastWriteTimeUtc = File.GetLastWriteTimeUtc(asm.Location),
                    }).ToArray(),
                };

                var serializer = new JsonSerializer();

                using (var fs = File.Open(MefCacheControlFile, FileMode.Create))
                    using (var sw = new StreamWriter(fs)) {
                        serializer.Serialize(sw, controlCache);
                    }
                timer.Trace("Composition control file written");
            }
Example #28
0
    public bool IsEquivalentItem(ITimeTracker other)
    {
        return(ID == other.ID);

        /*
         * NOTE: I was going to allow the player to pick up other Time Machines, but realized that the time histories
         *       would not necessarily line up and would cause a lot of potential issues, so opted for this feature
         *       to only be used for non-Time Machine objects for now.
         */
        /*TimeMachineController otherTimeMachine = other as TimeMachineController;
         * if (otherTimeMachine == null) return false; // incorrect object type
         *
         * if (isFoldable != otherTimeMachine.isFoldable) return false; // must match foldable
         *
         * // not equivalent item if other machine is active in any way
         * if (otherTimeMachine.IsActivatedOrOccupied || otherTimeMachine.Countdown.Current >= 0 || otherTimeMachine.Countdown.History >= 0)
         *  return false;
         *
         * return true;*/
    }
Example #29
0
        async Task InitializeInstanceAsync(ITimeTracker <CompositionLoadMetadata> timer, HashSet <Assembly> mefAssemblies)
        {
            var metadata  = timer.Metadata;
            var fullTimer = System.Diagnostics.Stopwatch.StartNew();
            var stepTimer = System.Diagnostics.Stopwatch.StartNew();

            var caching = new Caching(mefAssemblies, new IdeRuntimeCompositionExceptionHandler());

            // Try to use cached MEF data
            using (timer) {
                var canUse = metadata.ValidCache = caching.CanUse();
                if (canUse)
                {
                    LoggingService.LogInfo("Creating MEF composition from cache");
                    RuntimeComposition = await TryCreateRuntimeCompositionFromCache(caching);
                }
                metadata.Timings ["LoadFromCache"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                // Otherwise fallback to runtime discovery.
                if (RuntimeComposition == null)
                {
                    LoggingService.LogInfo("Creating MEF composition from runtime");
                    var(runtimeComposition, catalog) = await CreateRuntimeCompositionFromDiscovery(caching, timer);

                    RuntimeComposition = runtimeComposition;

                    CachedComposition cacheManager = new CachedComposition();
                    caching.Write(RuntimeComposition, catalog, cacheManager).Ignore();
                }
                metadata.Timings ["LoadRuntimeComposition"] = stepTimer.ElapsedMilliseconds;
                stepTimer.Restart();

                ExportProviderFactory = RuntimeComposition.CreateExportProviderFactory();
                ExportProvider        = ExportProviderFactory.CreateExportProvider();
                HostServices          = Microsoft.VisualStudio.LanguageServices.VisualStudioMefHostServices.Create(ExportProvider);

                metadata.Timings ["CreateServices"] = stepTimer.ElapsedMilliseconds;
                metadata.Duration = fullTimer.ElapsedMilliseconds;
            }
        }
Example #30
0
        /// <summary>
        /// Cleans the files produced by this solution item
        /// </summary>
        /// <param name='monitor'>
        /// A progress monitor
        /// </param>
        /// <param name='configuration'>
        /// Configuration to use to clean the project
        /// </param>
        public void Clean(IProgressMonitor monitor, ConfigurationSelector configuration)
        {
            ITimeTracker tt = Counters.BuildProjectTimer.BeginTiming("Cleaning " + Name);

            try {
                try {
                    SolutionEntityItem        it    = this as SolutionEntityItem;
                    SolutionItemConfiguration iconf = it != null?it.GetConfiguration(configuration) : null;

                    string confName = iconf != null ? iconf.Id : configuration.ToString();
                    monitor.BeginTask(GettextCatalog.GetString("Cleaning: {0} ({1})", Name, confName), 1);
                    RunTarget(monitor, ProjectService.CleanTarget, configuration);
                    monitor.Step(1);
                } finally {
                    monitor.EndTask();
                }
            }
            finally {
                tt.End();
            }
        }
Example #31
0
		void CleanDone (IProgressMonitor monitor, IBuildTarget entry, ITimeTracker tt)
		{
			tt.Trace ("Begin reporting clean result");
			try {
				monitor.Log.WriteLine ();
				monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));
				tt.Trace ("Reporting result");			
				monitor.ReportSuccess (GettextCatalog.GetString ("Clean successful."));
				OnEndClean (monitor, tt);
			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
Example #32
0
		void OnEndClean (IProgressMonitor monitor, ITimeTracker tt)
		{
			tt.Trace ("End clean event");
			if (EndClean != null) {
				EndClean (this, new CleanEventArgs (monitor));
			}
		}
Example #33
0
		void CleanAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt, bool isRebuilding)
		{
			try {
				tt.Trace ("Cleaning item");
				SolutionItem it = entry as SolutionItem;
				if (it != null) {
					it.Clean (monitor, IdeApp.Workspace.ActiveConfiguration);
				}
				else {
					entry.RunTarget (monitor, ProjectService.CleanTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Clean failed."), ex);
			} finally {
				tt.Trace ("Done cleaning");
			}
			
			if (isRebuilding) {
				if (EndClean != null) {
					DispatchService.GuiSyncDispatch (() => OnEndClean (monitor, tt));
				}
			} else {
				DispatchService.GuiDispatch (() => CleanDone (monitor, entry, tt));
			}
		}
Example #34
0
		void BuildDone (IProgressMonitor monitor, BuildResult result, IBuildTarget entry, ITimeTracker tt)
		{
			Task[] tasks = null;
			tt.Trace ("Begin reporting build result");
			try {
				if (result != null) {
					lastResult = result;
					monitor.Log.WriteLine ();
					monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));
					
					tt.Trace ("Updating task service");
					tasks = new Task [result.Errors.Count];
					for (int n=0; n<tasks.Length; n++) {
						tasks [n] = new Task (result.Errors [n]);
						tasks [n].Owner = this;
					}

					TaskService.Errors.AddRange (tasks);
					TaskService.Errors.ResetLocationList ();
					IdeApp.Workbench.ActiveLocationList = TaskService.Errors;
					
					tt.Trace ("Reporting result");
					
					string errorString = GettextCatalog.GetPluralString("{0} error", "{0} errors", result.ErrorCount, result.ErrorCount);
					string warningString = GettextCatalog.GetPluralString("{0} warning", "{0} warnings", result.WarningCount, result.WarningCount);

					if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) {
						monitor.ReportSuccess (GettextCatalog.GetString ("Build successful."));
					} else if (result.ErrorCount == 0 && result.WarningCount > 0) {
						monitor.ReportWarning(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString);
					} else if (result.ErrorCount > 0) {
						monitor.ReportError(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString, null);
					} else {
						monitor.ReportError(GettextCatalog.GetString("Build failed."), null);
					}
					tt.Trace ("End build event");
					OnEndBuild (monitor, lastResult.FailedBuildCount == 0, lastResult, entry as SolutionItem);
				} else {
					tt.Trace ("End build event");
					OnEndBuild (monitor, false);
				}
				
				tt.Trace ("Showing results pad");
				
				try {
					Pad errorsPad = IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ErrorListPad> ();
					switch (IdeApp.Preferences.ShowErrorPadAfterBuild) {
					case BuildResultStates.Always:
						if (!errorsPad.Visible)
							errorsPad.IsOpenedAutomatically = true;
						errorsPad.Visible = true;
						errorsPad.BringToFront ();
						break;
					case BuildResultStates.Never:
						break;
					case BuildResultStates.OnErrors:
						if (TaskService.Errors.Any (task => task.Severity == TaskSeverity.Error))
							goto case BuildResultStates.Always;
						goto case BuildResultStates.Never;
					case BuildResultStates.OnErrorsOrWarnings:
						if (TaskService.Errors.Any (task => task.Severity == TaskSeverity.Error || task.Severity == TaskSeverity.Warning))
							goto case BuildResultStates.Always;
						goto case BuildResultStates.Never;
					}
				} catch {}
				
				if (tasks != null) {
					Task jumpTask = null;
					switch (IdeApp.Preferences.JumpToFirstErrorOrWarning) {
					case JumpToFirst.Error:
						jumpTask = tasks.FirstOrDefault (t => t.Severity == TaskSeverity.Error && TaskStore.IsProjectTaskFile (t));
						break;
					case JumpToFirst.ErrorOrWarning:
						jumpTask = tasks.FirstOrDefault (t => (t.Severity == TaskSeverity.Error || t.Severity == TaskSeverity.Warning) && TaskStore.IsProjectTaskFile (t));
						break;
					}
					if (jumpTask != null) {
						tt.Trace ("Jumping to first result position");
						jumpTask.JumpToPosition ();
					}
				}
				
			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
Example #35
0
		void OnStartClean (IProgressMonitor monitor, ITimeTracker tt)
		{
			tt.Trace ("Start clean event");
			TaskService.Errors.ClearByOwner (this);
			if (StartClean != null) {
				StartClean (this, new CleanEventArgs (monitor));
			}
		}
Example #36
0
		void BuildSolutionItemAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt)
		{
			BuildResult result = null;
			try {
				tt.Trace ("Pre-build operations");
				result = DoBeforeCompileAction ();

				if (result.ErrorCount == 0) {
					tt.Trace ("Building item");
					SolutionItem it = entry as SolutionItem;
					if (it != null)
						result = it.Build (monitor, IdeApp.Workspace.ActiveConfiguration, true);
					else
						result = entry.RunTarget (monitor, ProjectService.BuildTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Build failed."), ex);
			} finally {
				tt.Trace ("Done building");
			}
			DispatchService.GuiDispatch (
				delegate {
					BuildDone (monitor, result, entry, tt);	// BuildDone disposes the monitor
			});
		}
Example #37
0
		void BeginBuild (IProgressMonitor monitor, ITimeTracker tt, bool isRebuilding)
		{
			tt.Trace ("Start build event");
			if (!isRebuilding) {
				TaskService.Errors.ClearByOwner (this);
			}
			if (StartBuild != null) {
				StartBuild (this, new BuildEventArgs (monitor, true));
			}
		}
		async Task<BuildResult> BuildSolutionItemAsync (IBuildTarget entry, ProgressMonitor monitor, ITimeTracker tt, bool skipPrebuildCheck = false, OperationContext operationContext = null)
		{
			BuildResult result = null;
			try {
				if (!skipPrebuildCheck) {
					tt.Trace ("Pre-build operations");
					result = DoBeforeCompileAction ();
				}

				//wait for any custom tools that were triggered by the save, since the build may depend on them
				await MonoDevelop.Ide.CustomTools.CustomToolService.WaitForRunningTools (monitor);

				if (skipPrebuildCheck || result.ErrorCount == 0) {
					tt.Trace ("Building item");
					result = await entry.Build (monitor, IdeApp.Workspace.ActiveConfiguration, true, operationContext);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Build failed."), ex);
				if (result == null)
					result = new BuildResult ();
				result.AddError ("Build failed. See the build log for details.");
				if (result.SourceTarget == null)
					result.SourceTarget = entry;
			} finally {
				tt.Trace ("Done building");
			}

			BuildDone (monitor, result, entry, tt);	// BuildDone disposes the monitor

			return result;
		}
		async Task<BuildResult> CleanAsync (IBuildTarget entry, ProgressMonitor monitor, ITimeTracker tt, bool isRebuilding, OperationContext operationContext)
		{
			BuildResult res = null;
			try {
				tt.Trace ("Cleaning item");
				res = await entry.Clean (monitor, IdeApp.Workspace.ActiveConfiguration, operationContext);
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Clean failed."), ex);
			} finally {
				tt.Trace ("Done cleaning");
			}
			
			if (isRebuilding) {
				if (EndClean != null) {
					OnEndClean (monitor, tt);
				}
			} else {
				CleanDone (monitor, entry, tt);
			}
			return res;
		}
		static void CommandServiceCommandTargetScanStarted (object sender, EventArgs e)
		{
			commandTimeCounter = Counters.CommandTargetScanTime.BeginTiming ();
		}
		void CleanDone (ProgressMonitor monitor, BuildResult result, IBuildTarget entry, ITimeTracker tt)
		{
			tt.Trace ("Begin reporting clean result");
			try {
				if (result != null) {
					monitor.Log.WriteLine ();
					monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));

					tt.Trace ("Updating task service");
				
					ReportErrors (result);

					tt.Trace ("Reporting result");

					string errorString = GettextCatalog.GetPluralString ("{0} error", "{0} errors", result.ErrorCount, result.ErrorCount);
					string warningString = GettextCatalog.GetPluralString ("{0} warning", "{0} warnings", result.WarningCount, result.WarningCount);

					if (monitor.CancellationToken.IsCancellationRequested) {
						monitor.ReportError (GettextCatalog.GetString ("Clean canceled."), null);
					} else if (result.ErrorCount == 0 && result.WarningCount == 0 && result.FailedBuildCount == 0) {
						monitor.ReportSuccess (GettextCatalog.GetString ("Clean successful."));
					} else if (result.ErrorCount == 0 && result.WarningCount > 0) {
						monitor.ReportWarning (GettextCatalog.GetString ("Clean: ") + errorString + ", " + warningString);
					} else if (result.ErrorCount > 0) {
						monitor.ReportError (GettextCatalog.GetString ("Clean: ") + errorString + ", " + warningString, null);
					} else {
						monitor.ReportError (GettextCatalog.GetString ("Clean failed."), null);
					}
				}

				OnEndClean (monitor, tt);

				tt.Trace ("Showing results pad");

				ShowErrorsPadIfNecessary ();

			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
		void BuildDone (ProgressMonitor monitor, BuildResult result, IBuildTarget entry, ITimeTracker tt)
		{
			TaskListEntry[] tasks = null;
			tt.Trace ("Begin reporting build result");
			try {
				if (result != null) {
					lastResult = result;
					monitor.Log.WriteLine ();
					monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));
					
					tt.Trace ("Updating task service");

					tasks = ReportErrors (result);

					tt.Trace ("Reporting result");
					
					string errorString = GettextCatalog.GetPluralString("{0} error", "{0} errors", result.ErrorCount, result.ErrorCount);
					string warningString = GettextCatalog.GetPluralString("{0} warning", "{0} warnings", result.WarningCount, result.WarningCount);

					if (monitor.CancellationToken.IsCancellationRequested) {
						monitor.ReportError (GettextCatalog.GetString ("Build canceled."), null);
					} else if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) {
						monitor.ReportSuccess (GettextCatalog.GetString ("Build successful."));
					} else if (result.ErrorCount == 0 && result.WarningCount > 0) {
						monitor.ReportWarning(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString);
					} else if (result.ErrorCount > 0) {
						monitor.ReportError(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString, null);
					} else {
						monitor.ReportError(GettextCatalog.GetString("Build failed."), null);
					}
					tt.Trace ("End build event");
					OnEndBuild (monitor, lastResult.FailedBuildCount == 0, lastResult, entry as SolutionFolderItem);
				} else {
					tt.Trace ("End build event");
					OnEndBuild (monitor, false);
				}
				
				tt.Trace ("Showing results pad");
				
				ShowErrorsPadIfNecessary ();

				if (tasks != null) {
					TaskListEntry jumpTask = null;
					switch (IdeApp.Preferences.JumpToFirstErrorOrWarning.Value) {
					case JumpToFirst.Error:
						jumpTask = tasks.FirstOrDefault (t => t.Severity == TaskSeverity.Error && TaskStore.IsProjectTaskFile (t));
						break;
					case JumpToFirst.ErrorOrWarning:
						jumpTask = tasks.FirstOrDefault (t => (t.Severity == TaskSeverity.Error || t.Severity == TaskSeverity.Warning) && TaskStore.IsProjectTaskFile (t));
						break;
					}
					if (jumpTask != null) {
						tt.Trace ("Jumping to first result position");
						jumpTask.JumpToPosition ();
					}
				}
				
			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
Example #43
0
		void BuildSolutionItemAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt, bool skipPrebuildCheck = false, ProjectOperationContext context = null)
		{
			BuildResult result = null;
			try {
				if (!skipPrebuildCheck) {
					tt.Trace ("Pre-build operations");
					result = DoBeforeCompileAction ();
				}

				//wait for any custom tools that were triggered by the save, since the build may depend on them
				MonoDevelop.Ide.CustomTools.CustomToolService.WaitForRunningTools (monitor);

				if (skipPrebuildCheck || result.ErrorCount == 0) {
					tt.Trace ("Building item");
					SolutionItem it = entry as SolutionItem;
					if (it != null)
						result = it.Build (monitor, IdeApp.Workspace.ActiveConfiguration, true, context);
					else if (entry is WorkspaceItem)
						result = ((WorkspaceItem)entry).Build (monitor, IdeApp.Workspace.ActiveConfiguration, context);
					else
						result = entry.RunTarget (monitor, ProjectService.BuildTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Build failed."), ex);
				if (result == null)
					result = new BuildResult ();
				result.AddError ("Build failed. See the build log for details.");
				if (result.SourceTarget == null)
					result.SourceTarget = entry;
			} finally {
				tt.Trace ("Done building");
			}
			DispatchService.GuiDispatch (
				delegate {
					BuildDone (monitor, result, entry, tt);	// BuildDone disposes the monitor
			});
		}
		void BackgroundInitialize (object state)
		{
			timer = Counters.TargetRuntimesLoading.BeginTiming ("Initializing Runtime " + Id);
			lock (initLock) {
				try {
					RunInitialization ();
				} catch (Exception ex) {
					LoggingService.LogInternalError ("Unhandled exception in SystemAssemblyService background initialisation thread.", ex);
				} finally {
					lock (initEventLock) {
						initializing = false;
						initialized = true;
						try {
							if (initializedEvent != null && !ShuttingDown)
								initializedEvent (this, EventArgs.Empty);
						} catch (Exception ex) {
							LoggingService.LogError ("Error while initializing the runtime: " + Id, ex);
						}
					}
					timer.End ();
				}
			}
		}