Exemplo n.º 1
0
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var returnUrl = context.HttpContext.Request.Url;
     var redirectUrl = urlHelper.Action("RequestToken", "TwitterOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl });
     return redirectUrl;
 }
Exemplo n.º 2
0
      protected sealed override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex)
      {     
         if (m_BeforeMatches.Count>0)
          foreach(var match in m_BeforeMatches.OrderedValues)
          {
            var matched = match.Make(work);
            if (matched!=null)
            {
              DoBeforeWork(work, matched);
              break;
            }
          }

         this.InvokeNextWorker(work, filters, thisFilterIndex);

         if (m_AfterMatches.Count>0)
          foreach(var match in m_AfterMatches.OrderedValues)
          {
            var matched = match.Make(work);
            if (matched!=null)
            {
              DoAfterWork(work, matched);
              break;
            }
          }
      }
 public ThemedViewResultFilter(IThemeManager themeManager, WorkContext workContext, ILayoutAwareViewEngine layoutAwareViewEngine)
 {
     _themeManager = themeManager;
     _workContext = workContext;
     _layoutAwareViewEngine = layoutAwareViewEngine;
     Logger = NullLogger.Instance;
 }
        public MissingSettingsBanner(IOrchardServices orchardServices, IWorkContextAccessor workContextAccessor)
        {
            _orchardServices = orchardServices;
            _workContext = workContextAccessor.GetContext();

            T = NullLocalizer.Instance;
        }
Exemplo n.º 5
0
        public string GetAccessToken(WorkContext wc, string code, string returnUrl)
        {
            try
            {
                var part = wc.CurrentSite.As<FacebookSettingsPart>();
                var clientId = part.ClientId;
                var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
                var url = string.Format(TokenRequestUrl, urlHelper.Encode(clientId), urlHelper.Encode(redirectUrl), urlHelper.Encode(clientSecret), urlHelper.Encode(code));
                var wr = WebRequest.Create(url);
                wr.Proxy = OAuthHelper.GetProxy();
                wr.Method = "GET";
                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var result = HttpUtility.ParseQueryString(sr.ReadToEnd());
                    return result["access_token"];
                }
                }
            catch (Exception ex)
            {
                string error = OAuthHelper.ReadWebExceptionMessage(ex);
                Logger.Error(ex, string.IsNullOrEmpty(error) ? ex.Message : error);
            }
            
            return null;
        }
 public ProfilerFilter(WorkContext workContext, IAuthorizer authorizer, IShapeFactory shapeFactory, IProfilerService profiler)
 {
     this.workContext = workContext;
     this.shapeFactory = shapeFactory;
     this.authorizer = authorizer;
     this.profiler = profiler;
 }
        public DataMigrationNotificationProvider(IDataMigrationManager dataMigrationManager, WorkContext workContext)
        {
            _dataMigrationManager = dataMigrationManager;
            _workContext = workContext;

            T = NullLocalizer.Instance;
        }
        public LayoutAwareViewEngine(IThemeAwareViewEngine themeAwareViewEngine, WorkContext workContext, IDisplayHelperFactory displayHelperFactory)
        {
            _themeAwareViewEngine = themeAwareViewEngine;
            _workContext = workContext.AsMvcWorkContext();
            _displayHelperFactory = displayHelperFactory;

            Logger = NullLogger.Instance;
        }
Exemplo n.º 9
0
 public TemplatesFilter(
     WorkContext workContext, 
     IAuthorizer authorizer,
     IShapeFactory shapeFactory) {
     _workContext = workContext;
     _authorizer = authorizer;
     _shapeFactory = shapeFactory;
 }
Exemplo n.º 10
0
 protected override void DoAfterWork(WorkContext work, JSONDataMap matched)
 {
   var txt = matched[VAR_ERROR].AsString();
   if (txt.IsNotNullOrWhiteSpace())
       throw new WaveException(txt);
   else
    work.Aborted = true;
 }
 public AdminCultureSelectorFactory(
     IWorkContextAccessor workContextAccessor, 
     IShapeFactory shapeFactory,
     ICultureManager cultureManager) {
     _cultureManager = cultureManager;
     _workContext = workContextAccessor.GetContext();
     Shape = shapeFactory;
 }
Exemplo n.º 12
0
      protected sealed override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex)
      {     
        if (work.m_PortalFilter==null)
        {
          try
          {
            work.m_PortalFilter = this;
            
            foreach(var match in m_PortalMatches.OrderedValues)
            {
              var matched = match.Make(work);
              if (matched!=null)
              {
                var portalName = matched[VAR_PORTAL_NAME].AsString();
                if (portalName.IsNotNullOrWhiteSpace())
                {
                  var portal = PortalHub.Instance.Portals[portalName];
                  if (portal!=null && !portal.Offline)
                  {
                    work.m_Portal = portal;
                    work.m_PortalMatch = match;
                    work.m_PortalMatchedVars = matched;
                  }
                  break;
                }
              }
            }

            if (work.m_Portal==null)
            {
              var defaultPortal = PortalHub.Instance.DefaultOnline;
              if (defaultPortal!=null)
              {
                 work.m_Portal = defaultPortal;
              } 
            }

            if (Server.m_InstrumentationEnabled &&
                work.m_Portal!=null && 
                work.m_Portal.InstrumentationEnabled)
            {
              Server.m_Stat_PortalRequest.IncrementLong(work.m_Portal.Name);
            }

            this.InvokeNextWorker(work, filters, thisFilterIndex);
          }
          finally
          {
            work.m_PortalFilter = null;
            work.m_Portal = null;
            work.m_PortalMatch = null;
            work.m_PortalMatchedVars = null;
            work.PortalTheme = null;
          }
        }
        else this.InvokeNextWorker(work, filters, thisFilterIndex);
      }
		public bool SetAuthenticatedUserForRequest(HttpRequestMessage request, WorkContext workContext)
		{
			var membershipService = workContext.Resolve<IMembershipService>();
			var authenticationService = workContext.Resolve<IAuthenticationService>();

			var credentials = this.GetCredentials(request.Headers.Authorization);
			var user = this.GetUserForCredentials(credentials, membershipService);
			return this.SetAuthenticatedUserForRequest(user, authenticationService);
		}
Exemplo n.º 14
0
 protected override void DoBeforeWork(WorkContext work, JSONDataMap matched)
 {
     work.Log(
        matched[VAR_TYPE].AsEnum<MessageType>(MessageType.Info),
        matched[VAR_TEXT].AsString(work.About),
        matched[VAR_FROM].AsString("{0}.Before".Args(GetType().FullName)),
        pars: matched.ToJSON(JSONWritingOptions.CompactASCII)
        );
 }
 public InlineShapeFactory(IAuthorizer authorizer, 
     IWorkContextAccessor workContextAccessor,
     IShapeTableManager shapeTableManager,
     IThemeManager themeManager) {
     _authorizer = authorizer;
     _shapeTableManager = shapeTableManager;
     _themeManager = themeManager;
     _workContext = workContextAccessor.GetContext();
 }
