예제 #1
0
        private void sendEmails(String subject, String message)
        {
            if (m_SmtpClient == null)
            {
                recycleSmtpClient();
            }

            if (m_SmtpClient == null)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Failed to create email client.");
                return;
            }

            try
            {
                m_SmtpClient.Send(this.m_MailSettings.SmtpSettings.SmtpFrom,
                                  this.m_MailSettings.SmtpSettings.SmtpRecipients,
                                  subject,
                                  message);
            }
            catch (System.Exception ex)
            {
                // dispose the SMTP client on failure
                m_SmtpClient.Dispose();
                m_SmtpClient = null;

                DiagnosticsHelper.LogException(DiagSeverity.Warning, "Failed to send email: ", ex);
            }
        }
예제 #2
0
        public static void Main()
        {
            if (SingleInstance <App> .InitializeAsFirstInstance("{E17EF702-0CDB-4CC2-808A-EE33BAA03B34}"))
            {
                var application = new App();

                // parse requested Uri if present
                StackHashUri stackHashUri = null;
                if (StackHashUri.TryParse(Environment.GetCommandLineArgs(), out stackHashUri))
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                 string.Format(CultureInfo.CurrentCulture,
                                                               "Command line requests navigation to {0}",
                                                               stackHashUri.RawUri));

                    application.CurrentStackHashUri = stackHashUri;
                }

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
예제 #3
0
        /// <summary>
        /// Called to indicate that a task has started.
        /// </summary>
        /// <param name="startedTask">The task that started.</param>
        protected virtual void OnTaskStarted(Task startedTask)
        {
            if (startedTask == null)
            {
                throw new ArgumentNullException("startedTask");
            }

            if (startedTask.LastException == null)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Task started: " + startedTask.Name);
            }
            else
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Task started: " + startedTask.Name + " " + startedTask.LastException);
            }

            TaskStartedEventArgs args = new TaskStartedEventArgs();

            args.StartedTask = startedTask;

            EventHandler <TaskStartedEventArgs> handler = TaskStarted;

            if (handler != null)
            {
                handler(this, args);
            }

            // Inform the task that the TaskStarted notification has been sent. It can then carry on.
            startedTask.TaskStartedNotificationEvent.Set();
        }
예제 #4
0
        /// <summary>
        /// Called to indicate that a task has completed.
        /// Signals interested parties.
        /// </summary>
        /// <param name="completedTask">The task that completed.</param>
        protected virtual void OnTaskCompleted(Task completedTask)
        {
            if (completedTask == null)
            {
                throw new ArgumentNullException("completedTask");
            }

            DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Task completed: " + completedTask.Name);
            if (completedTask.LastException != null)
            {
                String errorString = String.Format(CultureInfo.InvariantCulture, "Task Failed: {0} {1}",
                                                   completedTask.Name, completedTask.LastException);
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, errorString);
            }

            TaskCompletedEventArgs args = new TaskCompletedEventArgs();

            args.CompletedTask = completedTask;

            EventHandler <TaskCompletedEventArgs> handler = TaskCompleted;

            if (handler != null)
            {
                handler(this, args);
            }
        }
예제 #5
0
        /// <summary>
        /// Process a file table update. This may indicate a new item or the change to an existing item.
        /// </summary>
        private bool processFileUpdate(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);

            if (product == null)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing File: Inconsistent Update Table Entry = product not found: " + update.ProductId.ToString(CultureInfo.InvariantCulture));
                return(false);
            }
            if (file == null)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing File: Inconsistent Update Table Entry = file not found: " + update.FileId.ToString(CultureInfo.InvariantCulture));

                return(false);
            }

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

            if (update.TypeOfChange == StackHashChangeType.NewEntry)
            {
                m_TaskParameters.PlugInContext.FileAdded(null, BugTrackerReportType.Automatic, btProduct, btFile);
            }
            else
            {
                m_TaskParameters.PlugInContext.FileUpdated(null, BugTrackerReportType.Automatic, btProduct, btFile);
            }

            return(true);
        }
