예제 #1
0
        /// <summary>
        /// Gets the localized string associated with a StackHashErrorIndexDatabaseStatus
        /// </summary>
        /// <param name="databaseStatus">The StackHashErrorIndexDatabaseStatus</param>
        /// <returns>Localized string</returns>
        public static string GetDatabaseStatusMessage(StackHashErrorIndexDatabaseStatus databaseStatus)
        {
            string statusMessage = null;

            string resourceKey = string.Format(CultureInfo.InvariantCulture,
                                               "DatabaseStatus_{0}",
                                               databaseStatus);

            try
            {
                statusMessage = Properties.Resources.ResourceManager.GetString(resourceKey);
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "GetDatabaseStatusMessage Failed",
                                               ex);
            }

            if (statusMessage == null)
            {
                Debug.Assert(false,
                             string.Format(CultureInfo.InvariantCulture,
                                           "Missing localization for StackHashErrorIndexDatabaseStatus: {0}",
                                           databaseStatus));

                statusMessage = Properties.Resources.DatabaseStatus_Unknown;
            }

            return(statusMessage);
        }
예제 #2
0
        private void getAutomatedScripts()
        {
            m_AutomaticUserScriptNames = new List <StackHashScriptSettings>();

            // Now run all the scripts marked as automatic.
            StackHashScriptFileDataCollection scripts = m_TaskParameters.TheScriptManager.ScriptNames;

            foreach (StackHashScriptFileData scriptData in scripts)
            {
                StackHashScriptSettings script;

                try
                {
                    // Get the script details to see if it is automatic.
                    script = m_TaskParameters.TheScriptManager.LoadScript(scriptData.Name);

                    if ((script.RunAutomatically) && (script.Owner == StackHashScriptOwner.User))
                    {
                        m_AutomaticUserScriptNames.Add(script);
                    }
                }
                catch (System.Exception ex)
                {
                    // Ignore invalid script files.
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Invalid script file found: " + scriptData.Name, ex);
                }
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
 /// <summary>
 /// Main thread that runs the tasks on the queue.
 /// This thread will sit waiting for tasks to process or for an Abort notification.
 /// TaskQueued events signal that an event has been placed on the queue - or the queue
 /// should at least be checked for events to run.
 /// </summary>
 private void TaskRunnerStart()
 {
     try
     {
         // Keep looping until the thread is aborted.
         int eventIndex;
         while ((eventIndex = WaitHandle.WaitAny(m_Events)) != s_AbortEventIndex)
         {
             if (eventIndex == s_TaskQueuedEventIndex)
             {
                 // A task has been queued - start it if a queued task is not already running.
                 runQueuedTask();
             }
             else if (eventIndex == s_TaskCompletedEventIndex)
             {
                 // A concurrent task or queued task may have completed. Find and remove completed tasks.
                 removeCompletedQueuedTasks();
                 removeCompletedConcurrentTasks();
             }
             else
             {
                 throw new InvalidOperationException("Unexpected event ID " + eventIndex.ToString(CultureInfo.InvariantCulture));
             }
         }
     }
     catch (System.Exception ex)
     {
         // This shouldn't happen.
         DiagnosticsHelper.LogException(DiagSeverity.ApplicationFatal, "Task manager exiting", ex);
         throw;
     }
 }
예제 #5
0
        public DbConnection CreateConnection(bool master)
        {
            //if (m_CachedConnection != null)
            //    if (m_CachedConnection.State == ConnectionState.Open)
            //        return m_CachedConnection;

            DbConnection connection = m_ProviderFactory.CreateConnection();

            if (master)
            {
                connection.ConnectionString = m_MasterConnectionString;
            }
            else
            {
                connection.ConnectionString = m_ConnectionString;
            }

            try
            {
                connection.Open();
                m_ConnectReleaseToggle++;
//                m_CachedConnection = connection;
            }
            catch (System.Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning, "Failed to open connection", ex);
                DumpConnectionStatistics();
                throw;
            }
            return(connection);
        }
예제 #6
0
 private void CloseCabs()
 {
     try
     {
         if ((_cabs != null) && (_cabs.State != CommunicationState.Closed))
         {
             if (_cabs.State == CommunicationState.Faulted)
             {
                 _cabs.Abort();
             }
             else
             {
                 _cabs.Close();
             }
         }
     }
     catch (Exception ex)
     {
         DiagnosticsHelper.LogException(DiagSeverity.ComponentFatal,
                                        "ServiceProxy: Failed to close Cabs interface",
                                        ex);
     }
     finally
     {
         _cabs = null;
     }
 }
예제 #7
0
        private void checkLicense()
        {
            // If no license is defined then try and get a trial license.
            if (!m_TaskParameters.TheLicenseManager.LicenseData.LicenseDefined)
            {
                // TODO: Get the trial license.
            }

            // If still no license defined then bomb.
            if (!m_TaskParameters.TheLicenseManager.LicenseData.LicenseDefined)
            {
                throw new StackHashException("Licensed not installed", StackHashServiceErrorCode.NoLicense);
            }

            try
            {
                // Refresh the license.
            }
            catch (System.Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning, "Unable to refresh license", ex);
            }

            // Check expiry date.
            if (m_TaskParameters.TheLicenseManager.ExpiryUtc < DateTime.Now.ToUniversalTime())
            {
                throw new StackHashException("Licensed expired: " +
                                             m_TaskParameters.TheLicenseManager.ExpiryUtc.ToString(CultureInfo.InvariantCulture),
                                             StackHashServiceErrorCode.LicenseExpired);
            }
        }
