Example #1
0
        public UrlAlternatesFactory(IHttpContextAccessor httpContextAccessor) {
            _httpContextAccessor = httpContextAccessor;

            _urlAlternates = new Lazy<List<string>>(() => {
                var httpContext = _httpContextAccessor.Current();

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

                var request = _httpContextAccessor.Current().Request;

                // extract each segment of the url
                var urlSegments = VirtualPathUtility.ToAppRelative(request.Path.ToLower())
                    .Split('/')
                    .Skip(1) // ignore the heading ~ segment 
                    .Select(url => url.Replace("-", "__").Replace(".", "_")) // format the alternate
                    .ToArray();

                if (String.IsNullOrWhiteSpace(urlSegments[0])) {
                    urlSegments[0] = "homepage";
                }

                return Enumerable.Range(1, urlSegments.Count()).Select(range => String.Join("__", urlSegments.Take(range))).ToList();
            });
        }
		public ActionAlternatesFactory(IHttpContextAccessor httpContextAccessor)
		{
			_httpContextAccessor = httpContextAccessor;

			_actionAlternates = new Lazy<List<string>>(() =>
			{
				var httpContext = _httpContextAccessor.Current();

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

				var request = _httpContextAccessor.Current().Request;

				var actionSegments = new[] 
				{
					request.RequestContext.RouteData.GetRequiredString("area").Replace("-", "__").Replace(".", "_"), 
					request.RequestContext.RouteData.GetRequiredString("controller").Replace("-", "__").Replace(".", "_"), 
					request.RequestContext.RouteData.GetRequiredString("action").Replace("-", "__").Replace(".", "_")
				};

				return Enumerable.Range(1, actionSegments.Count()).Select(range => String.Join("__", actionSegments.Take(range))).ToList();
			});
		}
        public CombinatorResource(ResourceType type, IHttpContextAccessor httpContextAccessor)
        {
            _type = type;
            _httpContext = httpContextAccessor.Current();

            RequiredContext = new ResourceRequiredContext();
            IsOriginal = false;
        }
Example #4
0
        public CounterService(
            IContentManager manager,
            IHttpContextAccessor context,
            Lazy<IRepository<CounterRecord>> repo) {
            _locks = new ConcurrentDictionary<string, object>();
            _manager = manager;
            _context = context;
            _repo = repo;

            if (_context == null || _context.Current() == null || _context.Current().Session == null) {
                return;
            }
            // ReSharper disable PossibleNullReferenceException
            var dict = _context.Current().Session[SessionKey] as ConcurrentDictionary<string, SerializableCounter>;
            // ReSharper restore PossibleNullReferenceException
            if (dict == null) {
                // ReSharper disable PossibleNullReferenceException
                _context.Current().Session[SessionKey] = new ConcurrentDictionary<string, SerializableCounter>();
            }
            // ReSharper restore PossibleNullReferenceException
        }
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool isAdminService  = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AdminServiceAttribute), false).Any();
            bool skipPolicyCheck = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PolicyApiFilterAttribute), false).Where(x => ((PolicyApiFilterAttribute)x).Skip).Any();
            var  fullActionName  = filterContext.Controller.GetType().FullName + "." + filterContext.ActionDescriptor.ActionName;

            if (skipPolicyCheck || isAdminService)
            {
                return;
            }
            if (_workContext.GetContext().CurrentUser != null &&
                !allowedControllers.Contains(filterContext.Controller.GetType().FullName) &&
                !allowedControllers.Contains(fullActionName) &&
                !AdminFilter.IsApplied(filterContext.RequestContext))
            {
                var language = _workContext.GetContext().CurrentCulture;
                IEnumerable <PolicyTextInfoPart> neededPolicies = _userExtensionServices.GetUserLinkedPolicies(language);

                if (neededPolicies.Count() > 0)
                {
                    var missingPolicies = MissingRegistrationPolices();
                    if (missingPolicies.Count() > 0)
                    {
                        if (filterContext.Controller.GetType().FullName == "Laser.Orchard.WebServices.Controllers.JsonController")
                        {
                            string data = _policyServices.PoliciesLMNVSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id)));

                            filterContext.Result = new ContentResult {
                                Content = data, ContentType = "application/json"
                            };
                        }
                        else if (filterContext.Controller.GetType().FullName == "Laser.Orchard.WebServices.Controllers.WebApiController")
                        {
                            string data = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id)));

                            filterContext.Result = new ContentResult {
                                Content = data, ContentType = "application/json"
                            };
                        }
                        else
                        {
                            string outputFormat = _workContext.GetContext().HttpContext.Request.Headers["OutputFormat"];

                            if (String.Equals(outputFormat, "LMNV", StringComparison.OrdinalIgnoreCase))
                            {
                                string   data     = _policyServices.PoliciesLMNVSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id)));
                                Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data));

                                filterContext.Result = new ContentResult {
                                    Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json"
                                };
                            }
                            else if (String.Equals(outputFormat, "PureJson", StringComparison.OrdinalIgnoreCase))
                            {
                                string   data     = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id)));
                                Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data));

                                filterContext.Result = new ContentResult {
                                    Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json"
                                };
                            }
                            else
                            {
                                var returnType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;

                                if (returnType == typeof(JsonResult))
                                {
                                    string   data     = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id)));
                                    Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data));

                                    filterContext.Result = new ContentResult {
                                        Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json"
                                    };
                                }
                                else
                                {
                                    var encodedAssociatedPolicies = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(",", missingPolicies)));

                                    UrlHelper urlHelper = new UrlHelper(_httpContextAccessor.Current().Request.RequestContext);
                                    var       url       = urlHelper.Action("Index", "Policies", new { area = "Laser.Orchard.Policy", lang = language, policies = encodedAssociatedPolicies, returnUrl = _httpContextAccessor.Current().Request.RawUrl });

                                    filterContext.Result = new RedirectResult(url);
                                }
                            }
                        }
                    }
                }
            }

            return;
        }
 public void LoggedOut(IUser user)
 {
     _httpContext.Current().Response.Redirect("~/");
 }
