public virtual void SendEmailWithDefaultSender(EmailMessage emailMessage) { MailCredentials credentials = new MailCredentials { Host = (string)SysSettings.GetValue(UserConnection, "SmtpHost"), Port = int.Parse(SysSettings.GetValue(UserConnection, "SmtpPort").ToString()), UseSsl = (bool)SysSettings.GetValue(UserConnection, "SmtpEnableSsl"), UserName = (string)SysSettings.GetValue(UserConnection, "SmtpUserName"), UserPassword = (string)SysSettings.GetValue(UserConnection, "SmtpUserPassword") }; string[] to = emailMessage.To.ToArray(); EmailAddressCollection cc = GetEmailAddressCollection(emailMessage.Cc); EmailAddressCollection bcc = GetEmailAddressCollection(emailMessage.Bcc); var smtpClient = new SmtpClient(UserConnection); MailMessage message = smtpClient.CreateMessage(Body, Subject, to, credentials.UserName, true, new Dictionary <Guid, Tuple <byte[], string> >(0)); message.Cc = cc; message.Bcc = bcc; message.Priority = (MailPriority)emailMessage.Priority;; try { smtpClient.SendMessage(message, credentials); } catch { if (!IsIgnoreErrors) { throw; } } }
private EntityCollection GetUnprocessedEmailPack(UserConnection userConnection) { int rowNum = SysSettings.GetValue(userConnection, EmailPackCountSysSettingsName, DefEmailPackSize); int actualDaysPeriod = SysSettings.GetValue(userConnection, IdentificationActualPeriodSysSettingsName, 1); DateTime actualEmailsStartDate = DateTime.Today.AddDays(-actualDaysPeriod); EntitySchema activitySchema = userConnection.EntitySchemaManager.GetInstanceByName("Activity"); var esq = new EntitySchemaQuery(activitySchema) { IgnoreDisplayValues = true }; esq.PrimaryQueryColumn.IsVisible = true; esq.AddColumn("Body"); esq.AddColumn("IsHtmlBody"); esq.AddColumn("CreatedOn"); esq.AddColumn("SendDate").OrderByDesc(); esq.AddColumn("Sender"); esq.RowCount = rowNum; esq.Filters.AddLengthFilter(activitySchema, "Body", FilterComparisonType.Greater, 0); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Type", ActivityConsts.EmailTypeUId)); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "EnrichStatus", EnrichStatus.Inactive.ToString())); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "MessageType", ActivityConsts.IncomingEmailTypeId)); esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.GreaterOrEqual, "SendDate", actualEmailsStartDate)); return(esq.GetEntityCollection(userConnection)); }
public override void PostBpmSessionId(UserConnection userConnection, Entity leadEntity) { var sessionId = leadEntity.GetTypedColumnValue <Guid>("BpmSessionId"); var knownSessionRequest = new KnownSessionRequest(); var eventTrackingLogin = SysSettings.GetValue(userConnection, "EventTrackingLogin").ToString(); var eventTrackingPassword = SysSettings.GetValue(userConnection, "EventTrackingPassword").ToString(); var eventTrackingApiKey = SysSettings.GetValue(userConnection, "EventTrackingApiKey").ToString(); var eventTrackingWebAppUrl = SysSettings.GetValue(userConnection, "EventTrackingWebAppUrl").ToString(); if (string.IsNullOrEmpty(eventTrackingLogin) || string.IsNullOrEmpty(eventTrackingPassword) || string.IsNullOrEmpty(eventTrackingApiKey) || string.IsNullOrEmpty(eventTrackingWebAppUrl)) { return; } eventTrackingWebAppUrl += "/SetKnownSession?format=json"; knownSessionRequest.SetBasicAuth(eventTrackingLogin, eventTrackingPassword); knownSessionRequest.SetRequestMethod("POST"); knownSessionRequest.ApiKey = eventTrackingApiKey; knownSessionRequest.SessionId = sessionId; knownSessionRequest.Execute(eventTrackingWebAppUrl); }
public virtual string GetEstimateStringPic() { HttpContext httpContext = HttpContextAccessor.GetInstance(); string url = httpContext != null ? WebUtilities.GetBaseApplicationUrl(httpContext.Request) : (string)SysSettings.GetValue(UserConnection, "SiteUrl"); string divStyle = "width: 40px; height: 40px; font-size: 28px; text-align: center; " + "vertical-align: middle; float:left; background:{0};"; string hrefStyle = "text-decoration: none; color: white; vertical-align: middle; font-family: " + "Verdana, Arial,Tahoma;"; string link = "<td width='40' height='40' style='margin-top: 8px;'>" + "<div style='{1}'>" + "<a href='" + url + "/ServiceModel/CaseRatingManagementService.svc/RateCase/" + RecordId + "/{0}' style='{2}'>{0}</a>" + "</div>" + "</td>"; var result = string.Empty; var esq = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "SatisfactionLevel"); esq.AddColumn("Point").OrderDirection = OrderDirection.Descending; esq.AddColumn("Colour"); foreach (var satisfactionLevel in esq.GetEntityCollection(UserConnection)) { var point = satisfactionLevel.GetTypedColumnValue <int>("Point"); var color = satisfactionLevel.GetColumnValue("Colour").ToString(); var currDivStyle = string.Format(divStyle, color); result += string.Format(link, point, currDivStyle, hrefStyle); } return("<table border='0' cellpadding='0' cellspacing='1'><tr>" + result + "</tr></table>"); }
private SearchInfoRequest PrepareEnrichmentRequest() { string serviceUrl; string apiKey; GetRequiredParameters(out serviceUrl, out apiKey); #if NETFRAMEWORK _restClient.BaseUrl = serviceUrl; #else _restClient.BaseUrl = new Uri(serviceUrl); #endif _restClient.AddDefaultHeader("ApiKey", apiKey); int maxSocialLinksCount = SysSettings.GetValue(UserConnection, "EnrichmentSocialLinksLimit", 3); int maxPhoneNumbersCount = SysSettings.GetValue(UserConnection, "EnrichmentPhoneNumbersLimit", 3); int maxEmailsCount = SysSettings.GetValue(UserConnection, "EnrichmentEmailsLimit", 3); var requestBody = new SearchInfoRequest { ApiKey = apiKey, Config = new SearchInfoConfiguration { MaxSocialLinksCount = maxSocialLinksCount, MaxPhoneNumberCount = maxPhoneNumbersCount, MaxEmailsCount = maxEmailsCount } }; return(requestBody); }
public WebitelUserConnection GetUserConnection(string userId) { WebitelUserConnection response = new WebitelUserConnection(); Guid id; if (!Guid.TryParse(userId, out id)) { return(response); } var esqNumberPlan = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "WSysAccount"); EntitySchemaQueryColumn entryNumber = esqNumberPlan.AddColumn("Login"); EntitySchemaQueryColumn entryPassword = esqNumberPlan.AddColumn("Password"); esqNumberPlan.Filters.Add(esqNumberPlan.CreateFilterWithParameters(FilterComparisonType.Equal, "Contact", id)); EntityCollection entitiesNumberPlan = esqNumberPlan.GetEntityCollection(UserConnection); if (entitiesNumberPlan.Count > 0) { Entity entity = entitiesNumberPlan[0]; EntitySchemaColumn entryNumberColumnSchema = entity.Schema.Columns.GetByName(entryNumber.Name); EntitySchemaColumn entryPasswordColumnSchema = entity.Schema.Columns.GetByName(entryPassword.Name); response.login = entity.GetTypedColumnValue <string>(entryNumberColumnSchema.ColumnValueName); response.password = entity.GetTypedColumnValue <string>(entryPasswordColumnSchema.ColumnValueName); } response.customerId = (string)SysSettings.GetValue(UserConnection, "CustomerId"); return(response); }
/// <summary> /// Runs email mining and schedules next job. /// </summary> /// <param name="userConnection">User connection.</param> /// <param name="parameters">Job parameters.</param> public void Execute(UserConnection userConnection, IDictionary <string, object> parameters) { int timeShiftMinutes = 0; try { if (!SysSettings.GetValue <bool>(userConnection, EnableEmailMiningSysSettingsName, true)) { _log.InfoFormat("Email mining is disabled. See system settings value {0}", EnableEmailMiningSysSettingsName); return; } RunMiner(userConnection); } catch (IncorrectConfigurationException ex) { _log.Error(ex.Message); timeShiftMinutes = IncorrectConfigurationTimeShiftMinutes; } catch (Exception ex) { LogError(ex); throw; } finally { int periodMin = SysSettings.GetValue(userConnection, JobPeriodSysSettingsName, 0); if (periodMin == 0) { _log.Info($"SysSetting {JobPeriodSysSettingsName} equals to zero. Job will not be rescheduled."); } else { if (timeShiftMinutes > 0) { _log.Warn($"Next job will be run in {periodMin + timeShiftMinutes} minutes"); } SchedulerUtils.ScheduleNextRun(userConnection, EmailMiningAppListener.TargetJobGroupName, this, periodMin + timeShiftMinutes); } } }
/// <summary> /// Gets the API key. /// </summary> /// <param name="userConnection">The user connection.</param> /// <returns>Api key withoud leading and trailing whitespaces.</returns> private static string GetAPIKey(UserConnection userConnection) { var key = (string)SysSettings.GetValue(userConnection, "CloudServicesAPIKey"); if (key.IsNotNullOrEmpty()) { key = key.Trim(); } return(key); }
public BaseDeduplicationManager(UserConnection userConnection) { UserConnection = userConnection; DeduplicationWebApiUrl = SysSettings.GetValue(UserConnection, "DeduplicationWebApiUrl", string.Empty); if (string.IsNullOrEmpty(DeduplicationWebApiUrl)) { Log.Error("DeduplicationWebApiUrl is empty."); } GlobalSearchUrl = SysSettings.GetValue(UserConnection, "GlobalSearchUrl", string.Empty); }
/// <summary> /// Returns email template identifier for user password reminding. /// </summary> /// <param name="userConnection">User connection.</param> /// <returns>Remin password email template identifier.</returns> public static Guid GetRecoveryPasswordEmailTemplateId(UserConnection userConnection) { Guid recoveryEmailTemplateId = SysSettings.GetValue(userConnection, "PortalRecoveryPasswordEmailTemplate", Guid.Empty); if (recoveryEmailTemplateId == Guid.Empty) { recoveryEmailTemplateId = SSPConsts.RecoveryPasswordEmailTemplateId; } return(recoveryEmailTemplateId); }
/// <summary> /// Returns scoring map with scoring model and scoring rules. /// </summary> /// <returns>An <see cref="GetScoringMapResponse"/> result of invoking method.</returns> public virtual GetScoringMapResponse GetScoringMap() { GetScoringMapResponse response = new GetScoringMapResponse(); List <ScoringModel> models = GetScoringModels(); ApplyScoringRules(models); response.Models = models; DateTime?syncTime = (DateTime?)SysSettings.GetValue(UserConnection, "ScoringRulesSyncTime"); response.SyncTime = syncTime; return(response); }
/// <summary> /// Returns email template identifier for invitation template. /// </summary> /// <param name="userConnection">User connection.</param> /// <returns>Invitation email template identifier.</returns> public static Guid GetInvitationEmailTemplateId(UserConnection userConnection) { Guid invitationEmailTemplateId = SysSettings.GetValue(userConnection, "PortalInvitationEmailTemplate", Guid.Empty); if (invitationEmailTemplateId == Guid.Empty) { string errorMessage = GetLocalizableString(userConnection, "EmailTemplateNotFound"); throw new ArgumentNullOrEmptyException(errorMessage, null); } return(invitationEmailTemplateId); }
private static void SetupTrainingInfo(UserConnection userConnection, MLModelConfig modelConfig, IDataReader reader) { modelConfig.TrainingMinimumRecordsCount = reader.GetColumnValue <int>("TrainingMinimumRecordsCount"); if (modelConfig.TrainingMinimumRecordsCount == 0) { modelConfig.TrainingMinimumRecordsCount = SysSettings.GetValue(userConnection, TrainingMinimumRecordsCountSysSettingsName, 0); } modelConfig.TrainSessionId = reader.GetColumnValue <Guid>("TrainSessionId"); modelConfig.MetricThreshold = reader.GetColumnValue <double>("MetricThreshold"); modelConfig.TrainingOutputFilterData = reader.GetColumnValue <byte[]>("TrainingOutputFilterData"); }
public bool SaveEventTrackingData(Tracking tracking) { if (UserConnection == null) { _log.ErrorFormat("[EventTrackingService_SaveEventData. UserConnection = null]"); return(false); } if (tracking.ListTracking == null) { _log.ErrorFormat("[EventTrackingService_SaveEventData. ListTracking = null]"); return(false); } if (tracking.ListTracking.Count == 0) { _log.ErrorFormat("[EventTrackingService_SaveEventData. ListTracking.Count = 0]"); return(false); } var eventTrackingApiKey = SysSettings.GetValue(UserConnection, "EventTrackingApiKey").ToString(); if (tracking.ApiKey != eventTrackingApiKey) { _log.ErrorFormat("[EventTrackingService_SaveEventData. tracking.ApiKey != eventTrackingApiKey]"); return(false); } using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) { dbExecutor.StartTransaction(); try { List <Guid> eventsId = tracking.ListTracking.Select(trackingItem => trackingItem.Id).ToList(); List <Guid> existsEventsId = GetExistsSiteEventsIds(eventsId); List <TrackingParameters> newEvents = tracking.ListTracking .Where(item => !existsEventsId.Contains(item.Id)).ToList(); newEvents.ForEach(item => { var query = new Insert(UserConnection).Into("SiteEvent") .Set("Id", Column.Parameter(item.Id)) .Set("EventDate", Column.Parameter(Convert.ToDateTime(item.EventTime))) .Set("Source", Column.Parameter(item.Url)) .Set("SiteEventTypeId", Column.Parameter(item.EventTypeId)) .Set("BpmSessionId", Column.Parameter(item.SessionId)); query.Execute(dbExecutor); }); dbExecutor.CommitTransaction(); } catch (Exception e) { dbExecutor.RollbackTransaction(); _log.ErrorFormat("[EventTrackingService_SaveEventData. Insert data failed.]", e); return(false); } } return(true); }
/// <inheritdoc cref="BaseFileImporter"/> protected override void ImportInternal(Guid importSessionId) { base.ImportInternal(importSessionId); var parameters = GetImportParameters(importSessionId); parameters.ImportStage = FileImportStagesEnum.PrepareFileImportStage; parameters.ChunkSize = SysSettings.GetValue(UserConnection, "FileImportEntitySaveChunksCount", 500); SysUserInfo currentUser = UserConnection.CurrentUser; parameters.AuthorTimeZone = currentUser.TimeZone; parameters.AuthorId = currentUser.ContactId; ImportParametersRepository.Add(parameters); Import(parameters); }
public virtual void ActualizeTranslation() { const string translationActualizedOnSysSettingsCode = "TranslationActualizedOn"; DateTime dateTime = SysSettings.GetValue <DateTime>(UserConnection, translationActualizedOnSysSettingsCode, DateTime.MinValue); DataValueType dataValueType = UserConnection.DataValueTypeManager.GetDataValueTypeByValueType(typeof(DateTime)); DateTime translationActualizedOn = (DateTime)dataValueType.GetValueForSave(UserConnection, dateTime); ITranslationActualizersFactory translationActualizersFactory = ClassFactory.Get <TranslationActualizersFactory>( new ConstructorArgument("userConnection", UserConnection)); ITranslationActualizer translationActualizer = translationActualizersFactory.GetTranslationActualizer(); translationActualizer.ActualizeTranslation(translationActualizedOn); SysSettings.SetDefValue(UserConnection, translationActualizedOnSysSettingsCode, DateTime.UtcNow); }
private void GetRequiredParameters(out string serviceUrl, out string apiKey) { serviceUrl = SysSettings.GetValue(UserConnection, "AccountEnrichmentServiceUrl", string.Empty); if (serviceUrl.IsNullOrEmpty()) { throw new HttpException((int)HttpStatusCode.InternalServerError, "Enrichment account service url not set"); } apiKey = GetAPIKey(UserConnection); if (apiKey.IsNullOrEmpty()) { throw new HttpException((int)HttpStatusCode.InternalServerError, "Cloud service api key not set"); } }
private static string GetSspSupportEmail(UserConnection userConnection) { string sspSupportEmail = string.Empty; Guid sspSupportEmailId = SysSettings.GetValue(userConnection, "SSPRegistrationMailbox", default(Guid)); if (sspSupportEmailId != Guid.Empty) { Select select = new Select(userConnection) .Column("SenderEmailAddress") .From("MailboxSyncSettings") .Where("Id").IsEqual(Column.Parameter(sspSupportEmailId)) as Select; sspSupportEmail = select.ExecuteScalar <string>(); } return(sspSupportEmail); }
private void CheckRequiredParameters(out string serviceUrl, out string apiKey) { serviceUrl = SysSettings.GetValue(_userConnection, EmailMiningConsts.TextParsingServiceSysSetting, string.Empty); if (serviceUrl.IsNullOrEmpty()) { _metricReporter.Gauge(EmailMiningUnreachableMetricName, 1); throw new IncorrectConfigurationException(EmailMiningConsts.TextParsingServiceSysSetting); } apiKey = BpmonlineCloudEngine.GetAPIKey(_userConnection); if (apiKey.IsNullOrEmpty()) { _metricReporter.Gauge(EmailMiningUnreachableMetricName, 1); throw new IncorrectConfigurationException(CloudServicesAPIKey); } }
/// <summary> /// Returns bpm'online new email events endpoint uri. /// </summary> /// <returns>Bpm'online new email events endpoint uri.</returns> public string GetBpmEndpointUrl() { var endpointUrl = SysSettings.GetValue(_uc, "BpmonlineExchangeEventsEndpointUrl", ""); if (endpointUrl.IsEmpty()) { endpointUrl = GetNewBpmonlineExchangeEventsEndpointUrl(); SysSettings.SetDefValue(_uc, "BpmonlineExchangeEventsEndpointUrl", endpointUrl); } if (endpointUrl.IsEmpty()) { throw new InvalidObjectStateException("Bpmonline exchange events endpoint url cannot be created. " + "Fill BpmonlineExchangeEventsEndpointUrl system setting."); } return(endpointUrl); }
/// <summary> /// Sets route filters to null if route period greater or equal to response (campaign's campaign) /// actualization period. /// </summary> /// <param name="campaignId">Unique identifier of campaign.</param> private void UpdateUnconditionedRoutes(Guid campaignId) { var actualizePeriod = (int)SysSettings.GetValue(UserConnection, "PeriodActualizeBulkEmailRecipients") / DayHourCount; Select routePeriodSelect = GetStepRoutesSelectTemplate(campaignId, CampaignConsts.BulkEmailCampaignStepTypeId); using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) { using (IDataReader dr = routePeriodSelect.ExecuteReader(dbExecutor)) { while (dr.Read()) { var id = new Guid(dr[0].ToString()); var json = dr.GetColumnValue <string>("JSON"); double routePeriod = CampaignStepsHandler.DeserializeDayTransitionCount(json, UserConnection); if (routePeriod <= 0) { routePeriod = DefaultMinimumDayTransitionCount; } if (routePeriod >= actualizePeriod) { continue; } JObject jsonData = Json.Deserialize(json) as JObject; if (jsonData == null) { continue; } JObject jsonInfoData = jsonData[RouteJsonAddInfoSection] as JObject; if (jsonInfoData == null) { continue; } JArray jsonFiltersData = jsonInfoData[RouteJsonFilterSection] as JArray; if (jsonFiltersData == null) { continue; } jsonFiltersData.Replace(new JArray()); json = Json.Serialize(jsonData); new Update(_userConnection, "CampaignStepRoute") .Set("JSON", Column.Parameter(json)) .Where("Id").IsEqual(Column.Parameter(id)).Execute(); } } } }
/// <summary> /// Post event type to tracking service. /// </summary> /// <param name="userConnection">UserConnection.</param> /// <param name="listEventType">List event type</param> public static void SetEventType(UserConnection userConnection, List <EventType> listEventType) { var setEventTypeRequest = new SetEventType(); var eventTrackingLogin = SysSettings.GetValue(userConnection, "EventTrackingLogin").ToString(); var eventTrackingPassword = SysSettings.GetValue(userConnection, "EventTrackingPassword").ToString(); var eventTrackingApiKey = SysSettings.GetValue(userConnection, "EventTrackingApiKey").ToString(); var eventTrackingWebAppUrl = SysSettings.GetValue(userConnection, "EventTrackingWebAppUrl").ToString() + "/SetEventType?format=json"; setEventTypeRequest.SetBasicAuth(eventTrackingLogin, eventTrackingPassword); setEventTypeRequest.SetRequestMethod("POST"); setEventTypeRequest.ApiKey = eventTrackingApiKey; setEventTypeRequest.EventTypeList = listEventType; setEventTypeRequest.Execute(eventTrackingWebAppUrl); }
/// <summary> /// Start event tracking. /// </summary> /// <param name="userConnection">UserConnection.</param> /// <param name="apiKey">Api key.</param> /// <returns>Result code.</returns> public static int StartTracking(UserConnection userConnection, string apiKey) { var apiKeyRequest = new ApiKeyRequest(); string eventTrackingLogin = SysSettings.GetValue(userConnection, "EventTrackingLogin").ToString(); string eventTrackingPassword = SysSettings.GetValue(userConnection, "EventTrackingPassword").ToString(); SysSettings.SetDefValue(userConnection, "EventTrackingApiKey", apiKey); string eventTrackingWebAppUrl = SysSettings.GetValue(userConnection, "EventTrackingWebAppUrl").ToString() + "/SetupTracking?format=json"; string bpmUrl = SysSettings.GetValue(userConnection, "BpmEventTrackingServiceUrl").ToString(); string bpmAuthKey = SysSettings.GetValue(userConnection, "BpmAuthKey").ToString(); if (string.IsNullOrEmpty(bpmUrl) || string.IsNullOrEmpty(bpmAuthKey)) { return((int)EventTrackingResult.SysSettingIsEmpty); } var trackingDomainESQ = new EntitySchemaQuery(userConnection.EntitySchemaManager, "TrackingDomain"); var nameColumn = trackingDomainESQ.AddColumn("Name"); var trackingDomainCollection = trackingDomainESQ.GetEntityCollection(userConnection); apiKeyRequest.TrackingDomainList = trackingDomainCollection.Select(item => item.GetColumnValue(nameColumn.Name).ToString()).ToList(); if (!apiKeyRequest.TrackingDomainList.Any()) { return((int)EventTrackingResult.DomainIsEmpty); } apiKeyRequest.SetBasicAuth(eventTrackingLogin, eventTrackingPassword); apiKeyRequest.SetRequestMethod("POST"); apiKeyRequest.ApiKey = apiKey; apiKeyRequest.BpmAuthKey = bpmAuthKey; apiKeyRequest.BpmUrl = bpmUrl; int result = apiKeyRequest.Execute(eventTrackingWebAppUrl); if (!apiKeyRequest.Success) { return((int)EventTrackingResult.OtherError); } EventTypePostProcess.SetEventType(userConnection); return(result); }
private bool GenerateRemindingExecute(ProcessExecutingContext context) { string useGenerationStr = SysSettings.GetValue <string>(context.UserConnection, "UseGenerateAnniversaryRemindings", "true"); var useGeneration = Convert.ToBoolean(useGenerationStr); if (!useGeneration) { return(true); } var className = "Terrasoft.Configuration.BaseAnniversaryReminding"; var methodName = "GenerateActualRemindings"; Type classType = Type.GetType(className); IEnumerable <Type> inherits = Assembly.GetAssembly(classType) .GetTypes() .Where(type => type.IsSubclassOf(classType)); var args = new object[] { context.UserConnection }; Exception lastException = null; foreach (Type type in inherits) { object instance = Activator.CreateInstance(type, args); MethodInfo methodInfo = type.GetMethod(methodName, new[] { typeof(bool) }); if (methodInfo == null) { continue; } try { methodInfo.Invoke(instance, new object[] { false }); } catch (Exception e) { var log = LogManager.GetLogger("Notifications"); log.Error(e); lastException = e; } } if (lastException != null) { throw lastException; } return(true); }
/// <summary> /// Executes the job's task. /// </summary> /// <param name="userConnection">User connection.</param> /// <param name="parameters">Job parameters.</param> public void Execute(UserConnection userConnection, IDictionary <string, object> parameters) { int frequency = SysSettings.GetValue(userConnection, JobPeriodSysSettingsName, 0); if (frequency == 0) { _log.Info($"SysSetting {JobPeriodSysSettingsName} equals to zero. Task cancelled and job will not be rescheduled."); return; } try { ProcessAllModels(userConnection); } catch (IncorrectConfigurationException ex) { _log.Error(ex.Message); } catch (Exception ex) { _log.ErrorFormat("Exception was thrown during ML model batch prediction job", ex); throw; } finally { SchedulerUtils.ScheduleNextRun(userConnection, nameof(MLBatchPredictionJob), this, frequency); } }
/// <summary> /// Sets next fire time and execution period for trigger campaign. /// </summary> /// <param name="campaignId">Unique identifier of campaign.</param> /// <returns>Count of affected rows.</returns> private int UpdateCampaignFireTime(Guid campaignId) { var nextFireTime = DateTime.UtcNow; var rowsAffected = 0; double firePeriod = GetMinimumStepRoutePeriod(campaignId); int fireperiodInMinutes = (int)Math.Round((firePeriod * DayHourCount * HourMinutesCount), MidpointRounding.AwayFromZero); var actualizePeriod = (int)SysSettings.GetValue(UserConnection, "PeriodActualizeBulkEmailRecipients"); if ((actualizePeriod * HourMinutesCount) <= fireperiodInMinutes || fireperiodInMinutes <= 0) { return(rowsAffected); } var update = new Update(UserConnection, "Campaign") .Set("NextFireTime", Column.Parameter(nextFireTime)) .Set("FirePeriod", Column.Parameter(fireperiodInMinutes)) .Where("Id").IsEqual(Column.Parameter(campaignId)); rowsAffected = update.Execute(); return(rowsAffected); }
/// <summary> /// Runs ML model trainings and schedules next job. /// </summary> /// <param name="userConnection">User connection.</param> /// <param name="parameters">Job parameters.</param> public void Execute(UserConnection userConnection, IDictionary <string, object> parameters) { try { _trainingManager.ProcessAllModels(userConnection); } catch (IncorrectConfigurationException ex) { _log.Error(ex.Message); } catch (Exception ex) { LogError(ex); throw; } finally { int frequency = SysSettings.GetValue(userConnection, JobPeriodSysSettingsName, 0); if (frequency == 0) { _log.Info($"SysSetting {JobPeriodSysSettingsName} equals to zero. Job will not be rescheduled."); } else { SchedulerUtils.ScheduleNextRun(userConnection, nameof(MLModelTrainerJob), this, frequency); } } }
private AnalyticsReportingService CreateAnalyticsService() { var keyPath = String.Empty; var serviceEmail = (string)SysSettings.GetValue(_userConnection, "GAServiceEmail"); var certName = (string)SysSettings.GetValue(_userConnection, "GAServiceUniqueId"); var appName = (string)SysSettings.GetValue(_userConnection, "GAProjectName"); var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable); var certificate2 = GetCertificateFromStore(certName); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceEmail) { Scopes = new[] { AnalyticsReportingService.Scope.AnalyticsReadonly } }.FromCertificate(certificate2)); return(new AnalyticsReportingService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = appName })); }
private static AuthType GetAuthType(UserConnection userConnection) { var authTypeId = (Guid)SysSettings.GetValue(userConnection, LdapAuthType); var selectQuery = new Select(userConnection) .Column("Value") .From("LDAPAuthType").As("LAT") .Where("LAT", "Id").IsEqual(new QueryParameter(authTypeId)) as Select; using (DBExecutor executor = userConnection.EnsureDBConnection()) { using (IDataReader reader = selectQuery.ExecuteReader(executor)) { if (reader.Read()) { return((AuthType)Convert.ToInt32(reader.GetValue(reader.GetOrdinal("Value")))); } } } string errorMessage = "LDAP authentication type is not specified."; _log.Error(errorMessage); throw new Exception(errorMessage); }
/// <summary> /// Creates QRTZ job to launch actualization process of campaign steps. /// </summary> /// <param name="campaignId">Unique identifier of campaign.</param> private void CreateActualizeStepsCamapignJob(Guid campaignId) { try { UserConnection userConnection = UserConnection; if (userConnection == null) { var appConnection = (AppConnection)HttpContext.Current.Application["AppConnection"]; userConnection = appConnection.SystemUserConnection; } RemoveActualizeStepsCampaignJob(campaignId); string curCampaignJobName = ActualizeStepsCamapignJobName + campaignId; IJobDetail job = AppScheduler.CreateProcessJob(curCampaignJobName, CampaignJobGroupName, ActualizeStepsCamapignProcessName, userConnection.Workspace.Name, userConnection.CurrentUser.Name, new Dictionary <string, object> { { "CampaignId", campaignId } }); int affectedRows = UpdateCampaignFireTime(campaignId); string cronExpression = string.Empty; if (affectedRows > 0) { cronExpression = ActualizeStepsTriggerCampaignCronExpression; } if (string.IsNullOrEmpty(cronExpression)) { int interval = (int)SysSettings.GetValue(userConnection, "CampaignSyncJobPocessInterval"); if (interval <= 0 || interval > 23) { interval = DefaultCampaignSyncJobPocessInterval; } cronExpression = string.Format(ActualizeStepsCamapignCronExpressionPattern, interval); } var trigger = new CronTriggerImpl(curCampaignJobName + "Trigger", CampaignJobGroupName, cronExpression); trigger.TimeZone = TimeZoneInfo.Utc; AppScheduler.Instance.ScheduleJob(job, trigger); } catch (Exception e) { CampaignUtilities.Log.ErrorFormat("[CampaignService.CreateActualizeStepsCamapignJob].", e); } }