Exemplo n.º 16
0
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<FacebookSettingsPart>();
     var clientId = part.ClientId;
     var returnUrl = context.HttpContext.Request.Url;
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), urlHelper.Encode(returnUrl.ToString()));
 }
Exemplo n.º 17
0
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<LinkedInSettingsPart>();
     var clientId = part.ClientId;
     var returnUrl = context.HttpContext.Request.Url;
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "LinkedInOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl })).ToString();//
     var state = Guid.NewGuid().ToString().Trim('{', '}');
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state);
 }
 public TinyMceShapeDisplayEvent(
     ICacheManager cacheManager,
     IVirtualPathProvider virtualPathProvider,
     IWorkContextAccessor workContextAccessor,
     ISignals signals) {
     _signals = signals;
     _cacheManager = cacheManager;
     _virtualPathProvider = virtualPathProvider;
     _workContext = workContextAccessor.GetContext();
 }
Exemplo n.º 19
0
        public ThemeAwareViewEngine(
            WorkContext workContext,
            IEnumerable<IViewEngineProvider> viewEngineProviders,
            IConfiguredEnginesCache configuredEnginesCache) {
            _workContext = workContext;
            _viewEngineProviders = viewEngineProviders;
            _configuredEnginesCache = configuredEnginesCache;

            Logger = NullLogger.Instance;
        }
 public void Init() {
     var builder = new ContainerBuilder();
     _workContext = new StubWorkContext();
     builder.RegisterInstance(new StubCultureSelector("fr-CA")).As<ICultureSelector>();
     builder.RegisterInstance(new StubHttpContext("~/"));
     builder.RegisterInstance(_workContext);
     builder.RegisterType<StubHttpContextAccessor>().As<IHttpContextAccessor>();
     builder.RegisterType<CurrentCultureWorkContext>().As<IWorkContextStateProvider>();
     _container = builder.Build();
     _currentCultureStateProvider = _container.Resolve<IWorkContextStateProvider>();
 }
        private DoubanAccessTokenJsonModel GetAccessToken(WorkContext wc, string code)
        {
            try
            {
                var part = wc.CurrentSite.As<DoubanSettingsPart>();
                var clientId = part.ClientId;
                var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "DoubanOAuth", new { Area = "Cabbage.OAuth" })).ToString();

                var encodeUrl = urlHelper.Encode(redirectUrl);

                var wr = WebRequest.Create(string.Format(TokenRequestUrl, clientId, clientSecret, code, encodeUrl));
                wr.Proxy = OAuthHelper.GetProxy();
                wr.ContentType = "application/x-www-form-urlencoded";
                wr.Method = "POST";
                using (var stream = wr.GetRequestStream())
                using (var ws = new StreamWriter(stream, Encoding.UTF8))
                {
                    //此段参数为保险起见,加入的,实际上只需要URL拼接即可
                    ws.Write("client_id={0}&", clientId);
                    ws.Write("client_secret={0}&", clientSecret);
                    ws.Write("grant_type=authorization_code&");
                    ws.Write("code={0}&", code);
                    ws.Write("redirect_uri={0}", encodeUrl);

                }
                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                {
                    return OAuthHelper.FromJson<DoubanAccessTokenJsonModel>(stream);
                }
            }
            catch (WebException ex)
            {
                var webResponse = ex.Response as HttpWebResponse;
                using (var stream = webResponse.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var error = sr.ReadToEnd();
                    Logger.Error(ex, error);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
            }

            return null;
        }
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<RenrenSettingsPart>();
     var clientId = part.ClientId;
     var additional = part.Additional;
     //用于第三方应用防止CSRF攻击,成功授权后回调时会原样带回。请务必严格按照流程检查用户与state参数状态的绑定.
     var returnUrl = context.HttpContext.Request.Url;
     var state = urlHelper.Encode(returnUrl.ToString());
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "RenrenOAuth", new { Area = "Cabbage.OAuth" })).ToString();
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state, (string.IsNullOrWhiteSpace(additional) ? "" : ("&" + additional)));
 }
Exemplo n.º 23
0
 public ShapeTracingFactory(
     IWorkContextAccessor workContextAccessor, 
     IShapeTableManager shapeTableManager, 
     IThemeManager themeManager, 
     IWebSiteFolder webSiteFolder,
     IAuthorizer authorizer
     ) {
     _workContext = workContextAccessor.GetContext();
     _shapeTableManager = shapeTableManager;
     _themeManager = themeManager;
     _webSiteFolder = webSiteFolder;
     _authorizer = authorizer;
 }
Exemplo n.º 24
0
      protected override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex)
      {     
        if (m_Permissions!=null && m_Permissions.Any())
        {
          if (!m_BypassMatches.Any(match => match.Make(work)!=null))
          {
            work.NeedsSession();
            Permission.AuthorizeAndGuardAction(m_Permissions, "{0}({1})".Args(GetType().FullName, this.Name), work.Session);
          }
        }

        this.InvokeNextWorker(work, filters, thisFilterIndex);
      }
 public ShapeTracingFactory(
     WorkContext workContext, 
     IShapeTableManager shapeTableManager, 
     IThemeManager themeManager, 
     IWebSiteFolder webSiteFolder,
     IAuthorizer authorizer
     ) {
     _workContext = workContext;
     _shapeTableManager = shapeTableManager;
     _themeManager = themeManager;
     _webSiteFolder = webSiteFolder;
     _authorizer = authorizer;
 }