Example #7
0
 private OpenAuthSecurityManager SecurityManager(string providerName)
 {
     return(new OpenAuthSecurityManager(_httpContextAccessor.Current(), _orchardOpenAuthClientProvider.GetClient(providerName), _orchardOpenAuthDataProvider));
 }
Example #8
0
        public string Get(string id)
        {
            List <ClassCodeModel>      Response             = null;
            List <ClassCodeAjaxReturn> classCodeAjaxReturns = null;

            if (ModelState.IsValid)
            {
                UserModel currentUser = null;

                var session = _accessor.Current().Session;
                if (session != null)
                {
                    currentUser = session["CurrentUser"] as UserModel;
                }

                Response = ((ClassCodeService)_service).GetAllClassCodes().ToList();

                var result = Response.GroupBy(co => co.Code).Select(grp => grp.ToList()).ToList();

                classCodeAjaxReturns = new List <ClassCodeAjaxReturn>();
                for (int i = 0; i < 10; i++)
                {
                    ClassCodeAjaxReturn classCode = new ClassCodeAjaxReturn();
                    classCode.Code      = i.ToString();
                    classCode.Id        = i.ToString();
                    classCode.Childrens = new List <ClassCodeAjaxReturn>();
                    classCodeAjaxReturns.Add(classCode);
                }

                foreach (var res in result)
                {
                    ClassCodeAjaxReturn ajax;
                    ClassCodeAjaxReturn ajaxChild;

                    switch (string.IsNullOrEmpty(res[0].Code) ? string.Empty : res[0].Code[0].ToString())
                    {
                    case "0":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[0].Childrens.Add(ajax);
                        break;

                    case "1":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[1].Childrens.Add(ajax);
                        break;

                    case "2":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[2].Childrens.Add(ajax);
                        break;

                    case "3":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[3].Childrens.Add(ajax);
                        break;

                    case "4":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[4].Childrens.Add(ajax);
                        break;

                    case "5":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[5].Childrens.Add(ajax);
                        break;

                    case "6":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[6].Childrens.Add(ajax);
                        break;

                    case "7":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[7].Childrens.Add(ajax);
                        break;

                    case "8":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[8].Childrens.Add(ajax);
                        break;

                    case "9":
                        ajax             = new ClassCodeAjaxReturn();
                        ajax.Id          = res[0].Id.ToString();
                        ajax.Code        = res[0].Code;
                        ajax.Description = res[0].Description;
                        ajax.Childrens   = new List <ClassCodeAjaxReturn>();
                        foreach (var re in res)
                        {
                            ajaxChild             = new ClassCodeAjaxReturn();
                            ajaxChild.Id          = re.Id.ToString();
                            ajaxChild.Code        = re.Code;
                            ajaxChild.Description = re.Description;
                            ajax.Childrens.Add(ajaxChild);
                        }
                        classCodeAjaxReturns[9].Childrens.Add(ajax);
                        break;
                    }
                }
            }
            string gradChildNodes = string.Empty;
            string tempChildNodes = string.Empty;
            string parentNodes    = string.Empty;
            string childNodes     = string.Empty;
            string final          = string.Empty;

            foreach (ClassCodeAjaxReturn classCodes in classCodeAjaxReturns)
            {
                if (classCodes.Childrens.Count() > 1)
                {
                    childNodes = string.Empty;
                    foreach (ClassCodeAjaxReturn a in classCodes.Childrens)
                    {
                        tempChildNodes = string.Empty;
                        if (a.Childrens.Count() > 1)
                        {
                            gradChildNodes = string.Empty;
                            foreach (ClassCodeAjaxReturn b in a.Childrens)
                            {
                                gradChildNodes += "{ data: '" + b.Description.Replace("'", "") + "' , attr: { className: 'classCode', 'data-classCode': '" + b.Code + "', id: '" + "grandChild_" + b.Id + "',class:'leaveChild'} }" + ",";
                            }
                            gradChildNodes = gradChildNodes.Substring(0, gradChildNodes.Length - 1);
                            tempChildNodes = "{ id: '" + a.Id + "',data: '" + a.Code + "',attr: { id: '" + "child_" + a.Id + "' , 'data-classCode': '" + a.Code + "' },children: [" + gradChildNodes + "] }" + ",";
                        }
                        else
                        {
                            gradChildNodes = "{ data: '" + a.Description.Replace("'", "") + "' , attr: { className: 'classCode', 'data-classCode': '" + a.Code + "', id: '" + "grandChild_" + a.Id + "',class:'leaveChild'} }";
                            tempChildNodes = "{ id: '" + a.Id + "',data: '" + a.Code + "',attr: { id: '" + "child_" + a.Id + "', 'data-classCode': '" + a.Code + "' },children: [" + gradChildNodes + "] }" + ",";
                        }
                        childNodes += tempChildNodes;
                    }
                    childNodes  = childNodes.Substring(0, childNodes.Length - 1);
                    parentNodes = "{ id: '" + classCodes.Id + "',data: '" + classCodes.Code + "',attr: { id: '" + "parent_" + classCodes.Id + "' , 'data-classCode': '" + classCodes.Code + "'},children: [" + childNodes + "] }" + ",";
                }
                else
                {
                    parentNodes = "{ id: '" + classCodes.Id + "',data: '" + classCodes.Code + "',attr: { id: '" + "parent_" + classCodes.Id + "' , 'data-classCode': '" + classCodes.Code + "'}}" + ",";
                }
                final      += parentNodes;
                parentNodes = string.Empty;
            }
            final = final.TrimEnd(',');
            return("[" + final + "]");
        }
 public ScriptManager(ICacheManager cacheManager, IHttpContextAccessor contextAccessor)
 {
     _cacheManager = cacheManager;
     _context = contextAccessor.Current();
 }
        public IEnumerable <MenuItem> Filter(IEnumerable <MenuItem> items)
        {
            foreach (var item in items)
            {
                if (item.Content != null && item.Content.ContentItem.ContentType == "AliasBreadcrumbMenuItem")
                {
                    var request       = _hca.Current().Request;
                    var path          = request.Path;
                    var appPath       = request.ApplicationPath ?? "/";
                    var requestUrl    = (path.StartsWith(appPath) ? path.Substring(appPath.Length) : path).TrimStart('/');
                    var endsWithSlash = requestUrl.EndsWith("/");

                    var menuPosition = item.Position;

                    var urlLevel  = endsWithSlash ? requestUrl.Count(l => l == '/') - 1 : requestUrl.Count(l => l == '/');
                    var menuLevel = menuPosition.Count(l => l == '.');

                    // Checking menu item if it's the leaf element or it's an intermediate element
                    // or it's an unneccessary element according to the url.
                    RouteValueDictionary contentRoute;
                    if (menuLevel == urlLevel)
                    {
                        contentRoute = request.RequestContext.RouteData.Values;
                    }
                    else
                    {
                        // If menuLevel doesn't equal with urlLevel it can mean that this menu item is
                        // an intermediate element (the difference is a positive value) or this menu
                        // item is lower in the navigation hierarchy according to the url (negative
                        // value). If the value is negative, removing the menu item, if the value
                        // is positive finding its place in the hierarchy.
                        var levelDifference = urlLevel - menuLevel;
                        if (levelDifference > 0)
                        {
                            if (endsWithSlash)
                            {
                                levelDifference += levelDifference;
                            }
                            for (int i = 0; i < levelDifference; i++)
                            {
                                requestUrl = requestUrl.Remove(requestUrl.LastIndexOf('/'));
                                path       = path.Remove(path.LastIndexOf('/'));
                            }
                            contentRoute = _aliasService.Get(requestUrl);
                            if (contentRoute == null)
                            {
                                // After the exact number of segments is cut out from the url and the
                                // currentRoute is still null, trying another check with the added slash,
                                // because we don't know if the alias was created with a slash at the end or not.
                                contentRoute = _aliasService.Get(requestUrl.Insert(requestUrl.Length, "/"));
                                path         = path.Insert(path.Length, "/");
                                if (contentRoute == null)
                                {
                                    contentRoute = new RouteValueDictionary();
                                }
                            }
                        }
                        else
                        {
                            contentRoute = new RouteValueDictionary();
                        }
                    }

                    object id;
                    contentRoute.TryGetValue("Id", out id);
                    int contentId;
                    int.TryParse(id as string, out contentId);
                    if (contentId == 0)
                    {
                        // If failed to get the Id's value from currentRoute, transform the alias to the virtual path
                        // and try to get the content item's id from there. E.g. "Blogs/Blog/Item?blogId=12" where
                        // the last digits represents the content item's id. If there is a match in the path we get
                        // the digits after the equality sign.
                        // There is an another type of the routes: like "Contents/Item/Display/13", but when the
                        // content item's route is in this form we already have the id from contentRoute.TryGetValue("Id", out id).
                        var virtualPath = _aliasService.LookupVirtualPaths(contentRoute, _hca.Current()).FirstOrDefault();
                        int.TryParse(virtualPath != null ? virtualPath.VirtualPath.Substring(virtualPath.VirtualPath.LastIndexOf('=') + 1) : "0", out contentId);
                    }
                    if (contentId != 0)
                    {
                        var currentContentItem = _contentManager.Get(contentId);
                        if (currentContentItem != null)
                        {
                            var menuText = _contentManager.GetItemMetadata(currentContentItem).DisplayText;
                            var routes   = _contentManager.GetItemMetadata(currentContentItem).DisplayRouteValues;

                            var inserted = new MenuItem {
                                Text             = new LocalizedString(menuText),
                                IdHint           = item.IdHint,
                                Classes          = item.Classes,
                                Url              = path,
                                Href             = item.Href,
                                LinkToFirstChild = false,
                                RouteValues      = routes,
                                LocalNav         = item.LocalNav,
                                Items            = Enumerable.Empty <MenuItem>(),
                                Position         = menuPosition,
                                Permissions      = item.Permissions,
                                Content          = item.Content
                            };

                            yield return(inserted);
                        }
                    }
                }
                else
                {
                    yield return(item);
                }
            }
        }
        public string GetPreviewTheme()
        {
            var httpContext = _httpContextAccessor.Current();

            return(Convert.ToString(httpContext.Session[PreviewThemeKey]));
        }
