Пример #1
0
        public double Run(double[][] observations_db, int[] class_labels)
        {
            int class_count = mClassifier.ClassCount;

            double[] logLikelihood = new double[class_count];

            int K = class_labels.Length;

            DiagnosticsHelper.Assert(observations_db.Length == K);

            int[] class_label_counts = new int[class_count];

            Parallel.For(0, class_count, i =>
            {
                IUnsupervisedLearning teacher = mAlgorithmEntity(i);

                List <int> match_record_index_set = new List <int>();
                for (int k = 0; k < K; ++k)
                {
                    if (class_labels[k] == i)
                    {
                        match_record_index_set.Add(k);
                    }
                }

                int K2 = match_record_index_set.Count;

                class_label_counts[i] = K2;

                if (K2 != 0)
                {
                    double[][] observations_subdb = new double[K2][];
                    for (int k = 0; k < K2; ++k)
                    {
                        int record_index      = match_record_index_set[k];
                        observations_subdb[k] = observations_db[record_index];
                    }


                    logLikelihood[i] = teacher.Run(observations_subdb);
                }
            });

            if (mEmpirical)
            {
                for (int i = 0; i < class_count; i++)
                {
                    mClassifier.Priors[i] = (double)class_label_counts[i] / K;
                }
            }

            //if (mRejection)
            //{
            //    mClassifier.Threshold = Threshold();
            //}

            return(logLikelihood.Sum());
        }
Пример #2
0
        /// <summary />
        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            base.OnSessionEnding(e);

            DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                         string.Format(CultureInfo.InvariantCulture,
                                                       "Session Ending: {0}",
                                                       e.ReasonSessionEnding));
        }
Пример #3
0
        protected virtual void Configure()
        {
            DiagnosticsHelper.ConfigureDiagnosticMonitor(_diagnosticsLogLevel);
            _logger.Info("WebRole.OnStart called");
            AzureConfig.ConfigureRole();

            var storageAccount = CloudStorageAccount.FromConfigurationSetting(Constants.StorageConnectionStringKey);

            Container = AutofacConfig.BuildContainer(storageAccount, _logFactory, _logLevel);
        }
        private void ValidateStorageAccountKey()
        {
            this.StorageAccountKey = this.StorageAccountKey ??
                                     DiagnosticsHelper.InitializeStorageAccountKey(this.StorageClient, this.StorageAccountName, this.DiagnosticsConfigurationPath);

            if (string.IsNullOrEmpty(this.StorageAccountKey))
            {
                throw new ArgumentException(Resources.DiagnosticsExtensionNullStorageAccountKey);
            }
        }
Пример #5
0
 public Task <DiagnosticsResults> RunAsync()
 {
     _logger.LogInformation("Running diagnostics tests");
     return(DiagnosticsHelper.RunDiagnosticsTests(new [] {
         (Func <Task>)_component.PerformHealthCheckAsync,
         (Func <Task>)_genericSampleComponentType1.PerformHealthCheckAsync,
         (Func <Task>)_genericSampleComponentType2.PerformHealthCheckAsync,
         LocalTestFunc
     }, parallel: true));
 }
        private void InitializeStorageAccountName()
        {
            this.StorageAccountName = this.StorageAccountName ??
                                      DiagnosticsHelper.InitializeStorageAccountName(this.StorageContext, this.DiagnosticsConfigurationPath);

            if (string.IsNullOrEmpty(this.StorageAccountName))
            {
                throw new ArgumentException(Properties.Resources.DiagnosticsExtensionNullStorageAccountName);
            }
        }
Пример #7
0
 /// <summary>
 /// Stop logging.
 /// </summary>
 public void StopLogging()
 {
     if (m_Listener != null)
     {
         DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Logging disabled");
         Trace.Listeners.Remove(m_Listener);
         m_Listener.Flush();
         m_Listener.Close();
         m_Listener = null;
     }
 }