Exemplo n.º 26
0
        /// <summary>
        /// Get navigation list using full path
        /// </summary>
        /// <returns>Navigation list</returns>
        public static IEnumerable<Navigation> GetNavigationHierarchy(string fullPath, WorkContext workContext)
        {
            var navigations = new List<Navigation>();
            int indexStart = fullPath.IndexOf("/Publication/") + 1;
            string[] navigationParts = fullPath.Substring(indexStart, (fullPath.Length - indexStart)).Split('/');
            string currentPath = fullPath.Substring(0, indexStart - 1);
            string partName;
            int index = 0;
            while( index < (navigationParts.Count() - 1)){
                switch (navigationParts[index])
                {
                    case("Publication"):
                        partName = "Publications";
                        break;
                    case ("Issue"):
                        partName = "Issues";
                        break;
                    case ("Article"):
                        partName = "Articles";
                        break;
                    case ("Category"):
                        partName = "Categories";
                        break;
                    default:
                        partName = "";
                        break;
                }

                var orchardServices = workContext.Resolve<IOrchardServices>();
                var name = "";
                if (index < (navigationParts.Count() - 2))
                {
                    var navigationValue = GetNavigationValue(navigationParts[index + 1]);
                    if (navigationValue > 0) {
                        name = GetNavigationName(partName, navigationValue, orchardServices);
                    }
                }

                currentPath = currentPath + "\\" + navigationParts[index];
                index++;
                if (partName != "")
                {
                    navigations.Add(new Navigation { Name = partName, Path = currentPath });
                }
                if(name != "") {
                    navigations.Add(new Navigation { Name = name, Path = "" });
                }
            }

            return navigations;
        }
        public ThemeAwareViewEngine(
            WorkContext workContext,
            IEnumerable<IViewEngineProvider> viewEngineProviders,
            IConfiguredEnginesCache configuredEnginesCache,
            IExtensionManager extensionManager,
            ShellDescriptor shellDescriptor) {
            _workContext = workContext;
            _viewEngineProviders = viewEngineProviders;
            _configuredEnginesCache = configuredEnginesCache;
            _extensionManager = extensionManager;
            _shellDescriptor = shellDescriptor;

            Logger = NullLogger.Instance;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Override to add logic/filtering finally after the invocation of action method
        /// </summary>
        protected internal virtual void ActionInvocationFinally(WorkContext work, string action, MethodInfo method, object[] args, object result)
        {
            //1 Method Level
             var filters = GetActionFilters(method);
             if (filters!=null)
               for(var i=filters.Length-1; i>=0; i--)
             filters[i].ActionInvocationFinally(this, work, action, method, args, ref result);

             //2 Class Level
             filters = GetActionFilters(GetType());
             if (filters!=null)
               for(var i=filters.Length-1; i>=0; i--)
             filters[i].ActionInvocationFinally(this, work, action, method, args, ref result);
        }
Exemplo n.º 29
0
 public LinkRewriteService(
     IWorkContextAccessor wca,
     IRepository<LinkRewriteSettingsRecord> rewriteRuleRepository,
     IContentManager contentManager,
     ICacheManager cacheManager,
     ISignals signals)
 {
     _context = wca.GetContext();
     _rewriteRuleRepository = rewriteRuleRepository;
     _contentManager = contentManager;
     _cacheManager = cacheManager;
     _signals = signals;
     T = NullLocalizer.Instance;
 }
 public PerformanceMonitorDataService(
     IClock clock,
     ISignals signals,
     IRepository<PerformanceMonitorRecord> performanceMonitorRecordRepository,
     IRepository<PerformanceMonitorDataRecord> performanceMonitorDataRecordRepository,
     WorkContext workContext
     ) 
 { 
     _clock = clock;
     _signals = signals;
     _performanceMonitorRecordRepository = performanceMonitorRecordRepository;
     _performanceMonitorDataRecordRepository = performanceMonitorDataRecordRepository;
     _workContext = workContext;
     T = NullLocalizer.Instance;
 }
Exemplo n.º 31
0
        public virtual Collection ToLiquidCollection(storefrontModel.Category category, WorkContext workContext)
        {
            var result = new Collection();

            result.Id            = category.Id;
            result.Description   = null;
            result.Handle        = category.SeoInfo != null ? category.SeoInfo.Slug : category.Id;
            result.Title         = category.Name;
            result.Url           = category.Url;
            result.DefaultSortBy = "manual";
            result.Images        = category.Images.Select(x => x.ToShopifyModel()).ToArray();
            if (category.PrimaryImage != null)
            {
                result.Image = ToLiquidImage(category.PrimaryImage);
            }

            if (category.Products != null)
            {
                result.Products = new MutablePagedList <Product>((pageNumber, pageSize, sortInfos) =>
                {
                    category.Products.Slice(pageNumber, pageSize, sortInfos);
                    return(new StaticPagedList <Product>(category.Products.Select(x => ToLiquidProduct(x)), category.Products));
                }, category.Products.PageNumber, category.Products.PageSize);
            }

            if (category.Parents != null)
            {
                result.Parents = new Collections(new MutablePagedList <Collection>((pageNumber, pageSize, sortInfos) =>
                {
                    category.Parents.Slice(pageNumber, pageSize, sortInfos);
                    return(new StaticPagedList <Collection>(category.Parents.Select(x => ToLiquidCollection(x, workContext)), category.Parents));
                }, category.Parents.PageNumber, category.Parents.PageSize));
            }

            if (category.Categories != null)
            {
                result.Collections = new Collections(new MutablePagedList <Collection>((pageNumber, pageSize, sortInfos) =>
                {
                    category.Categories.Slice(pageNumber, pageSize, sortInfos);
                    return(new StaticPagedList <Collection>(category.Categories.Select(x => ToLiquidCollection(x, workContext)), category.Categories));
                }, category.Categories.PageNumber, category.Categories.PageSize));
            }

            if (workContext.Aggregations != null)
            {
                result.Tags = new TagCollection(new MutablePagedList <Tag>((pageNumber, pageSize, sortInfos) =>
                {
                    workContext.Aggregations.Slice(pageNumber, pageSize, sortInfos);
                    var tags = workContext.Aggregations.Where(a => a.Items != null)
                               .SelectMany(a => a.Items.Select(item => ToLiquidTag(item, a)));
                    return(new StaticPagedList <Tag>(tags, workContext.Aggregations));
                }, workContext.Aggregations.PageNumber, workContext.Aggregations.PageSize));
            }

            if (workContext.CurrentProductSearchCriteria.SortBy != null)
            {
                result.SortBy = workContext.CurrentProductSearchCriteria.SortBy;
            }

            if (!category.Properties.IsNullOrEmpty())
            {
                result.Metafields = new MetaFieldNamespacesCollection(new[] { new MetafieldsCollection("properties", category.Properties) });
            }

            return(result);
        }
Exemplo n.º 32
0
 public RedirectPartDriver(IWorkContextAccessor workContextAccessor)
 {
     WorkContext = workContextAccessor.GetContext();
 }
Exemplo n.º 33
0
 /// <summary>
 /// Override to add logic/filtering right after the invocation of action method. Must return TRUE to stop processing chain
 /// </summary>
 protected internal abstract bool AfterActionInvocation(Controller controller, WorkContext work, string action, MethodInfo method, object[] args, ref object result);
Exemplo n.º 34
0
        /// <summary>
        /// Endpoint to retrieve a secured file. Content Item permissions are inherited from the parent content item.
        /// </summary>
        /// <param name="id">Unique Id on Parent Content Item</param>
        /// <param name="fieldName">Unique Field Name for the file field.</param>
        /// <returns></returns>
        public ActionResult GetSecureFile(int id, string fieldName)
        {
            var         accessGranted = false;
            WorkContext wc            = _services.WorkContext;
            IUser       user          = _services.WorkContext.CurrentUser;

            if (!String.IsNullOrEmpty(wc.CurrentSite.SuperUser) &&
                user != null &&
                String.Equals(user.UserName, wc.CurrentSite.SuperUser, StringComparison.Ordinal))
            {
                accessGranted = true;
            }

            var content = _services.ContentManager.Get <ContentPart>(id);

            if (content == null)
            {
                return(null);
            }

            var part = content.ContentItem.As <ContentPermissionsPart>();

            // if the content item has no right attached, check on the container
            if (part == null || !part.Enabled)
            {
                var commonPart = part.As <CommonPart>();
                if (commonPart != null && commonPart.Container != null)
                {
                    part = commonPart.As <ContentPermissionsPart>();
                }
            }

            //if we do not have access level permissions for this content item then we need to give access
            if (part == null || !part.Enabled)
            {
                accessGranted = true;
            }
            else
            {
                var hasOwnership = HasOwnership(user, content.ContentItem);

                IEnumerable <string> authorizedRoles;

                //we only care about view permission in this field
                authorizedRoles = (hasOwnership ? part.ViewOwnContent : part.ViewContent).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                // determine what set of roles should be examined by the access check
                IEnumerable <string> rolesToExamine;
                if (user == null)
                {
                    rolesToExamine = AnonymousRole;
                }
                else if (user.Has <IUserRoles>())
                {
                    // the current user is not null, so get his roles and add "Authenticated" to it
                    rolesToExamine = user.As <IUserRoles>().Roles;

                    // when it is a simulated anonymous user in the admin
                    if (!rolesToExamine.Contains(AnonymousRole[0]))
                    {
                        rolesToExamine = rolesToExamine.Concat(AuthenticatedRole);
                    }
                }
                else
                {
                    // the user is not null and has no specific role, then it's just "Authenticated"
                    rolesToExamine = AuthenticatedRole;
                }

                accessGranted = rolesToExamine.Any(x => authorizedRoles.Contains(x, StringComparer.OrdinalIgnoreCase));
            }

            if (accessGranted)
            {
                var field    = (Fields.SecureFileField)(content.ContentItem).Parts.SelectMany(p => p.Fields).First(f => f.Name == fieldName);
                var settings = field.PartFieldDefinition.Settings.GetModel <SecureFileFieldSettings>();
                IStorageProvider provider;

                provider = new SecureFileStorageProvider(settings.SecureDirectoryName);

                IStorageFile file = provider.Get <StorageFile>(field.Url);
                Stream       fs   = new MemoryStream(file.FileBytes);

                return(new FileStreamResult(fs, file.ContentType)
                {
                    FileDownloadName = file.FileName
                });
            }

            return(new HttpUnauthorizedResult());
        }
Exemplo n.º 35
0
 public ProductController(WorkContext context, IStorefrontUrlBuilder urlBuilder, ICatalogSearchService catalogSearchService)
     : base(context, urlBuilder)
 {
     _catalogSearchService = catalogSearchService;
 }
Exemplo n.º 36
0
        public string GetLogOnUrl(WorkContext context)
        {
            var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);

            return(urlHelper.Action("Dummy", "LogOn", new { Area = "RM.QuickLogOn", ReturnUrl = context.HttpContext.Request.Url.ToString() }));
        }