예제 #6
0
        /// <summary>
        /// Notify ServiceProxy that a cab is about to be downloaded.
        /// If the number of bytes is greater that the current interface
        /// maximum then the interface is recycled to accommodate the download.
        /// </summary>
        /// <param name="bytesToDownload">Length of the cab in bytes</param>
        public void NotifyCabDownloadLength(long bytesToDownload)
        {
            // include a safety margin (check for overflow)
            int bytesToDownloadWithMargin;

            checked
            {
                bytesToDownloadWithMargin = (int)(bytesToDownload * IncreaseMaxReceivedMessageSizeFactor);
            }

            if (bytesToDownloadWithMargin > _maxCabContractReceivedMessageSize)
            {
                lock (_lock)
                {
                    if (bytesToDownloadWithMargin > _maxCabContractReceivedMessageSize)
                    {
                        DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "ServiceProxy: Increasing cabs client MaxReceivedMessageSize to {0:n0} bytes",
                                                                   bytesToDownloadWithMargin));

                        _maxCabContractReceivedMessageSize = bytesToDownloadWithMargin;

                        // recycle the cabs service
                        _recycleCabsNeeded = true;
                    }
                }
            }
        }
예제 #7
0
        public void UpdateServiceEndpointAndAccount(string host, int port, string username, string password, string domain)
        {
            if ((host != _serviceHost) || (port != _servicePort) ||
                (username != _serviceUsername) || (password != _servicePassword) || (domain != _serviceDomain))
            {
                lock (_lock)
                {
                    if ((host != _serviceHost) || (port != _servicePort))
                    {
                        DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "ServiceProxy: Updating service endpoint to {0}:{1}",
                                                                   host,
                                                                   port));

                        _serviceHost = host;
                        _servicePort = port;

                        // recycle services the next time they are accessed
                        _recycleAdminNeeded    = true;
                        _recycleProjectsNeeded = true;
                        _recycleCabsNeeded     = true;
                        _recycleTestNeeded     = true;
                    }

                    if ((username != _serviceUsername) || (password != _servicePassword) || (domain != _serviceDomain))
                    {
                        DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "ServiceProxy: Updating service account to {0}{1}",
                                                                   string.IsNullOrEmpty(domain) ? "" : domain + "\\",
                                                                   string.IsNullOrEmpty(username) ? "current credentials" : username));

                        _impersonateCredential = null;
                        _serviceUsername       = username;
                        _servicePassword       = password;
                        _serviceDomain         = domain;

                        if ((!string.IsNullOrEmpty(_serviceUsername)) && (!string.IsNullOrEmpty(_servicePassword)))
                        {
                            if (string.IsNullOrEmpty(_serviceDomain))
                            {
                                _impersonateCredential = new NetworkCredential(_serviceUsername, _servicePassword);
                            }
                            else
                            {
                                _impersonateCredential = new NetworkCredential(_serviceUsername, _servicePassword, _serviceDomain);
                            }
                        }

                        // recycle services the next time they are accessed
                        _recycleAdminNeeded    = true;
                        _recycleProjectsNeeded = true;
                        _recycleCabsNeeded     = true;
                        _recycleTestNeeded     = true;
                    }
                }
            }
        }
예제 #8
0
        /// <summary />
        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            base.OnSessionEnding(e);

            DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                         string.Format(CultureInfo.InvariantCulture,
                                                       "Session Ending: {0}",
                                                       e.ReasonSessionEnding));
        }
예제 #9
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;
     }
 }
예제 #10
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");
        }
예제 #11
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);
     }
 }
예제 #12
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();
                }
            }
        }
예제 #13
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);
        }
예제 #14
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);
            }
        }
예제 #15
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);
        }
