Exemplo n.º 1
0
 private static void Serialize(string filename, WorkerResult result)
 {
     Stream stream = File.Open(filename, FileMode.Create);
     BinaryFormatter bFormatter = new BinaryFormatter();
     bFormatter.Serialize(stream, result.Primes);
     stream.Close();
 }
Exemplo n.º 2
0
		public override Task<ISearchDataSource> GetResults (SearchPopupSearchPattern searchPattern, int resultsCount, CancellationToken token)
		{
			return Task.Factory.StartNew (delegate {
				if (searchPattern.Tag != null && !validTags.Contains (searchPattern.Tag))
					return null;
				try {
					var newResult = new WorkerResult (widget);
					newResult.pattern = searchPattern.Pattern;
					newResult.IncludeFiles = true;
					newResult.IncludeTypes = true;
					newResult.IncludeMembers = true;

					string toMatch = searchPattern.Pattern;
					newResult.matcher = StringMatcher.GetMatcher (toMatch, false);
					newResult.FullSearch = true;

					AllResults (lastResult, newResult, token);
					newResult.results.SortUpToN (new DataItemComparer (token), resultsCount);
					lastResult = newResult;
					return (ISearchDataSource)newResult.results;
				} catch {
					token.ThrowIfCancellationRequested ();
					throw;
				}
			}, token);
		}
		void AllResults (WorkerResult lastResult, WorkerResult newResult, CancellationToken token)
		{
			newResult.filteredCommands = new List<Command> ();
			bool startsWithLastFilter = lastResult != null && lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern) && lastResult.filteredCommands != null;
			IEnumerable<Command> allCommands = startsWithLastFilter ? lastResult.filteredCommands : IdeApp.CommandService.GetCommands ();
			foreach (Command cmd in allCommands) {
				token.ThrowIfCancellationRequested ();
				SearchResult curResult = newResult.CheckCommand (cmd);
				if (curResult != null) {
					newResult.filteredCommands.Add (cmd);
					newResult.results.AddResult (curResult);
				}
			}
		}
Exemplo n.º 4
0
        public JobNotification(WorkerResult result)
        {
            if (result == null)
                throw new ApplicationException("Impossible to log this notification");

            this.Status = result.Status;
            this.NotificationDate = result.TimeFinished;
            this.Details = result.DetailedMessage;
            if (result.WorkerException != null)
            {
                this.ErrorDetails = result.WorkerException.Message;
                if (result.WorkerException.InnerException != null)
                    this.ErrorDetails += ": " + result.WorkerException.InnerException.Message;
            }
        }