Exemplo n.º 37
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Logger.Debug("Incoming request for URL '{0}'.", filterContext.RequestContext.HttpContext.Request.RawUrl);

            // This filter is not reentrant (multiple executions within the same request are
            // not supported) so child actions are ignored completely.
            if (filterContext.IsChildAction)
            {
                Logger.Debug("Action '{0}' ignored because it's a child action.", filterContext.ActionDescriptor.ActionName);
                return;
            }

            _now         = _clock.UtcNow;
            _workContext = _workContextAccessor.GetContext();

            var configurations = _cacheService.GetRouteConfigs();

            if (configurations.Any())
            {
                var route = filterContext.Controller.ControllerContext.RouteData.Route;
                var key   = _cacheService.GetRouteDescriptorKey(filterContext.HttpContext, route);
                _cacheRouteConfig = configurations.FirstOrDefault(c => c.RouteKey == key);
            }

            if (!RequestIsCacheable(filterContext))
            {
                return;
            }

            // Computing the cache key after we know that the request is cacheable means that we are only performing this calculation on requests that require it
            _cacheKey          = String.Intern(ComputeCacheKey(filterContext, GetCacheKeyParameters(filterContext)));
            _invariantCacheKey = ComputeCacheKey(filterContext, null);

            Logger.Debug("Cache key '{0}' was created.", _cacheKey);

            try {
                // Is there a cached item, and are we allowed to serve it?
                var allowServeFromCache = filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] != "no-cache" || CacheSettings.IgnoreNoCache;
                var cacheItem           = GetCacheItem(_cacheKey);
                if (allowServeFromCache && cacheItem != null)
                {
                    Logger.Debug("Item '{0}' was found in cache.", _cacheKey);

                    // Is the cached item in its grace period?
                    if (cacheItem.IsInGracePeriod(_now))
                    {
                        // Render the content unless another request is already doing so.
                        if (Monitor.TryEnter(_cacheKey))
                        {
                            Logger.Debug("Item '{0}' is in grace period and not currently being rendered; rendering item...", _cacheKey);
                            BeginRenderItem(filterContext);
                            return;
                        }
                    }

                    // Cached item is not yet in its grace period, or is already being
                    // rendered by another request; serve it from cache.
                    Logger.Debug("Serving item '{0}' from cache.", _cacheKey);
                    ServeCachedItem(filterContext, cacheItem);
                    return;
                }

                // No cached item found, or client doesn't want it; acquire the cache key
                // lock to render the item.
                Logger.Debug("Item '{0}' was not found in cache or client refuses it. Acquiring cache key lock...", _cacheKey);
                if (Monitor.TryEnter(_cacheKey))
                {
                    Logger.Debug("Cache key lock for item '{0}' was acquired.", _cacheKey);

                    // Item might now have been rendered and cached by another request; if so serve it from cache.
                    if (allowServeFromCache)
                    {
                        cacheItem = GetCacheItem(_cacheKey);
                        if (cacheItem != null)
                        {
                            Logger.Debug("Item '{0}' was now found; releasing cache key lock and serving from cache.", _cacheKey);
                            Monitor.Exit(_cacheKey);
                            ServeCachedItem(filterContext, cacheItem);
                            return;
                        }
                    }
                }

                // Either we acquired the cache key lock and the item was still not in cache, or
                // the lock acquisition timed out. In either case render the item.
                Logger.Debug("Rendering item '{0}'...", _cacheKey);
                BeginRenderItem(filterContext);
            }
            catch {
                // Remember to release the cache key lock in the event of an exception!
                Logger.Debug("Exception occurred for item '{0}'; releasing any acquired lock.", _cacheKey);
                ReleaseCacheKeyLock();
                throw;
            }
        }
 private static string GetAsyncListKey(WorkContext context, string listName, string type)
 {
     return(string.Join(":", listName, context.CurrentUser.Id, context.CurrentStore.Id, type));
 }
