Exemple #1
0
        private static void ConfigureMailNotifications()
        {
            SyncEngineLogger.EnableMailNotifications = _serviceConfig.EnableMailNotifications;

            if (_serviceConfig.EnableMailNotifications)
            {
                try
                {
                    var fromAddress = new MailAddress(_serviceConfig.FromEmailAddress);

                    var toAddresses = new List <MailAddress>();

                    foreach (var toAddress in _serviceConfig.ToEmailAddresses)
                    {
                        toAddresses.Add(new MailAddress(toAddress));
                    }

                    SyncEngineLogger.MailConfig = new MailConfig(fromAddress, toAddresses,
                                                                 _serviceConfig.SmtpHost, _serviceConfig.SmtpPort);

                    SyncEngineLogger.MailConfig.EnableSsl = _serviceConfig.SmtpRequiresSsl;

                    if (!(_serviceConfig.SmtpUsername == null || _serviceConfig.SmtpUsername.Trim() == string.Empty))
                    {
                        SyncEngineLogger.MailConfig.Credentials = new NetworkCredential(_serviceConfig.SmtpUsername, _serviceConfig.SmtpPassword);
                    }
                }
                catch (Exception ex)
                {
                    EventViewerLogger.WriteToLog(ex);

                    SyncEngineLogger.WriteExceptionToLog(ex);
                }
            }
        }
Exemple #2
0
        public void InsertEntry(int pPersonID, string pOperatorName, string pPhone, int pCountryID)
        {
            try
            {
                CountryEN personCountry = topupDAL.GetCountryByID(pCountryID);
                string    operatorBrand = pOperatorName + " " + personCountry.Name;

                OperatorEN operatorFound = topupDAL.GetOperatorByBrand(pCountryID, operatorBrand);

                if (operatorFound != null)
                {
                    RangeAzureSearch item = new RangeAzureSearch();
                    item.country_code = (operatorFound.ISO2Code != String.Empty) ? operatorFound.ISO2Code : "";
                    item.mnc          = (operatorFound.Mnc != String.Empty) ? operatorFound.Mnc : "";
                    item.mcc          = "706";
                    item.mno_id       = Convert.ToString(operatorFound.OperatorID);
                    item.term_end     = pPhone;
                    item.term_init    = pPhone;
                    item.term_id      = Guid.NewGuid().ToString();

                    AzureSearchValue        azureValue = new AzureSearchValue();
                    List <RangeAzureSearch> values     = new List <RangeAzureSearch>();
                    values.Add(item);
                    azureValue.value = values;

                    InsertValueIntoAzureSearch(azureValue);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLogger.LogError("AzureSearch: " + ex.Message);
            }
        }
Exemple #3
0
        private void InsertValueIntoAzureSearch(AzureSearchValue pItem)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://gpstermsearch.search.windows.net/indexes/gpsterms/docs/index?api-version=2015-02-28");

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Headers.Add("api-key", Values.AzureSearchApiKey);

            try
            {
                var serializer       = new JavaScriptSerializer();
                var serializedResult = serializer.Serialize(pItem);
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(serializedResult);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                WebResponse response     = request.GetResponse();
                var         streamReader = new StreamReader(response.GetResponseStream());
                var         result       = streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLogger.LogError("AzureSearch: " + ex.Message);
            }
        }
Exemple #4
0
        public static void RefreshServiceConfig()
        {
            try
            {
                _serviceConfig = _configurator.GetServiceConfig();

                JobQueueManager.Stop();

                ConfigureMailNotifications();

                if (!_serviceConfig.LogToDatabase)
                {
                    SyncEngineLogger.DeregisterLogger(_databaseLogger);
                }

                if (!_serviceConfig.LogToFile)
                {
                    SyncEngineLogger.DeregisterLogger(_textFileLogger);
                }

                JobQueueManager.Start(_serviceConfig.IntervalInSeconds);
            }
            catch (Exception ex)
            {
                EventViewerLogger.WriteToLog(ex);

                SyncEngineLogger.WriteExceptionToLog(ex);

                SyncEngineLogger.WriteToLog(LogEntryType.Warning, "The service config could not be refreshed and will occur the next time the service starts.");
            }
        }