Exemplo n.º 5
0
        public override Task<ISearchDataSource> GetResults(SearchPopupSearchPattern searchPattern, int resultsCount, CancellationToken token)
        {
            // NOTE: This is run on the UI thread as checking whether or not a command is enabled is not thread-safe
            return Task.Factory.StartNew (delegate {
                try {
                    if (searchPattern.Tag != null && !validTags.Contains (searchPattern.Tag) || searchPattern.HasLineNumber)
                        return null;
                    WorkerResult newResult = new WorkerResult (widget);
                    newResult.pattern = searchPattern.Pattern;

                    newResult.matcher = StringMatcher.GetMatcher (searchPattern.Pattern, false);
                    newResult.FullSearch = true;

                    AllResults (lastResult, newResult, token);
                    newResult.results.SortUpToN (new DataItemComparer (token), resultsCount);
                    lastResult = newResult;
                    return (ISearchDataSource)newResult.results;
                } catch {
                    token.ThrowIfCancellationRequested ();
                    throw;
                }
            }, token, TaskCreationOptions.None, Xwt.Application.UITaskScheduler);
        }
		public override Task<ISearchDataSource> GetResults (SearchPopupSearchPattern searchPattern, int resultsCount, CancellationToken token)
		{
			return Task.Factory.StartNew (delegate {
				if (searchPattern.Tag != null && !(typeTags.Contains (searchPattern.Tag) || memberTags.Contains (searchPattern.Tag)) || searchPattern.HasLineNumber)
					return null;
				try {
					var newResult = new WorkerResult (widget);
					newResult.pattern = searchPattern.Pattern;
					newResult.IncludeFiles = true;
					newResult.Tag = searchPattern.Tag;
					newResult.IncludeTypes = searchPattern.Tag == null || typeTags.Contains (searchPattern.Tag) ;
					newResult.IncludeMembers = searchPattern.Tag == null || memberTags.Contains (searchPattern.Tag);
					var firstType = types.FirstOrDefault ();
					newResult.ambience = firstType != null ? AmbienceService.GetAmbienceForFile (firstType.Region.FileName) : AmbienceService.DefaultAmbience;
					
					string toMatch = searchPattern.Pattern;
					newResult.matcher = StringMatcher.GetMatcher (toMatch, false);
					newResult.FullSearch = toMatch.IndexOf ('.') > 0;
					var oldLastResult = lastResult;
					if (newResult.FullSearch && oldLastResult != null && !oldLastResult.FullSearch)
						oldLastResult = new WorkerResult (widget);
//					var now = DateTime.Now;

					AllResults (oldLastResult, newResult, token);
					newResult.results.SortUpToN (new DataItemComparer (token), resultsCount);
					lastResult = newResult;
//					Console.WriteLine ((now - DateTime.Now).TotalMilliseconds);
					return (ISearchDataSource)newResult.results;
				} catch {
					token.ThrowIfCancellationRequested ();
					throw;
				}
			}, token);
		}
Exemplo n.º 7
0
 public CommandSearchCategory(Widget widget)
     : base(GettextCatalog.GetString("Commands"))
 {
     this.widget = widget;
     this.lastResult = new WorkerResult (widget);
 }