예제 #16
0
        private void DumpStatus(StackHashStatus status)
        {
            if (status == null)
            {
                return;
            }

            try
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Dumping Service Status...");
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ". Initialization failed: {0}", status.InitializationFailed));
                DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ". Host running in test mode: {0}", status.HostRunningInTestMode));

                foreach (StackHashContextStatus contextStatus in status.ContextStatusCollection)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Active: {0}", contextStatus.IsActive));
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Last synchronization logon failed: {0}", contextStatus.LastSynchronizationLogOnFailed));
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Last synchronization login service error: {0}", contextStatus.LastSynchronizationLogOnServiceError));
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Last synchronization logon exception: {0}", contextStatus.LastSynchronizationLogOnException));
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Current error: {0}", contextStatus.CurrentError));
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information, string.Format(CultureInfo.InvariantCulture, ".. Last context exception: {0}", contextStatus.LastContextException));

                    foreach (StackHashTaskStatus taskStatus in contextStatus.TaskStatusCollection)
                    {
                        DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "... Type: {0}, State: {1}, Last Exception: {2}, Last Duration: {3}, Run Count: {4}, Success: {5}, Failure: {6}, Last Started: {7}, Last Succeeded: {8}, Last Failed: {9}",
                                                                   taskStatus.TaskType,
                                                                   taskStatus.TaskState,
                                                                   taskStatus.LastException,
                                                                   taskStatus.LastDurationInSeconds,
                                                                   taskStatus.RunCount,
                                                                   taskStatus.SuccessCount,
                                                                   taskStatus.FailedCount,
                                                                   taskStatus.LastStartedTimeUtc,
                                                                   taskStatus.LastSuccessfulRunTimeUtc,
                                                                   taskStatus.LastFailedRunTimeUtc));
                    }
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "Failed to dump service status",
                                               ex);
            }
        }
예제 #17
0
        public Object ExecuteScalarWithRetry(DbCommand sqlCommand)
        {
            sqlCommand.Connection = null;

            try
            {
                for (int retryCount = 0; retryCount < m_ConnectionRetryLimit; retryCount++)
                {
                    // Connect to the the DBMS.
                    // An exception might occur here under heavy load. i.e. the connection pool is exhausted and
                    // a timeout occurred getting the connection. Let that exception filter back to the client.
                    sqlCommand.Connection = CreateConnection(false);

                    try
                    {
                        return(sqlCommand.ExecuteScalar());
                    }
                    catch (System.Exception ex)
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.Warning, "ExecuteScalarWithRetry failed for command: " + sqlCommand.CommandText, ex);

                        // Retry or not.
                        ReleaseConnection(sqlCommand.Connection);
                        sqlCommand.Connection = null;

                        if (retryCount >= m_ConnectionRetryLimit - 1)
                        {
                            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "ExecuteScalarWithRetry failed. Retry limit exceeeded.");

                            throw;
                        }
                    }
                }

                // Shouldn't get here.
                return(0);
            }
            finally
            {
                if (sqlCommand.Connection != null)
                {
                    ReleaseConnection(sqlCommand.Connection);
                    sqlCommand.Connection = null;
                }
            }
        }
예제 #18
0
 static void Synopsis()
 {
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "***************************************************************************************");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "ATOMSYNC Version 1.0 - Copyright (c) Cucku, Inc 2010");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "***************************************************************************************");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "NOT FOR REDISTRIBUTION. TO BE USED BY RECIPIENT ONLY AS AGREED BY CUCKU, INC.");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, " atomsync [options] username password ");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, " atomsync [options] username password proxyHost proxyPort");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, " atomsync [options] username password proxyHost proxyPort proxyUsername proxyPassword");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, " atomsync [options] username password proxyHost proxyPort proxyUsername proxyPassword proxyDomain");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, " where [options] are... ");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "  -iN          - Number of iterations e.g. -i1000");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "  -nocabs      - Don't download any cabs");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "  -aIPADDRESS  - Use a specific IP address for winqual.microsoft.com e.g. -a131.107.97.31");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "  -xml         - log XML");
     DiagnosticsHelper.LogMessage(DiagSeverity.Information, "***************************************************************************************");
 }
예제 #19
0
        /// <summary>
        /// Called to stop the service. The controller is disposed.
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (m_StaticObjects != null)
                {
                    m_StaticObjects.Dispose();
                    m_StaticObjects = null;
                }
            }
            catch (System.Exception ex)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.ApplicationFatal, "Failed to stop Stack Hash service " + ex.ToString());
                throw;
            }

            AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(UnhandledException);
        }
예제 #20
0
        /// <summary />
        public bool SignalExternalCommandLineArgs(IList <string> args)
        {
            DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                         "Other instance activation...");

            // only take action if no owned windows are active
            if (this.MainWindow.OwnedWindows.Count == 0)
            {
                // activate the main window
                if (this.MainWindow != null)
                {
                    if (this.MainWindow.WindowState == WindowState.Minimized)
                    {
                        this.MainWindow.WindowState = WindowState.Normal;
                    }

                    this.MainWindow.Activate();
                }

                // parse the requested Uri (if present) and request navigation
                StackHashUri stackHashUri = null;
                if (StackHashUri.TryParse(args, out stackHashUri))
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                 string.Format(CultureInfo.CurrentCulture,
                                                               "Other instance requests navigation to {0}",
                                                               stackHashUri.RawUri));

                    this.CurrentStackHashUri = stackHashUri;
                    if (StackHashUriNavigationRequest != null)
                    {
                        StackHashUriNavigationRequest(this, EventArgs.Empty);
                    }
                }
            }
            else
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning,
                                             "Other instance activation ignored as owned windows exist");
            }

            return(true);
        }
