コード例 #1
0
        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;
        }
コード例 #2
0
 private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e)
 {
     using (ThreadDataManager.Initialize())
     {
         Execute();
     }
 }
コード例 #3
0
        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());
            }
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        /// <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());
            }
        }
コード例 #6
0
        /// <summary>
        /// Gets an instance of a DataContext.
        /// </summary>
        /// <returns></returns>
        internal DataContext GetDataContext()
        {
            string threadDataKey = "SqlDataContext" + _providerName;

            var threadData = ThreadDataManager.GetCurrentNotNull();

            if (threadData.HasValue(threadDataKey))
            {
                DataContext result = Verify.ResultNotNull(threadData[threadDataKey] as DataContext);

                // In a result of a flush, data context type can be changed
                if (result.GetType().GUID == DataContextClass.GUID)
                {
                    return(result);
                }
            }

            DataContext dataContext = CreateDataContext();

            dataContext.ObjectTrackingEnabled = false;

            threadData.OnDispose += dataContext.Dispose;

            threadData.SetValue(threadDataKey, dataContext);

            if (_sqlLoggingContext.Enabled)
            {
                dataContext.Log = new SqlLoggerTextWriter(_sqlLoggingContext);
            }

            return(dataContext);
        }
コード例 #7
0
        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;
        }
コード例 #8
0
        /// <exclude />
        public static void ApplicationStartInitialize(bool displayDebugInfo = false)
        {
            ThreadDataManager.InitializeThroughHttpContext();

            if (displayDebugInfo)
            {
                Log.LogVerbose("Global.asax", "--- Web Application Start, {0} Id = {1} ---", DateTime.Now.ToLongTimeString(), AppDomain.CurrentDomain.Id);
            }

            PerformanceCounterFacade.SystemStartupIncrement();

            using (GlobalInitializerFacade.GetPreInitHandlersScope())
            {
                ApplicationStartupFacade.FireConfigureServices(ServiceLocator.ServiceCollection);

                ServiceLocator.BuildServiceProvider();
                ServiceLocator.CreateRequestServicesScope(HttpContext.Current);

                ApplicationStartupFacade.FireBeforeSystemInitialize(ServiceLocator.ServiceProvider);
            }

            TempDirectoryFacade.OnApplicationStart();

            HostnameBindingsFacade.Initialize();

            ApplicationStartupFacade.FireSystemInitialized(ServiceLocator.ServiceProvider);

            ThreadDataManager.FinalizeThroughHttpContext();
        }
コード例 #9
0
        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;
            }
        }
コード例 #10
0
        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));
            }
        }
コード例 #11
0
        void context_BeginRequest(object sender, EventArgs e)
        {
            if (!SystemSetupFacade.IsSystemFirstTimeInitialized)
            {
                return;
            }

            ThreadDataManager.InitializeThroughHttpContext(true);

            var httpContext = (sender as HttpApplication).Context;

            if (CheckForHostnameAliasRedirect(httpContext))
            {
                return;
            }

            if (HandleMediaRequest(httpContext))
            {
                return;
            }

            SetCultureByHostname();

            PrettifyPublicMarkup(httpContext);

            HandleRootRequestInClassicMode(httpContext);
        }
コード例 #12
0
 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)));
     }
 }
コード例 #13
0
        private void InitializeThreadData()
        {
            _threadDataManager = ThreadDataManager.EnsureInitialize();

#if ConnectionLeakCheck
            _allocationCallStack = new StackTrace().ToString();
#endif
        }
コード例 #14
0
 private void refreshCodeActivity_ExecuteCode(object sender, EventArgs e)
 {
     using (ThreadDataManager.EnsureInitialize())
     {
         Log.LogVerbose("RefreshWorkflow", "Run '{0}' function", RefreshFunction.Method.Name);
         RefreshFunction();
     }
 }
コード例 #15
0
 private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e)
 {
     using (ThreadDataManager.Initialize())
         using (ServiceLocator.EnsureThreadDataServiceScope())
         {
             Execute();
         }
 }
コード例 #16
0
 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));
     }
 }
コード例 #17
0
        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();
            }
        }
コード例 #18
0
        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);
            }
        }
コード例 #19
0
        /// <exclude />
        public static void Application_BeginRequest(object sender, EventArgs e)
        {
            var context = (sender as HttpApplication).Context;

            ThreadDataManager.InitializeThroughHttpContext();

            ServiceLocator.CreateRequestServicesScope(context);

            if (LogRequestDetails)
            {
                // LoggingService.LogVerbose("Begin request", string.Format("{0}", Request.Path));
                context.Items.Add("Global.asax timer", Environment.TickCount);
            }
        }
