/// <summary> /// Get the Url of the AddToWishList SignIn page. /// </summary> public virtual string GetSignInUrl(GetWishListUrlParam parameters) { using (ThreadDataManager.EnsureInitialize()) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.CultureInfo == null) { throw new ArgumentException("parameters.CultureInfo is required", "parameters"); } var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); var signInPath = PageService.GetPageUrl(pagesConfiguration.LoginPageId, parameters.CultureInfo); if (string.IsNullOrWhiteSpace(parameters.ReturnUrl)) { return(signInPath); } var urlBuilder = new UrlBuilder(signInPath); urlBuilder["ReturnUrl"] = GetReturnUrl(parameters); // url builder will encode the query string value return(urlBuilder.ToString()); } }
public static void GetUsersAndGroupsWithReadAccess(EntityToken entityToken, out IEnumerable <EntityToken> ancestors, out IEnumerable <string> users, out IEnumerable <Guid> userGroups) { var userSet = new HashSet <string>(); var userGroupSet = new HashSet <Guid>(); var ancestorsSet = new HashSet <EntityToken>(); using (ThreadDataManager.EnsureInitialize()) using (new DataScope(DataScopeIdentifier.Administrated)) { CollectUsersAndGroupsRec(entityToken, GetUserAccessDefinitions(), GetUserGroupAccessDefinitions(), ImmutableHashSet <string> .Empty, ImmutableHashSet <Guid> .Empty, userSet, userGroupSet, ancestorsSet, 20); } ancestors = ancestorsSet; users = userSet; userGroups = userGroupSet; }
private void OnWorkflowInstanceTerminatedCleanup(Guid instanceId) { AbortedWorkflows.Remove(instanceId); WorkflowFlowToken flowToken = new WorkflowFlowToken(instanceId); TaskManagerFacade.CompleteTasks(flowToken); ReleaseAllLocks(instanceId); SetWorkflowInstanceStatus(instanceId, WorkflowInstanceStatus.Terminated, false); RemoveFlowControllerServicesContainer(instanceId); RemoveIfExistFormData(instanceId); RemovePersistingType(instanceId); DeletePersistedWorkflow(instanceId); DeletePersistedFormData(instanceId); using (ThreadDataManager.EnsureInitialize()) { FlowControllerFacade.FlowComplete(new WorkflowFlowToken(instanceId)); } }
public virtual string GetStoreUrl(GetStoreUrlParam parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (string.IsNullOrWhiteSpace(parameters.BaseUrl)) { throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(parameters.BaseUrl)), nameof(parameters)); } if (string.IsNullOrWhiteSpace(parameters.StoreNumber)) { throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(parameters.StoreNumber)), nameof(parameters)); } if (parameters.CultureInfo == null) { throw new ArgumentException(GetMessageOfNull(nameof(parameters.CultureInfo)), nameof(parameters)); } // Because of ConfigureAwait(false), we lost context here. // Therefore we need to re-initialize C1 context because getting the Url. using (ThreadDataManager.EnsureInitialize()) { var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); if (pagesConfiguration == null) { return(null); } var baseUrl = PageService.GetPageUrl(pagesConfiguration.StoreListPageId, parameters.CultureInfo); var url = string.Format(UrlTemplate, baseUrl, UrlFormatter.Format(parameters.StoreName), parameters.StoreNumber); var urlBuilder = new UrlBuilder(url); return(urlBuilder.ToString()); } }
private void watcher_Changed(object sender, FileSystemEventArgs e) { if (FunctionNotifier == null || !HandleChange(e.FullPath)) { return; } lock (_lock) { var timeSpan = DateTime.Now - _lastUpdateTime; if (!(timeSpan.TotalMilliseconds > 100)) { return; } Thread.Sleep(50); using (ThreadDataManager.EnsureInitialize()) { FunctionNotifier.FunctionsUpdated(); } _lastUpdateTime = DateTime.Now; } }
private static void EnsureHookingFacade(object timeSpanToDelayStart) { // NOTE: Condition is made for unit-testing if (System.Web.Hosting.HostingEnvironment.IsHosted) { var kvp = (KeyValuePair <TimeSpan, StackTrace>)timeSpanToDelayStart; _hookingFacadeException = null; Thread.Sleep(kvp.Key); try { using (ThreadDataManager.EnsureInitialize()) { HookingFacade.EnsureInitialization(); } } catch (Exception ex) { _hookingFacadeException = ex; } } _hookingFacadeThread = null; }
Message IRequestHandler.ProcessRequestForMessage(Stream messageBody) { Message result; // System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true; IDisposable disposable = null; try { disposable = ThreadDataManager.EnsureInitialize(); result = base.ProcessRequestForMessage(messageBody); } catch (Exception) { if (disposable != null) { disposable.Dispose(); } throw; } var messageWrapper = new MessageWrapper(result); messageWrapper.OnDispose += disposable.Dispose; return(messageWrapper); }
private void InitializeThreadData() { _threadDataManager = ThreadDataManager.EnsureInitialize(); #if ConnectionLeakCheck _allocationCallStack = new StackTrace().ToString(); #endif }
private void refreshCodeActivity_ExecuteCode(object sender, EventArgs e) { using (ThreadDataManager.EnsureInitialize()) { Log.LogVerbose("RefreshWorkflow", "Run '{0}' function", RefreshFunction.Method.Name); RefreshFunction(); } }
private void refreshCodeActivity_ExecuteCode(object sender, EventArgs e) { using (ThreadDataManager.EnsureInitialize()) { FeedAggregatorFacade.UpdateFeeds(Queries); LoggingService.LogVerbose("FeedAggregator", string.Format("Update feeds: {0}", string.Join(", ", Queries))); } }
private string GetPageUrl(Guid pageId, CultureInfo cultureInfo) { // Because of ConfigureAwait(false), we lost context here. // Therefore we need to re-initialize C1 context because getting the Url. using (ThreadDataManager.EnsureInitialize()) { return(PageService.GetPageUrl(pageId, cultureInfo)); } }
private void UpdateTypes(IEnumerable <SynchronizationTypeDefinition> types) { lock (UpdateLock) { _log.AppendToLog("Job started"); using (ThreadDataManager.EnsureInitialize()) { using (var data = new DataConnection()) { try { foreach (var t in types) { _cancellationToken.ThrowIfCancellationRequested(); try { t.Method.Invoke(this, new[] { t.Mapper, data, t.PostProcessor }); } catch (OperationCanceledException) { throw; } catch (ThreadAbortException exc) { throw new OperationCanceledException("Thread aborted", exc); } catch (Exception exc) { if (exc.InnerException is OperationCanceledException) { throw exc.InnerException; } _log.LogException(t.Type, exc); } } } catch (OperationCanceledException exc) { _log.AppendToLog("Operation canceled with message '{0}'", exc.Message); throw; } catch (Exception exc) { _log.AppendToLog("Error when updating data: {0}", exc); } } } _log.AppendToLog("Job finished"); _log.Dispose(); } }
public void Execute(BackgroundProcessContext context) { try { SetCultureFromWebConfig(); ECommerceLog.WriteLog("Worker is starting, orderprocessor is " + ECommerce.OrderProcessor.GetType().FullName); var ticker = 60; using (ThreadDataManager.EnsureInitialize()) { while (!context.IsShutdownRequested) { try { if (!_processOrdersNow && ticker != 60) { continue; } _processOrdersNow = false; PostProcessPendingOrders(context); } catch (Exception ex) { ECommerceLog.WriteLog("Unhandled error when postprocessing orders", ex); } finally { if (ticker == 60) { ticker = 0; } ticker = ticker + 1; context.CancellationToken.WaitHandle.WaitOne(OneSecond); context.CancellationToken.ThrowIfCancellationRequested(); } } } } catch (OperationCanceledException) { } catch (Exception ex) { ECommerceLog.WriteLog("Unhandled error in ThreadDataManager, worker is stopping", ex); } }
public virtual string GetStoreLocatorUrl(GetStoreLocatorUrlParam parameters) { using (ThreadDataManager.EnsureInitialize()) { var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); var url = PageService.GetPageUrl(pagesConfiguration.StoreListPageId, parameters.CultureInfo); if (string.IsNullOrEmpty(url)) { Log.LogError("StoreUrlProvider", "StoreList PageId is not configured"); return(string.Empty); } var urlBuilder = new UrlBuilder(url); return(urlBuilder.ToString()); } }
public virtual string GetStoresDirectoryUrl(GetStoresDirectoryUrlParam parameters) { using (ThreadDataManager.EnsureInitialize()) { var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); var url = PageService.GetPageUrl(pagesConfiguration.StoreDirectoryPageId, parameters.CultureInfo); var urlBuilder = new UrlBuilder(url); var queryString = new NameValueCollection(); if (parameters.Page != 1) { queryString.Add("page", parameters.Page.ToString()); } return(UrlFormatter.AppendQueryString(urlBuilder.ToString(), queryString)); } }
public string BuildCategoryBrowsingUrl(BuildCategoryBrowsingUrlParam param) { var websiteId = WebsiteContext.WebsiteId; var scope = DataScopeManager.CurrentDataScope; var key = $"{websiteId}{param.CategoryId}{param.IsAllProductsPage}{scope}"; var cacheKey = new CacheKey(CacheConfigurationCategoryNames.CategoryUrls, key, param.CultureInfo); var categoryBaseUrl = CacheProvider.GetOrAdd(cacheKey, () => { // Because of ConfigureAwait(false), we lost context here. // Therefore we need to re-initialize C1 context because getting the Url. using (ThreadDataManager.EnsureInitialize()) { var map = GetCategoryMap(scope, param.CultureInfo); if (!map.TryGetValue(param.CategoryId, out var categoryPages)) { return(null); } foreach (var categoryPage in categoryPages.Where(_ => _.IsAllProductsPage == param.IsAllProductsPage)) { if (HasAncestor(categoryPage.PageId, websiteId)) { return(PageService.GetPageUrl(categoryPage.PageId, param.CultureInfo)); } } } return(null); }); // Category page is not found if (categoryBaseUrl == null) { return(null); } var finalUrl = UrlFormatter.AppendQueryString(categoryBaseUrl, BuildSearchQueryString(new BuildSearchUrlParam { SearchCriteria = param.Criteria })); return(finalUrl); }
public static void Run(object data) { using (ThreadDataManager.EnsureInitialize()) { try { if (NeedToRun()) { Functions.Send404MailReport(); } } catch (Exception ex) { _exception = ex; Log.LogError("Composite.Tools.LegacyUrlHandler Send404Mails Thread", ex); } } }
public static void Initialize() { lock (typeof(HostnameBindingsFacade)) { using (ThreadDataManager.EnsureInitialize()) { if (DataFacade.GetData <IUrlConfiguration>().Any()) { return; } var configurationData = DataFacade.BuildNew <IUrlConfiguration>(); configurationData.Id = new Guid("c7bd886b-7208-4257-b641-df2571a4872b"); configurationData.PageUrlSuffix = string.Empty; DataFacade.AddNew(configurationData); } } }
/// <summary> /// Filtering search results to which the given user does not have read access permission. /// </summary> /// <param name="userName"></param> public void FilterByUser(string userName) { Verify.ArgumentNotNullOrEmpty(userName, nameof(userName)); var tokens = new List <string> { userName }; using (ThreadDataManager.EnsureInitialize()) { tokens.AddRange(UserGroupFacade.GetUserGroupIds(userName).Select(id => id.ToString())); } Selection.Add(new SearchQuerySelection { FieldName = DocumentFieldNames.ConsoleAccess, Operation = SearchQuerySelectionOperation.Or, Values = tokens.ToArray() }); }
public virtual string GetStoreUrl(GetStoreUrlParam parameters) { Assert(parameters); // Because of ConfigureAwait(false), we lost context here. // Therefore we need to re-initialize C1 context because getting the Url. using (ThreadDataManager.EnsureInitialize()) { var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); if (pagesConfiguration == null) { return(null); } var baseUrl = PageService.GetPageUrl(pagesConfiguration.StoreListPageId, parameters.CultureInfo); var url = string.Format(UrlTemplate, baseUrl, UrlFormatter.Format(parameters.StoreName), parameters.StoreNumber); var urlBuilder = new UrlBuilder(url); return(urlBuilder.ToString()); } }
/// <summary> /// Loads task persisted in database /// </summary> private void LoadTasks() { using (ThreadDataManager.EnsureInitialize()) { IEnumerable <ITaskItem> taskItems = DataFacade.GetData <ITaskItem>().Evaluate(); var toDelete = new List <ITaskItem>(); foreach (ITaskItem taskItem in taskItems) { Type type = TypeManager.TryGetType(taskItem.TaskManagerType); if (type == null) { Log.LogWarning(nameof(TaskManagerFacade), $"Removing task item with id '{taskItem.TaskId}'. The Task Manager Type '{taskItem.TaskManagerType}' can not be found."); toDelete.Add(taskItem); if (toDelete.Count >= 100) { DataFacade.Delete <ITaskItem>(toDelete); toDelete.Clear(); } continue; } Task task = new Task(taskItem.TaskId, type) { StartTime = taskItem.StartTime, FlowToken = taskItem.SerializedFlowToken }; _tasks.Add(task); } if (toDelete.Count > 0) { DataFacade.Delete <ITaskItem>(toDelete); } } }
private void ReloadAllTrees() { using (ThreadDataManager.EnsureInitialize()) { LoadAllTrees(); InitializeTreeAttachmentPoints(); TreeSharedRootsFacade.Clear(); using (_resourceLocker.ReadLocker) { var refreshTreeMessageQueueItem = new RefreshTreeMessageQueueItem { EntityToken = _resourceLocker.Resources.RootEntityToken }; ConsoleMessageQueueFacade.Enqueue(refreshTreeMessageQueueItem, null); } } }
private void OnNewWorkflowFileAdded(Guid instanceId) { Thread.Sleep(100); if (HostingEnvironment.ApplicationHost.ShutdownInitiated()) { return; } Log.LogInformation(LogTitle, "New workflow detected: " + instanceId); using (ThreadDataManager.EnsureInitialize()) { LoadPersistedWorkflow(instanceId); string formDataFilename = GetFormDataFileName(instanceId); if (C1File.Exists(formDataFilename)) { TryLoadPersistedFormData(formDataFilename); } } }
public virtual string GetShareUrl(GetShareWishListUrlParam parameters) { using (ThreadDataManager.EnsureInitialize()) { var token = SharedWishListTokenizer.GenerateToken(new SharedWishListToken { CustomerId = parameters.CustomerId, Scope = parameters.Scope }); var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); var shareWishListPageUrl = PageService.GetPageUrl(pagesConfiguration.SharedWishListPageId, parameters.CultureInfo); var url = $"{shareWishListPageUrl}?id={token}"; var uri = new Uri( new Uri(parameters.BaseUrl, UriKind.Absolute), new Uri(url, UriKind.Relative)); return(uri.ToString()); } }
public static void GetUsersAndGroupsWithReadAccess(EntityToken entityToken, out IEnumerable <string> users, out IEnumerable <Guid> userGroups) { var userSet = new HashSet <string>(); var userGroupSet = new HashSet <Guid>(); using (ThreadDataManager.EnsureInitialize()) { CollectUsersAndGroupsRec(entityToken, GetUserAccessDefinitions(), GetUserGroupAccessDefinitions(), ImmutableHashSet <string> .Empty, ImmutableHashSet <Guid> .Empty, userSet, userGroupSet, new HashSet <EntityToken>(), 20); } users = userSet; userGroups = userGroupSet; }
/// <summary> /// Get the Url of the WishList page. /// </summary> public virtual string GetWishListUrl(GetWishListUrlParam parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (parameters.CultureInfo == null) { throw new ArgumentException(GetMessageOfNull(nameof(parameters.CultureInfo)), nameof(parameters)); } using (ThreadDataManager.EnsureInitialize()) { var pagesConfiguration = SiteConfiguration.GetPagesConfiguration(parameters.CultureInfo, WebsiteContext.WebsiteId); if (pagesConfiguration == null) { return(null); } return(PageService.GetPageUrl(pagesConfiguration.MyWishListPageId, parameters.CultureInfo)); } }
void OnFileWatcherEvent(object sender, FileSystemEventArgs e) { FileSystemEventHandler hander = FileChangedEvent; if (hander != null) { lock (_fileUpdateLock) { bool fileExists = true; if (fileExists) { // Supress multiple events fireing by observing last write time DateTime writeTime = C1File.GetLastWriteTime(e.FullPath); if (_lastWriteHandleTime < writeTime) { _lastWriteHandleTime = writeTime; try { using (ThreadDataManager.EnsureInitialize()) { hander(sender, e); } } catch (ThreadAbortException) { } catch (Exception ex) { Log.LogWarning(LogTitle, "Failed to reload functions on file watcher event"); Log.LogError(LogTitle, ex); } } } } } }
/// <summary> /// Loads task persisted in database /// </summary> private void LoadTasks() { using (ThreadDataManager.EnsureInitialize()) { IEnumerable <ITaskItem> taskItems = DataFacade.GetData <ITaskItem>().Evaluate(); foreach (ITaskItem taskItem in taskItems) { Type type = TypeManager.TryGetType(taskItem.TaskManagerType); if (type == null) { LoggingService.LogWarning("TaskManagerFacade", string.Format("Could not get the type '{0}'", taskItem.TaskManagerType)); LoggingService.LogWarning("TaskManagerFacade", string.Format("Removing task item with id '{0}'. The Task Manager Type can not be found.", taskItem.TaskId)); DataFacade.Delete <ITaskItem>(taskItem); continue; } Task task = new Task(taskItem.TaskId, type); task.StartTime = taskItem.StartTime; task.FlowToken = taskItem.SerializedFlowToken; _tasks.Add(task); } } }
/// <summary> /// This method will initialize the system (if it has not been initialized). /// </summary> public static void InitializeTheSystem() { Verify.That(!_preInitHandlersRunning, "DataFacade related methods should not be called in OnBeforeInitialize() method of a startup handler. Please move the code to OnInitialized() instead."); // if (AppDomain.CurrentDomain.Id == 3) SimpleDebug.AddEntry(string.Format("INITIALIZING {0} {1} {2}", Thread.CurrentThread.ManagedThreadId, _initializing, _coreInitialized)); if (_exceptionThrownDuringInitialization != null) { TimeSpan timeSpan = DateTime.Now - _exceptionThrownDuringInitializationTimeStamp; if (timeSpan < TimeSpan.FromMinutes(5.0)) { Log.LogCritical(LogTitleNormal, "Exception recorded:" + timeSpan + " ago"); throw new Exception("Failed to initialize the system", _exceptionThrownDuringInitialization); } _exceptionThrownDuringInitialization = null; } if (!_initializing && !_coreInitialized) { using (GlobalInitializerFacade.CoreLockScope) { if (!_initializing && !_coreInitialized) { try { _initializing = true; if (!SystemSetupFacade.IsSystemFirstTimeInitialized && RuntimeInformation.IsDebugBuild) { Log.LogWarning(LogTitleNormal, new InvalidOperationException("System is initializing, yet missing first time initialization")); } using (ThreadDataManager.EnsureInitialize()) { DoInitialize(); } GC.Collect(); // Collecting generation 2 after initialization _fatalErrorFlushCount = 0; } catch (Exception ex) { _exceptionThrownDuringInitialization = ex; _exceptionThrownDuringInitializationTimeStamp = DateTime.Now; var shutdownReason = HostingEnvironment.ShutdownReason; if (shutdownReason != ApplicationShutdownReason.None) { Log.LogCritical(LogTitleNormal, "Shutdown reason: " + HostingEnvironment.ShutdownReason); } Log.LogCritical(LogTitleNormal, ex); throw; } finally { _coreInitialized = true; _initializing = false; } } EnabledUnhandledExceptionsLogging(); } } }
private void InitializeThreadData() { _threadDataManager = ThreadDataManager.EnsureInitialize(); }