예제 #8
0
        private static string SearchDdkDirForCdb(ImageFileMachine architecture)
        {
            string path = null;

            try
            {
                string ddkFolder = System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)), DdkFolder);
                if (Directory.Exists(ddkFolder))
                {
                    DirectoryInfo ddkFolderInfo = new DirectoryInfo(ddkFolder);
                    FileInfo[]    candidates    = ddkFolderInfo.GetFiles("cdb.exe", SearchOption.AllDirectories);

                    if (candidates.Length > 0)
                    {
                        for (int i = candidates.Length - 1; i >= 0; i--)
                        {
                            if (ClientUtils.VerifyArchitecture(architecture, candidates[i].FullName))
                            {
                                path = candidates[i].FullName;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "SearchDdkDirForCdb Failed",
                                               ex);
            }

            return(path);
        }
예제 #9
0
        private void buttonSelectDatabse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // save settings (to pass to the config tool)
                DBConfigSettings.Settings.ResetSettings();
                DBConfigSettings.Settings.IsNewProfile    = true;
                DBConfigSettings.Settings.ServiceHost     = ServiceProxy.Services.ServiceHost;
                DBConfigSettings.Settings.ServicePort     = ServiceProxy.Services.ServicePort;
                DBConfigSettings.Settings.ServiceUsername = UserSettings.Settings.ServiceUsername;
                DBConfigSettings.Settings.ServicePassword = UserSettings.Settings.ServicePassword;
                DBConfigSettings.Settings.ServiceDomain   = UserSettings.Settings.ServiceDomain;

                if (this.ClientLogic.ContextCollection != null)
                {
                    foreach (DisplayContext settings in this.ClientLogic.ContextCollection)
                    {
                        DBConfigSettings.Settings.ExistingProfileFolders.Add(settings.StackHashContextSettings.ErrorIndexSettings.Folder);
                        DBConfigSettings.Settings.ExistingProfileNames.Add(settings.StackHashContextSettings.ErrorIndexSettings.Name);
                    }
                }

                DBConfigSettings.Settings.IsDatabaseInCabFolder = _isDatabaseInCabFolder;
                DBConfigSettings.Settings.ProfileFolder         = _pathLocalStore;
                DBConfigSettings.Settings.ConnectionString      = _connectionString;
                DBConfigSettings.Settings.Save();

                Mouse.OverrideCursor = Cursors.Wait;
                _dbConfigProcess     = Process.Start("StackHashDBConfig.exe");
                _dbConfigProcess.EnableRaisingEvents = true;
                _dbConfigProcess.Exited += new EventHandler(_dbConfigProcess_Exited);
            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;

                bool           userCancel = false;
                Win32Exception win32ex    = ex as Win32Exception;
                if (win32ex != null)
                {
                    userCancel = (win32ex.NativeErrorCode == 1223);
                }

                if (!userCancel)
                {
                    DiagnosticsHelper.LogException(DiagSeverity.ComponentFatal,
                                                   "Failed to launch StackHashDBConfig.exe",
                                                   ex);

                    StackHashMessageBox.Show(Window.GetWindow(this),
                                             Properties.Resources.DBConfigLaunchFailedMBMessage,
                                             Properties.Resources.DBConfigLaunchFailedMBTitle,
                                             StackHashMessageBoxType.Ok,
                                             StackHashMessageBoxIcon.Error,
                                             ex,
                                             StackHashMessageBox.ParseServiceErrorFromException(ex));
                }
            }
        }
