コード例 #1
0
        private void CheckRuntimeEnvironment(string str)
        {
            var callStack = new StackTrace();

            //Log("CheckRuntimeEnvironment - {0} Executing={1}", str, executing);
            if (executing)
            {
                var errorMsg = string.Format(
                    "Found out that grain {0} is already in the middle of execution."
                    + "\n Single threaded-ness violation!"
                    + "\n {1} \n Call Stack={2}",
                    _id, CaptureRuntimeEnvironment(), callStack);
                logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
                OrleansTaskScheduler.Instance.DumpSchedulerStatus();
                TraceLogger.Flush();
                //Environment.Exit(1);
                throw new Exception(errorMsg);
            }
            //Assert.IsFalse(executing, "Found out that this grain is already in the middle of execution. Single threaded-ness violation!");
            executing = true;
            //Log("CheckRuntimeEnvironment - Start sleep " + str);
            Thread.Sleep(10);
            executing = false;
            //Log("CheckRuntimeEnvironment - End sleep " + str);
        }
コード例 #2
0
ファイル: SiloHost.cs プロジェクト: sramkumarmca/orleans
        /// <summary>
        /// Report an error during silo startup.
        /// </summary>
        /// <remarks>
        /// Information on the silo startup issue will be logged to any attached Loggers,
        /// then a timestamped StartupError text file will be written to
        /// the current working directory (if possible).
        /// </remarks>
        /// <param name="exc">Exception which caused the silo startup issue.</param>
        public void ReportStartupError(Exception exc)
        {
            if (string.IsNullOrWhiteSpace(Name))
            {
                Name = "Silo";
            }

            var errMsg = "ERROR starting Orleans silo name=" + Name + " Exception=" + TraceLogger.PrintException(exc);

            if (logger != null)
            {
                logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc);
            }

            // Dump Startup error to a log file
            var          now        = DateTime.UtcNow;
            const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
            var          dateString = now.ToString(dateFormat, CultureInfo.InvariantCulture);
            var          startupLog = Name + "-StartupError-" + dateString + ".txt";

            try
            {
                File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg);
            }
            catch (Exception exc2)
            {
                if (logger != null)
                {
                    logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2);
                }
            }

            TraceLogger.Flush();
        }
コード例 #3
0
ファイル: GoFunc.cs プロジェクト: jinyuttt/NsqCli
        /// <summary>
        /// Run a new "goroutine".
        /// </summary>
        /// <param name="action">The method to execute.</param>
        /// <param name="threadName">The name to assign to the thread (optional).</param>
        public static void Run(Action action, string threadName)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            var t = new Thread(() =>
            {
                try
                {
                    action();
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    var logger = new TraceLogger();
                    logger.Output(LogLevel.Critical, string.Format("{0} - {1}", threadName, ex));
                    logger.Flush();
                    Trace.Flush();
                    throw;
                }
            }
                               );

            if (threadName != null)
            {
                t.Name = threadName;
            }

            t.IsBackground = true;
            t.Start();
        }
コード例 #4
0
        private async void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var itm = sender as MenuItem;

            switch (itm.Tag.ToString())
            {
            case "Copy":
                Clipboard.SetData(DataFormats.Text, _model.TagList);
                tagInput.FocusInput();
                break;

            case "Refresh":
                if (pBar.Visibility == System.Windows.Visibility.Hidden)
                {
                    pBar.Visibility = System.Windows.Visibility.Visible;
                    await _model.LoadSuggestedTagsAsync();

                    if (tagInput.Tags != null)
                    {
                        suggestedTags.Highlighter = new TextSplitter(tagInput.Tags);
                    }
                    pBar.Visibility = System.Windows.Visibility.Hidden;
                }
                Properties.Settings.Default.Save();
                TraceLogger.Flush();
                break;
            }
        }
コード例 #5
0
        private void Hyperlink_RequestLogNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            TraceLogger.Flush();
            Hyperlink hl = (Hyperlink)sender;

            string path = hl.NavigateUri.LocalPath;

            Process.Start(new ProcessStartInfo("notepad.exe", path));

            e.Handled = true;
        }