Example #12
0
        protected override DriverResult Editor(CloudVideoPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var results = new List <DriverResult>();

            results.Add(ContentShape("Parts_CloudVideo_Edit", () => {
                var settings    = _services.WorkContext.CurrentSite.As <CloudMediaSettingsPart>();
                var httpContext = _httpContextAccessor.Current();

                var occupiedSubtitleLanguagesQuery =
                    from asset in part.Assets
                    where asset is SubtitleAsset
                    select((SubtitleAsset)asset).Language;
                var availableSubtitleLanguagesQuery =
                    from language in settings.SubtitleLanguages
                    where !occupiedSubtitleLanguagesQuery.Contains(language)
                    select language;

                var viewModel = new CloudVideoPartViewModel(availableSubtitleLanguagesQuery.ToArray())
                {
                    Id   = part.Id,
                    Part = part,
                    AllowedVideoFilenameExtensions = settings.AllowedVideoFilenameExtensions,
                    TemporaryVideoFile             = new TemporaryFileViewModel {
                        OriginalFileName  = part.MezzanineAsset != null ? part.MezzanineAsset.OriginalFileName : "",
                        FileSize          = 0,
                        TemporaryFileName = ""
                    },
                    AddedSubtitleLanguage = settings.SubtitleLanguages.FirstOrDefault(),
                    WamsVideo             = new WamsAssetViewModel(),
                    WamsThumbnail         = new WamsAssetViewModel(),
                    WamsSubtitle          = new WamsAssetViewModel()
                };

                if (updater != null)
                {
                    if (updater.TryUpdateModel(viewModel, Prefix, null, null) && AVideoWasUploaded(part, updater, viewModel))
                    {
                        ProcessCreatedWamsAssets(part, viewModel);
                        ProcessUploadedFiles(part, viewModel);

                        var unpublish = httpContext.Request.Form["submit.Save"] == "submit.Unpublish";
                        if (unpublish)
                        {
                            _services.ContentManager.Unpublish(part.ContentItem);
                            _services.Notifier.Success(T("Your {0} has been unpublished.", part.ContentItem.TypeDefinition.DisplayName));
                        }

                        if (part.IsPublished())
                        {
                            _assetManager.PublishAssetsFor(part);
                        }
                    }
                }

                return(shapeHelper.EditorTemplate(TemplateName: "Parts/CloudVideo", Model: viewModel, Prefix: Prefix));
            }));

            if (part.TypeDefinition.Settings.GetModel <ContentTypeSettings>().Draftable)
            {
                if (part.IsPublished())
                {
                    results.Add(ContentShape("CloudVideo_Edit_UnpublishButton", actions => actions));
                }
            }

            return(Combined(results.ToArray()));
        }
        public void Displaying(ShapeDisplayingContext context)
        {
            if (context.ShapeMetadata.Type != "DocumentZone" || context.Shape.ZoneName != "Head")
            {
                return;
            }

            var httpContext = _hca.Current();

            if (httpContext == null)
            {
                return;
            }
            if (AdminFilter.IsApplied(httpContext.Request.RequestContext))
            {
                return;
            }

            var resourceManager = _resourceManagerWork.Value;

            var overrides = _themeOverrideService.GetOverrides();

            if (overrides.FaviconUri != null)
            {
                resourceManager.RegisterLink(new LinkEntry {
                    Type = "image/x-icon", Rel = "shortcut icon", Href = overrides.FaviconUri.ToString()
                });
            }

            if (overrides.StylesheetUris.Any())
            {
                foreach (var uri in overrides.StylesheetUris)
                {
                    var url = uri.ToString();
                    resourceManager.Include("stylesheet", url, url);
                }
            }

            if (overrides.CustomStyles.Uri != null)
            {
                var url = overrides.CustomStyles.Uri.ToString();
                resourceManager.Include("stylesheet", url, url);
            }

            if (overrides.HeadScriptUris.Any())
            {
                foreach (var uri in overrides.HeadScriptUris)
                {
                    var url = uri.ToString();
                    resourceManager.Include("script", url, url).AtHead();
                }
            }

            if (overrides.CustomHeadScript.Uri != null)
            {
                var url = overrides.CustomHeadScript.Uri.ToString();
                resourceManager.Include("script", url, url).AtHead();
            }


            if (overrides.FootScriptUris.Any())
            {
                foreach (var uri in overrides.FootScriptUris)
                {
                    var url = uri.ToString();
                    resourceManager.Include("script", url, url).AtFoot();
                }
            }

            if (overrides.CustomFootScript.Uri != null)
            {
                var url = overrides.CustomFootScript.Uri.ToString();
                resourceManager.Include("script", url, url).AtFoot();
            }
        }
        public override IList <ResourceRequiredContext> BuildRequiredResources(string stringResourceType)
        {
            // It's necessary to make a copy since making a change to the local variable also changes the private one.
            var resources = new List <ResourceRequiredContext>(base.BuildRequiredResources(stringResourceType));

            var settingsPart = _siteService.GetSiteSettings().As <CombinatorSettingsPart>();

            if (resources.Count == 0 ||
                Orchard.UI.Admin.AdminFilter.IsApplied(_httpContextAccessor.Current().Request.RequestContext) && !settingsPart.EnableForAdmin)
            {
                return(resources);
            }

            var resourceType = ResourceTypeHelper.StringTypeToEnum(stringResourceType);

            try
            {
                Uri resourceBaseUri = null;
                if (!string.IsNullOrEmpty(settingsPart.ResourceBaseUrl))
                {
                    resourceBaseUri = UriHelper.CreateUri(settingsPart.ResourceBaseUrl);
                }

                var settings = new CombinatorSettings
                {
                    CombineCdnResources     = settingsPart.CombineCdnResources,
                    ResourceBaseUri         = resourceBaseUri,
                    EmbedCssImages          = settingsPart.EmbedCssImages,
                    EmbeddedImagesMaxSizeKB = settingsPart.EmbeddedImagesMaxSizeKB,
                    GenerateImageSprites    = settingsPart.GenerateImageSprites,
                    MinifyResources         = settingsPart.MinifyResources,
                    EnableResourceSharing   = settingsPart.EnableResourceSharing
                };

                if (!string.IsNullOrEmpty(settingsPart.CombinationExcludeRegex))
                {
                    settings.CombinationExcludeFilter = new Regex(settingsPart.CombinationExcludeRegex);
                }
                if (!string.IsNullOrEmpty(settingsPart.RemoteStorageUrlRegex))
                {
                    settings.RemoteStorageUrlPattern = new Regex(settingsPart.RemoteStorageUrlRegex);
                }
                if (!string.IsNullOrEmpty(settingsPart.EmbedCssImagesStylesheetExcludeRegex))
                {
                    settings.EmbedCssImagesStylesheetExcludeFilter = new Regex(settingsPart.EmbedCssImagesStylesheetExcludeRegex);
                }
                if (!string.IsNullOrEmpty(settingsPart.MinificationExcludeRegex))
                {
                    settings.MinificationExcludeFilter = new Regex(settingsPart.MinificationExcludeRegex);
                }
                if (!string.IsNullOrEmpty(settingsPart.ResourceSharingExcludeRegex))
                {
                    settings.ResourceSharingExcludeFilter = new Regex(settingsPart.ResourceSharingExcludeRegex);
                }

                if (!string.IsNullOrEmpty(settingsPart.ResourceSetRegexes))
                {
                    var setRegexes = new List <Regex>();
                    foreach (var regex in settingsPart.ResourceSetRegexesEnumerable)
                    {
                        if (!string.IsNullOrEmpty(regex))
                        {
                            setRegexes.Add(new Regex(regex));
                        }
                    }
                    settings.ResourceSetFilters = setRegexes.ToArray();
                }

                DiscoverResourceOverrides(resources, resourceType);

                IList <ResourceRequiredContext> result;

                if (resourceType == ResourceType.Style)
                {
                    result = _combinatorService.CombineStylesheets(resources, settings);
                }
                else if (resourceType == ResourceType.JavaScript)
                {
                    result = _combinatorService.CombineScripts(resources, settings);
                }
                else
                {
                    return(base.BuildRequiredResources(stringResourceType));
                }

                RemoveOriginalResourceShapes(result, resourceType);

                return(result);
            }
            catch (Exception ex)
            {
                if (ex.IsFatal())
                {
                    throw;
                }
                Logger.Error(ex, "Error when combining " + resourceType + " files");
                return(base.BuildRequiredResources(stringResourceType));
            }
        }