Пример #8
0
    /// <summary>
    /// Easy to use Exception logger that shows the user a custom error message
    /// </summary>
    /// <param name="exception">Exception that occurs</param>
    /// <param name="dialogTitle">MessageDialog's title</param>
    /// <param name="dialogMessage">MessageDialog's message</param>
    /// <returns>Task</returns>
    public static async Task LogExceptionWithUserMessage(this Exception exception, string dialogMessage, string dialogTitle)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        }

        Trace.TraceError($"LogExceptionWithUserMessage {exception.Message}");

        if (string.IsNullOrEmpty(dialogTitle))
        {
            throw new ArgumentNullException(nameof(dialogTitle));
        }

        if (string.IsNullOrEmpty(dialogMessage))
        {
            throw new ArgumentNullException(nameof(dialogMessage));
        }

        if (string.IsNullOrEmpty(dialogMessage))
        {
            dialogMessage = "Sorry, there has been an unexpected error. If you'd like to send a technical summary to the app development team, click Yes.";
        }

        var exceptionMessage = CreateErrorMessage(exception);

        // Manages and saves local log files
        await LogFileWriteAsync(exceptionMessage);

        var md = new MessageDialog(dialogMessage, dialogTitle);

        md.Commands.Add(new UICommand("yes (summary)"));
        md.Commands.Add(new UICommand("yes (full)"));
        md.Commands.Add(new UICommand("no"));

        var result = await md.ShowAsync();

        switch (result.Label)
        {
        case "yes (summary)":
            await FeedbackHelpers.Current.EmailErrorMessageAsync(exceptionMessage);

            break;

        case "yes (full)":
        {
            var text = await DiagnosticsHelper.DumpAsync(exception);

            await FeedbackHelpers.Current.EmailErrorMessageAsync(exceptionMessage + "\r\n\n" + text);

            break;
        }
        }
    }