예제 #21
0
        public void StartLogging_TestMode_CallStartTwiceBySystem_Reload()
        {
            LogManager logManager = new LogManager(true, true);

            String logFileName = Path.GetFileName(logManager.LogFileName);

            Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_00000001.txt", StringComparison.OrdinalIgnoreCase));

            logManager.StartLogging(false);

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Log Manager Test 1");
            logFileName = Path.GetFileName(logManager.LogFileName);
            Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_00000001.txt", StringComparison.OrdinalIgnoreCase));

            Assert.AreEqual(true, File.Exists(logManager.LogFileName));
            logManager.StopLogging();

            logManager.Dispose();

            logManager = new LogManager(true, true);

            String allText = File.ReadAllText(logManager.LogFileName);

            Assert.AreEqual(true, allText.Contains("Log Manager Test 1"));

            // Start the logger again as if by the user.
            logManager.StartLogging(false);

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Log Manager Test 2");
            logFileName = Path.GetFileName(logManager.LogFileName);
            Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_00000001.txt", StringComparison.OrdinalIgnoreCase));

            Assert.AreEqual(true, File.Exists(logManager.LogFileName));
            logManager.StopLogging();

            allText = File.ReadAllText(logManager.LogFileName);

            Assert.AreEqual(true, allText.Contains("Log Manager Test 2"));
            Assert.AreEqual(true, allText.Contains("Log Manager Test 1"));

            logManager.Dispose();
        }
예제 #22
0
        public DbDataReader ExecuteReaderWithRetry(DbCommand sqlCommand)
        {
            sqlCommand.Connection = null;
            try
            {
                for (int retryCount = 0; retryCount < m_ConnectionRetryLimit; retryCount++)
                {
                    // Connect to the the DBMS.
                    // An exception might occur here under heavy load. i.e. the connection pool is exhausted and
                    // a timeout occurred getting the connection. Let that exception filter back to the client.
                    sqlCommand.Connection = CreateConnection(false);

                    try
                    {
                        return(sqlCommand.ExecuteReader(CommandBehavior.CloseConnection));
                    }
                    catch (System.Exception ex)
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.Warning, "ExecuteReader failed for command: " + sqlCommand.CommandText, ex);

                        // Retry or not.
                        ReleaseConnection(sqlCommand.Connection);
                        sqlCommand.Connection = null;

                        if (retryCount >= m_ConnectionRetryLimit - 1)
                        {
                            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "ExecuteReader failed. Retry limit exceeeded.");
                            throw;
                        }
                    }
                }

                // Shouldn't get here.
                return(null);
            }
            finally
            {
                // Don't free the connection. When the caller closes the data reader, the connection will be closed.
            }
        }
예제 #23
0
        /// <summary>
        /// Process an event note table update. This may indicate a new item or the change to an existing item.
        /// </summary>
        private bool processEventNoteUpdate(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));
            StackHashNoteEntry note     = m_Index.GetEventNote((int)update.ChangedObjectId);

            if ((product == null) || (file == null) || (theEvent == null) || (note == null))
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Event 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);


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

            String newBugId = null;

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

            setPlugInBugReference(product, file, theEvent, newBugId);

            return(true);
        }
예제 #24
0
        public void StartLogging_TestMode_NoLogFiles()
        {
            LogManager logManager = new LogManager(true, true);

            String logFileName = Path.GetFileName(logManager.LogFileName);

            Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_00000001.txt", StringComparison.OrdinalIgnoreCase));

            logManager.StartLogging(true);

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Log Manager Test");
            logFileName = Path.GetFileName(logManager.LogFileName);
            Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_00000001.txt", StringComparison.OrdinalIgnoreCase));

            Assert.AreEqual(true, File.Exists(logManager.LogFileName));
            logManager.StopLogging();

            String allText = File.ReadAllText(logManager.LogFileName);

            Assert.AreEqual(true, allText.Contains("Log Manager Test"));
            logManager.Dispose();
        }