Exemplo n.º 39
0
        public static catalogDto.ProductIndexedSearchCriteria ToProductSearchCriteriaDto(this ProductSearchCriteria criteria, WorkContext workContext)
        {
            var currency = criteria.Currency ?? workContext.CurrentCurrency;

            var result = new catalogDto.ProductIndexedSearchCriteria
            {
                SearchPhrase  = criteria.Keyword,
                LanguageCode  = criteria.Language?.CultureName ?? workContext.CurrentLanguage.CultureName,
                StoreId       = workContext.CurrentStore.Id,
                CatalogId     = workContext.CurrentStore.Catalog,
                Outline       = criteria.Outline,
                Currency      = currency.Code,
                Pricelists    = workContext.CurrentPricelists.Where(p => p.Currency.Equals(currency)).Select(p => p.Id).ToList(),
                PriceRange    = criteria.PriceRange?.ToNumericRangeDto(),
                UserGroups    = criteria.UserGroups,
                Terms         = criteria.Terms.ToStrings(),
                Sort          = criteria.SortBy,
                Skip          = criteria.Start,
                Take          = criteria.PageSize,
                ResponseGroup = ((int)criteria.ResponseGroup).ToString(),
                IsFuzzySearch = criteria.IsFuzzySearch,
            };

            // Add vendor id to terms
            if (!string.IsNullOrEmpty(criteria.VendorId))
            {
                if (result.Terms == null)
                {
                    result.Terms = new List <string>();
                }

                result.Terms.Add(string.Concat("vendor:", criteria.VendorId));
            }

            if (!criteria.ObjectIds.IsNullOrEmpty())
            {
                result.ObjectIds = criteria.ObjectIds.ToArray();
            }

            return(result);
        }
Exemplo n.º 40
0
        public static catalogDto.CategoryIndexedSearchCriteria ToCategorySearchCriteriaDto(this CategorySearchCriteria criteria, WorkContext workContext)
        {
            var result = new catalogDto.CategoryIndexedSearchCriteria
            {
                SearchPhrase  = criteria.Keyword,
                LanguageCode  = criteria.Language?.CultureName ?? workContext.CurrentLanguage.CultureName,
                StoreId       = workContext.CurrentStore.Id,
                CatalogId     = workContext.CurrentStore.Catalog,
                Outline       = criteria.Outline,
                UserGroups    = workContext.CurrentUser?.Contact?.UserGroups ?? new List <string>(), // null value disables filtering by user groups
                Sort          = criteria.SortBy,
                Skip          = criteria.Start,
                Take          = criteria.PageSize,
                ResponseGroup = ((int)criteria.ResponseGroup).ToString(),
                IsFuzzySearch = criteria.IsFuzzySearch,
            };

            return(result);
        }
Exemplo n.º 41
0
 public static TaxEvaluationContext ToTaxEvaluationContext(this WorkContext workContext, IEnumerable <Product> products = null)
 {
     return(TaxConverterInstance.ToTaxEvaluationContext(workContext, products));
 }
Exemplo n.º 42
0
 public DealsManager(WorkContext context)
 {
     _context = context;
 }
 private static string GetAsyncLockKey(string orderNumber, WorkContext ctx)
 {
     return(string.Join(":", "Order", orderNumber, ctx.CurrentStore.Id, ctx.CurrentUser.Id));
 }
Exemplo n.º 44
0
        private Func <long> TryCreateTaskForApplyingPrecomputedBatchForNewIndex(Index index, IndexDefinition definition)
        {
            if (Database.Configuration.MaxPrecomputedBatchSizeForNewIndex <= 0) //precaution -> should never be lower than 0
            {
                index.IsMapIndexingInProgress = false;
                return(null);
            }

            var generator = IndexDefinitionStorage.GetViewGenerator(definition.IndexId);

            if (generator.ForEntityNames.Count == 0 && index.IsTestIndex == false)
            {
                // we don't optimize if we don't have what to optimize _on_, we know this is going to return all docs.
                // no need to try to optimize that, then
                index.IsMapIndexingInProgress = false;
                return(null);
            }

            //only one precomputed batch can run at a time except for test indexes
            if (index.IsTestIndex == false)
            {
                lock (precomputedLock)
                {
                    if (isPrecomputedBatchForNewIndexIsRunning)
                    {
                        index.IsMapIndexingInProgress = false;
                        return(null);
                    }

                    isPrecomputedBatchForNewIndexIsRunning = true;
                }
            }

            try
            {
                var cts  = new CancellationTokenSource();
                var task = new Task(() =>
                {
                    try
                    {
                        ApplyPrecomputedBatchForNewIndex(index, generator,
                                                         index.IsTestIndex == false ?
                                                         Database.Configuration.MaxPrecomputedBatchSizeForNewIndex :
                                                         Database.Configuration.Indexing.MaxNumberOfItemsToProcessInTestIndexes, cts);
                    }
                    catch (TotalDataSizeExceededException e)
                    {
                        Log.Warn(string.Format(
                                     @"Aborting applying precomputed batch for index {0}, 
                                because total data size gatherered exceeded 
                                configured data size ({1} bytes)",
                                     index, Database.Configuration.MaxPrecomputedBatchTotalDocumentSizeInBytes), e);
                        throw;
                    }
                    catch (Exception e)
                    {
                        Log.Warn("Could not apply precomputed batch for index " + index, e);
                    }
                    finally
                    {
                        if (index.IsTestIndex == false)
                        {
                            isPrecomputedBatchForNewIndexIsRunning = false;
                        }
                        index.IsMapIndexingInProgress = false;
                        WorkContext.ShouldNotifyAboutWork(() => "Precomputed indexing batch for " + index.PublicName + " is completed");
                        WorkContext.NotifyAboutWork();
                    }
                }, TaskCreationOptions.LongRunning);

                return(() =>
                {
                    try
                    {
                        task.Start();

                        long id;
                        Database
                        .Tasks
                        .AddTask(
                            task,
                            new TaskBasedOperationState(task),
                            new TaskActions.PendingTaskDescription
                        {
                            StartTime = DateTime.UtcNow,
                            Payload = index.PublicName,
                            TaskType = TaskActions.PendingTaskType.NewIndexPrecomputedBatch
                        },
                            out id,
                            cts);
                        return id;
                    }
                    catch (Exception)
                    {
                        index.IsMapIndexingInProgress = false;
                        if (index.IsTestIndex == false)
                        {
                            isPrecomputedBatchForNewIndexIsRunning = false;
                        }
                        throw;
                    }
                });
            }
            catch (Exception)
            {
                index.IsMapIndexingInProgress = false;
                if (index.IsTestIndex == false)
                {
                    isPrecomputedBatchForNewIndexIsRunning = false;
                }
                throw;
            }
        }