Пример #9
0
        public static bool VerifyArchitecture(ImageFileMachine architecture, string exePath)
        {
            bool matches = false;

            if (exePath == null)
            {
                return(false);
            }

            try
            {
                if (File.Exists(exePath))
                {
                    int machineType = 0;

                    using (FileStream fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader br = new BinaryReader(fs);

                        fs.Seek(0x3c, SeekOrigin.Begin);
                        int peOffset = br.ReadInt32();
                        fs.Seek(peOffset, SeekOrigin.Begin);
                        uint peHead = br.ReadUInt32();
                        if (peHead == 0x00004550)
                        {
                            machineType = br.ReadUInt16();
                        }
                    }

                    switch (architecture)
                    {
                    case ImageFileMachine.AMD64:
                        matches = machineType == 0x8664;
                        break;

                    case ImageFileMachine.I386:
                        matches = machineType == 0x14c;
                        break;

                    default:
                        // not supported
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "VerifyArchitecture Failed",
                                               ex);
            }

            return(matches);
        }
        private void ValidateStorageAccountEndpoint()
        {
            this.StorageAccountEndpoint = this.StorageAccountEndpoint ??
                                          DiagnosticsHelper.InitializeStorageAccountEndpoint(this.StorageAccountName, this.StorageAccountKey, this.StorageClient,
                                                                                             this.StorageContext, this.DiagnosticsConfigurationPath, this.DefaultContext);

            if (string.IsNullOrEmpty(this.StorageAccountEndpoint))
            {
                throw new ArgumentNullException(Resources.DiagnosticsExtensionNullStorageAccountEndpoint);
            }
        }
Пример #11
0
 void runWinQualSyncTask()
 {
     try
     {
         m_TaskParameters.ControllerContext.RunSynchronizeTask(null, false, false, false, null, true, m_IsRetryRequest); // Don't wait for completion.
     }
     catch (System.Exception ex)
     {
         DiagnosticsHelper.LogException(DiagSeverity.Information, "Unable to start scheduled Win Qual Sync service", ex);
     }
 }
Пример #12
0
        /// <summary>
        /// Deletes the current license.
        /// </summary>
        private void deleteLicense()
        {
            m_LicenseData = new StackHashLicenseData(false, null, null, null, 0, 0, new DateTime(0), false);

            if (File.Exists(m_LicenseFileName))
            {
                File.Delete(m_LicenseFileName);
            }

            DiagnosticsHelper.LogMessage(DiagSeverity.Information, "License deleted");
        }
Пример #13
0
 void runPurgeTask()
 {
     try
     {
         DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Purge Timer Task: Attempting to start scheduled Purge task");
         m_TaskParameters.ControllerContext.RunPurgeTask(m_TaskParameters.ClientData); // Don't wait for completion.
     }
     catch (System.Exception ex)
     {
         DiagnosticsHelper.LogException(DiagSeverity.Information, "Unable to start scheduled Purge task", ex);
     }
 }
Пример #14
0
        /// <summary>
        /// Opens services associated with the internal or external host.
        /// An internal host uses TCP for comms on an intranet along with HTTP to publish
        /// the metadata (mex - metadata exchange).
        /// An external host exposes services via HTTP to the internet.
        /// On Vista a service cannot use HTTP directly because the whole http:\ namespace is
        /// owned by AdminUser. Therefore you need to reassign say http:\\localhost\stackhash using
        /// netsh http add urlacl url=http:\\localhost\stackhash /user=NetworkService
        /// </summary>
        /// <param name="internalHost">True - internal contract is registered - false - external contract registered.</param>

        public static void OpenServiceHosts(bool internalHost)
        {
            if (internalHost)
            {
                // Get the environment variables that can override the STACKHASHPORT.
                //String portString = Environment.GetEnvironmentVariable("STACKHASHPORT");
                //int port = -1;
                //try
                //{
                //    if (!String.IsNullOrEmpty(portString))
                //    {
                //        port = Int32.Parse(portString, CultureInfo.InvariantCulture);
                //        DiagnosticsHelper.LogMessage(DiagSeverity.Information, "STACKHASHPORT=" + port.ToString(CultureInfo.InvariantCulture));
                //    }
                //}
                //catch (System.Exception ex)
                //{
                //    DiagnosticsHelper.LogException(DiagSeverity.ApplicationFatal, "STACKHASHPORT invalid - defaulting to port 9000", ex);
                //}


                if (s_InternalServiceHost == null)
                {
                    try
                    {
                        s_InternalServiceHost = new ServiceHost(typeof(InternalService));

                        if (s_InternalServiceHost.BaseAddresses != null)
                        {
                            foreach (Uri baseAddress in s_InternalServiceHost.BaseAddresses)
                            {
                                DiagnosticsHelper.LogMessage(DiagSeverity.Information, "WCF Using base address: " + baseAddress.ToString());
                            }
                        }

                        s_InternalServiceHost.Open();
                    }
                    catch (AddressAlreadyInUseException ex)
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.ApplicationFatal, "WCF port is already in use.", ex);
                        throw;
                    }
                }
            }
            else
            {
                if (s_ExternalServiceHost == null)
                {
                    s_ExternalServiceHost = new ServiceHost(typeof(ExternalService));
                    s_ExternalServiceHost.Open();
                }
            }
        }
Пример #15
0
        public void UpdateScriptFile()
        {
            bool saveAutoScript = false;
            bool fileExists     = File.Exists(m_ScriptFileName);

            if (fileExists)
            {
                // Load in the script and check the version number. If there is an error during load
                // then just create a new copy of the file.
                try
                {
                    StackHashScriptSettings thisScript = StackHashScriptSettings.Load(m_ScriptFileName);
                    saveAutoScript = !IsScriptCurrent(thisScript);
                }
                catch (System.Exception ex)
                {
                    String message = String.Format(CultureInfo.InvariantCulture, "Failed to load script {0} - Reconstructing", ScriptName);
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, message, ex);
                    saveAutoScript = true;
                }
            }
            else
            {
                saveAutoScript = true;
            }

            FileAttributes currentAttributes;

            if (saveAutoScript)
            {
                if (fileExists)
                {
                    currentAttributes = File.GetAttributes(m_ScriptFileName);

                    // Turn off the readonly permission so the file can be updated.
                    if ((currentAttributes & FileAttributes.ReadOnly) != 0)
                    {
                        // Clear the read only flag.
                        File.SetAttributes(m_ScriptFileName, currentAttributes & ~FileAttributes.ReadOnly);
                    }
                }
                StackHashScriptSettings autoScript = GenerateScript();
                autoScript.Save(m_ScriptFileName);
            }

            // Make sure the file is marked read only so the client can't delete it.
            currentAttributes = File.GetAttributes(m_ScriptFileName);
            if ((currentAttributes & FileAttributes.ReadOnly) == 0)
            {
                // Set the read only flag.
                File.SetAttributes(m_ScriptFileName, currentAttributes | FileAttributes.ReadOnly);
            }
        }