Exemplo n.º 8
0
        /// <summary>
        /// This method is called by the job after the worker is run.
        /// The code should determine, based on the worker result,
        /// whether or not a notification should be sent.</summary>
        public void RequestNotification(WorkerResult result)
        {
            bool notify = false;

              // If the status warrants notification and no notification was sent for this status in the allotted time period, send it.
              if ( ShouldNotify(result.Status) &&	(DateTime.Now.Subtract(LastNotified(result.State)) >= MaxNotificationFrequency) )
            notify = true;

            // If the PREVIOUS status warrants notification and the state has changed, send this notification too.
              else if ( (_lastWorkerResult != null) && ShouldNotify(_lastWorkerResult.Status) && (result.State != _lastWorkerResult.State) )
            notify = true;

              // no matter what, do not exceed this many notifications in the specified period
              if ( CheckPeriodNotificationsCount() >= MaxNotificationCountInPeriod )
            notify = false;

              // NOTIFY?
              if ( notify )
              {
            _lastWorkerResult = result;
            _lastNotifiedByState[result.State] = DateTime.Now;
            _notificationHistory.Add(DateTime.Now);
            FireNotify(result);
              }
        }
		void AllResults (WorkerResult lastResult, WorkerResult newResult, CancellationToken token)
		{
			if (newResult.isGotoFilePattern)
				return;
			uint x = 0;
			// Search Types
			if (newResult.IncludeTypes && (newResult.Tag == null || typeTags.Any (t => t == newResult.Tag))) {
				newResult.filteredTypes = new List<ITypeDefinition> ();
				bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern, StringComparison.Ordinal) && lastResult.filteredTypes != null;
				var allTypes = startsWithLastFilter ? lastResult.filteredTypes : types;
				foreach (var type in allTypes) {
					if (unchecked(x++) % 100 == 0 && token.IsCancellationRequested)
						return;

					if (newResult.Tag != null) {
						if (newResult.Tag == "c" && type.Kind != TypeKind.Class)
							continue;
						if (newResult.Tag == "s" && type.Kind != TypeKind.Struct)
							continue;
						if (newResult.Tag == "i" && type.Kind != TypeKind.Interface)
							continue;
						if (newResult.Tag == "e" && type.Kind != TypeKind.Enum)
							continue;
						if (newResult.Tag == "d" && type.Kind != TypeKind.Delegate)
							continue;
					}
					SearchResult curResult = newResult.CheckType (type);
					if (curResult != null) {
						newResult.filteredTypes.Add (type);
						newResult.results.AddResult (curResult);
					}
				}
			}
			
			// Search members
			if (newResult.IncludeMembers && (newResult.Tag == null || memberTags.Any (t => t == newResult.Tag))) {
				newResult.filteredMembers = new List<Tuple<ITypeDefinition, IUnresolvedMember>> ();
				bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern, StringComparison.Ordinal) && lastResult.filteredMembers != null;
				if (startsWithLastFilter) {
					foreach (var t in lastResult.filteredMembers) {
						if (unchecked(x++) % 100 == 0 && token.IsCancellationRequested)
							return;
						var member = t.Item2;
						if (newResult.Tag != null) {
							if (newResult.Tag == "m" && member.EntityType != EntityType.Method)
								continue;
							if (newResult.Tag == "p" && member.EntityType != EntityType.Property)
								continue;
							if (newResult.Tag == "f" && member.EntityType != EntityType.Field)
								continue;
							if (newResult.Tag == "evt" && member.EntityType != EntityType.Event)
								continue;
						}
						SearchResult curResult = newResult.CheckMember (t.Item1, member);
						if (curResult != null) {
							newResult.filteredMembers.Add (t);
							newResult.results.AddResult (curResult);
						}
					}
				} else {
					Func<IUnresolvedMember, bool> mPred = member => {
						if (newResult.Tag != null) {
							if (newResult.Tag == "m" && member.EntityType != EntityType.Method)
								return false;
							if (newResult.Tag == "p" && member.EntityType != EntityType.Property)
								return false;
							if (newResult.Tag == "f" && member.EntityType != EntityType.Field)
								return false;
							if (newResult.Tag == "evt" && member.EntityType != EntityType.Event)
								return false;
						}
						return newResult.IsMatchingMember (member);
					};

					getMembersTimer.BeginTiming ();
					try {
						foreach (var type in types) {
							if (type.Kind == TypeKind.Delegate)
								continue;
							foreach (var p in type.Parts) {
								foreach (var member in p.Members.Where (mPred)) {
									if (unchecked(x++) % 100 == 0 && token.IsCancellationRequested)
										return;
									SearchResult curResult = newResult.CheckMember (type, member);
									if (curResult != null) {
										newResult.filteredMembers.Add (Tuple.Create (type, member));
										newResult.results.AddResult (curResult);
									}
								}
							}
						}
					} finally {
						getMembersTimer.EndTiming ();
					}
				}
			}
		}
 private void PoolOnPushResult(WorkerResult workerResult)
 {
     _taskManager.WriteResult(workerResult);
     _pauseEvent.Set();
 }
Exemplo n.º 11
0
		void AllResults (ISearchResultCallback searchResultCallback, WorkerResult lastResult, WorkerResult newResult, IReadOnlyList<DeclaredSymbolInfo> completeTypeList, CancellationToken token)
		{
			// Search Types
			newResult.filteredSymbols = new List<DeclaredSymbolInfo> ();
			bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern, StringComparison.Ordinal) && lastResult.filteredSymbols != null;
			var allTypes = startsWithLastFilter ? lastResult.filteredSymbols : completeTypeList;
			foreach (var type in allTypes) {
				if (token.IsCancellationRequested) {
					newResult.filteredSymbols = null;
					return;
				}
				SearchResult curResult = newResult.CheckType (type);
				if (curResult != null) {
					newResult.filteredSymbols.Add (type);
					searchResultCallback.ReportResult (curResult);
				}
			}
		}