Example #15
0
        public ViewreportModel VerifyGetReport(string reportId)
        {
            UserModel       currentUser = null;
            ViewreportModel result      = new ViewreportModel();

            var session = _accessor.Current().Session;

            if (session != null)
            {
                currentUser = session["CurrentUser"] as UserModel;

                var reportItems = ((UsageInfoService)_serviceUsageInfo).
                                  GetByUserNameAndDate(currentUser.Email, !(currentUser.ReportsViewByMonth));

                if (currentUser.ReportsViewByMonth)
                {
                    if (reportItems.Count() < currentUser.MaxReportViewsPerMonth)
                    {
                        //commented by aloha
                        //var companyModel = ((CompanyModelService)_service).GetById(reportId);

                        //get company
                        CompanyModel companyModel = ((CompanyModelService)_service).GetPrimaryById(reportId);

                        //save count for report view
                        var usageModel = _mapper.Map <CompanyModel, UsageInfoModel>(companyModel);
                        usageModel.UserName = currentUser.Email;
                        _serviceUsageInfo.Create(usageModel);

                        result.Company       = companyModel;
                        result.ViewReportbit = true;
                        return(result);
                        //return true;
                    }
                }
                else
                {
                    if (reportItems.Count() < currentUser.MaxReportViewsPerYear)
                    {
                        //commented by aloha
                        //var companyModel = ((CompanyModelService)_service).GetById(reportId);

                        //get company
                        var companyModel = ((CompanyModelService)_service).GetPrimaryById(reportId);

                        //save count for report view
                        var usageModel = _mapper.Map <CompanyModel, UsageInfoModel>(companyModel);
                        usageModel.UserName = currentUser.Email;
                        _serviceUsageInfo.Create(usageModel);

                        result.Company       = companyModel;
                        result.ViewReportbit = true;
                        //return true;
                        return(result);
                    }
                }
                result.ViewReportbit = false;
                return(result);
                //return false;
            }

            //TODO: not return true, need clear auth when session null
            result.ViewReportbit = true;
            return(result);

            //return true;
        }