Exemplo n.º 45
0
        protected override void DoHandleWork(WorkContext work)
        {
            var fp         = work.MatchedVars[VAR_FILE_PATH].AsString("none");
            var attachment = work.MatchedVars[VAR_ATTACHMENT].AsBool(true);
            var chunked    = work.MatchedVars[VAR_CHUNKED].AsBool(true);

            //Sanitize
            fp = fp.Replace("..", string.Empty)
                 .Replace(":/", string.Empty)
                 .Replace(@"\\", @"\");

            //Cut the surrogate out of path, i.e. '/static/img/@@767868768768/picture.png' -> '/static/img/picture.png'
            fp = CutVersionSegment(fp, m_VersionSegmentPrefix);


            string            fileName  = null;
            IFileSystem       fs        = null;
            FileSystemSession fsSession = null;
            FileSystemFile    fsFile    = null;
            bool exists = false;

            if (m_UsePortalHub)
            {
                var hub = PortalHub.Instance;
                fs       = hub.ContentFileSystem;
                fileName = m_RootPath != null?fs.CombinePaths(hub.ContentFileSystemRootPath, m_RootPath, fp)
                               : fs.CombinePaths(hub.ContentFileSystemRootPath, fp);

                fsSession = fs.StartSession(hub.ContentFileSystemConnectParams);
                fsFile    = fsSession[fileName] as FileSystemFile;
                exists    = fsFile != null;
            }
            else
            {
                fileName = Path.Combine(RootPath, fp);
                exists   = File.Exists(fileName);
            }

            try
            {
                if (!exists)
                {
                    var text = StringConsts.FILE_DL_HANDLER_NOT_FOUND_INFO.Args(fileName);
                    if (m_Throw)
                    {
                        throw new HTTPStatusException(WebConsts.STATUS_404, WebConsts.STATUS_404_DESCRIPTION, text);
                    }

                    work.Response.ContentType = ContentType.TEXT;
                    work.Response.Write(text);
                    work.Response.StatusCode        = WebConsts.STATUS_404;
                    work.Response.StatusDescription = WebConsts.STATUS_404_DESCRIPTION;
                    return;
                }

                if (!work.Response.WasWrittenTo)
                {
                    work.Response.Buffered = !chunked;
                }

                if (m_CacheMaxAgeSec > 0)
                {
                    work.Response.Headers[HttpResponseHeader.CacheControl] = "private, max-age={0}, must-revalidate".Args(m_CacheMaxAgeSec);
                }
                else
                {
                    work.Response.Headers[HttpResponseHeader.CacheControl] = "no-cache";
                }

                if (fsFile == null)
                {
                    work.Response.WriteFile(fileName, attachment: attachment);
                }
                else
                {
                    var ext = Path.GetExtension(fsFile.Name);
                    work.Response.ContentType = NFX.Web.ContentType.ExtensionToContentType(ext, NFX.Web.ContentType.BINARY);
                    work.Response.WriteStream(fsFile.FileStream, attachmentName: attachment ? Path.GetFileName(fileName) : null);
                }
            }
            finally
            {
                DisposableObject.DisposeAndNull(ref fsSession);
            }
        }
Exemplo n.º 46
0
 public Prefetcher(WorkContext workContext)
 {
     this.workContext = workContext;
 }
Exemplo n.º 47
0
        public static DynamicContentEvaluationContext ToDynamicContentEvaluationContext(this WorkContext workContext, IEnumerable <Product> products = null)
        {
            var result = new DynamicContentEvaluationContext(workContext.CurrentLanguage, workContext.CurrentCurrency)
            {
                User    = workContext.CurrentUser,
                StoreId = workContext.CurrentStore.Id,
            };

            return(result);
        }
Exemplo n.º 48
0
 protected override WaveSession MakeNewSessionInstance(WorkContext work)
 {
     return(new WebManagerSession(Guid.NewGuid(), App.Random.NextRandomUnsignedLong));
 }
Exemplo n.º 49
0
        internal long PutNewIndexIntoStorage(string name, IndexDefinition definition, bool disableIndex = false)
        {
            Debug.Assert(Database.IndexStorage != null);
            Debug.Assert(TransactionalStorage != null);
            Debug.Assert(WorkContext != null);

            Index index = null;

            TransactionalStorage.Batch(actions =>
            {
                var maxId = 0;
                if (Database.IndexStorage.Indexes.Length > 0)
                {
                    maxId = Database.IndexStorage.Indexes.Max();
                }
                definition.IndexId = (int)Database.Documents.GetNextIdentityValueWithoutOverwritingOnExistingDocuments("IndexId", actions);
                if (definition.IndexId <= maxId)
                {
                    actions.General.SetIdentityValue("IndexId", maxId + 1);
                    definition.IndexId = (int)Database.Documents.GetNextIdentityValueWithoutOverwritingOnExistingDocuments("IndexId", actions);
                }

                IndexDefinitionStorage.RegisterNewIndexInThisSession(name, definition);

                // this has to happen in this fashion so we will expose the in memory status after the commit, but
                // before the rest of the world is notified about this.

                IndexDefinitionStorage.CreateAndPersistIndex(definition);
                Database.IndexStorage.CreateIndexImplementation(definition);
                index = Database.IndexStorage.GetIndexInstance(definition.IndexId);

                // If we execute multiple indexes at once and want to activate them all at once we will disable the index from the endpoint
                if (disableIndex)
                {
                    index.Priority = IndexingPriority.Disabled;
                }

                //ensure that we don't start indexing it right away, let the precomputation run first, if applicable
                index.IsMapIndexingInProgress = true;
                if (definition.IsTestIndex)
                {
                    index.MarkQueried(); // test indexes should be mark queried, so the cleanup task would not delete them immediately
                }
                InvokeSuggestionIndexing(name, definition, index);

                actions.Indexing.AddIndex(definition.IndexId, definition.IsMapReduce);
            });

            Debug.Assert(index != null);

            Func <long> precomputeTask = null;

            if (WorkContext.RunIndexing &&
                name.Equals(Constants.DocumentsByEntityNameIndex, StringComparison.InvariantCultureIgnoreCase) == false &&
                Database.IndexStorage.HasIndex(Constants.DocumentsByEntityNameIndex) && isPrecomputedBatchForNewIndexIsRunning == false)
            {
                // optimization of handling new index creation when the number of document in a database is significantly greater than
                // number of documents that this index applies to - let us use built-in RavenDocumentsByEntityName to get just appropriate documents

                precomputeTask = TryCreateTaskForApplyingPrecomputedBatchForNewIndex(index, definition);
            }
            else
            {
                index.IsMapIndexingInProgress = false;// we can't apply optimization, so we'll make it eligible for running normally
            }

            // The act of adding it here make it visible to other threads
            // we have to do it in this way so first we prepare all the elements of the
            // index, then we add it to the storage in a way that make it public
            IndexDefinitionStorage.AddIndex(definition.IndexId, definition);

            // we start the precomuteTask _after_ we finished adding the index
            long operationId = -1;

            if (precomputeTask != null)
            {
                operationId = precomputeTask();
            }

            WorkContext.ShouldNotifyAboutWork(() => "PUT INDEX " + name);
            WorkContext.NotifyAboutWork();

            return(operationId);
        }
Exemplo n.º 50
0
        public virtual Search ToLiquidSearch(IMutablePagedList <storefrontModel.Product> products, WorkContext workContext)
        {
            var result = new Search();

            result.Performed = true;
            result.Terms     = workContext.CurrentProductSearchCriteria.Keyword;

            result.Results = new MutablePagedList <dotLiquid.Drop>((pageNumber, pageSize, sortInfos) =>
            {
                products.Slice(pageNumber, pageSize, sortInfos);
                return(new StaticPagedList <dotLiquid.Drop>(products.Select(x => x.ToShopifyModel()), products));
            }, 1, products.PageSize);

            if (workContext.Aggregations != null)
            {
                result.AllTags = new TagCollection(new MutablePagedList <Tag>((pageNumber, pageSize, sortInfos) =>
                {
                    workContext.Aggregations.Slice(pageNumber, pageSize, sortInfos);
                    var tags = workContext.Aggregations
                               .Where(a => a.Items != null)
                               .SelectMany(a => a.Items.Select(item => item.ToShopifyModel(a)));
                    return(new StaticPagedList <Tag>(tags, workContext.Aggregations));
                }, workContext.Aggregations.PageNumber, workContext.Aggregations.PageSize));
            }

            return(result);
        }
Exemplo n.º 51
0
 protected override void Resolve(ILifetimeScope container)
 {
     _workContext = container.Resolve <IWorkContextAccessor>().CreateWorkContextScope().WorkContext;
 }
Exemplo n.º 52
0
        /// <summary>
        /// Handles the exception by responding appropriately with error page with conditional level of details and logging
        /// </summary>
        public static void HandleException(WorkContext work,
                                           Exception error,
                                           OrderedRegistry <WorkMatch> showDumpMatches,
                                           OrderedRegistry <WorkMatch> logMatches,
                                           string securityRedirectURL    = null,
                                           string securityRedirectTarget = null,
                                           OrderedRegistry <WorkMatch> securityRedirectMatches = null,
                                           Type customPageType = null
                                           )
        {
            if (work == null || error == null)
            {
                return;
            }

            var showDump = showDumpMatches != null?
                           showDumpMatches.OrderedValues.Any(m => m.Make(work) != null) : false;

            if (work.Response.Buffered)
            {
                work.Response.CancelBuffered();
            }

            var json = false;

            if (work.Request != null && work.Request.AcceptTypes != null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null
            {
                json = work.Request.AcceptTypes.Any(at => at.EqualsIgnoreCase(ContentType.JSON));
            }

            var actual = error;

            if (actual is FilterPipelineException fpe)
            {
                actual = fpe.RootException;
            }

            if (actual is MvcException mvce)
            {
                actual = mvce.InnerException;
            }


            var securityError = Security.AuthorizationException.IsDenotedBy(error);

            var hsp = error.SearchThisOrInnerExceptionOf <IHttpStatusProvider>();

            if (hsp != null)
            {
                work.Response.StatusCode        = hsp.HttpStatusCode;
                work.Response.StatusDescription = hsp.HttpStatusDescription;
            }
            else
            {
                if (securityError)
                {
                    work.Response.StatusCode        = WebConsts.STATUS_403;
                    work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION;
                }
                else
                {
                    work.Response.StatusCode        = WebConsts.STATUS_500;
                    work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION;
                }
            }


            if (json)
            {
                work.Response.ContentType = ContentType.JSON;
                work.Response.WriteJSON(error.ToClientResponseJsonMap(showDump), JsonWritingOptions.PrettyPrintRowsAsMap);
            }
            else
            {
                if (securityRedirectMatches != null && securityRedirectMatches.Count > 0)
                {
                    JsonDataMap matched = null;
                    foreach (var match in securityRedirectMatches.OrderedValues)
                    {
                        matched = match.Make(work, actual);
                        if (matched != null)
                        {
                            break;
                        }
                    }
                    if (matched != null)
                    {
                        var url    = matched[VAR_SECURITY_REDIRECT_URL].AsString();
                        var target = matched[VAR_SECURITY_REDIRECT_TARGET].AsString();

                        if (url.IsNotNullOrWhiteSpace())
                        {
                            securityRedirectURL = url;
                        }
                        if (target.IsNotNullOrWhiteSpace())
                        {
                            securityRedirectTarget = target;
                        }
                    }
                }

                if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError && !work.IsAuthenticated)
                {
                    var url    = securityRedirectURL;
                    var target = securityRedirectTarget;
                    if (target.IsNotNullOrWhiteSpace())
                    {
                        var partsA = url.Split('#');
                        var parts  = partsA[0].Split('?');
                        var query  = parts.Length > 1 ? parts[0] + "&" : string.Empty;
                        url = "{0}?{1}{2}={3}{4}".Args(parts[0], query,
                                                       target, Uri.EscapeDataString(work.Request.Url.PathAndQuery),
                                                       partsA.Length > 1 ? "#" + partsA[1] : string.Empty);
                    }
                    work.Response.RedirectAndAbort(url);
                }
                else
                {
                    WaveTemplate errorPage = null;

                    if (customPageType != null)
                    {
                        try
                        {
                            //20201130 DKh fix #376
                            var simpleCtor = customPageType.GetConstructor(new Type[] { typeof(Exception), typeof(bool) }) == null;
                            errorPage = (simpleCtor ? Activator.CreateInstance(customPageType) :
                                         Activator.CreateInstance(customPageType, error, showDump)
                                         ) as WaveTemplate;//fix #376

                            if (errorPage == null)
                            {
                                throw new WaveException("not a {0}".Args(nameof(WaveTemplate)));
                            }
                        }
                        catch (Exception actErr)
                        {
                            work.Log(Log.MessageType.Error,
                                     StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()),
                                     typeof(ErrorFilter).FullName + ".ctor(customPageType)",
                                     actErr);
                        }
                    }

                    if (errorPage == null)
                    {
                        errorPage = new ErrorPage(error, showDump);
                    }

                    errorPage.Render(work, error);
                }
            }

            if (logMatches != null && logMatches.Count > 0)
            {
                JsonDataMap matched = null;
                foreach (var match in logMatches.OrderedValues)
                {
                    matched = match.Make(work, error);
                    if (matched != null)
                    {
                        break;
                    }
                }
                if (matched != null)
                {
                    matched["$ip"]   = work.EffectiveCallerIPEndPoint.ToString();
                    matched["$ua"]   = work.Request.UserAgent.TakeFirstChars(78, "..");
                    matched["$mtd"]  = work.Request.HttpMethod;
                    matched["$uri"]  = work.Request.Url.ToString().TakeFirstChars(78, "..");
                    matched["$ref"]  = work.Request.UrlReferrer?.ToString().TakeFirstChars(78, "..");
                    matched["$stat"] = "{0}/{1}".Args(work.Response.StatusCode, work.Response.StatusDescription);

                    if (work.Portal != null)
                    {
                        matched["$portal"] = work.Portal.Name;
                    }

                    if (work.GeoEntity != null)
                    {
                        matched["$geo"] = work.GeoEntity.LocalityName;
                    }

                    work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJson(JsonWritingOptions.CompactASCII));
                }
            }
        }