Exemplo n.º 12
0
 public JobComponentFinishedEventArgs(JobComponent jobComp, WorkerResult result)
     : base()
 {
     this._sequenceNr = jobComp.SequenceNumber;
     this.jobComponentName = jobComp.Name;
     if (result == null)
         throw new ApplicationException("The result of the job can not be null");
     else if (result.Status == WorkerResultStatus.Ok)
         isOK = true;
     this.result = result;
 }
Exemplo n.º 13
0
		static void DisposeSymbolInfoTask ()
		{
			symbolInfoTokenSrc.Cancel ();
			if (SymbolInfoTask != null) {
				try {
					var old = SymbolInfoTask.Result;
					if (old != null)
						old.Dispose ();
				} catch (TaskCanceledException) {
					// Ignore
				} catch (Exception ex) {
					LoggingService.LogError ("UpdateSymbolInfos failed", ex);
				}
			}
			symbolInfoTokenSrc = new CancellationTokenSource();
			lastResult = new WorkerResult (widget);
			SymbolInfoTask = null;
		}
Exemplo n.º 14
0
 public ProjectSearchCategory(SearchPopupWindow widget)
     : base(GettextCatalog.GetString("Solution"))
 {
     this.widget = widget;
     this.lastResult = new WorkerResult (widget);
 }
Exemplo n.º 15
0
 public void WriteResult(WorkerResult result)
 {
     string fileName = Guid.NewGuid() + _ext;
     _tags.Add(new FileTag(result, fileName));
     Serialize(fileName, result);
 }
Exemplo n.º 16
0
 public void WriteResult(WorkerResult result)
 {
     _taskRange.Push(result.MainTask);
     _writer.WriteResult(result);
 }
Exemplo n.º 17
0
 /// <summary>
 /// This method must be implemented by the derived class and must
 /// do the actual notification.</summary>
 protected abstract void Notify(WorkerResult result);
Exemplo n.º 18
0
        /// <summary>
        /// This method is called when RequestNotify determines that notification should take place.</summary>
        protected void FireNotify(WorkerResult result)
        {
            try
              {
            Notify(result);
            if ( NotifierSwitch.TraceVerbose )
              System.Diagnostics.Trace.WriteLine(string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\tNotifier\t{2}\t{3}\t{4}",
                DateTime.Now, Thread.CurrentThread.ManagedThreadId, "Notify()",
                this.GetType(), "OK" ));
              }
              catch (Exception e)
              {
              // log that the Notifier was not fired
              log.Error(string.Format("The Notifier {0} was not fired: {1}", this.ToString(), e.Message));

              if (NotifierSwitch.TraceError)
              System.Diagnostics.Trace.WriteLine(string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\tNotifier\t{2}\t{3}\t{4}",
                DateTime.Now, Thread.CurrentThread.ManagedThreadId, "Notify()",
                this.GetType(), e.Message ));
              }
        }