예제 #10
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);
     }
 }
예제 #11
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);
        }
예제 #12
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);
     }
 }
예제 #13
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);
            }
        }
예제 #14
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);
        }
예제 #15
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();
                }
            }
        }
예제 #16
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 { }
            }
        }
예제 #17
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);
            }
        }
예제 #18
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);
            }
        }
예제 #19
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);
            }
        }
예제 #20
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);
     }
 }
예제 #21
0
        public override void EntryPoint()
        {
            try
            {
                SetTaskStarted(m_TaskParameters.ErrorIndex);

                startTimer();

                // Now wait for the 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);

                        runPurgeTask();

                        startTimer();
                    }
                    else
                    {
                        throw new InvalidOperationException("Unexpected event ID " + eventIndex.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (!CurrentTaskState.AbortRequested)
                {
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Purge timer task stopped", ex);
                }
                LastException = ex;
            }
            finally
            {
                if (m_Timer != null)
                {
                    m_Timer.Change(Timeout.Infinite, Timeout.Infinite);
                    m_Timer.Dispose();
                    m_Timer = null;
                }
                SetTaskCompleted(m_TaskParameters.ErrorIndex);
            }
        }
예제 #22
0
        public void ReleaseConnection(DbConnection connection)
        {
//            if (m_CachedConnection != connection)
            try
            {
                connection.Close();
                connection.Dispose();
                m_ConnectReleaseToggle--;
            }
            catch (System.Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning, "Failed to release connection", ex);
                DumpConnectionStatistics();
                throw;
            }
        }
예제 #23
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);
            }
        }