Exemplo n.º 53
0
        private string PutIndexInternal(string name, IndexDefinition definition, out long opId, bool disableIndexBeforePut = false, bool isUpdateBySideSide = false, IndexCreationOptions?creationOptions = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            opId = -1;
            name = name.Trim();
            IsIndexNameValid(name);

            var existingIndex = IndexDefinitionStorage.GetIndexDefinition(name);

            if (existingIndex != null)
            {
                switch (existingIndex.LockMode)
                {
                case IndexLockMode.SideBySide:
                    if (isUpdateBySideSide == false)
                    {
                        Log.Info("Index {0} not saved because it might be only updated by side-by-side index");
                        throw new InvalidOperationException("Can not overwrite locked index: " + name + ". This index can be only updated by side-by-side index.");
                    }
                    break;

                case IndexLockMode.LockedIgnore:
                    Log.Info("Index {0} not saved because it was lock (with ignore)", name);
                    return(null);

                case IndexLockMode.LockedError:
                    throw new InvalidOperationException("Can not overwrite locked index: " + name);
                }
            }

            AssertAnalyzersValid(definition);

            switch (creationOptions ?? FindIndexCreationOptions(definition, ref name))
            {
            case IndexCreationOptions.Noop:
                return(null);

            case IndexCreationOptions.UpdateWithoutUpdatingCompiledIndex:
                // ensure that the code can compile
                new DynamicViewCompiler(definition.Name, definition, Database.Extensions, IndexDefinitionStorage.IndexDefinitionsPath, Database.Configuration).GenerateInstance();
                IndexDefinitionStorage.UpdateIndexDefinitionWithoutUpdatingCompiledIndex(definition);
                return(null);

            case IndexCreationOptions.Update:
                // ensure that the code can compile
                new DynamicViewCompiler(definition.Name, definition, Database.Extensions, IndexDefinitionStorage.IndexDefinitionsPath, Database.Configuration).GenerateInstance();
                DeleteIndex(name);
                break;
            }

            opId = PutNewIndexIntoStorage(name, definition, disableIndexBeforePut);

            WorkContext.ClearErrorsFor(name);

            TransactionalStorage.ExecuteImmediatelyOrRegisterForSynchronization(() => Database.Notifications.RaiseNotifications(new IndexChangeNotification
            {
                Name = name,
                Type = IndexChangeTypes.IndexAdded,
            }));

            return(name);
        }