Exemple #5
0
        private void UpdateCurrentPhone(string pTermID, string pNewPhone)
        {
            string requestBody = "{\"value\":[{\"@search.action\":\"merge\",\"term_id\":\"" + pTermID + "\",\"mno_id\":\"" + pNewPhone + "\"}]}";

            string         updateUrl   = "https://gpstermsearch.search.windows.net/indexes/gpsterms/docs/index?api-version=2015-02-28";
            HttpWebRequest postRequest = (HttpWebRequest)HttpWebRequest.Create(updateUrl);

            postRequest.Method      = "POST";
            postRequest.ContentType = "application/json";
            postRequest.Headers.Add("api-key", Values.AzureSearchApiKey);

            try
            {
                using (var streamWriter = new StreamWriter(postRequest.GetRequestStream()))
                {
                    streamWriter.Write(requestBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                WebResponse response     = postRequest.GetResponse();
                var         streamReader = new StreamReader(response.GetResponseStream());
                var         result       = streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLogger.LogError("AzureSearch: " + ex.Message);
            }
        }
        /// <summary>
        /// Loads a custom logger. If one was not specified, or the loading fails, loads the default logger.
        /// </summary>
        /// <returns>The logger.</returns>
        public static ILogger LoadLogger()
        {
            var defaultLogger = new EventViewerLogger("Cache Host", "Dache");

            //var defaultLogger = new FileLogger();

            // Configure custom logging
            try
            {
                var customLoggerTypeString = CacheHostConfigurationSection.Settings.CustomLogger.Type;
                // Check for custom logger
                if (string.IsNullOrWhiteSpace(customLoggerTypeString))
                {
                    // No custom logging
                    return(defaultLogger);
                }

                // Have a custom logger, attempt to load it and confirm it
                var customLoggerType = Type.GetType(customLoggerTypeString);
                // Verify that it implements our ILogger interface
                if (customLoggerType != null && typeof(ILogger).IsAssignableFrom(customLoggerType))
                {
                    return((ILogger)Activator.CreateInstance(customLoggerType));
                }
            }
            catch (Exception ex)
            {
                defaultLogger.Error(ex);
                // Custom logger load failed - no custom logging
            }

            return(defaultLogger);
        }
Exemple #7
0
        public void btnSyncField_Click(IRibbonControl control)
        {
            var doc             = new OfficeDocument(Globals.ThisAddIn.Application.ActiveDocument);
            var proptectionType = -1;

            try
            {
                proptectionType = doc.TurnOffProtection(string.Empty);
                var contentcontrol = Globals.ThisAddIn.Application.Selection.Range.ParentContentControl;
                if (contentcontrol == null)
                {
                    return;
                }
                var matchingControls =
                    Globals.ThisAddIn.Application.ActiveDocument.SelectContentControlsByTag(contentcontrol.Tag);
                foreach (WordOM.ContentControl mc in matchingControls)
                {
                    mc.Range.Text = contentcontrol.Range.Text;
                }
            }
            catch (Exception e)
            {
                var logger = new EventViewerLogger();
                logger.Log(e.ToString(), Type.Error);

#if DEBUG
                MessageBox.Show(e.ToString(), @"sorry");
#endif
            }
            finally
            {
                doc.TurnOnProtection(proptectionType, string.Empty);
            }
        }
Exemple #8
0
        private void OnError(Exception ex)
        {
            var logger = new EventViewerLogger();

            logger.Log(ex.ToString(), Type.Error);

#if DEBUG
            MessageBox.Show(ex.ToString(), @"sorry");
#endif
        }
        protected virtual void OnError(Exception e)
        {
            var logger = new EventViewerLogger();

            logger.Log(e.ToString(), BusinessLogic.Interfaces.Logging.Type.Error);

#if DEBUG
            MessageBox.Show(e.ToString(), @"sorry");
#endif
        }
Exemple #10
0
        public void btnSyncTable_Click(Microsoft.Office.Core.IRibbonControl control)
        {
            var doc             = new OfficeDocument(Globals.ThisAddIn.Application.ActiveDocument);
            var proptectionType = -1;

            try
            {
                //proptectionType = doc.TurnOffProtection(String.Empty);

                var tables = Globals.ThisAddIn.Application.Selection.Tables;
                if (tables == null || tables.Count == 0)
                {
                    MessageBox.Show(@"Please ensure your cursor is within a table", @"No Table Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var table = tables[1];


                var contentcontrols = table.Range.ContentControls;
                if (contentcontrols == null)
                {
                    return;
                }

                foreach (WordOM.ContentControl contentControl in contentcontrols)
                {
                    if (String.IsNullOrEmpty(contentControl.Tag))
                    {
                        continue;
                    }

                    var matchingControls =
                        Globals.ThisAddIn.Application.ActiveDocument.SelectContentControlsByTag(contentControl.Tag);
                    foreach (WordOM.ContentControl mc in matchingControls)
                    {
                        mc.Range.Text = contentControl.Range.Text;
                    }
                }
            }
            catch (Exception e)
            {
                var logger = new EventViewerLogger();
                logger.Log(e.ToString(), BusinessLogic.Interfaces.Logging.Type.Error);

#if DEBUG
                MessageBox.Show(e.ToString(), @"sorry");
#endif
            }
            finally
            {
                //   doc.TurnOnProtection(proptectionType, String.Empty);
            }
        }
        private AuthenticationResult GetAuthorizationBearerTokenFromPrompt()
        {
            var logger = new EventViewerLogger();

            logger.Log(string.Format("Getting Authorization Bearer Token from prompt"), BusinessLogic.Interfaces.Logging.Type.Debug);

            //var activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            var ac  = new AuthenticationContext(Settings.Default.TenantMetadataUrl);
            var arr = ac.AcquireToken(Settings.Default.TokenResourceUrl, ClientId, RedirectUri, PromptBehavior.Auto);

            return(arr);
        }
        private static string GetADALAttribute()
        {
            var logger = new EventViewerLogger();

            if (UserPrincipal.Current.EmailAddress.IndexOf("@ajg.com.au") > 0)
            {
                logger.Log(string.Format("Current user's e-mail {0} address includes @ajg.com.au, no need to append the domain for authenticating to O365", UserPrincipal.Current.EmailAddress), BusinessLogic.Interfaces.Logging.Type.Debug);
                return(UserPrincipal.Current.EmailAddress);
            }
            logger.Log(string.Format("Current user's e-mail {0} address doesn't include @ajg.com.au, append the domain to the account for authenticating to O365", UserPrincipal.Current.EmailAddress), BusinessLogic.Interfaces.Logging.Type.Debug);
            return(UserPrincipal.Current.SamAccountName + "@ajg.com.au");
        }
Exemple #13
0
        public bool ComparePhoneNumber(string pMsisdn, string pOperatorName, int pPersonID, int pPersonCountryID)
        {
            bool   isTheSame           = false;
            string countryOperatorName = string.Empty;

            string url = "https://gpstermsearch.search.windows.net/indexes/gpsterms/docs?search=*&$filter= term_init  eq '" + pMsisdn + "' &api-version=2015-02-28";

            HttpWebResponse response = null;
            HttpWebRequest  request  = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method      = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("api-key", Values.AzureSearchApiKey);

            string jsonResult;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    jsonResult = sr.ReadToEnd();
                }

                AzureSearchValue searchValue  = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <AzureSearchValue>(jsonResult);
                string           currentMnoID = searchValue.value[0].mno_id;


                CountryEN personCountry = topupDAL.GetCountryByID(pPersonCountryID);
                countryOperatorName = pOperatorName + " " + personCountry;


                OperatorEN operatorFound = topupDAL.GetOperatorByBrand(pPersonCountryID, countryOperatorName);

                if (operatorFound != null)
                {
                    isTheSame = (String.Equals(currentMnoID, operatorFound.OperatorID)) ? true : false;

                    if (!isTheSame)
                    {
                        UpdateCurrentPhone(searchValue.value[0].term_id, Convert.ToString(operatorFound.OperatorID));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLogger.LogError("AzureSearch: " + ex.Message);
            }

            return(isTheSame);
        }
Exemple #14
0
        private void ThisAddIn_DocumentOpen(Document doc)
        {
            try
            {
                var logger = new EventViewerLogger();
                logger.Log(string.Format("DocumentOpen event"), Type.Information);

                if (doc == null)
                {
                    logger.Log(string.Format("DocumentOpen event - doc is null, returning"), Type.Information);
                    return;
                }

                doc.ActiveWindow.View.ShadeEditableRanges = 0;
                Ribbon.ribbon.Invalidate();


                var document   = new OfficeDocument(doc);
                var documentId = document.GetPropertyValue(Constants.WordDocumentProperties.DocumentId);
                logger.Log(string.Format("DocumentOpen event - documentId = {0}", documentId), Type.Information);

                // disabled update check Nov 2017 DSZ
                //var fragmentsUsedPropertyValue = document.GetPropertyValue(Constants.WordDocumentProperties.UsedDateOfFragements);
                //var logoPropertyValue = document.GetPropertyValue(Constants.WordDocumentProperties.UsedDateOfLogo);
                //var themePropertyValue = document.GetPropertyValue(Constants.WordDocumentProperties.UsedDateOfTheme);
                //var mainTemplatePropertyValue =
                //    document.GetPropertyValue(Constants.WordDocumentProperties.BuiltInTitle) + ";" +
                //    document.GetPropertyValue(Constants.WordDocumentProperties.DocumentGeneratedDate);

                //var spList = ListFactory.Create("TemplateUpdateTracking");
                //var item = spList.GetListItemByTitle(documentId);
                //var shouldHide = "false";
                //var hideChosedDate = "";
                //if (item != null)
                //{
                //    shouldHide = item.GetFieldValue("Hide");
                //    hideChosedDate = item.GetFieldValue("Modified");
                //}

                //var task =
                //    Task.Factory.StartNew(
                //        () =>
                //            ExecuteUpdateChecker(shouldHide, fragmentsUsedPropertyValue, themePropertyValue,
                //                logoPropertyValue, mainTemplatePropertyValue, documentId, hideChosedDate));

                //System.Threading.Tasks.Task.Factory.StartNew(() => ThisAddIn.CheckStartupTasks(document), CancellationToken.None, TaskCreationOptions.None, uiScheduler);
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
 private void SharePointClientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
 {
     lock (Lock)
     {
         var logger = new EventViewerLogger();
         logger.Log(string.Format("Executing Web Request to obtain SharePoint Client Context: {0}", e.WebRequestExecutor.WebRequest.RequestUri), BusinessLogic.Interfaces.Logging.Type.Debug);
         if (_result == null)
         {
             _result = GetAuthorizationBearerTokenFromAdfs() ?? GetAuthorizationBearerTokenFromPrompt();
         }
         if (_result == null)
         {
             return;
         }
         e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + _result.AccessToken;
     }
 }
Exemple #16
0
        public bool CheckExistingEntry(string msisdn)
        {
            bool exists = false;

            string url        = "https://gpstermsearch.search.windows.net/indexes/gpsterms/docs?search=*&$filter= term_init  eq '" + msisdn + "' &api-version=2015-02-28";
            string jsonResult = null;

            HttpWebResponse response = null;
            HttpWebRequest  request  = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method      = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("api-key", Values.AzureSearchApiKey);

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                var streamReader = new StreamReader(response.GetResponseStream());
                jsonResult = streamReader.ReadToEnd();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var resultObjects = AllChildren(JObject.Parse(jsonResult)).First(c => c.Type == JTokenType.Array && c.Path.Contains("value")).Children <JObject>();

                    int resultCount = resultObjects.Count();

                    if (resultCount > 0)
                    {
                        exists = true;
                    }
                    else
                    {
                        exists = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLogger.LogError("AzureSearch: " + ex.Message);
            }

            return(exists);
        }
Exemple #17
0
        public static void RefreshIntegrationInLogger(Guid integrationId)
        {
            try
            {
                SyncEngineLogger.DeregisterIntegration(integrationId);

                var integrationToRegister = _configurator.GetIntegrationById(integrationId);

                SyncEngineLogger.RegisterIntegration(integrationToRegister);
            }
            catch (Exception ex)
            {
                EventViewerLogger.WriteToLog(ex);

                SyncEngineLogger.WriteExceptionToLog(ex);

                SyncEngineLogger.WriteToLog(LogEntryType.Warning, "The integration '{0}' could not be refreshed and will occur the next time the service starts.", integrationId);
            }
        }
 internal AuthenticationResult GetAuthorizationBearerTokenFromAdfs()
 {
     try
     {
         var logger = new EventViewerLogger();
         logger.Log(string.Format("Getting Authorization Bearer Token from ADFS"), BusinessLogic.Interfaces.Logging.Type.Debug);
         _authContext = new AuthenticationContext(Authority, FileCache);
         var r =
             _authContext.AcquireToken(Settings.Default.TokenResourceUrl, ClientId, RedirectUri,
                                       PromptBehavior.Auto, new UserIdentifier(GetADALAttribute(), UserIdentifierType.OptionalDisplayableId));
         return(r);
     }
     catch (Exception ex)
     {
         var logger = new EventViewerLogger();
         logger.Log(string.Format("Exception occured Getting Authorization Bearer Token from ADFS: {0}", ex.Message), BusinessLogic.Interfaces.Logging.Type.Error);
         return(null);
     }
 }
Exemple #19
0
        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            try
            {
                var logger = new EventViewerLogger();
                logger.Log(string.Format("Startup event"), Type.Information);

                ((ApplicationEvents4_Event)Application).NewDocument += ThisAddIn_NewDocument;
                (Application).DocumentOpen += ThisAddIn_DocumentOpen;
                if (Application.Documents.Count > 0)
                {
                    logger.Log(string.Format("Startup event - Application document count greater than 0"), Type.Information);
                    Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.ShadeEditableRanges = 0;
                    newTemplate(Globals.ThisAddIn.Application.ActiveDocument);
                    //required as they open from SharePoint links now too
                }
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
Exemple #20
0
        /// <summary>
        /// The process action async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="method">
        /// The method.
        /// </param>
        /// <typeparam name="TReq">
        /// Request type.
        /// </typeparam>
        /// <typeparam name="TResp">
        /// Response type.
        /// </typeparam>
        /// <returns>
        /// The response.
        /// </returns>
        protected async Task <HttpResponseMessage> ProcessActionAsync <TReq, TResp>(TReq request, Func <TReq, Task <TResp> > method)
        {
            var output     = new ActionResponse <TResp>();
            var statusCode = HttpStatusCode.OK;

            try
            {
                output.HasError = false;
                output.Results  = await method(request);
            }
            catch (Exception ex)
            {
                var financesException = new FinancesException(ex.GetType().Name, ex);
                EventViewerLogger.LogException(financesException);
                output.ErrorMessage = ex.Message;
                output.ErrorGuid    = financesException.ErrorCode.ToString();
                output.HasError     = true;
                statusCode          = HttpStatusCode.InternalServerError;
            }

            return(this.Request.CreateResponse(statusCode, output));
        }
Exemple #21
0
        public int UpdatePlayerTracking(PlayersTrackingEN tracking)
        {
            int?result = default(int);

            try
            {
                connection.Cnn.Open();
                result = connection.Cnn.Update(tracking);
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message);
                EventViewerLogger.LogError("UpdatePlayerTracking: " + ex.Message);
            }
            finally
            {
                connection.Cnn.Close();
            }

            return(Convert.ToInt32(result));
        }
Exemple #22
0
        public int InsertWinCoin(WinCoinEN WinCoin)
        {
            int?inserted = default(int);

            try
            {
                connection.Cnn.Open();

                inserted = connection.Cnn.Insert(WinCoin);
            }
            catch (Exception ex)
            {
                inserted = 0;
                Console.WriteLine(ex.Message);
                EventViewerLogger.LogError("InsertWinCoin: " + ex.Message);
            }
            finally
            {
                connection.Cnn.Close();
            }

            return(Convert.ToInt32(inserted));
        }
Exemple #23
0
        public int InsertPlayerTracking(int pTotalWinCoins, int pCurrentCoinsProgress, int pConsumerID, DateTime pDate)
        {
            int result = default(int);

            try
            {
                connection.Cnn.Open();
                using (SqlTransaction tran = connection.Cnn.BeginTransaction())
                {
                    result = connection.Cnn.Query <int>(@"INSERT INTO [Consumer].[PlayersTracking](TotalWinCoins, CurrentCoinsProgress, TotalWinPrizes, ConsumerID, RegDate)
                                                    VALUES(@TotalWinCoins,
                                                           @CurrentCoinsProgress,
                                                           @TotalWinPrizes,
                                                           @ConsumerID,
                                                           @RegDate)", new
                    {
                        TotalWinCoins        = pTotalWinCoins,
                        CurrentCoinsProgress = pCurrentCoinsProgress,
                        TotalWinPrizes       = 0,
                        ConsumerID           = pConsumerID,
                        RegDate = pDate
                    }, tran).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message);
                EventViewerLogger.LogError("InsertPlayerTracking: " + ex.Message);
            }
            finally
            {
                connection.Cnn.Close();
            }

            return(result);
        }
Exemple #24
0
        public PlayersTrackingEN GetProgressGame(int consumerID)
        {
            PlayersTrackingEN result = new PlayersTrackingEN();

            try
            {
                connection.Cnn.Open();

                result = connection.Cnn.Query <PlayersTrackingEN>("SpGetProgressGameByConsumer", new { @ConsumerID = consumerID },
                                                                  commandType: CommandType.StoredProcedure).FirstOrDefault();
            }
            catch (Exception ex)
            {
                result = null;
                Console.WriteLine("GetProgressGameDAL: " + ex.Message);
                EventViewerLogger.LogError(ex.Message);
            }
            finally
            {
                connection.Cnn.Close();
            }

            return(result);
        }
Exemple #25
0
        public static void RefreshJobInLogger(Guid jobId)
        {
            try
            {
                var integrationToRegister = _configurator.GetIntegrationByJobId(jobId);

                if (integrationToRegister == null)
                {
                    throw new Exception(string.Format("No integration exists for job '{0}'.", jobId));
                }

                SyncEngineLogger.DeregisterIntegration(integrationToRegister.Id);

                SyncEngineLogger.RegisterIntegration(integrationToRegister);
            }
            catch (Exception ex)
            {
                EventViewerLogger.WriteToLog(ex);

                SyncEngineLogger.WriteExceptionToLog(ex);

                SyncEngineLogger.WriteToLog(LogEntryType.Warning, "The job '{0}' could not be refreshed and will occur the next time the service starts.", jobId);
            }
        }
        public void TestEventViewerLogger()
        {
            var logger = new EventViewerLogger("YourApplicationName", "BusinessLogicModuleName");

            WriteLogMessages(logger);
        }
Exemple #27
0
        // Start the Windows service.
        protected override void OnStart(string[] onStartArgs)
        {
            try
            {
                // get connection string from connectionStrings in App.config
                GetIntegrationDbConnectionString();

                // test connection to the queue database
                TestIntegrationDbConnection(IntegrationDbConnectionString);

                _dbQueueLogger = new JobQueueDatabaseLogger(IntegrationDbConnectionString);
                _configurator  = new SyncEngineDatabaseConfigurator(IntegrationDbConnectionString);

                JobQueueManager.Configurator = _configurator;

                _serviceConfig = _configurator.GetServiceConfig();

                // reset the logger as a precaution
                SyncEngineLogger.Clear();

                // configure mail notifications, if enabled
                if (_serviceConfig.EnableMailNotifications)
                {
                    ConfigureMailNotifications();
                }

                // add database and text file loggers
                RegisterLoggers();

                // register integrations for the database and text file loggers
                RegisterIntegrations();

                // associate the database logger with the queue manager
                JobQueueLogManager.AddLogger(_dbQueueLogger);

                // recover any job instances from a server or service restart; this will only apply to on-demand job instances
                _dbQueueLogger.RecoverJobInstancesFromQueueLog();

                // add the next run times for each scheduled job; clear any existing scheduled jobs from the queue
                _scheduledJobManager = new ScheduledJobManager(_configurator);
                _scheduledJobManager.QueueScheduledJobs(clearExistingScheduledJobInstancesFromWaitingQueue: true);

                // once a scheduled job is complete (i.e. queue request), queue for the next run time
                JobQueueManager.JobQueueRequestStatusChanged += new EventHandler <JobQueueRequestStatusChangedArgs>((s, e) =>
                {
                    if (e.QueueRequest.Status == JobQueueRequestStatus.Completed &&
                        e.QueueRequest.InvocationSourceType == JobInvocationSourceType.Scheduled)
                    {
                        _scheduledJobManager.QueueJobForNextScheduledRunTime(e.QueueRequest.Job.Id);
                    }
                });

                JobQueueManager.MaxDelayedStartByJobPriority = _configurator.GetJobPriorityConfig();

                JobQueueManager.Start(_serviceConfig.IntervalInSeconds);

                InitializeWebServiceHosts();
            }
            catch (Exception ex)
            {
                EventViewerLogger.WriteToLog(ex);

                SyncEngineLogger.WriteExceptionToLog(ex);

                // stop the service
                this.Stop();
            }
        }