Пример #16
0
        public void StartLogging()
        {
            // Don't start the listener if already started.
            if (m_Listener == null)
            {
                m_Listener        = new TextWriterTraceListener();
                m_Listener.Writer = System.Console.Out;
                Trace.Listeners.Add(m_Listener);

                DiagnosticsHelper.LogApplicationStartup();
            }
        }
Пример #17
0
        public bool CabMatchesSearchCriteria(StackHashProduct product,
                                             StackHashFile file, StackHashEvent theEvent, StackHashCab cab, StackHashSearchCriteria searchCriteria)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (theEvent == null)
            {
                throw new ArgumentNullException("theEvent");
            }
            if (cab == null)
            {
                throw new ArgumentNullException("cab");
            }
            if (searchCriteria == null)
            {
                throw new ArgumentNullException("searchCriteria");
            }

            // Get a list of script result files for this cab.
            StackHashScriptResultFiles resultFiles = GetResultFiles(product, file, theEvent, cab);

            if ((resultFiles == null) || (resultFiles.Count == 0))
            {
                return(false);
            }

            foreach (StackHashScriptResultFile resultFile in resultFiles)
            {
                try
                {
                    StackHashScriptResult resultFileData = GetResultFileData(product, file, theEvent, cab, resultFile.ScriptName);

                    if (resultFileData.Search(searchCriteria))
                    {
                        return(true);
                    }
                }
                catch (System.Exception ex)
                {
                    // Don't allow corrupt files to stop the search.
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Corrupt or missing results file: " + resultFile.ScriptName +
                                                   " for cab " + cab.Id.ToString(CultureInfo.InvariantCulture), ex);
                }
            }

            return(false);
        }
        public void MapDiagnosticSeverityTest()
        {
            var level = ScriptFileMarkerLevel.Error;

            Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error);
            level = ScriptFileMarkerLevel.Warning;
            Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Warning);
            level = ScriptFileMarkerLevel.Information;
            Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Information);
            level = (ScriptFileMarkerLevel)100;
            Assert.Equal(DiagnosticsHelper.MapDiagnosticSeverity(level), DiagnosticSeverity.Error);
        }
Пример #19
0
        // ----- AddString ----------------------------------------------------------------------------

        /// <summary>
        /// Adds a text string to this path.
        /// </summary>
        public void AddString(string s, XFontFamily family, XFontStyle style, double emSize, XPoint origin,
                              XStringFormat format)
        {
            try
            {
                DiagnosticsHelper.HandleNotImplemented("XGraphicsPath.AddString");
            }
            catch
            {
                throw;
            }
        }