Exemplo n.º 19
0
        // This event handler deals with the results of the
        // background operation.
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            WorkerResult result;
            // log the that the worker is running
            Trace.WriteLineIf(_jobSwitch.TraceVerbose,
              string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\tJob\t{2}\t{3}",
              DateTime.Now, Thread.CurrentThread.ManagedThreadId, "Worker",
              _worker.Description));

            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                result = new WorkerResult(WorkerResult.STATE_EXCEPTION, WorkerResultStatus.Exception, Name,
                    string.Format(_worker.MessageException, DateTime.Now, e.Error.Message),
                    e.Error);
            }
            else
            {
                try
                {
                    result = e.Result as WorkerResult;
                }
                catch (Exception)
                {
                    // error or whatever
                    result = null;
                }

                if (e.Cancelled)
                {
                    // Next, handle the case where the user canceled the operation.
                    // Note that due to a race condition in the DoWork event handler, the Cancelled
                    // flag may not have been set, even though CancelAsync was called.
                    if (result == null)
                        result = new WorkerResult(WorkerResult.STATE_NORMAL, WorkerResultStatus.Cancelled, "JobComponent " + Name + " was cancelled");
                }
                else
                {
                    // Finally, handle the case where the operation succeeded.
                    if (result == null)
                        result = new WorkerResult(WorkerResult.STATE_NORMAL, WorkerResultStatus.Ok, Name + " ran ok");
                }
            }

            // Check to see if the result is an ignorable exception and if so when the worker should be rescheduled
            long retryDelayMilliseconds = 0;
            bool ignoreException = CheckForIgnorableException(result, ref retryDelayMilliseconds);

            // log the worker result
            Trace.WriteLineIf(_jobSwitch.TraceInfo,
              string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\tJob\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}",
              DateTime.Now, Thread.CurrentThread.ManagedThreadId, "Worker",
              _worker.Description, result.Status,
              (result.WorkerException == null) ? null : result.WorkerException.GetType(),
              (result.WorkerException == null) ? string.Empty : result.WorkerException.Message,
              ignoreException ? "IGNORE" : "NOTIFY"));

            // determine how to proceed
            if (ignoreException)
            {
                // Tell the Job that this jobComponent has finished with an error
                FinishedWithError(this, new JobComponentFinishedEventArgs(this, result));

                // this was an exception that can be ignored, but we need to reschedule
                // the job with the scheduler that called us
                AgentScheduler scheduler = this.Job.Schedulers.GetLastScheduled();
                if (scheduler != null)
                {
                    TimeSpan retryDelayTimeSpan = new TimeSpan(TimeSpan.TicksPerMillisecond * retryDelayMilliseconds);
                    scheduler.RequestRescheduling(retryDelayTimeSpan);
                }
            }
            else
            {
                // this is a normal worker result that is not ignored, so let's request notification
                foreach (AgentNotifier notifier in Job.manager.Notifiers)
                    notifier.RequestNotification(result);

                // Tell the Job that this jobComponent has finished
                Finished(this, new JobComponentFinishedEventArgs(this, result));
            }

            progressPercentage = 0;
            isBusy = false;
            // store this result as the previous result
            _lastWorkerResult = result;
        }
Exemplo n.º 20
0
		static async Task DisposeSymbolInfoTask ()
		{
			symbolInfoTokenSrc.Cancel ();
			if (SymbolInfoTask != null) {
				try {
					var old = await SymbolInfoTask;
					if (old != null)
						old.Dispose ();
				} catch (OperationCanceledException) {
					// Ignore
				} catch (Exception ex) {
					LoggingService.LogError ("UpdateSymbolInfos failed", ex);
				}
			}
			symbolInfoTokenSrc = new CancellationTokenSource();
			lastResult = new WorkerResult ();
			SymbolInfoTask = null;
		}
Exemplo n.º 21
0
		static bool IsSameFilterStart (WorkerResult oldLastResult, WorkerResult newResult)
		{
			return oldLastResult.pattern != null && newResult.pattern.StartsWith (oldLastResult.pattern, StringComparison.Ordinal) && oldLastResult.filteredSymbols != null;
		}