コード例 #6
0
        internal int EnqueuePagesForTagging(TagOperation op)
        {
            // bring suggestions up-to-date with new tags that may have been entered
            TagSuggestions.AddAll(from t in _pageTags where !TagSuggestions.ContainsKey(t.Key) select new HitHighlightedTagButtonModel()
            {
                TagName = t.TagName
            });
            TagSuggestions.Save();

            // covert scope to context
            TagContext ctx;

            switch (Scope)
            {
            default:
            case TaggingScope.CurrentNote:
                ctx = TagContext.CurrentNote;
                break;

            case TaggingScope.SelectedNotes:
                ctx = TagContext.SelectedNotes;
                break;

            case TaggingScope.CurrentSection:
                ctx = TagContext.CurrentSection;
                break;
            }

            IEnumerable <string> pageIDs = null;

            if (ScopesEnabled)
            {
                TagsAndPages tc = new TagsAndPages(OneNoteApp);
                tc.LoadPageTags(ctx);
                pageIDs = tc.Pages.Select(p => p.Key);
            }
            else
            {
                pageIDs = PagesToTag;
            }

            int enqueuedPages = 0;

            string[] pageTags = (from t in _pageTags.Values select t.TagName).ToArray();
            foreach (string pageID in pageIDs)
            {
                OneNoteApp.TaggingService.Add(new TaggingJob(pageID, pageTags, op));
                enqueuedPages++;
            }
            TraceLogger.Log(TraceCategory.Info(), "{0} page(s) enqueued for tagging with '{1}' using {2}", enqueuedPages, string.Join(";", pageTags), op);
            TraceLogger.Flush();
            return(enqueuedPages);
        }
コード例 #7
0
 private void CurrentDomain_DomainUnload(object sender, EventArgs e)
 {
     try
     {
         logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
                     String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
         TraceLogger.Flush();
     }
     catch (Exception)
     {
         // just ignore, make sure not to throw from here.
     }
 }
コード例 #8
0
        /// <summary>
        /// Extract tags from page descriptors.
        /// </summary>
        /// <param name="pageDescriptors">
        /// XML document describing pages in the OneNote hierarchy or search result.
        /// </param>
        /// <param name="selectedPagesOnly">true to process only pages selected by user</param>
        /// <param name="omitUntaggedPages">drip untagged pages</param>
        internal void ExtractTags(XDocument pageDescriptors, bool selectedPagesOnly, bool omitUntaggedPages = false)
        {
            // parse the search results
            _tags.Clear();
            _pages.Clear();
            try
            {
                XNamespace one = pageDescriptors.Root.GetNamespaceOfPrefix("one");

                Dictionary <string, TagPageSet> tags = new Dictionary <string, TagPageSet>();
                foreach (XElement page in pageDescriptors.Descendants(one.GetName("Page")))
                {
                    TaggedPage tp = new TaggedPage(page);
                    if (selectedPagesOnly && !tp.IsSelected)
                    {
                        continue;
                    }
                    // assign Tags
                    int tagcount = 0;
                    foreach (string tagname in tp.TagNames)
                    {
                        tagcount++;
                        TagPageSet t;

                        if (!tags.TryGetValue(tagname, out t))
                        {
                            t = new TagPageSet(tagname);
                            tags.Add(tagname, t);
                        }
                        t.AddPage(tp);
                        tp.Tags.Add(t);
                    }
                    if (!omitUntaggedPages || tagcount > 0)
                    {
                        _pages.Add(tp.Key, tp);
                    }
                }
                // bulk update for performance reasons
                _tags.UnionWith(tags.Values);
                TraceLogger.Log(TraceCategory.Info(), "Extracted {0} tags from {1} pages.", _tags.Count, _pages.Count);
            }
            catch (Exception ex)
            {
                TraceLogger.Log(TraceCategory.Error(), "Parsing Hierarchy data failed: {0}", ex);
                TraceLogger.Flush();
            }
        }