Пример #20
0
        private static void DisplayUnhandledExceptionAndDie(Exception ex)
        {
            DiagnosticsHelper.LogException(DiagSeverity.ApplicationFatal,
                                           "Unhandled Exception",
                                           ex);

            try
            {
                Window owner = null;
                if (Application.Current != null)
                {
                    owner = Application.Current.MainWindow;
                }

                StackHashMessageBox.Show(owner,
                                         UnhandledExceptionMessage,
                                         UnhandledExceptionTitle,
                                         StackHashMessageBoxType.Ok,
                                         StackHashMessageBoxIcon.Error,
                                         ex,
                                         StackHashService.StackHashServiceErrorCode.NoError);
            }
            catch (XamlParseException xex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.ApplicationFatal,
                                               "XamlParseException displaying fatal error message",
                                               xex);

                try
                {
                    // this will happen if the XAML window can't be created for some reason -
                    // try showing a regular message box in this case
                    MessageBox.Show(UnhandledExceptionMessage,
                                    UnhandledExceptionTitle,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Hand);
                }
                catch { }
            }
            catch { }
            finally
            {
                try
                {
                    if (App.Current != null)
                    {
                        App.Current.Shutdown(1);
                    }
                }
                catch { }
            }
        }
        private string GenerateCompiledFileAndReturnBuildOutputMessage(string bicepFilePath, DocumentUri documentUri)
        {
            string compiledFilePath = PathHelper.GetDefaultBuildOutputPath(bicepFilePath);
            string compiledFile     = Path.GetFileName(compiledFilePath);

            // If the template exists and contains bicep generator metadata, we can go ahead and replace the file.
            // If not, we'll fail the build.
            if (File.Exists(compiledFilePath) && !TemplateContainsBicepGeneratorMetadata(File.ReadAllText(compiledFilePath)))
            {
                return("Build failed. The file \"" + compiledFile + "\" already exists and was not generated by Bicep. If overwriting the file is intended, delete it manually and retry the Build command.");
            }

            var fileUri = documentUri.ToUri();
            RootConfiguration?configuration = null;

            try
            {
                configuration = this.configurationManager.GetConfiguration(fileUri);
            }
            catch (ConfigurationException exception)
            {
                // Fail the build if there's configuration errors.
                return(exception.Message);
            }

            CompilationContext?context = compilationManager.GetCompilation(fileUri);
            Compilation        compilation;

            if (context is null)
            {
                SourceFileGrouping sourceFileGrouping = SourceFileGroupingBuilder.Build(this.fileResolver, this.moduleDispatcher, new Workspace(), fileUri, configuration);
                compilation = new Compilation(features, namespaceProvider, sourceFileGrouping, configuration, new LinterAnalyzer(configuration));
            }
            else
            {
                compilation = context.Compilation;
            }

            KeyValuePair <BicepFile, IEnumerable <IDiagnostic> > diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile()
                                                                                     .FirstOrDefault(x => x.Key.FileUri == fileUri);

            if (diagnosticsByFile.Value.Any(x => x.Level == DiagnosticLevel.Error))
            {
                return("Build failed. Please fix below errors:\n" + DiagnosticsHelper.GetDiagnosticsMessage(diagnosticsByFile));
            }

            using var fileStream = new FileStream(compiledFilePath, FileMode.Create, FileAccess.ReadWrite);
            var        emitter = new TemplateEmitter(compilation.GetEntrypointSemanticModel(), emitterSettings);
            EmitResult result  = emitter.Emit(fileStream);

            return("Build succeeded. Created file " + compiledFile);
        }
        public void TestGetEventHubFromXmlConfig()
        {
            var table = new Hashtable();

            DiagnosticsHelper.AddEventHubPrivateConfig(table, @"Resources\Diagnostics\diagnostics.wadcfgx");

            var eventHubConfig = table["EventHub"] as Hashtable;

            Assert.NotNull(eventHubConfig);
            Assert.Equal(eventHubConfig["Url"], "Url");
            Assert.Equal(eventHubConfig["SharedAccessKeyName"], "sasKeyName");
            Assert.Equal(eventHubConfig["SharedAccessKey"], "sasKey");
        }