Exemplo n.º 22
0
        /// <summary>
        /// Check's to see if the worker's result is an exception that can be ignored and the work rescheduled.</summary>
        protected virtual bool CheckForIgnorableException(WorkerResult result, ref long retryDelayMilliseconds)
        {
            // assume the worst
            bool ignorableException = true;

            // was there an exception?
            if ( result.Status != WorkerResultStatus.Exception )
            {
                // no exception - therefore not an ignorable exception
                ignorableException = false;
            }
            else
            {
                // there was an exception - search through the job's ignorable exeptions for a match
                AgentIgnorableException exception = _ignorableExceptions.Find(result.WorkerException);

                // if there was no match, search through the global ignorable exceptions for a match
                if ( exception == null )
                    exception = _globalIgnorableExceptions.Find(result.WorkerException);

                // was this an ignorable exception?
                if ( exception == null )
                {
                    // if there was still no match, then it was not an ignorable exception
                    ignorableException = false;
                }
                else
                {
                    // IGNORABLE EXCEPTION

                    // return the number of milliseconds to wait before re-trying after this exception
                    retryDelayMilliseconds = exception.RetryDelayMilliseconds;

                    // is this the same as the previous ignorable exception?
                    if ( lastIgnorableExceptionName != exception.Name )
                    {
                        // it is not the same - reset the previous name to this one and the count to 0
                        lastIgnorableExceptionName = exception.Name;
                        lastIgnorableExceptionCount = 0;
                    }

                    // increment the consecutive specific ignorable exception count
                    lastIgnorableExceptionCount++;

                    // log the ignorable exception count
                    Trace.WriteLineIf(_jobSwitch.TraceVerbose,
                        "Execpetion count: " + lastIgnorableExceptionCount.ToString());

                    // increment the consecutive total ignorable exception count
                    totalConsecutiveIgnorableExceptionsCount++;

                    // see if the consecutive counts exceeds the limits
                    if ( lastIgnorableExceptionCount > exception.MaximumConsecutiveIgnoreCount )
                    {
                        // specific one does exceed the limit, so it is no longer ignorable
                        ignorableException = false;
                    }
                    else if ( totalConsecutiveIgnorableExceptionsCount > MaximumConsecutiveExceptionIgnoreCount )
                    {
                    // total count exceeds the limit, so it is no longer ignorable
                    ignorableException = false;
                    }
                } // exception is ignorable
            } // result is an exception

            // is this an ignorable exception?
            if ( !ignorableException )
            {
                // it is NOT an ignorable exeption so reset the counts and previous exception name
                totalConsecutiveIgnorableExceptionsCount = 0;
                lastIgnorableExceptionCount = 0;
                lastIgnorableExceptionName = string.Empty;
            }

            // return the final status of whether this was ignorable or not
            return ignorableException;
        }