コード例 #9
0
        /// <summary>
        /// Run the background tagger.
        /// </summary>
        /// <returns></returns>
        public Task Run()
        {
            TaskFactory       tf     = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
            CancellationToken cancel = _cancel.Token;

            return(tf.StartNew(() =>
            {
                TraceLogger.Log(TraceCategory.Info(), "Background tagging service started");
                try
                {
                    OneNotePageProxy lastPage = null;
                    while (!_jobs.IsCompleted)
                    {
                        TaggingJob j = _jobs.Take();
                        cancel.ThrowIfCancellationRequested();
                        try
                        {
                            lastPage = j.Execute(_onenote, lastPage);
                            if (lastPage != null && _jobs.Count == 0)
                            { // no more pending pages - must update the last one and stop carrying forward
                                lastPage.Update();
                                lastPage = null;
                            }
                        }
                        catch (Exception e)
                        {
                            lastPage = null;
                            TraceLogger.ShowGenericErrorBox("page tagging failed", e);
                        }
                    }
                }
                catch (InvalidOperationException)
                {
                    TraceLogger.Log(TraceCategory.Warning(), "Background tagging job queue depleted");
                    TraceLogger.Flush();
                }
                catch (OperationCanceledException)
                {
                    TraceLogger.Log(TraceCategory.Warning(), "Background tagging canceled");
                    TraceLogger.Flush();
                }
            }, cancel));
        }
コード例 #10
0
ファイル: LoggerTest.cs プロジェクト: marcin-waligora/orleans
 public void Dispose()
 {
     TraceLogger.Flush();
     TraceLogger.UnInitialize();
 }
コード例 #11
0
 public void TestCleanup()
 {
     TraceLogger.Flush();
     TraceLogger.UnInitialize();
 }