Пример #23
0
        private void AddNoteToParagraph(StackHashNoteEntry note, ref Paragraph para)
        {
            // create header
            Span noteHeaderSpan = new Span();

            noteHeaderSpan.FontWeight = FontWeights.Bold;
            noteHeaderSpan.Inlines.Add(new Run(string.Format(CultureInfo.CurrentCulture,
                                                             Properties.Resources.NotesControl_HeaderName,
                                                             note.User)));

            Span noteInfoSpan = new Span();

            noteInfoSpan.Foreground = Brushes.Gray;
            noteInfoSpan.Inlines.Add(new Run(string.Format(CultureInfo.CurrentCulture,
                                                           Properties.Resources.NotesControl_HeaderDetails,
                                                           (string)_dateTimeDisplayConverter.Convert(note.TimeOfEntry, typeof(string), null, CultureInfo.CurrentCulture),
                                                           note.Source)));

            // create note
            Run noteRun = new Run(note.Note);

            Hyperlink linkEditNote = new Hyperlink(new Run("Edit"));

            linkEditNote.Tag              = note;
            linkEditNote.NavigateUri      = new Uri("http://www.stackhash.com/");
            linkEditNote.RequestNavigate += new RequestNavigateEventHandler(linkEditNote_RequestNavigate);

            para.Inlines.Add(noteHeaderSpan);
            para.Inlines.Add(new Run(" "));
            para.Inlines.Add(noteInfoSpan);
            para.Inlines.Add(new Run(" ("));
            para.Inlines.Add(linkEditNote);
            para.Inlines.Add(new Run(")"));
            para.Inlines.Add(new LineBreak());
            para.Inlines.Add(noteRun);
            para.Inlines.Add(new LineBreak());
            para.Inlines.Add(new LineBreak());

            // add hyperlinks to note run
            try
            {
                while (ProcessInlines(para.Inlines.FirstInline))
                {
                }
                ;
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning, "AddNoteToParagraph failed", ex);
            }
        }
Пример #24
0
        /// <summary>
        /// Process a cab note table update. This may indicate a new item or the change to an existing item.
        /// </summary>
        private bool processCabNoteUpdate(StackHashBugTrackerUpdate update)
        {
            // Get the associated product and file information.
            StackHashProduct   product  = m_Index.GetProduct((int)update.ProductId);
            StackHashFile      file     = m_Index.GetFile(product, (int)update.FileId);
            StackHashEvent     theEvent = m_Index.GetEvent(product, file, new StackHashEvent((int)update.EventId, update.EventTypeName));
            StackHashCab       cab      = m_Index.GetCab(product, file, theEvent, (int)update.CabId);
            StackHashNoteEntry note     = m_Index.GetCabNote((int)update.ChangedObjectId);

            if ((product == null) || (file == null) || (theEvent == null) || (cab == null) || (note == null))
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Cab Note: Inconsistent Update Table Entry");
                return(false);
            }

            BugTrackerProduct   btProduct      = new BugTrackerProduct(product.Name, product.Version, product.Id);
            BugTrackerFile      btFile         = new BugTrackerFile(file.Name, file.Version, file.Id);
            NameValueCollection eventSignature = new NameValueCollection();

            foreach (StackHashParameter param in theEvent.EventSignature.Parameters)
            {
                eventSignature.Add(param.Name, param.Value);
            }

            BugTrackerEvent btEvent = new BugTrackerEvent(theEvent.BugId, theEvent.PlugInBugId, theEvent.Id, theEvent.EventTypeName,
                                                          theEvent.TotalHits, eventSignature);

            NameValueCollection analysis = new NameValueCollection();

            analysis.Add("DotNetVersion", cab.DumpAnalysis.DotNetVersion);
            analysis.Add("MachineArchitecture", cab.DumpAnalysis.MachineArchitecture);
            analysis.Add("OSVersion", cab.DumpAnalysis.OSVersion);
            analysis.Add("ProcessUpTime", cab.DumpAnalysis.ProcessUpTime);
            analysis.Add("SystemUpTime", cab.DumpAnalysis.SystemUpTime);

            String        cabFileName = m_Index.GetCabFileName(product, file, theEvent, cab);
            BugTrackerCab btCab       = new BugTrackerCab(cab.Id, cab.SizeInBytes, cab.CabDownloaded, cab.Purged, analysis, cabFileName);

            BugTrackerNote btCabNote = new BugTrackerNote(note.TimeOfEntry, note.Source, note.User, note.Note);

            String newBugId = null;

            if (update.TypeOfChange == StackHashChangeType.NewEntry)
            {
                newBugId = m_TaskParameters.PlugInContext.CabNoteAdded(null, BugTrackerReportType.Automatic, btProduct, btFile, btEvent, btCab, btCabNote);
            }

            setPlugInBugReference(product, file, theEvent, newBugId);

            return(true);
        }