Exemplo n.º 23
0
		public override Task GetResults (ISearchResultCallback searchResultCallback, SearchPopupSearchPattern searchPattern, CancellationToken token)
		{
			return Task.Run (async delegate {
				if (searchPattern.Tag != null && !(typeTags.Contains (searchPattern.Tag) || memberTags.Contains (searchPattern.Tag)) || searchPattern.HasLineNumber)
					return;
				try {
					if (SymbolInfoTask == null)
						SymbolInfoTask = Task.FromResult (default(SymbolCache)).ContinueWith(t => GetSymbolInfos (token));
					var cache = await SymbolInfoTask.ConfigureAwait (false);
					var allTypes = cache.GetAllTypes (searchPattern.Tag, token);
					if (token.IsCancellationRequested)
						return;
					string toMatch = searchPattern.Pattern;
					var newResult = new WorkerResult ();
					newResult.pattern = searchPattern.Pattern;
					newResult.Tag = searchPattern.Tag;
					newResult.matcher = StringMatcher.GetMatcher (toMatch, false);
					newResult.FullSearch = toMatch.IndexOf ('.') > 0;
					var oldLastResult = lastResult;
					if (newResult.FullSearch && oldLastResult != null && !oldLastResult.FullSearch)
						oldLastResult = new WorkerResult ();
//					var now = DateTime.Now;

					AllResults (searchResultCallback, oldLastResult, newResult, allTypes, token);
					//newResult.results.SortUpToN (new DataItemComparer (token), resultsCount);
					lastResult = newResult;
					//					Console.WriteLine ((now - DateTime.Now).TotalMilliseconds);
				} catch {
					token.ThrowIfCancellationRequested ();
					throw;
				}
			}, token);
		}
		void AllResults (ISearchResultCallback searchResultCallback, WorkerResult lastResult, WorkerResult newResult, IReadOnlyList<DeclaredSymbolInfo> completeTypeList, CancellationToken token)
		{
			if (newResult.isGotoFilePattern)
				return;
			uint x = 0;
			// Search Types
			newResult.filteredSymbols = new List<DeclaredSymbolInfo> ();
			bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern, StringComparison.Ordinal) && lastResult.filteredSymbols != null;
			var allTypes = startsWithLastFilter ? lastResult.filteredSymbols : completeTypeList;
			foreach (var type in allTypes) {
				if (unchecked(x++) % 100 == 0 && token.IsCancellationRequested) {
					newResult.filteredSymbols = null;
					return;
				}

				if (type.Kind == DeclaredSymbolInfoKind.Constructor ||
				    type.Kind == DeclaredSymbolInfoKind.Module ||
				    type.Kind == DeclaredSymbolInfoKind.Indexer)
					continue;
				
				if (newResult.Tag != null) {
					if ((newResult.Tag == "type" || newResult.Tag == "t") && type.Kind != DeclaredSymbolInfoKind.Class && type.Kind != DeclaredSymbolInfoKind.Struct && type.Kind != DeclaredSymbolInfoKind.Interface && type.Kind != DeclaredSymbolInfoKind.Enum && type.Kind != DeclaredSymbolInfoKind.Delegate)
					    continue;
					
					if (newResult.Tag == "class" && type.Kind != DeclaredSymbolInfoKind.Class)
						continue;
				    if (newResult.Tag == "struct" && type.Kind != DeclaredSymbolInfoKind.Struct)
						continue;
				    if (newResult.Tag == "interface" && type.Kind != DeclaredSymbolInfoKind.Interface)
						continue;
				    if (newResult.Tag == "enum" && type.Kind != DeclaredSymbolInfoKind.Enum)
						continue;
				    if (newResult.Tag == "delegate" && type.Kind != DeclaredSymbolInfoKind.Delegate)
						continue;

					if ((newResult.Tag == "member" || newResult.Tag == "m") && type.Kind != DeclaredSymbolInfoKind.Method && type.Kind != DeclaredSymbolInfoKind.Property && type.Kind != DeclaredSymbolInfoKind.Field && type.Kind != DeclaredSymbolInfoKind.Event)
					    continue;
					if (newResult.Tag == "method" && type.Kind != DeclaredSymbolInfoKind.Method)
						continue;
					if (newResult.Tag == "property" && type.Kind != DeclaredSymbolInfoKind.Property)
						continue;
					if (newResult.Tag == "field" && type.Kind != DeclaredSymbolInfoKind.Field)
						continue;
					if (newResult.Tag == "event" && type.Kind != DeclaredSymbolInfoKind.Event)
						continue;
					
				}
				SearchResult curResult = newResult.CheckType (type);
				if (curResult != null) {
					newResult.filteredSymbols.Add (type);
					newResult.results.AddResult (curResult);
					searchResultCallback.ReportResult (curResult);
				}
			}
		}
Exemplo n.º 25
0
		public override void Initialize (Components.PopoverWindow popupWindow)
		{
			lastResult = new WorkerResult ();
		}