Exemplo n.º 54
0
 protected internal override bool AfterActionInvocation(Controller controller, WorkContext work, string action, MethodInfo method, object[] args, ref object result)
 {
     return(false);
 }
Exemplo n.º 55
0
 public ApiCatalogController(WorkContext workContext, IStorefrontUrlBuilder urlBuilder, ICatalogSearchService catalogSearchService)
     : base(workContext, urlBuilder)
 {
     _catalogSearchService = catalogSearchService;
 }
Exemplo n.º 56
0
        protected internal override bool BeforeActionInvocation(Controller controller, WorkContext work, string action, MethodInfo method, object[] args, ref object result)
        {
            if (work.IsGET)
            {
                return(false);
            }

            work.NeedsSession(OnlyExistingSession);

            var session  = work.Session;
            var supplied = work.MatchedVars[TokenName].AsString();

            if (session == null ||
                !session.CSRFToken.EqualsOrdIgnoreCase(supplied))
            {
                throw new HTTPStatusException(NFX.Wave.SysConsts.STATUS_400, NFX.Wave.SysConsts.STATUS_400_DESCRIPTION, "CSRF failed");
            }

            return(false);
        }
Exemplo n.º 57
0
        public static Search ToShopifyModel(this IMutablePagedList <storefrontModel.Product> products, WorkContext workContext)
        {
            var converter = new ShopifyModelConverter();

            return(converter.ToLiquidSearch(products, workContext));
        }
Exemplo n.º 58
0
        public static Collection ToShopifyModel(this storefrontModel.Category category, WorkContext workContext)
        {
            var converter = new  ShopifyModelConverter();

            return(converter.ToLiquidCollection(category, workContext));
        }
Exemplo n.º 59
0
        public void ProcessItems()
        {
            int count = Interlocked.Decrement(ref _queuedCalls);

            // exit if there are more callbacks following us
            if (count % 10000 == 0)
            {
                _loggerRef.Target.LogDebug("ProcessItems: Queued calls remaining: {0}", count);
            }
            if (count != 0)
            {
                return;
            }
            ICoreItem item = null;

            _queuedItems.Locked(queue =>
            {
                if (queue.Count > 0)
                {
                    item = queue.Dequeue();
                }
            });
            while (item != null)
            {
                if (item.Data is QuotedAssetSet)
                {
                    var nameSpace       = item.AppProps.GetValue <string>(EnvironmentProp.NameSpace);
                    var marketName      = item.AppProps.GetValue <string>(CurveProp.MarketAndDate);
                    var curveType       = item.AppProps.GetValue <string>(CurveProp.PricingStructureType);
                    var curveName       = item.AppProps.GetValue <string>(CurveProp.CurveName);
                    var curveGenRequest = new OrdinaryCurveGenRequest
                    {
                        NameSpace   = nameSpace,
                        BaseDate    = DateTime.Now,
                        RequestId   = Guid.NewGuid().ToString(),
                        RequesterId = new UserIdentity
                        {
                            Name        = _clientRef.Target.ClientInfo.Name,
                            DisplayName = _clientRef.Target.ClientInfo.UserFullName
                        },
                        UseSavedMarketData     = true,
                        ForceGenerateEODCurves = true,
                        CurveSelector          = new[] { new CurveSelection
                                                         {
                                                             NameSpace  = nameSpace,
                                                             MarketName = marketName,
                                                             CurveType  = curveType,
                                                             CurveName  = curveName
                                                         } }
                    };
                    IWorkContext context = new WorkContext(_loggerRef.Target, _clientRef.Target, "DEV");
                    using (var workflow = new WFGenerateOrdinaryCurve())
                    {
                        workflow.Initialise(context);
                        WorkflowOutput <HandlerResponse> output = workflow.Execute(curveGenRequest);
                        WorkflowHelper.ThrowErrors(output.Errors);
                    }
                    item = null;
                    _queuedItems.Locked(queue =>
                    {
                        if (queue.Count > 0)
                        {
                            item = queue.Dequeue();
                        }
                    });
                }
            }
        }
Exemplo n.º 60
0
 public CultureRuleProvider(WorkContext workContext)
 {
     _workContext = workContext;
 }