예제 #25
0
        public void StartLogging_TestMode_CallStartNTimer()
        {
            LogManager logManager = new LogManager(true, true);

            for (int i = 1; i < 100; i++)
            {
                logManager.StartLogging(true);

                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Log Manager Test 1");
                String logFileName = Path.GetFileName(logManager.LogFileName);
                Assert.AreEqual(0, String.Compare(logFileName, "StackHashServiceDiagnosticsLog_" + i.ToString("D8") + ".txt", StringComparison.OrdinalIgnoreCase));

                Assert.AreEqual(true, File.Exists(logManager.LogFileName));
                logManager.StopLogging();

                String allText = File.ReadAllText(logManager.LogFileName);

                Assert.AreEqual(true, allText.Contains("Log Manager Test 1"));
            }

            logManager.Dispose();
        }
예제 #26
0
        public void Save()
        {
            Exception finalException = null;

            for (int retry = 0; retry < SaveRetryCount; retry++)
            {
                try
                {
                    finalException = null;

                    if (retry > 0)
                    {
                        // wait a little bit before trying again
                        Thread.Sleep(SaveRetryWaitMs);

                        DiagnosticsHelper.LogMessage(DiagSeverity.Warning,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "DBConfigSettings.Save Retry attempt {0}",
                                                                   retry));
                    }

                    SaveCore();
                    break;
                }
                catch (Exception ex)
                {
                    finalException = ex;

                    DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                                   "DBConfigSettings.Save Failed",
                                                   ex);
                }
            }

            if (finalException != null)
            {
                throw finalException;
            }
        }
예제 #27
0
        /// <summary>
        /// Process a product table update. This may indicate a new item or the change to an existing item.
        /// </summary>
        private bool processProductUpdate(StackHashBugTrackerUpdate update)
        {
            // Get the associated product information.
            StackHashProduct product = m_Index.GetProduct((int)update.ProductId);

            if (product == null)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Product: Inconsistent Update Table Entry");
                return(false);
            }

            BugTrackerProduct btProduct = new BugTrackerProduct(product.Name, product.Version, product.Id);

            if (update.TypeOfChange == StackHashChangeType.NewEntry)
            {
                m_TaskParameters.PlugInContext.ProductAdded(null, BugTrackerReportType.Automatic, btProduct);
            }
            else
            {
                m_TaskParameters.PlugInContext.ProductUpdated(null, BugTrackerReportType.Automatic, btProduct);
            }

            return(true);
        }
예제 #28
0
        public void UpdateMap(StackHashProductLocaleSummaryCollection localeSummary)
        {
            Debug.Assert(localeSummary != null);

            ResetMap();

            if (localeSummary != null)
            {
                ulong maxEvents     = 0;
                ulong currentEvents = 0;

                StringCollection localeMisses = null;

                foreach (StackHashProductLocaleSummary summary in localeSummary)
                {
                    if (!string.IsNullOrEmpty(summary.Locale))
                    {
                        string lowerLocale = summary.Locale.ToLower(CultureInfo.InvariantCulture);
                        if (_localeToCountry.ContainsKey(lowerLocale))
                        {
                            currentEvents = _localeToCountry[lowerLocale].EventCount += (ulong)summary.TotalHits;

                            if (currentEvents > maxEvents)
                            {
                                maxEvents = currentEvents;
                            }
                        }
                        else
                        {
                            if (localeMisses == null)
                            {
                                localeMisses = new StringCollection();
                            }

                            if ((!localeMisses.Contains(lowerLocale)) &&
                                (lowerLocale != "none"))
                            {
                                localeMisses.Add(lowerLocale);
                            }
                        }
                    }
                }

                // log any locales not on the map
                if (localeMisses != null)
                {
                    foreach (string missedLocale in localeMisses)
                    {
                        DiagnosticsHelper.LogMessage(DiagSeverity.Information,
                                                     string.Format(CultureInfo.InvariantCulture,
                                                                   "WorldMapControl: no country is associated with culture {0}",
                                                                   missedLocale));
                    }
                }

                // update the map by setting the highest event count
                foreach (CountryInfo countryInfo in _localeToCountry.Values)
                {
                    countryInfo.SetMaxEventsAndUpdate(maxEvents);
                }
            }
        }