Example #16
0
        public SearchResponseModel Get(SearchModel searchModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UserModel     currentUser = null;
                    List <string> States      = new List <string>();
                    var           session     = _accessor.Current().Session;
                    if (session != null)
                    {
                        currentUser = session["CurrentUser"] as UserModel;
                    }

                    if (currentUser != null)
                    {
                        var searchLogModel = _mapper.Map <SearchModel, SearchLogModel>(searchModel);
                        if (!string.IsNullOrEmpty(searchModel.SearchName))
                        {
                            searchLogModel.UserId    = currentUser.Id;
                            searchLogModel.SicCode   = string.Join(",", searchModel.SicCodes);
                            searchLogModel.ClassCode = string.Join(",", searchModel.ClassCodes);
                            searchLogModel.PhoneEmp  = searchModel.HasPhoneNumber;
                            _serviceSearchLog.Create(searchLogModel);
                        }

                        List <decimal?> carrierNumbers = new List <decimal?>();
                        foreach (string group in searchModel.CarrierGroups)
                        {
                            carrierNumbers.AddRange(((carrierNameAutocompleteService)_serviceCarrierName).GetCarrierGroupName(group.Trim()).ConvertAll <decimal?>(p => p));
                        }

                        carrierNumbers.AddRange(searchModel.CarrierNumbers.ToList());
                        searchModel.CarrierNumbers = carrierNumbers.ToArray();

                        List <string> classcodeitem = new List <string>();
                        List <string> sicCodeItem   = new List <string>();
                        foreach (string classcode in searchModel.ClassCodes)
                        {
                            if (classcode.Length == 1)
                            {
                                classcodeitem.AddRange(((ClassCodeService)_serviceClassCode).GetClassCodeByPrefix(classcode));
                            }
                            else
                            {
                                classcodeitem.Add(classcode);
                            }
                        }
                        searchModel.ClassCodes = classcodeitem.ToArray();

                        foreach (string sicCode in searchModel.SicCodes)
                        {
                            if (sicCode.Split(',').Length == 2)
                            {
                                sicCodeItem.AddRange(((SicCodeService)_serviceSicCodes).GetSicCodeByRange(sicCode.Split(',')[0], sicCode.Split(',')[1]));
                            }
                            else
                            {
                                sicCodeItem.Add(sicCode);
                            }
                        }
                        searchModel.SicCodes = sicCodeItem.ToArray();

                        var companyModel = _mapper.Map <SearchModel, CompanyModel>(searchModel);
                        companyModel.UserId        = currentUser.Id;
                        companyModel.ShowCarrier   = currentUser.ShowCarrier;
                        companyModel.ShowStatusFld = currentUser.ShowStatusFld;

                        if (searchModel.States != null)
                        {
                            States = searchModel.States.ToList();
                        }

                        companyModel.States = ((UserStatesService)_serviceUserStates).GetAllStatesByUserId(currentUser.Id).ToList();

                        var response = ((CompanyModelService)_service).GetAllByCompanyModel(companyModel, States);

                        response.UserId        = currentUser.Id;
                        response.ShowCarrier   = currentUser.ShowCarrier;
                        response.ShowStatusFld = currentUser.ShowStatusFld;
                        return(response);
                    }
                    else
                    {
                        var companyModel = _mapper.Map <SearchModel, CompanyModel>(searchModel);
                        States = searchModel.States.ToList();
                        return(((CompanyModelService)_service).GetAllByCompanyModel(companyModel, States));
                    }
                }

                return(null);
            }
            catch (Exception ex) { return(null); }
        }
        protected override DriverResult Editor(HighlightsGroupPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var group           = new HighlightsGroup();
            var httpContext     = _httpContextAccessor.Current();
            var HighlightsItems = _HighlightsService.GetHighlightsItemsByGroupId(part.Id);
            var form            = httpContext.Request.Form;

            int[] Ordinati = new int[form.Count];

            string Suffisso;
            int    Riga = 0;

            foreach (string key in form.Keys)
            {
                if (key.StartsWith("HighlightsItems"))
                {
                    Suffisso = key.Substring(key.IndexOf("].") + 2);
                    switch (Suffisso)
                    {
                    case "Position":
                        //Lista[Riga, 0] = Convert.ToInt32(form[key]);
                        break;

                    case "ItemId":
                        Ordinati[Riga++] = Convert.ToInt32(form[key]);
                        break;

                    default:
                        break;
                    }
                }
            }


            String Messaggio;

            Messaggio = "";
            if (Messaggio != "")
            {
                updater.AddModelError(this.Prefix, T(Messaggio));
            }

            Array.Resize <int>(ref Ordinati, Riga);

            if (updater.TryUpdateModel(group, Prefix, null, null))
            {
                if (group.DisplayPlugin.StartsWith(group.DisplayTemplate.ToString() + " - "))
                {
                    part.DisplayPlugin = group.DisplayPlugin;
                }
                else
                {
                    part.DisplayPlugin = "";
                }
                part.DisplayTemplate = group.DisplayTemplate;
                part.ItemsSourceType = group.ItemsSourceType;
                if (group.ItemsSourceType == Enums.ItemsSourceTypes.ByHand)
                {
                    if (group.HighlightsItemsOrder != null)
                    {
                        for (var i = 0; i < Ordinati.Length; i++)
                        {
                            _HighlightsService.UpdateOrder(Convert.ToInt32(Ordinati[i]), i);
                        }
                    }
                }
                else
                {
                    part.Query_Id = group.Query_Id;
                }
            }
            else
            {
                _transactions.Cancel();
            }
            return(Editor(part, shapeHelper));
        }
        protected override DriverResult Editor(AutoroutePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var settings    = part.TypePartDefinition.Settings.GetModel <AutorouteSettings>();
            var itemCulture = _cultureManager.GetSiteCulture();

            // If we are editing an existing content item, check to see if we are an ILocalizableAspect so we can use its culture for alias generation.
            if (part.Record.Id != 0)
            {
                var localizableAspect = part.As <ILocalizableAspect>();

                if (localizableAspect != null)
                {
                    itemCulture = localizableAspect.Culture;
                }
            }

            if (settings.UseCulturePattern)
            {
                // Hack: if the LocalizedPart is attached to the content item, it will submit the following form value,
                // which we use to determine what culture to use for alias generation.
                var context = _httpContextAccessor.Current();
                if (!String.IsNullOrEmpty(context.Request.Form["Localization.SelectedCulture"]))
                {
                    itemCulture = context.Request.Form["Localization.SelectedCulture"].ToString();
                }
            }

            // We update the settings assuming that when
            // pattern culture = null or "" it means culture = default website culture
            // for patterns that we migrated.
            foreach (var pattern in settings.Patterns.Where(x => String.IsNullOrWhiteSpace(x.Culture)))
            {
                pattern.Culture = _cultureManager.GetSiteCulture();;
            }

            // We do the same for default patterns.
            foreach (var pattern in settings.DefaultPatterns.Where(x => String.IsNullOrWhiteSpace(x.Culture)))
            {
                pattern.Culture = _cultureManager.GetSiteCulture();
            }

            // If the content type has no pattern for autoroute, then use a default one.
            if (!settings.Patterns.Any(x => String.Equals(x.Culture, itemCulture, StringComparison.OrdinalIgnoreCase)))
            {
                settings.Patterns = new List <RoutePattern> {
                    new RoutePattern {
                        Name = "Title", Description = "my-title", Pattern = "{Content.Slug}", Culture = itemCulture
                    }
                };
            }

            // If the content type has no defaultPattern for autoroute, then use a default one.
            if (!settings.DefaultPatterns.Any(x => String.Equals(x.Culture, itemCulture, StringComparison.OrdinalIgnoreCase)))
            {
                // If we are in the default culture, check the old setting.
                if (String.Equals(itemCulture, _cultureManager.GetSiteCulture(), StringComparison.OrdinalIgnoreCase))
                {
                    if (!String.IsNullOrWhiteSpace(settings.DefaultPatternIndex))
                    {
                        var patternIndex = settings.DefaultPatternIndex;
                        settings.DefaultPatterns.Add(new DefaultPattern {
                            PatternIndex = patternIndex, Culture = itemCulture
                        });
                    }
                    else
                    {
                        settings.DefaultPatterns.Add(new DefaultPattern {
                            PatternIndex = "0", Culture = itemCulture
                        });
                    }
                }
                else
                {
                    settings.DefaultPatterns.Add(new DefaultPattern {
                        PatternIndex = "0", Culture = itemCulture
                    });
                }
            }

            var viewModel = new AutoroutePartEditViewModel {
                CurrentUrl     = part.DisplayAlias,
                Settings       = settings,
                CurrentCulture = itemCulture
            };

            // Retrieve home page.
            var homePageId = _homeAliasService.GetHomePageId(VersionOptions.Latest);
            var isHomePage = part.Id == homePageId;

            viewModel.IsHomePage        = isHomePage;
            viewModel.PromoteToHomePage = part.PromoteToHomePage;

            if (settings.PerItemConfiguration)
            {
                // If enabled, the list of all available patterns is displayed, and the user can select which one to use.
                // todo: later
            }

            var previous = part.DisplayAlias;

            if (updater != null && updater.TryUpdateModel(viewModel, Prefix, null, null))
            {
                // Remove any leading slash in the permalink.
                if (viewModel.CurrentUrl != null)
                {
                    viewModel.CurrentUrl = viewModel.CurrentUrl.TrimStart('/');
                }

                part.DisplayAlias = viewModel.CurrentUrl;

                // Reset the alias if we need to force regeneration, and the user didn't provide a custom one.
                if (settings.AutomaticAdjustmentOnEdit && previous == part.DisplayAlias)
                {
                    part.DisplayAlias = String.Empty;
                }

                if (!_autorouteService.IsPathValid(part.DisplayAlias))
                {
                    updater.AddModelError("CurrentUrl", T("Please do not use any of the following characters in your permalink: \":\", \"?\", \"#\", \"[\", \"]\", \"@\", \"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\", \", \"<\", \">\", \"\\\", \"|\", \"%\", \".\". No spaces are allowed (please use dashes or underscores instead)."));
                }

                if (part.DisplayAlias != null && part.DisplayAlias.Length > 1850)
                {
                    updater.AddModelError("CurrentUrl", T("Your permalink is too long. The permalink can only be up to 1,850 characters."));
                }

                // Mark the content item to be the homepage. Once this content isp ublished, the home alias will be updated to point to this content item.
                part.PromoteToHomePage = viewModel.PromoteToHomePage;
            }

            return(ContentShape("Parts_Autoroute_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Autoroute.Edit", Model: viewModel, Prefix: Prefix)));
        }