Пример #25
0
        public override void EntryPoint()
        {
            bool loggedOn = false;

            try
            {
                SetTaskStarted(m_TaskParameters.ErrorIndex);


                // Don't allow the PC to go into sleep mode while syncing.
                StackHashUtilities.SystemInformation.DisableSleep();

                try
                {
                    // Log on to WinQual.
                    m_WinQualServices.LogOn(m_TaskParameters.WinQualSettings.UserName, m_TaskParameters.WinQualSettings.Password);

                    // Upload the file.
                    m_WinQualServices.UploadFile(m_TaskParameters.FileName);
                }
                finally
                {
                    try
                    {
                        if (loggedOn)
                        {
                            m_WinQualServices.LogOff();
                        }
                    }
                    catch (System.Exception ex)
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.Warning, "Failed to log off Win Qual", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                LastException = ex;
            }
            finally
            {
                if (File.Exists(m_TaskParameters.FileName))
                {
                    File.Delete(m_TaskParameters.FileName);
                }

                StackHashUtilities.SystemInformation.EnableSleep();
                SetTaskCompleted(m_TaskParameters.ErrorIndex);
            }
        }
Пример #26
0
        /// <summary>
        /// Attempts to get the architecture of a crash dump from the Version.txt file
        /// </summary>
        /// <param name="versionFilePath">Full path to Version.txt</param>
        /// <returns>DumpArchitecture</returns>
        public static DumpArchitecture GetArchitectureFromVersionFile(string versionFilePath)
        {
            Debug.Assert(versionFilePath != null);
            Debug.Assert(File.Exists(versionFilePath));

            DumpArchitecture arch = DumpArchitecture.Unknown;

            char[] splitChars = new char[] { ' ', ':' };

            // looking for (i.e.) "Architecture: X64"
            using (StreamReader sr = File.OpenText(versionFilePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] bits = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                    if (bits.Length >= 2)
                    {
                        // found the architecture line
                        if (string.Compare("Architecture", bits[0], StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (string.Compare("X86", bits[1], StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                arch = DumpArchitecture.X86;
                            }
                            else if (string.Compare("X64", bits[1], StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                arch = DumpArchitecture.X64;
                            }
                            else if (string.Compare("IA64", bits[1], StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                arch = DumpArchitecture.IA64;
                            }
                            else
                            {
                                DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                             string.Format(CultureInfo.InvariantCulture,
                                                                           "GetArchitectureFromVersionFile: Unknown Architecture: {0}",
                                                                           bits[1]));
                            }

                            // break out of the while loop
                            break;
                        }
                    }
                }
            }

            return(arch);
        }
Пример #27
0
        /// <summary>
        /// Sets the current license data.
        /// null causes a refresh.
        /// </summary>
        /// <param name="licenseId">The ID of the new license.</param>
        public void SetLicense(String licenseId)
        {
            Monitor.Enter(this);

            try
            {
                // TODO: Go get the license data associated with the specified license ID from the license server.
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, "License changed to: " + licenseId);
            }
            finally
            {
                Monitor.Exit(this);
            }
        }
Пример #28
0
 public void Run()
 {
     try
     {
         _logger.Info("WebRole.Run called");
         Container.Resolve <ISyncService>().SyncForever(() => Constants.SyncInterval);
     }
     catch (Exception e)
     {
         _logger.Error("Uncaught exception in Run()", e);
         DiagnosticsHelper.WriteExceptionToBlobStorage(e);
         throw;
     }
 }
Пример #29
0
        public override void EntryPoint()
        {
            try
            {
                SetTaskStarted(m_TaskParameters.ErrorIndex);
                startTimer();

                // Now wait for an abort or timer event.
                int eventIndex;
                while ((eventIndex = WaitHandle.WaitAny(m_Events)) != s_AbortEventIndex)
                {
                    if (eventIndex == s_TimeExpiredEventIndex)
                    {
                        // The timer may go off fractionally before time. In this case if you start the timer again too soon
                        // it may set a time of only a couple of milliseconds into the future (as the real next time hasn't quite
                        // arrived because the system timer went off a bit early).
                        Thread.Sleep(1000);

                        runWinQualSyncTask();

                        m_IsRetryRequest = false;

                        // There is a race condition where the task that is started above completes with a failure and reschedules
                        // for say 15 minutes time before this call is reached. In this case the startTimer will overwrite the
                        // desired 15 minutes with the next scheduled time. The startTimer function allows for this and only
                        // sets the timer if it hasn't already been set up.
                        startTimer();
                    }
                    else
                    {
                        throw new InvalidOperationException("Unexpected event ID " + eventIndex.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (!CurrentTaskState.AbortRequested)
                {
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Sync timer task stopped", ex);
                }

                LastException = ex;
            }
            finally
            {
                stopTimer();
                SetTaskCompleted(m_TaskParameters.ErrorIndex);
            }
        }
Пример #30
0
 public void SetTaskCompleted(IErrorIndex index)
 {
     try
     {
         m_TaskState.TaskCompleted = true;
         OnTaskStateChange();
         m_TaskCompletedEvent.Set();
         UpdateTaskCompletedStatistics(index);
     }
     catch (System.Exception ex)
     {
         // Log and ignore.
         DiagnosticsHelper.LogException(StackHashUtilities.DiagSeverity.ComponentFatal, "Error updating task status in index", ex);
     }
 }
        /// <summary>
        /// Initializes a new instance of the Forwarder class.
        /// </summary>
        /// <param name="a">The stream for one connection.</param>
        /// <param name="b">The stream for the other connection.</param>
        /// <param name="closeHandler">
        /// An optional close callback handler.
        /// </param>
        public Forwarder(Stream a, Stream b, ForwarderCloseHandler closeHandler, DiagnosticsHelper webRoleDiagnostics)
        {
            if (null == webRoleDiagnostics)
                this.wd = new StandaloneDiagnosticHost();
            else
                this.wd = webRoleDiagnostics;

#region ENTER
using (AutoEnterExitTrace aeet = new AutoEnterExitTrace(wd, wd.WebTrace, "Forwarder_ctor()"))
{
#endregion ENTER
            this.streams = new Stream[2] { a, b };
            this.closeHandler = closeHandler;
            this.halfOpen = false;
            this.closing = 0;
            this.directions = new PerDirection[2];
            this.directions[0] = new PerDirection(this, a, b, this.wd);
            this.directions[1] = new PerDirection(this, b, a, this.wd);
#region LEAVE
}
#endregion LEAVE
        }
            /// <summary>
            /// Initializes a new instance of the PerDirection class.
            /// </summary>
            /// <param name="forwarder">
            /// The forwarder object to which this instance belongs.
            /// </param>
            /// <param name="from">The connection to read from.</param>
            /// <param name="to">The connection to write to.</param>
            public PerDirection(Forwarder forwarder, Stream from, Stream to, DiagnosticsHelper wd)
            {
                this.wd = wd;
#region ENTER
using (AutoEnterExitTrace aeet = new AutoEnterExitTrace(wd, wd.WebTrace, "Forwarder_PerDirection_ctor()"))
{
#endregion ENTER

                aeet.WriteDiagnosticInfo(System.Diagnostics.TraceEventType.Information, TraceEventID.traceFlow, "PerDirection Forwarder object: {0} was created for streams:  from:{1} to:{2}", this.GetHashCode(), from.GetHashCode(), to.GetHashCode());
                
                this.forwarder = forwarder;
                this.inbound = from;
                this.outbound = to;
                this.buffer = new byte[1500];
                this.streamBufState = new StreamBufferState();
                this.streamBufState.SetBuffer(this.buffer, 0, this.buffer.Length);

                // -
                // Start things going by issuing a receive on the inbound side.
                // -
                this.StartReceive();
#region LEAVE
}
#endregion LEAVE
            }