コード例 #12
0
        /// <summary>
        /// Add items to the sorted collection in batches.
        /// </summary>
        /// <remarks>
        /// Groups the given items into contiguous ranges of batches and adds each batch at
        /// once, firing one change notification per batch.
        /// </remarks>
        /// <param name="items">items to add</param>
        internal void AddAll(IEnumerable <TValue> items)
        {
            List <KeyValuePair <int, TValue> > toAdd = new List <KeyValuePair <int, TValue> >();

            foreach (TValue item in items)
            {
                if (!_dictionary.ContainsKey(item.Key))
                {
                    // lookup insertion point
                    int insertionPoint = _sortedList.BinarySearch(new KeyValuePair <TSort, TValue>(item.SortKey, item), _comparer);
#if DEBUG
                    Debug.Assert(insertionPoint < 0, string.Format("Item with key {0} already present in list at index {1}", item.Key, insertionPoint));
#endif
                    if (insertionPoint < 0)
                    {
                        _dictionary.Add(item.Key, item);
                        toAdd.Add(new KeyValuePair <int, TValue>(~insertionPoint, item));
                    }
                    else
                    {
                        TraceLogger.Log(TraceCategory.Error(), "List is inconsistency! Attempting to recover");
                        TraceLogger.Flush();
                        _dictionary.Add(item.Key, item);
                    }
                }
            }
            toAdd.Sort(_indexComparer);

            // process the sorted list of items to add in reverse order so that we do not
            // have to correct indices

            while (toAdd.Count > 0)
            {
                List <KeyValuePair <TSort, TValue> > batch = new List <KeyValuePair <TSort, TValue> >();

                int lastItemIndex = toAdd.Count - 1;
                KeyValuePair <int, TValue> itemToAdd = toAdd[lastItemIndex];

                // add the first item to the batch
                int insertionPoint = itemToAdd.Key;
                batch.Add(new KeyValuePair <TSort, TValue>(itemToAdd.Value.SortKey, itemToAdd.Value));

                toAdd.RemoveAt(lastItemIndex);
                lastItemIndex = toAdd.Count - 1;

                while (lastItemIndex >= 0 && toAdd[lastItemIndex].Key == insertionPoint)
                {
                    itemToAdd = toAdd[lastItemIndex];
                    batch.Add(new KeyValuePair <TSort, TValue>(itemToAdd.Value.SortKey, itemToAdd.Value));

                    toAdd.RemoveAt(lastItemIndex);
                    lastItemIndex = toAdd.Count - 1;
                }

                batch.Sort(_comparer);

                _sortedList.InsertRange(insertionPoint, batch);

                if (CollectionChanged != null)
                {
                    NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,
                                                                                                 (from b in batch select b.Value).ToList(),
                                                                                                 insertionPoint);

                    CollectionChanged(this, args);
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Remove or rename tag from suggestions when user control is tapped.
        /// </summary>
        /// <param name="sender">user control emitting this event</param>
        /// <param name="e">     event details</param>
        private void Tag_Action(object sender, RoutedEventArgs e)
        {
            var rt     = sender as RemovableTag;
            var rt_mdl = rt.DataContext as RemovableTagModel;

            string[] toRemove = new string[] { rt_mdl.Key };
            if ("DeleteTag".Equals(rt.Tag))
            {
                _model.SuggestedTags.RemoveAll(toRemove);
                // schedule all pages with this tag for tag removal
                if (rt_mdl.Tag != null)
                {
                    foreach (var tp in rt_mdl.Tag.Pages)
                    {
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, toRemove, TagOperation.SUBTRACT));
                    }
                    suggestedTags.Notification = rt_mdl.Tag.Pages.Count == 0 ? Properties.Resources.TagEditor_Popup_NothingTagged : string.Format(Properties.Resources.TagEditor_Popup_TaggingInProgress, rt_mdl.Tag.Pages.Count);
                    TraceLogger.Log(TraceCategory.Info(), "{0} page(s) enqueued for background tagging; Operation SUBTRACT {1}", rt_mdl.Tag.Pages.Count, toRemove[0]);
                }
                else
                {
                    suggestedTags.Notification = Properties.Resources.TagEditor_Popup_NothingTagged;
                }
            }
            else if ("RenameTag".Equals(rt.Tag))
            {
                _model.SuggestedTags.RemoveAll(toRemove);

                string[] newTagNames = (from tn in OneNotePageProxy.ParseTags(rt_mdl.LocalName) select TagFormatter.Format(tn)).ToArray();

                // create new tag models unless they already exist
                List <RemovableTagModel> newTagModels = new List <RemovableTagModel>();
                foreach (var newName in newTagNames)
                {
                    RemovableTagModel tagmodel;
                    if (!_model.SuggestedTags.TryGetValue(newName, out tagmodel))
                    {
                        tagmodel = new RemovableTagModel()
                        {
                            Tag = new TagPageSet(newName)
                        };
                        newTagModels.Add(tagmodel);
                    }
                    else if (tagmodel.Tag == null && rt_mdl.Tag != null)
                    {
                        tagmodel.Tag = new TagPageSet(newName);
                    }

                    if (rt_mdl.Tag != null)
                    {
                        // copy the pages into the new tag and update the tag count
                        foreach (var pg in rt_mdl.Tag.Pages)
                        {
                            tagmodel.Tag.Pages.Add(pg);
                        }
                        tagmodel.UseCount = tagmodel.Tag.Pages.Count;
                    }
                }
                _model.SuggestedTags.AddAll(newTagModels);

                if (rt_mdl.Tag != null)
                {
                    // remove the old tag and add new tag to the pages
                    foreach (var tp in rt_mdl.Tag.Pages)
                    {
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, toRemove, TagOperation.SUBTRACT));
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, newTagNames, TagOperation.UNITE));
                    }
                    suggestedTags.Notification = rt_mdl.Tag.Pages.Count == 0 ? Properties.Resources.TagEditor_Popup_NothingTagged : string.Format(Properties.Resources.TagEditor_Popup_TaggingInProgress, rt_mdl.Tag.Pages.Count);
                    TraceLogger.Log(TraceCategory.Info(), "{0} page(s) enqueued for background tagging; Operation UNITE {1} SUBTRACT {2}", rt_mdl.Tag.Pages.Count, string.Join(",", newTagNames), toRemove[0]);
                }
                else
                {
                    suggestedTags.Notification = Properties.Resources.TagEditor_Popup_NothingTagged;
                }
            }
            TraceLogger.Flush();
            _model.SaveChanges();
        }