Example #19
0
        public override IList <ResourceRequiredContext> BuildRequiredResources(string stringResourceType)
        {
            // It's necessary to make a copy since making a change to the local variable also changes the private one.
            var resources = new List <ResourceRequiredContext>(base.BuildRequiredResources(stringResourceType));

            var settingsPart = _cacheManager.Get("Piedone.Combinator.CombinatorSettingsPart", ctx =>
            {
                _combinatorEventMonitor.MonitorConfigurationChanged(ctx);

                return(_siteService.GetSiteSettings().As <CombinatorSettingsPart>());
            });

            if (resources.Count == 0 ||
                Orchard.UI.Admin.AdminFilter.IsApplied(_httpContextAccessor.Current().Request.RequestContext) && !settingsPart.EnableForAdmin)
            {
                return(resources);
            }

            var resourceType = ResourceTypeHelper.StringTypeToEnum(stringResourceType);

            try
            {
                var settings = new CombinatorSettings
                {
                    CombineCDNResources     = settingsPart.CombineCDNResources,
                    EmbedCssImages          = settingsPart.EmbedCssImages,
                    EmbeddedImagesMaxSizeKB = settingsPart.EmbeddedImagesMaxSizeKB,
                    MinifyResources         = settingsPart.MinifyResources
                };

                if (!String.IsNullOrEmpty(settingsPart.CombinationExcludeRegex))
                {
                    settings.CombinationExcludeFilter = new Regex(settingsPart.CombinationExcludeRegex);
                }
                if (!String.IsNullOrEmpty(settingsPart.EmbedCssImagesStylesheetExcludeRegex))
                {
                    settings.EmbedCssImagesStylesheetExcludeFilter = new Regex(settingsPart.EmbedCssImagesStylesheetExcludeRegex);
                }
                if (!String.IsNullOrEmpty(settingsPart.MinificationExcludeRegex))
                {
                    settings.MinificationExcludeFilter = new Regex(settingsPart.MinificationExcludeRegex);
                }

                if (!String.IsNullOrEmpty(settingsPart.ResourceSetRegexes))
                {
                    var setRegexes = new List <Regex>();
                    foreach (var regex in settingsPart.ResourceSetRegexes.Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (!String.IsNullOrEmpty(regex))
                        {
                            setRegexes.Add(new Regex(regex));
                        }
                    }
                    settings.ResourceSetFilters = setRegexes.ToArray();
                }

                if (resourceType == ResourceType.Style)
                {
                    // Checking for overridden stylesheets
                    var currentTheme = _themeManager.GetRequestTheme(_httpContextAccessor.Current().Request.RequestContext);
                    var shapeTable   = _shapeTableLocator.Lookup(currentTheme.Id);

                    foreach (var resource in resources)
                    {
                        var shapeName = StylesheetBindingStrategy.GetAlternateShapeNameFromFileName(resource.Resource.GetFullPath());

                        // Simply included CDN stylesheets are not in the ShapeTable, so we have to check
                        if (shapeTable.Bindings.ContainsKey("Style__" + shapeName))
                        {
                            var binding = shapeTable.Bindings["Style__" + shapeName].BindingSource;
                            resource.Resource.SetUrl(binding, null);
                        }
                    }

                    return(_combinatorService.CombineStylesheets(resources, settings));
                }
                else if (resourceType == ResourceType.JavaScript)
                {
                    return(_combinatorService.CombineScripts(resources, settings));
                }

                return(base.BuildRequiredResources(stringResourceType));
            }
            catch (Exception ex)
            {
                if (ex.IsFatal())
                {
                    throw;
                }
                Logger.Error(ex, "Error when combining " + resourceType + " files");
                return(base.BuildRequiredResources(stringResourceType));
            }
        }
Example #20
0
 /// <summary>
 /// Method to save the ProxyGrantingTicket to the backing storage facility.
 /// </summary>
 /// <param name="proxyGrantingTicketIou">used as the key</param>
 /// <param name="proxyGrantingTicket">used as the value</param>
 public void InsertProxyGrantingTicketMapping(string proxyGrantingTicketIou, string proxyGrantingTicket)
 {
     _httpContextAccessor.Current().Cache.Insert(proxyGrantingTicketIou, proxyGrantingTicket, null, _clock.UtcNow.Add(DefaultExpiration), Cache.NoSlidingExpiration);
 }
Example #21
0
 public ApplicationSignInManager Create()
 {
     return(_httpContextAccessor.Current().GetOwinContext().Get <ApplicationSignInManager>());
 }