Exemplo n.º 26
0
        private static void ProcessQueue()
        {
            var stopWatch = new Stopwatch();

            Logger.Info("ProcessQueue started.");

            while (true)
            {
                var cmd = queue.Dequeue();

                if (cmd == null)
                {
                    continue;
                }

                var timeInQueue = DateTime.UtcNow - cmd.Submitted;

                Logger.Info("Job received after {0:N3} seconds in queue.", timeInQueue.TotalSeconds);

                if (timeInQueue > cmd.TimeoutPeriod)
                {
                    Logger.Warn("Job was in queue for longer than {0} seconds, skipping!", cmd.TimeoutPeriod.Seconds);
                    continue;
                }

                var startedOn = DateTime.UtcNow;
                stopWatch.Start();

                var assembly = Compiler.Compile(cmd);

                ExecutionResult result;
                if (assembly == null)
                {
                    result = new ExecutionResult
                             {
                                 Result = "[compiling of code failed]"
                             };
                }
                else
                {
                    using (var executor = new Sandbox())
                    {
                        result = executor.Execute(assembly, cmd.TimeoutPeriod);
                    }
                }

                stopWatch.Stop();
                var stoppedOn = DateTime.UtcNow;

                Logger.Info("Work completed in {0} milliseconds.", stopWatch.ElapsedMilliseconds);

                try
                {
                    var response = new WorkerResult
                                   {
                                       ExecutionId = cmd.ExecutionId,
                                       ClientId = cmd.ClientId,
                                       StartTime = startedOn,
                                       StopTime = stoppedOn,
                                       RunDuration = stopWatch.Elapsed,
                                       ProcessorTime = result.ProcessorTime,
                                       TotalMemoryAllocated = result.TotalMemoryAllocated,
                                       ConsoleOutput = result.ConsoleOutput,
                                       Result = result.Result
                                   };

                    var message = Serializer.Serialize(response);
                    messenger.Publish("workers:job-done", message);
                }
                catch (JsonSerializationException ex)
                {
                    Logger.ErrorException("An error occurred while attempting to serialize the JSON result.", ex);
                }

                stopWatch.Reset();
            }
        }
Exemplo n.º 27
0
 void AllResults(WorkerResult lastResult, WorkerResult newResult, CancellationToken token)
 {
     // Search files
     if (newResult.IncludeFiles) {
         newResult.filteredFiles = new List<ProjectFile> ();
         bool startsWithLastFilter = lastResult != null && lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern) && lastResult.filteredFiles != null;
         IEnumerable<ProjectFile> allFiles = startsWithLastFilter ? lastResult.filteredFiles : files;
         foreach (ProjectFile file in allFiles) {
             token.ThrowIfCancellationRequested ();
             SearchResult curResult = newResult.CheckFile (file);
             if (curResult != null) {
                 newResult.filteredFiles.Add (file);
                 newResult.results.Add (curResult);
             }
         }
     }
 }
Exemplo n.º 28
0
        private static void ProcessCommand(EvaluateCodeCommand cmd)
        {
            if (cmd == null)
            {
                return;
            }

            var now = DateTimeOffset.UtcNow;
            var timeInQueue = now - cmd.Submitted;

            Logger.Info("Job received after {0:N3} seconds in queue.", timeInQueue.TotalSeconds);

            if (now > cmd.Expires)
            {
                Logger.Warn("Job was in queue for longer than {0} seconds, skipping!", (cmd.Expires - cmd.Submitted).Seconds);
                return;
            }

            var startedOn = DateTimeOffset.UtcNow;
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            var assembly = Compiler.Compile(cmd);

            ExecutionResult result;
            if (assembly == null)
            {
                result = new ExecutionResult
                {
                    Result = "[compiling of code failed]"
                };
            }
            else
            {
                using (var executor = new Sandbox())
                {
                    result = executor.Execute(assembly, TimeSpan.FromSeconds(5));
                }
            }

            stopWatch.Stop();
            var stoppedOn = DateTime.UtcNow;

            Logger.Info("Work completed in {0} milliseconds.", stopWatch.ElapsedMilliseconds);

            var response = new WorkerResult
            {
                ClientId = cmd.ClientId,
                StartTime = startedOn,
                StopTime = stoppedOn,
                RunDuration = stopWatch.Elapsed,
                ProcessorTime = result.ProcessorTime,
                TotalMemoryAllocated = result.TotalMemoryAllocated,
                ConsoleOutput = result.ConsoleOutput,
                Result = result.Result
            };

            Bus.Instance.Publish(response);

            stopWatch.Reset();
        }