예제 #24
0
        public override void EntryPoint()
        {
            try
            {
                SetTaskStarted(m_TaskParameters.ErrorIndex);

                // Hook up to receive error index updates.
                m_TaskParameters.ErrorIndex.IndexUpdateAdded += new EventHandler <ErrorIndexEventArgs>(this.ErrorIndexUpdated);

                // Following a PC reboot it may take a while before connections are established etc... so don't automatically
                // kick off the processing of the Update table (even if there are already entries to process) until a sync
                // is performed.
                try
                {
                    // Now wait for the an abort or Update event.
                    int eventIndex;
                    while ((eventIndex = WaitHandle.WaitAny(m_Events)) != s_AbortEventIndex)
                    {
                        if (eventIndex == s_UpdateArrived)
                        {
                            processUpdateTable();
                        }
                        else
                        {
                            throw new InvalidOperationException("Unexpected event ID " + eventIndex.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
                finally
                {
                    m_TaskParameters.ErrorIndex.IndexUpdateAdded -= new EventHandler <ErrorIndexEventArgs>(this.ErrorIndexUpdated);
                }
            }
            catch (System.Exception ex)
            {
                if (!CurrentTaskState.AbortRequested)
                {
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Bug Tracker Task Stopped", ex);
                }

                LastException = ex;
            }
            finally
            {
                SetTaskCompleted(/*m_TaskParameters.ErrorIndex*/ null); // Don't update the index task stats for this task.
            }
        }
예제 #25
0
        public static BitmapSource GetShieldIconAsBitmapSource()
        {
            BitmapSource shieldSource = null;
            IntPtr       hIcon        = IntPtr.Zero;

            try
            {
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    // Windows Vista / 2008 or later, get the stock icon
                    NativeMethods.SHSTOCKICONINFO sii = new NativeMethods.SHSTOCKICONINFO();
                    sii.cbSize = (UInt32)Marshal.SizeOf(typeof(NativeMethods.SHSTOCKICONINFO));

                    Marshal.ThrowExceptionForHR(NativeMethods.SHGetStockIconInfo(NativeMethods.SHSTOCKICONID.SIID_SHIELD,
                                                                                 NativeMethods.SHGSI.SHGSI_ICON | NativeMethods.SHGSI.SHGSI_SMALLICON,
                                                                                 ref sii));

                    hIcon = sii.hIcon;

                    shieldSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(hIcon,
                                                                                              Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
                else
                {
                    // Older platform, use SystemIcons.Shield... can't use this on Win 7 because it returns the wrong icon
                    shieldSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(System.Drawing.SystemIcons.Shield.Handle,
                                                                                              Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
            }
            catch (Exception ex)
            {
                DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                               "GetShieldIconAsBitmapSource failed",
                                               ex);
            }
            finally
            {
                // free icon handle if one was created
                if (hIcon != IntPtr.Zero)
                {
                    NativeMethods.DestroyIcon(hIcon);
                }
            }

            return(shieldSource);
        }
예제 #26
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;
                }
            }
        }
예제 #27
0
        public void ProvideFault(Exception error,
                                 System.ServiceModel.Channels.MessageVersion version,
                                 ref System.ServiceModel.Channels.Message fault)
        {
            if (m_ReentrancyCheck)
            {
                return;
            }

            m_ReentrancyCheck = true;

            try
            {
                if ((fault == null) && (error != null))
                {
                    ReceiverFaultDetail receiverFaultDetail = new ReceiverFaultDetail(
                        error.Message, getDescription(error), StackHashException.GetServiceErrorCode(error));

                    FaultException <ReceiverFaultDetail> fe = new FaultException <ReceiverFaultDetail>(
                        receiverFaultDetail, error.Message, FaultCode.CreateReceiverFaultCode(new FaultCode("ReceiverFault")));

                    MessageFault mf = fe.CreateMessageFault();

                    fault = Message.CreateMessage(version, mf, fe.Action);


                    try
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.Warning, "Service exception occurred", error);
                    }
                    catch (System.Exception)
                    {
                        // Ignore the error.
                    }
                }
            }
            finally
            {
                m_ReentrancyCheck = false;
            }
        }
예제 #28
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.
            }
        }
예제 #29
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;
            }
        }
예제 #30
0
        /// <summary>
        /// Gets the localized string associated with a StackHashServiceErrorCode
        /// See file://R:\StackHash\BusinessLogic\BusinessLogic\BusinessObjects\ErrorCodes.cs
        /// Last Updated: 2011-02-11
        /// </summary>
        /// <param name="serviceError">The StackHashServiceErrorCode</param>
        /// <returns>Localized string</returns>
        public static string GetServiceErrorCodeMessage(StackHashServiceErrorCode serviceError)
        {
            string serviceErrorMessage = null;

            if (serviceError != StackHashServiceErrorCode.NoError)
            {
                string resourceKey = string.Format(CultureInfo.InvariantCulture,
                                                   "ServiceError_{0}",
                                                   serviceError);

                try
                {
                    serviceErrorMessage = Properties.Resources.ResourceManager.GetString(resourceKey);
                }
                catch (Exception ex)
                {
                    DiagnosticsHelper.LogException(DiagSeverity.Warning,
                                                   "GetServiceErrorCodeMessage Failed",
                                                   ex);
                }

                if (serviceErrorMessage == null)
                {
                    Debug.Assert(false,
                                 string.Format(CultureInfo.InvariantCulture,
                                               "Missing localization for StackHashServiceErrorCode: {0}",
                                               serviceError));

                    serviceErrorMessage = Properties.Resources.ServiceError_UnexpectedError;
                }
            }
            else
            {
                serviceErrorMessage = string.Empty;
            }

            return(serviceErrorMessage.Trim());
        }