コード例 #20
0
        /// <exclude />
        public static void Application_End(object sender, EventArgs e)
        {
            if (RuntimeInformation.IsDebugBuild)
            {
                Log.LogInformation(_verboseLogEntryTitle, "AppDomain {0} ended at {1} in process {2}", AppDomain.CurrentDomain.Id, DateTime.Now.ToString("HH:mm:ss:ff"), Process.GetCurrentProcess().Id);
            }

            if (!SystemSetupFacade.IsSystemFirstTimeInitialized)
            {
                return;
            }


            using (ThreadDataManager.Initialize())
            {
                try
                {
                    CodeGenerationManager.ValidateCompositeGenerate(_startTime);
                    CodeGenerationManager.GenerateCompositeGeneratedAssembly();
                }
                catch (Exception ex)
                {
                    Log.LogCritical("Global.asax", "Error updating Composite.Generated.dll");
                    Log.LogCritical("Global.asax", ex);
                }

                try
                {
                    GlobalEventSystemFacade.PrepareForShutDown();
                    if (RuntimeInformation.IsDebugBuild)
                    {
                        LogShutDownReason();
                    }
                    GlobalEventSystemFacade.ShutDownTheSystem();

                    TempDirectoryFacade.OnApplicationEnd();
                }
                catch (Exception ex)
                {
                    Log.LogCritical("Global.asax", ex);

                    throw;
                }

                Log.LogVerbose("Global.asax", string.Format("--- Web Application End, {0} Id = {1}---",
                                                            DateTime.Now.ToLongTimeString(),
                                                            AppDomain.CurrentDomain.Id));
            }
        }
コード例 #21
0
 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));
     }
 }
コード例 #22
0
 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());
     }
 }
コード例 #23
0
        internal static IDisposable EnsureThreadDataServiceScope()
        {
            if (RequestScopedServiceProvider != null || ServiceLocatorNotInitialized)
            {
                return(EmptyDisposable.Instance);
            }

            var current = ThreadDataManager.GetCurrentNotNull();

            var serviceScopeFactory = (IServiceScopeFactory)_serviceProvider.GetService(typeof(IServiceScopeFactory));
            var serviceScope        = serviceScopeFactory.CreateScope();

            current.SetValue(ThreadDataKey, serviceScope);

            return(new ThreadDataServiceScopeDisposable(current));
        }
コード例 #24
0
        /// <exclude />
        public static Measurement EndProfiling()
        {
            var threadData = ThreadDataManager.GetCurrentNotNull();

            var stack = threadData[ProfilerKey] as Stack <Measurement>;

            Verify.That(stack.Count == 1, "Performance node stack should have exactly one (the root) node");

            threadData.SetValue(ProfilerKey, null);

            var measurement = stack.Pop();

            measurement.MemoryUsage = GC.GetTotalMemory(false) - measurement.MemoryUsage;

            return(measurement);
        }
コード例 #25
0
        public string Authenticate(string loginAndPassword)
        {
            if (SystemSetupFacade.IsSystemFirstTimeInitialized == false)
            {
                return("");
            }

            bool userIsValid;

            string login;
            string password;

            int separatorOffset = loginAndPassword.IndexOf("|");

            if (separatorOffset > 0 && separatorOffset < loginAndPassword.Length - 1)
            {
                login    = loginAndPassword.Substring(0, separatorOffset);
                password = loginAndPassword.Substring(separatorOffset + 1);
            }
            else
            {
                // Backward compatibility with old LogViewer
                login    = "******";
                password = loginAndPassword;
            }

            bool userIsAdmin = false;

            using (ThreadDataManager.Initialize())
            {
                userIsValid = LoginProviderPluginFacade.FormValidateUser(login, password) == LoginResult.Success;

                if (userIsValid)
                {
                    string userName = login.ToLowerInvariant();
                    var    userPermissionDefinitions      = PermissionTypeFacade.GetUserPermissionDefinitions(userName).ToList();
                    var    userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(userName).ToList();

                    EntityToken rootEntityToken = AttachingPoint.PerspectivesRoot.EntityToken;
                    var         permissions     = PermissionTypeFacade.GetCurrentPermissionTypes(new UserToken(userName), rootEntityToken, userPermissionDefinitions, userGroupPermissionDefinitions);

                    userIsAdmin = permissions.Contains(PermissionType.Administrate);
                }
            }

            return((userIsValid && userIsAdmin) ? LoggerPassword : string.Empty);
        }
コード例 #26
0
        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);
        }
コード例 #27
0
 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);
         }
     }
 }
        private void scavengeCodeActivity_Scavenge_ExecuteCode(object sender, EventArgs e)
        {
            if (HostingEnvironment.ApplicationHost.ShutdownInitiated())
            {
                return;
            }

            try
            {
                using (ThreadDataManager.Initialize())
                {
                    ConsoleFacade.Scavenge();
                }
            }
            catch
            {
                // Ignore exceptions
            }
        }
コード例 #29
0
        private static void SubscribeToTransactionRollbackEvent()
        {
            var transaction = Transaction.Current;

            if (transaction == null)
            {
                return;
            }

            var currentThreadData = ThreadDataManager.GetCurrentNotNull();

            Hashset <string> transactions;

            const string tlsKey = "XmlDataProvider enlisted transactions";

            if (!currentThreadData.HasValue(tlsKey))
            {
                transactions = new Hashset <string>();
                currentThreadData.SetValue(tlsKey, transactions);
            }
            else
            {
                transactions = (Hashset <string>)currentThreadData[tlsKey];
            }

            string transactionId = transaction.TransactionInformation.LocalIdentifier;

            if (transactions.Contains(transactionId))
            {
                return;
            }

            transactions.Add(transactionId);


            ThreadStart logging = () =>
            {
                var exception = new TransactionException("XML data provider does not support transaction's API, changes were not rolled back.");
                Log.LogWarning(LogTitle, exception);
            };

            transaction.EnlistVolatile(new TransactionRollbackHandler(logging), EnlistmentOptions.None);
        }
コード例 #30
0
        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);
                }
            }
        }