예제 #29
0
        /// <summary>
        /// Process a debug script change.
        /// </summary>
        private bool processDebugScriptUpdate(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));

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: getting cab data1");
            StackHashCab cab = m_Index.GetCab(product, file, theEvent, (int)update.CabId);

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: getting cab data2");
            StackHashNoteEntry note = m_Index.GetCabNote((int)update.ChangedObjectId);

            if ((product == null) || (file == null) || (theEvent == null) || (cab == null) || (note == null))
            {
                if (product == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : product");
                }
                if (file == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : file");
                }
                if (theEvent == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : the Event");
                }
                if (cab == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : cab: " + update.CabId.ToString(CultureInfo.InvariantCulture));
                }
                if (note == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : note");
                }
                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);

            // A note entry will be written when a script is run. Pick out the name of the script.
            // Format is "Script {0} executed".
            int    startIndex = btCabNote.Note.IndexOf("Script ", StringComparison.OrdinalIgnoreCase) + "Script ".Length;
            int    endIndex   = btCabNote.Note.IndexOf("executed", StringComparison.OrdinalIgnoreCase) - 2;
            int    length     = endIndex - startIndex + 1;
            String scriptName = btCabNote.Note.Substring(startIndex, length);

            StackHashScriptResult stackHashScriptResult = m_TaskParameters.TheScriptResultsManager.GetResultFileData(product, file, theEvent, cab, scriptName);

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

            BugTrackerScriptResult btScriptResult = new BugTrackerScriptResult(stackHashScriptResult.Name, stackHashScriptResult.ScriptVersion,
                                                                               stackHashScriptResult.LastModifiedDate, stackHashScriptResult.RunDate, stackHashScriptResult.ToString());

            String newBugId = null;

            if (update.TypeOfChange == StackHashChangeType.NewEntry)
            {
                newBugId = m_TaskParameters.PlugInContext.DebugScriptExecuted(null, BugTrackerReportType.Automatic, btProduct, btFile, btEvent, btCab, btScriptResult);
            }
            setPlugInBugReference(product, file, theEvent, newBugId);

            return(true);
        }
예제 #30
0
        protected override void OnStart(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (args.Length > 0)
            {
                // The first parameter exists so assume it is the time to wait.
                // This allows a debugger to be attached to the process early on in the debug cycle.
                int timeToWait = 0;
                try
                {
                    timeToWait = int.Parse(args[0], CultureInfo.InvariantCulture);
                }
                catch (System.FormatException)
                {
                    // Just ignore format exceptions and assume that no value was specified.
                }

                if (timeToWait != 0)
                {
                    Thread.Sleep(timeToWait);
                }
            }


            try
            {
                // Tell the diagnostics helper where to log system events to.
                DiagnosticsHelper.SetEventLog(EventLog);

                // Cater for unhandled exceptions. Do this after the event log has been set up.
                // Load in the settings from the application directory if there are any.
                string pathForSystem              = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                string pathForServiceSettings     = pathForSystem + "\\StackHash";
                string pathForTestServiceSettings = pathForServiceSettings + "\\Test";

                if (!Directory.Exists(pathForServiceSettings))
                {
                    Directory.CreateDirectory(pathForServiceSettings);
                }

                string testModeFileName     = pathForServiceSettings + "\\testmode.xml";
                string testSettingsFileName = pathForTestServiceSettings + "\\testsettings.xml";
                string settingsFileName     = pathForServiceSettings + "\\settings.xml";

                // Now initialise the controller with those settings.
                if (File.Exists(testModeFileName) && (TestSettings.TestMode == "1"))
                {
                    if (!Directory.Exists(pathForTestServiceSettings))
                    {
                        Directory.CreateDirectory(pathForTestServiceSettings);
                    }

                    m_StaticObjects = new StaticObjects(testSettingsFileName, true, true);
                }
                else
                {
                    m_StaticObjects = new StaticObjects(settingsFileName, true, false);
                }

                m_StaticObjects.EnableServices();
            }
            catch (System.Exception ex)
            {
                DiagnosticsHelper.LogMessage(DiagSeverity.ApplicationFatal, "Failed to start Stack Hash service " + ex.ToString());
                throw;
            }
        }