Example #1
2
 public bool Applies(ShoppingCartQuantityProduct quantityProduct, IEnumerable<ShoppingCartQuantityProduct> cartProducts) {
     if (DiscountPart == null) return false;
     var now = _clock.UtcNow;
     if (DiscountPart.StartDate != null && DiscountPart.StartDate > now) return false;
     if (DiscountPart.EndDate != null && DiscountPart.EndDate < now) return false;
     if (DiscountPart.StartQuantity != null &&
         DiscountPart.StartQuantity > quantityProduct.Quantity)
         return false;
     if (DiscountPart.EndQuantity != null &&
         DiscountPart.EndQuantity < quantityProduct.Quantity)
         return false;
     if (!string.IsNullOrWhiteSpace(DiscountPart.Pattern)) {
         string path;
         if (DiscountPart.DisplayUrlResolver != null) {
             path = DiscountPart.DisplayUrlResolver(quantityProduct.Product);
         }
         else {
             var urlHelper = new UrlHelper(_wca.GetContext().HttpContext.Request.RequestContext);
             path = urlHelper.ItemDisplayUrl(quantityProduct.Product);
         }
         if (!path.StartsWith(DiscountPart.Pattern, StringComparison.OrdinalIgnoreCase))
             return false;
     }
     if (DiscountPart.Roles.Any()) {
         var user = _wca.GetContext().CurrentUser;
         if (user.Has<UserRolesPart>()) {
             var roles = user.As<UserRolesPart>().Roles;
             if (!roles.Any(r => DiscountPart.Roles.Contains(r))) return false;
         }
     }
     return true;
 }
 public static MvcHtmlString ImageActionLink(
     this HtmlHelper helper,
     string imageUrl,
     string altText,
     string actionName,
     string controllerName,
     object routeValues,
     object linkHtmlAttributes,
     object imgHtmlAttributes)
 {
     var linkAttributes = AnonymousObjectToKeyValue(linkHtmlAttributes);
     var imgAttributes = AnonymousObjectToKeyValue(imgHtmlAttributes);
     var imgBuilder = new TagBuilder("img");
     imgBuilder.MergeAttribute("src", imageUrl);
     imgBuilder.MergeAttribute("alt", altText);
     imgBuilder.MergeAttributes(imgAttributes, true);
     var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
     var linkBuilder = new TagBuilder("a");
     linkBuilder.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
     linkBuilder.MergeAttributes(linkAttributes, true);
     var text = linkBuilder.ToString(TagRenderMode.StartTag);
     text += imgBuilder.ToString(TagRenderMode.SelfClosing);
     text += linkBuilder.ToString(TagRenderMode.EndTag);
     return MvcHtmlString.Create(text);
 }
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            try
            {
                HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie != null)
                {
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    if (authTicket.UserData == "OAuth") return;

                    var currentUser = serializer.Deserialize<CurrentUserPrincipal>(authTicket.UserData);
                    currentUser.SetIdentity(authTicket.Name);
                    HttpContext.Current.User = currentUser;
                }
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                FormsAuthentication.SignOut();
                HttpCookie oldCookie = new HttpCookie(".ASPXAUTH");
                oldCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(oldCookie);

                HttpCookie ASPNET_SessionId = new HttpCookie("ASP.NET_SessionId");
                ASPNET_SessionId.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(ASPNET_SessionId);

                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                Response.Redirect(urlHelper.Action(MVC.OAuth.ActionNames.SignIn, MVC.OAuth.Name));
            }
        }
        public async Task <object> DownLoadAttachment(MailListDetailItems mailListDetailItems)
        {
            try
            {
                var attachmentRequest = await GraphHelper.DownloadAttachments(mailListDetailItems.Id);

                if (!System.IO.Directory.Exists(ConfigurationManager.AppSettings["filePath"]))
                {
                    CreateDiretoryIfNotExists(ConfigurationManager.AppSettings["filePath"]);
                }
                var filePath = ConfigurationManager.AppSettings["filePath"] + "/" + mailListDetailItems.EmailID;
                if (!System.IO.Directory.Exists(filePath))
                {
                    CreateDiretoryIfNotExists(filePath);
                }
                foreach (var item in attachmentRequest)
                {
                    var fileAttachment = (FileAttachment)item;
                    System.IO.File.WriteAllBytes(System.IO.Path.Combine(filePath, fileAttachment.Name), fileAttachment.ContentBytes);
                }
                var redirectUrl = new System.Web.Mvc.UrlHelper(Request.RequestContext).Action("Index", "Mail", new { });
                return(Json(new { Url = redirectUrl, status = "OK" }));
            }
            catch (Exception ex)
            {
                Flash(ex.Message, null);
                throw;
            }
        }
    protected void SetLinks(AtomEntry e)
    {
      LogService.Debug("AnnotateService.SetLinks entryId={0}", e.Id);
      var links = e.Links.ToList();
      var url = new UrlHelper(Container.GetInstance<RequestContext>());
      //atom threading extension
      if (e.InReplyTo != null)
      {
        e.InReplyTo.Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force);
        links.Merge(new AtomLink
        {
          Rel = "related",
          Type = "text/html",
          Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force)
        });
      }

      //atom threading extension
      links.Merge(new AtomLink
      {
        Href = url.RouteIdUri("AnnotateEntryAnnotationsFeed", e.Id, AbsoluteMode.Force),
        Rel = "replies",
        Type = Atom.ContentType,
        Count = e.Total,
        Updated = DateTimeOffset.UtcNow
      });
      e.Links = links;
    }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var urlHelper = new System.Web.Mvc.UrlHelper(filterContext.RequestContext);

            var currentUser = _context.Users.Where(u => u.Email == HttpContext.Current.User.Identity.Name).FirstOrDefault();

            if (currentUser != null)
            {
                if (currentUser.RoleId == 1)
                {
                    var IfEmployeeHasProfile = _context.Employees.Where(e => e.Id == currentUser.Id).FirstOrDefault();
                    if (IfEmployeeHasProfile == null)
                    {
                        filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Employees"));
                    }
                }

                if (currentUser.RoleId == 2)
                {
                    var IfCompanyHasProfile = _context.Companies.Where(e => e.Id == currentUser.Id).FirstOrDefault();

                    if (IfCompanyHasProfile == null)
                    {
                        //filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Companies"));
                        filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Companies"));
                    }
                }
            }


            base.OnActionExecuting(filterContext);
        }
        public ActionResult Rsd(string blogPath) {
            Logger.Debug("RSD requested");

            BlogPart blogPart = _blogService.Get(blogPath);

            if (blogPart == null)
                return HttpNotFound();

            const string manifestUri = "http://archipelago.phrasewise.com/rsd";

            var urlHelper = new UrlHelper(ControllerContext.RequestContext, _routeCollection);
            var url = urlHelper.Action("", "", new { Area = "XmlRpc" });

            var options = new XElement(
                XName.Get("service", manifestUri),
                new XElement(XName.Get("engineName", manifestUri), "Orchard CMS"),
                new XElement(XName.Get("engineLink", manifestUri), "http://orchardproject.net"),
                new XElement(XName.Get("homePageLink", manifestUri), "http://orchardproject.net"),
                new XElement(XName.Get("apis", manifestUri),
                    new XElement(XName.Get("api", manifestUri),
                        new XAttribute("name", "MetaWeblog"),
                        new XAttribute("preferred", true),
                        new XAttribute("apiLink", url),
                        new XAttribute("blogID", blogPart.Id))));

            var doc = new XDocument(new XElement(
                                        XName.Get("rsd", manifestUri),
                                        new XAttribute("version", "1.0"),
                                        options));

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return Content(doc.ToString(), "text/xml");
        }
Example #8
0
        public static MvcHtmlString LinkWithSID(this System.Web.Mvc.UrlHelper Url, string Title, string ActionName, string ControllerName, object RouteValues, object HtmlAttributes)
        {
            string url = Url.Action(ActionName, ControllerName) + "?";

            if (RouteValues != null)
            {
                var RouteValuesProperties = RouteValues.GetType().GetProperties();
                foreach (var p in RouteValuesProperties)
                {
                    url += p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(RouteValues).ToString()) + "&";
                }
            }
            url += "sid=" + Url.RequestContext.HttpContext.Session["sid"];
            var attributes = " ";

            if (HtmlAttributes != null)
            {
                var HtmlAttributesProperties = HtmlAttributes.GetType().GetProperties();
                foreach (var p in HtmlAttributesProperties)
                {
                    attributes += p.Name + "=\"" + p.GetValue(HtmlAttributes) + "\" ";
                }
            }
            return(new MvcHtmlString("<a href=\"javascript:window.location='" + url + "'\"" + attributes + "/>" + HttpUtility.HtmlEncode(Title) + "</a>"));
        }
 public IEnumerable<NotifyEntry> GetNotifications() {
     if ( string.IsNullOrWhiteSpace(_orchardServices.WorkContext.CurrentSite.BaseUrl)) {
         var urlHelper = new UrlHelper(_workContext.HttpContext.Request.RequestContext);
         var url = urlHelper.Action("Index", "Admin", new {Area = "Settings"});
         yield return new NotifyEntry { Message = T("The Warmup feature needs the <a href=\"{0}\">Base Url site setting</a> to be set.", url), Type = NotifyType.Warning };
     }
 }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var userId = filterContext.HttpContext.User.Identity.GetUserId();
                var userManager = filterContext.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var currentUser = userManager.FindById(userId);
                if (currentUser.EmailConfirmed == false)
                {

                    //取得 URLHelper
                    var urlHelper = new UrlHelper(filterContext.RequestContext);

                    //將路徑名稱組合
                    var currentControllerAndActionName =
                        string.Concat(filterContext.RouteData.Values["controller"],
                        "_",
                        filterContext.RouteData.Values["action"]);

                    //明確開放[登入][登出][EMAIL驗證]
                    var allowAction = new[] { "Account_Login", "Account_LogOff", "Account_VerifyMail" };

                    if (allowAction.Contains(currentControllerAndActionName) == false)
                    {
                        //所有沒有通過EMAIL驗證的都導向驗證頁面(請視專案需求調整)
                        var redirect = new RedirectResult(urlHelper.Action("VerifyMail", "Account"));
                        filterContext.Result = redirect;
                    }

                }
            }
        }
        public static MvcHtmlString CustomComboBoxWithCustomDataFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string action, string controller, string placeHolderString = "", params string[] paramControls)
        {
            var    urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var    url       = urlHelper.Action(action, controller);
            var    metadata  = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value     = metadata.Model == null ? string.Empty : metadata.Model.ToString();

            value = Convert.ToInt32(value) > 0 ? value : string.Empty;
            string fieldId = metadata.PropertyName;
            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;

            var attributes = new RouteValueDictionary();

            attributes["controltype"]     = "kendoComboBoxForCustomData";
            attributes["serverFiltering"] = false.ToString();
            attributes["url"]             = url;
            attributes["placeHolder"]     = placeHolderString.Equals(string.Empty) ? PlaceHolder : placeHolderString;
            attributes["customType"]      = "text";
            attributes["parameter"]       = string.Join(",", paramControls);
            attributes["id"]   = fieldId;
            attributes["name"] = fieldId;

            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
Example #12
0
        public string GenerateContentUrl(string relativePath)
        {
            var httpRequest = GetCurrentRequest();
            var urlHelper = new UrlHelper(httpRequest.RequestContext, RouteTable.Routes);

            return urlHelper.Content(relativePath);
        }
Example #13
0
        public string GetBaseUrl()
        {
            var httpRequest = GetCurrentRequest();
            var urlHelper = new UrlHelper(httpRequest.RequestContext, RouteTable.Routes);

            return urlHelper.Action("Index", "Blog", null, httpRequest.Url.Scheme);
        }
Example #14
0
        public static string Generate(RequestContext requestContext, NavigationRequest navigationItem, RouteValueDictionary routeValues)
        {
            if (requestContext == null)
                throw new ArgumentNullException("requestContext");
            if (navigationItem == null)
                throw new ArgumentNullException("navigationItem");

            var urlHelper = new UrlHelper(requestContext);
            string generatedUrl = null;

            if (!string.IsNullOrEmpty(navigationItem.RouteName))
            {
                generatedUrl = urlHelper.RouteUrl(navigationItem.RouteName, routeValues);
            }
            else if (!string.IsNullOrEmpty(navigationItem.ControllerName) && !string.IsNullOrEmpty(navigationItem.ActionName))
            {
                generatedUrl = urlHelper.Action(navigationItem.ActionName, navigationItem.ControllerName, routeValues, null, null);
            }
            else if (!string.IsNullOrEmpty(navigationItem.Url))
            {
                generatedUrl = navigationItem.Url.StartsWith("~/", StringComparison.Ordinal) 
                    ? urlHelper.Content(navigationItem.Url) 
                    : navigationItem.Url;
            }
            else if (routeValues.Any())
            {
                generatedUrl = urlHelper.RouteUrl(routeValues);
            }

            return generatedUrl;

        }
Example #15
0
        public string GenerateAtomFeedUrl()
        {
            var httpRequest = GetCurrentRequest();
            var urlHelper = new UrlHelper(httpRequest.RequestContext, RouteTable.Routes);

            return urlHelper.Action("Atom", "Feed", null, httpRequest.Url.Scheme, httpRequest.Url.Host);
        }
        void ServerVariablesParser_Parsing(object sender, Dictionary<string, object> e)
        {
            if (HttpContext.Current == null) return;
            var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));

            var mainDictionary = new Dictionary<string, object>
            {
                {
                    "ocBaseUrl",
                    urlHelper.GetUmbracoApiServiceBaseUrl<ObjectController>(controller => controller.PostCreate(null))
                },
                {
                    "pecBaseUrl",
                    urlHelper.GetUmbracoApiServiceBaseUrl<PropertyEditorsApiController>(
                        controller => controller.GetAllTypes())
                },
                {
                    "fcBaseUrl",
                    urlHelper.GetUmbracoApiServiceBaseUrl<FieldApiController>(controller => controller.GetAllUsers())
                }
            };

            if (!e.Keys.Contains("uioMatic"))
            {
                e.Add("uioMatic", mainDictionary);
            }
        }
Example #17
0
        private static MvcHtmlString MvcCaptcha(this HtmlHelper helper, string actionName, string controllerName, MvcCaptchaOptions options)
        {
            if (options == null)
            {
                options = new MvcCaptchaOptions();
            }
            MvcCaptchaImage mvcCaptchaImage = new MvcCaptchaImage(options);
            HttpContext.Current.Session.Add(mvcCaptchaImage.UniqueId, mvcCaptchaImage);
            UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            StringBuilder stringBuilder = new StringBuilder(1500);
            stringBuilder.Append("\r\n<!--MvcCaptcha 1.1 for ASP.NET MVC 2 RC Copyright:2009-2010 Webdiyer (http://www.webdiyer.com)-->\r\n");
            stringBuilder.Append("<input type=\"hidden\" name=\"_mvcCaptchaGuid\" id=\"_mvcCaptchaGuid\"");
            if (options.DelayLoad)
            {
                stringBuilder.Append("/><script language=\"javascript\" type=\"text/javascript\">if (typeof (jQuery) == \"undefined\") { alert(\"jQuery脚本库未加载,请检查!\"); }");
                stringBuilder.Append("var _mvcCaptchaPrevGuid = null,_mvcCaptchaImgLoaded = false;function _loadMvcCaptchaImage(){");
                stringBuilder.Append("if(!_mvcCaptchaImgLoaded){$.ajax({type:'GET',url:'");
                stringBuilder.Append(urlHelper.Action("MvcCaptchaLoader", "_MvcCaptcha", new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }));
                stringBuilder.Append("?'+_mvcCaptchaPrevGuid,global:false,success:function(data){_mvcCaptchaImgLoaded=true;");
                stringBuilder.Append("$(\"#_mvcCaptchaGuid\").val(data);_mvcCaptchaPrevGuid=data;$(\"#");
                stringBuilder.Append(options.CaptchaImageContainerId).Append("\").html('");
                stringBuilder.Append(MvcCaptchaHelper.CreateImgTag(urlHelper.Action(actionName, controllerName, new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }) + "?'+data+'", options, null));
                stringBuilder.Append("');}});} };function _reloadMvcCaptchaImage(){_mvcCaptchaImgLoaded=false;_loadMvcCaptchaImage();};$(function(){");
                stringBuilder.Append("if($(\"#").Append(options.ValidationInputBoxId).Append("\").length==0){alert(\"未能找到验证码输入文本框,请检查ValidationInputBoxId属性是否设置正确!\");}");
                stringBuilder.Append("if($(\"#").Append(options.CaptchaImageContainerId).Append("\").length==0){alert(\"未能找到验证码图片父容器,请检查CaptchaImageContainerId属性是否设置正确!\");}");
                stringBuilder.Append("$(\"#").Append(options.ValidationInputBoxId);
                stringBuilder.Append("\").bind(\"focus\",_loadMvcCaptchaImage)});</script>");
            }
            else
            {
                stringBuilder.AppendFormat(" value=\"{0}\" />", mvcCaptchaImage.UniqueId);
                stringBuilder.Append(MvcCaptchaHelper.CreateImgTag(urlHelper.Action(actionName, controllerName, new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }) + "?" + mvcCaptchaImage.UniqueId, options, mvcCaptchaImage.UniqueId));
                stringBuilder.Append("<script language=\"javascript\" type=\"text/javascript\">function _reloadMvcCaptchaImage(){var ci=document.getElementById(\"");
                stringBuilder.Append(mvcCaptchaImage.UniqueId);
                stringBuilder.Append("\");var sl=ci.src.length;if(ci.src.indexOf(\"&\")>-1)sl=ci.src.indexOf(\"&\");ci.src=ci.src.substr(0,sl)+\"&\"+(new Date().valueOf());}</script>");
            }
            stringBuilder.Append("\r\n<!--MvcCaptcha 1.1 for ASP.NET MVC 2 RC Copyright:2009-2010 Webdiyer (http://www.webdiyer.com)-->\r\n");
            return MvcHtmlString.Create(stringBuilder.ToString());
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NoPermission",
                        LogOnUrl = urlHelper.Action("index", "login")
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                context.Result = new RedirectToRouteResult(
                                       new RouteValueDictionary
                                   {
                                       { "action", "index" },

                                       { "controller", "error" },

                                       { "id", (int)ErrorType.NoPermission},

                                       {"returnurl",context.RequestContext.HttpContext.Request.Url}
                                   });
            }
        }
        public static MvcHtmlString CustomComboBoxWithCascadeFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string entityTypeLookup, string customActionCascade, string controller, object htmlAttributes = null)
        {
            var    urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var    url       = urlHelper.Action(customActionCascade, controller);
            var    metadata  = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value     = metadata.Model == null ? string.Empty : metadata.Model.ToString();

            value = Convert.ToInt32(value) > 0 ? value : string.Empty;
            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;
            string fieldId = metadata.PropertyName;

            var attributes = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);

            attributes["service"]         = entityTypeLookup;
            attributes["controltype"]     = "kendoComboBoxWithCascade";
            attributes["serverFiltering"] = false.ToString();
            attributes["placeHolder"]     = PlaceHolder;
            attributes["customType"]      = "text";
            attributes["urlCascade"]      = url;
            attributes["id"]   = fieldId;
            attributes["name"] = fieldId;
            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
        public PackageListViewModel(IQueryable<Package> packages,
            string searchTerm,
            string sortOrder,
            int totalCount,
            int pageIndex,
            int pageSize,
            UrlHelper url,
            bool includePrerelease)
        {
            // TODO: Implement actual sorting
            IEnumerable<ListPackageItemViewModel> items;
            using (MiniProfiler.Current.Step("Querying and mapping packages to list"))
            {
                items = packages.ToList()
                                .Select(pv => new ListPackageItemViewModel(pv, needAuthors: false));
            }
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = totalCount;
            SortOrder = sortOrder;
            SearchTerm = searchTerm;
            int pageCount = (TotalCount + PageSize - 1) / PageSize;

            var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
                items,
                PageIndex,
                pageCount,
                page => url.PackageList(page, sortOrder, searchTerm, includePrerelease)
            );
            Items = pager.Items;
            FirstResultIndex = 1 + (PageIndex * PageSize);
            LastResultIndex = FirstResultIndex + Items.Count() - 1;
            Pager = pager;
            IncludePrerelease = includePrerelease ? "true" : null;
        }
        public static IHtmlString RenderApplicationUrls(this HtmlHelper helper)
        {
            var url = new UrlHelper(helper.ViewContext.RequestContext);

            var applicationUrls = new
            {
                LoginUrl = url.Action(MVC.Authentication.Login()),
                LogoutUrl = url.Action(MVC.Authentication.Logout()),
                LoginCheckUrl = url.Action(MVC.Authentication.LoginCheck()),
                ListUsersUrl = url.Action("Index", "Api/Users"),
                CreateUserUrl = url.Action("Create", "Api/Users"),
                UpdateUserUrl = url.Action("Update", "Api/Users"),
                DeleteUsersUrl = url.Action("Delete", "Api/Users"),
                ListDashboardPermissionsUrl = url.Action("Index", "Api/DashboardPermissions"),
                ListMessagesUrl = url.Action("Index", "Api/Messages"),
                CreateMessageUrl = url.Action("Create", "Api/Messages"),
                DeleteMessagesUrl = url.Action("Delete", "Api/Messages"),
                ListOrganizationsUrl = url.Action("Index", "Api/Organizations"),
                CreateOrganizationUrl = url.Action("Create", "Api/Organizations"),
                UpdateOrganizationUrl = url.Action("Update", "Api/Organizations"),
                DeleteOrganizationsUrl = url.Action("Delete", "Api/Organizations"),
                ListRolesUrl = url.Action("Index", "Api/Roles")
            };

            var script = @"<script type='text/javascript'>
                        angular.module('colorSoft').constant('ApplicationUrls', <INSERT_URLS>);
                    </script>".Replace("<INSERT_URLS>", CreateJavascriptHash(applicationUrls));

            return MvcHtmlString.Create(script);
        }
        private static void ServerVariablesParserParsing(object sender, Dictionary<string, object> items)
        {
            if (!items.ContainsKey("umbracoUrls")) return;

            var umbracoUrls = (Dictionary<string, object>)items["umbracoUrls"];

            var url = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));

            umbracoUrls.Add("merchelloProductApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<ProductApiController>(
                controller => controller.GetAllProducts()));
            umbracoUrls.Add("merchelloProductVariantsApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<ProductVariantApiController>(
                controller => controller.GetProductVariant(Guid.NewGuid())));
            umbracoUrls.Add("merchelloSettingsApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<SettingsApiController>(
                controller => controller.GetAllCountries()));
            umbracoUrls.Add("merchelloWarehouseApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<WarehouseApiController>(
                controller => controller.GetDefaultWarehouse()));
            umbracoUrls.Add("merchelloCatalogShippingApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<CatalogShippingApiController>(
                controller => controller.GetShipCountry(Guid.NewGuid())));
            umbracoUrls.Add("merchelloCatalogFixedRateShippingApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<CatalogFixedRateShippingApiController>(
                controller => controller.GetAllShipCountryFixedRateProviders(Guid.NewGuid())));
            umbracoUrls.Add("merchelloPaymentGatewayApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<PaymentGatewayApiController>(
                controller => controller.GetAllGatewayProviders()));
            umbracoUrls.Add("merchelloTaxationGatewayApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<TaxationGatewayApiController>(
                controller => controller.GetAllGatewayProviders()));
            umbracoUrls.Add("merchelloInvoiceApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<InvoiceApiController>(
                controller => controller.GetAllInvoices()));
            umbracoUrls.Add("merchelloOrderApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<OrderApiController>(
                controller => controller.GetOrder(Guid.NewGuid())));
            umbracoUrls.Add("merchelloShipmentApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<ShipmentApiController>(
                controller => controller.GetShipment(Guid.NewGuid())));
            umbracoUrls.Add("merchelloPaymentApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<PaymentApiController>(
                controller => controller.GetPayment(Guid.NewGuid())));
            umbracoUrls.Add("merchelloGatewayProviderApiBaseUrl", url.GetUmbracoApiServiceBaseUrl<GatewayProviderApiController>(
                controller => controller.GetGatewayProvider(Guid.NewGuid())));
        }
Example #23
0
        /// <summary>
        /// Creates and Action link with a clickable image instead of text.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="controller">Controller</param>
        /// <param name="action">Action</param>
        /// <param name="parameters">Parameters</param>
        /// <param name="src">Image source</param>
        /// <param name="alt">Alternate text(Optional)</param>
        /// <returns>An HTML anchor tag with a nested image tag.</returns>
        public static MvcHtmlString ActionImage(this HtmlHelper helper, String controller, String action, Object parameters, String src, String alt = "", String title = "")
        {
            var tagBuilder = new TagBuilder("img");
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var url = urlHelper.Action(action, controller, parameters);
            var imgUrl = urlHelper.Content(src);
            var image = "";
            var html = new StringBuilder();

            // build the image tag.
            tagBuilder.MergeAttribute("src", imgUrl);
            tagBuilder.MergeAttribute("alt", alt);
            tagBuilder.MergeAttribute("width", "100");
            tagBuilder.MergeAttribute("height", "100");
            tagBuilder.MergeAttribute("title", title);
            image = tagBuilder.ToString(TagRenderMode.SelfClosing);

            html.Append("<a href=\"");
            html.Append(url);
            html.Append("\">");
            html.Append(image);
            html.Append("</a>");

            return MvcHtmlString.Create(html.ToString());
        }
Example #24
0
 public static string GetActionAbsoluteUrl(UrlHelper urlHelper, string actionName, string controllerName, object routeValues)
 {
     var baseUri = new Uri(GetWebRootUrl());
     string relativeUri = urlHelper.Action(actionName, controllerName, routeValues);
     var uri = new Uri(baseUri, relativeUri);
     return uri.AbsoluteUri;
 }
        /// <summary>
        /// Called by the ASP.NET MVC framework after the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null || !filterContext.HttpContext.Request.IsAjaxRequest())
            {
                return;
            }

            // Preparing Json object for AJAX.success processing in forms.js javascript
            string destinationUrl = string.Empty;
            if (filterContext.Result is RedirectResult)
            {
                var result = filterContext.Result as RedirectResult;
                destinationUrl = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
            }

            if (filterContext.Result is RedirectToRouteResult)
            {
                var result = filterContext.Result as RedirectToRouteResult;
                var helper = new UrlHelper(filterContext.RequestContext);
                destinationUrl = helper.RouteUrl(result.RouteValues);
            }

            // Rendered context is getting reloaded by AJAX.success in forms.js javascript
            if (filterContext.Result is ViewResult)
            {
                return;
            }

            var jsonResult = new JsonResult { Data = new { resultType = "Redirect", redirectUrl = destinationUrl } };
            filterContext.Result = jsonResult;
        }
Example #26
0
        private static String GetUrl(System.Web.Mvc.UrlHelper urlHelper, String action, Int32 page, IDictionary <String, Object> args)
        {
            var routeValues = new RouteValueDictionary(args);

            routeValues.Add("page", page);
            return(urlHelper.Action(action, routeValues));
        }
Example #27
0
        /// <summary>
        /// Loads the menu items.
        /// </summary>
        /// <param name="urlHelper">The URL helper.</param>
        /// <param name="runAsTenant">The run as tenant id.</param>
        /// <returns></returns>
        public static IList<MenuItem> LoadMenuItems(UrlHelper urlHelper)
        {
            var repo = ServiceLocator.Current.GetInstance<IRepositoryFactory>();
            var repoMenu = repo.CreateWithGuid<Menu>();

            var menus = repoMenu.GetAll().ToList();

            var items = new List<MenuItem>();

            foreach (var menu in menus)
            {
                var link = string.Empty;
                link = urlHelper.RouteUrl("Default", new { controller = menu.Controller, action = menu.Action });

                var item = new MenuItem()
                {
                    Text = menu.Name,
                    Link = link,
                    IsAdministration = menu.IsAdministration
                };

                items.Add(item);
            }
            //var items = new List<MenuItem>();
            if (items == null)
                items = new List<MenuItem>();

            return items;
        }
 public ShippingMethodAdminService(IEnumerable<IShippingMethod> shippingMethods, UrlHelper urlHelper,
     IConfigurationProvider configurationProvider)
 {
     _shippingMethods = shippingMethods;
     _urlHelper = urlHelper;
     _configurationProvider = configurationProvider;
 }
        public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
        {
            if (model.Exception != null)
                throw model.Exception;

            var client = model.AuthenticatedClient;
            var username = client.UserInformation.UserName;

            FormsAuthentication.SetAuthCookie(username, false);

            context.Response.AppendCookie(new HttpCookie("AccessToken", client.AccessToken.SecretToken)
            {
                Secure = !context.IsDebuggingEnabled,
                HttpOnly = true
            });

            var urlHelper = new UrlHelper(((MvcHandler)context.Handler).RequestContext);
            var redirectUrl = string.Format("/{0}/", username);
            var cookie = context.Request.Cookies["returnUrl"];
            if (cookie != null && urlHelper.IsLocalUrl(cookie.Value))
            {
                redirectUrl = cookie.Value;
                cookie.Expires = DateTime.Now.AddDays(-1);
                context.Response.Cookies.Add(cookie);
            }

            return new RedirectResult(redirectUrl);
        }
 public EmailSendAttempt SendWelcome(RequestContext request, User u)
 {
     var template = LoadTemplate(
         "template-user-welcome",
         request.HttpContext.Server.MapPath("~/Messages/UserWelcome.template")
     );
     var url = new UrlHelper(request).Action(MVC.Public.Login.Index());
     var e = Builder.Transform(
         template,
         new TemplateData
             {
                 {"login", u.Login},
                 {"program", Application.ProgramName},
                 {"url", url.ToAbsoluteUrl(request.HttpContext.Request).ToString() },
             },
         request.HttpContext.Request
     );
     e.Recipient = new EmailAddress { Address = u.Email, Name = u.DisplayName };
    
     var attempt = Sender.Send(e);
     if (attempt.Success)
     {
         u.LastWeclomeEmailSent = DateTime.UtcNow;
         UserRepository.Save(u);
     }
     return attempt;
 }
Example #31
0
        public string ToString(UrlHelper url)
        {
            TagBuilder tagBuilder = new TagBuilder("script");

            if (!string.IsNullOrWhiteSpace(Id))
            {
                tagBuilder.Attributes["id"] = Id;
            }

            if (!string.IsNullOrWhiteSpace(Src))
            {
                tagBuilder.Attributes["src"] = Src;
            }

            if (!string.IsNullOrWhiteSpace(Content))
            {
                tagBuilder.InnerHtml = Content;
            }

            if (Criteria != null)
            {
                return Criteria.BeginTag + tagBuilder.ToString(TagRenderMode.Normal) + Criteria.EndTag;
            }
            return tagBuilder.ToString(TagRenderMode.Normal);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            HttpSessionStateBase session = filterContext.HttpContext.Session;

            Services.User user = (Services.User)session[Constants.SESSION_USER];
            if (user != null) {
                return;
            }

            String urlFrom = String.Empty;
            UrlHelper url;

            //send them off to the login page
            url = new UrlHelper(filterContext.RequestContext);
            urlFrom = filterContext.Controller.ControllerContext.RequestContext.HttpContext.Request.RawUrl;
            if (!String.IsNullOrEmpty(urlFrom)) {
                urlFrom = String.Format("?{0}", urlFrom);
            }
            var loginUrl = url.Content(String.Format("~/LogIn{0}", urlFrom));
            session.RemoveAll();
            session.Clear();
            session.Abandon();

            filterContext.HttpContext.Response.StatusCode = 403;
            filterContext.HttpContext.Response.Redirect(loginUrl, false);
            filterContext.Result = new EmptyResult();
        }
        public PackageListViewModel(
            IQueryable<Package> packages,
            DateTime? indexTimestampUtc,
            string searchTerm,
            int totalCount,
            int pageIndex,
            int pageSize,
            UrlHelper url,
            string curatedFeed)
        {
            // TODO: Implement actual sorting
            IEnumerable<ListPackageItemViewModel> items = packages.ToList().Select(pv => new ListPackageItemViewModel(pv));
            PageIndex = pageIndex;
            IndexTimestampUtc = indexTimestampUtc;
            PageSize = pageSize;
            TotalCount = totalCount;
            SearchTerm = searchTerm;
            int pageCount = (TotalCount + PageSize - 1) / PageSize;

            var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
                items,
                PageIndex,
                pageCount,
                page => curatedFeed == null ?
                    url.PackageList(page, searchTerm) :
                    url.CuratedPackageList(page, searchTerm, curatedFeed)
                );
            Items = pager.Items;
            FirstResultIndex = 1 + (PageIndex * PageSize);
            LastResultIndex = FirstResultIndex + Items.Count() - 1;
            Pager = pager;
        }
Example #34
0
        public static string Minify(System.Web.Mvc.UrlHelper urlHelper, string cssPath, string requestPath, string cssContent)
        {
            // this construct is to enable us to refer to the relativePath above ...
            MatchEvaluator urlDelegate = new MatchEvaluator(delegate(Match m)
            {
                // Change relative (to the original CSS) URL references to make them relative to the requested URL (controller / action)
                string url = m.Value;

                Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

                if (uri.IsAbsoluteUri || VirtualPathUtility.IsAbsolute(url))
                {
                    // if the URL is absolute ("http://server/path/file.ext") or app absolute ("/path/file.ext") then leave it as it is
                }
                else
                {
                    // get app relative url
                    url = VirtualPathUtility.Combine(cssPath, url);
                    url = VirtualPathUtility.MakeRelative(requestPath, url);


                    url = urlHelper.Content(url);
                }

                return(url);
            });

            return(Minify(urlHelper, urlDelegate, cssContent, 0));
        }
Example #35
0
 /// <summary>
 /// Builds main menu
 /// </summary>
 public static MvcHtmlString BuildMainMenuItems(this HtmlHelper helper, UrlHelper urlHelper, string activeItemTitle)
 {
     var sb = new StringBuilder();
     var menuItems = new[]{
         new MenuItem("Главная", urlHelper.RouteUrl("Main")),
         new MenuItem("Программы",urlHelper.RouteUrl("AllTravels")),
         new MenuItem("Расписание", urlHelper.RouteUrl("EventSchedule")),
         new MenuItem("Статьи", urlHelper.RouteUrl("AllArticles")),
         new MenuItem("Фотогалерея", urlHelper.RouteUrl("AllAlbums")),
         new MenuItem("Книги", urlHelper.RouteUrl("AllBooks")),
         new MenuItem("Новости", urlHelper.RouteUrl("AllNews")),
         new MenuItem("Отзывы", "javascript:notImplemented()"),
         new MenuItem("Цены", "javascript:notImplemented()"),
         new MenuItem("Контакты", "javascript:notImplemented()")
     };
     foreach (var menuItem in menuItems)
     {
         sb.AppendLine(
             string.Format("<li {0}><a href='{1}'>{2}</a></li>",
             (menuItem.Title == activeItemTitle) ? "class='active'" : string.Empty,
             menuItem.Url,
             menuItem.Title));
     }
     return new MvcHtmlString(sb.ToString());
 }
Example #36
0
        private XRpcStruct MetaWeblogNewMediaObject(
            string userName,
            string password,
            XRpcStruct file,
            UrlHelper url) {

            var user = _membershipService.ValidateUser(userName, password);
            if (!_authorizationService.TryCheckAccess(Permissions.ManageMediaContent, user, null)) {
                throw new OrchardCoreException(T("Access denied"));
            }

            var name = file.Optional<string>("name");
            var bits = file.Optional<byte[]>("bits");

            string directoryName = Path.GetDirectoryName(name);
            if (string.IsNullOrWhiteSpace(directoryName)) { // Some clients only pass in a name path that does not contain a directory component.
                directoryName = "media";
            }

            try {
                // delete the file if it already exists, e.g. an updated image in a blog post
                // it's safe to delete the file as each content item gets a specific folder
                _mediaLibraryService.DeleteFile(directoryName, Path.GetFileName(name));
            }
            catch {
                // current way to delete a file if it exists
            }

            string publicUrl = _mediaLibraryService.UploadMediaFile(directoryName, Path.GetFileName(name), bits);
            _mediaLibraryService.ImportMedia(directoryName, Path.GetFileName(name));
            return new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well.
                .Set("file", publicUrl)
                .Set("url", url.MakeAbsolute(publicUrl))
                .Set("type", file.Optional<string>("type"));
        }
 public EntryToEntryViewModelMapper(
     IDocumentSession session,
     UrlHelper urlHelper)
 {
     this.session = session;
     this.urlHelper = urlHelper;
 }
Example #38
0
        //<< Fields

        public override void WriteInitializationScript(TextWriter writer)
        {
            var container = "document.body";

            var options = new Dictionary <string, object>(Events);

            options.Add("hideAddressBar", HideAddressBar);
            options.Add("updateDocumentTitle", UpdateDocumentTitle);
            options.Add("serverNavigation", ServerNavigation);

            if (Skin.HasValue())
            {
                options.Add("skin", Skin);
            }

            if (!WebAppCapable)
            {
                options.Add("webAppCapable", false);
            }

            if (Layout.HasValue())
            {
                options.Add("layout", Layout);
            }

            if (Loading.HasValue())
            {
                options.Add("loading", Loading);
            }

            if (Platform.HasValue())
            {
                options.Add("platform", Platform);
            }

            if (Transition.HasValue())
            {
                options.Add("transition", Transition);
            }

            if (Id.HasValue())
            {
                container = "\"" + Selector + "\"";
            }

            if (PushState)
            {
                options.Add("pushState", PushState);
                var url       = new System.Web.Mvc.UrlHelper(ViewContext.RequestContext);
                var routeData = ViewContext.RequestContext.RouteData.Values;
                var root      = url.Action(string.Empty, routeData);

                options.Add("root", Regex.Replace(root, "/$", "/"));
            }

            writer.Write(String.Format("jQuery(function(){{ new kendo.mobile.Application(jQuery({0}), {1}); }});", container, Initializer.Serialize(options)));

            base.WriteInitializationScript(writer);
        }
Example #39
0
        public virtual UrlHelper UrlInit()
        {
            var controllerContext = ControllerContextCreator.Create(new FakeController());
            var CC  = controllerContext.RequestContext;
            var Url = new System.Web.Mvc.UrlHelper(CC);

            return(Url);
        }
        public static string GetSitemap(this System.Web.Mvc.UrlHelper urlHelper, IEnumerable <Tuple <string, string, object, SitemapFrequency, double> > routes)
        {
            XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            XElement   root  = new XElement(xmlns + "urlset");
            IEnumerable <SitemapNode> sitemapNodes = getSitemapNodes(urlHelper);

            foreach (SitemapNode sitemapNode in sitemapNodes)
            {
                XElement urlElement = new XElement(
                    xmlns + "url",
                    new XElement(xmlns + "loc", Uri.EscapeUriString(sitemapNode.Url)),
                    sitemapNode.LastModified == null ? null : new XElement(
                        xmlns + "lastmod",
                        sitemapNode.LastModified.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:sszzz")),
                    sitemapNode.Frequency == null ? null : new XElement(
                        xmlns + "changefreq",
                        sitemapNode.Frequency.Value.ToString().ToLowerInvariant()),
                    sitemapNode.Priority == null ? null : new XElement(
                        xmlns + "priority",
                        sitemapNode.Priority.Value.ToString("F1", CultureInfo.InvariantCulture)));
                root.Add(urlElement);
            }

            XDocument document = new XDocument(root);

            return(document.ToString());

            IReadOnlyCollection <SitemapNode> getSitemapNodes(System.Web.Mvc.UrlHelper _urlHelper)
            {
                if (routes == null)
                {
                    throw new ArgumentNullException("routes");
                }

                List <SitemapNode> nodes = new List <SitemapNode>();

                //nodes.Add(
                //    new SitemapNode()
                //    {
                //        Url = urlHelper.AbsoluteRouteUrl("HomeGetIndex" , new { id = Id } ),
                //        Priority = 1
                //    });


                foreach (var route in routes)
                {
                    nodes.Add(
                        new SitemapNode()
                    {
                        Url       = _urlHelper.AbsoluteRouteUrl("{0}Get{1}".FormatString(route.Item1, route.Item2), route.Item3),
                        Frequency = route.Item4,
                        Priority  = route.Item5
                    });
                }

                return(nodes);
            }
        }
Example #41
0
        protected void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

            // Get the exception object.
            Exception exc = Server.GetLastError();

            // Handle HTTP errors
            if (exc != null && exc.GetType() == typeof(HttpException))
            {
                if (SiteConfigurationReader.EnableHttpErrorLog)
                {
                    ExceptionManager.Manage(exc);
                }
                // The Complete Error Handling Example generates
                // some errors using URLs with "NoCatch" in them;
                // ignore these here to simulate what would happen
                // if a global.asax handler were not implemented.
                if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
                {
                    return;
                }

                //Redirect HTTP errors to HttpError page
                //WebHelper.CurrentSession.Content.ErrorMessage = ExceptionManager.BuildErrorStack(exc);
                //UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                //Response.Redirect(url.Action(Constants.Actions.Error, Constants.Controllers.Home, new { Area="" }));
            }
            else
            {
                // Log the exception and notify system operators
                if (exc != null)
                {
                    if (exc.GetType() == typeof(CustomException))
                    {
                        WebHelper.CurrentSession.Content.ErrorMessage = exc.Message;
                    }
                    else
                    {
                        WebHelper.CurrentSession.Content.ErrorMessage = ExceptionManager.BuildErrorStack(exc);
                    }
                    ExceptionManager.Manage(exc);
                }
                try
                {
                    if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null && !HttpContext.Current.Request.Url.ToString().Contains("Error"))
                    {
                        UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                        Response.Redirect(url.Action(Constants.Actions.Error, Constants.Controllers.Home, new { Area = "" }));
                    }
                }
                catch { }
            }

            // Clear the error from the server
            Server.ClearError();
        }
Example #42
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            System.Web.Mvc.UrlHelper helper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            string link = helper.Action("Partial_Index", "Home2");

            if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg") && HttpContext.Current.Request.UrlReferrer.Host != "localhost")
            {
                HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/imgs/forbid.png"));
                HttpContext.Current.Response.End();
            }
        }
Example #43
0
        /// <summary>
        /// Gets the relative URL for the specified controller action.
        /// </summary>
        /// <param name="action">The controller action
        /// The action.
        /// </param>
        /// <typeparam name="TController">The generic parameter for the Controller class.
        /// </typeparam>
        /// <returns>
        /// The relative URL in the form '/Home/About'>.
        /// </returns>
        public string GetRelativeUrlFor <TController>(Expression <Action <TController> > action)
            where TController : Controller
        {
            var requestContext = new RequestContext(FakeHttpContext.Root(), new RouteData());

            var actionRouteValues = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
            var urlHelper         = new System.Web.Mvc.UrlHelper(requestContext, _routeCollection);
            var relativeUrl       = urlHelper.RouteUrl(new RouteValueDictionary(actionRouteValues));

            return(relativeUrl);
        }
Example #44
0
 public BootstrapHelper(mvc.ViewContext viewContext, mvc.UrlHelper urlHelper, Func <int, string> messageSource)
 {
     this.ViewContext = viewContext;
     this.UrlHelper   = urlHelper;
     parents          = (Stack <IWritableItem>)viewContext.HttpContext.Items[ParentStackContextKey];
     if (parents == null)
     {
         parents = new Stack <IWritableItem>(5);
         parents.Push(null);
         viewContext.HttpContext.Items[ParentStackContextKey] = parents;
     }
 }
Example #45
0
        public static Editor PrepairEditorWithName(Action <Editor> oninit, string name, bool isajax)
        {
            Editor editor = new Editor(System.Web.HttpContext.Current, name);

            editor.ClientFolder = "/richtexteditor/";
            //editor.ClientFolder = "/Content/richtexteditor/";
            //editor.ClientFolder = "/Scripts/richtexteditor/";

            editor.Text = "";

            var urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            editor.AjaxPostbackUrl = urlHelper.Action("EditorAjaxHandler", "EditorAjax");

            if (oninit != null)
            {
                oninit(editor);
            }

            //try to handle the upload/ajax requests


            if (isajax)
            {
                return(editor);
            }

            //load the form data if any
            if (HttpContext.Current.Request.HttpMethod == "POST")
            {
                try
                {
                    string formdata = HttpContext.Current.Request.Form[editor.Name];
                    if (formdata != null)
                    {
                        editor.LoadFormData(formdata);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            return(editor);
        }
Example #46
0
        public BootstrapContext(mvc.ViewContext viewContext, mvc.UrlHelper urlHelper, mvc.ViewDataDictionary viewData, Func <int, string> messageSource)
        {
            this.ViewContext   = viewContext;
            this.Url           = urlHelper;
            this.ViewData      = viewData;
            this.MessageSource = messageSource;

            var httpContext = viewContext.RequestContext.HttpContext;

            if (httpContext.Items.Contains(CachedDataContextKey))
            {
                cachedData = (Stack)httpContext.Items[CachedDataContextKey];
            }
            else
            {
                cachedData = new Stack(5);
                httpContext.Items[CachedDataContextKey] = cachedData;
            }
        }
        public static string GetObjectColorImageUrl(ObjectColor color)
        {
            var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            if (color == ObjectColor.Red)
            {
                return(url.Content("~/Content/Icons/Circle-Red.png"));
            }

            if (color == ObjectColor.Yellow)
            {
                return(url.Content("~/Content/Icons/Circle-Yellow.png"));
            }

            if (color == ObjectColor.Green)
            {
                return(url.Content("~/Content/Icons/Circle-Green.png"));
            }

            return(url.Content("~/Content/Icons/Circle-Gray.png"));
        }
Example #48
0
        /// <summary>
        /// Для unit-тестов
        /// </summary>
        public ContextController(Guid?accountId, Guid?userId)
        {
            ControllerContext = new ControllerContext();

            var request = new HttpRequest(
                string.Empty,
                @"//localhost/",
                string.Empty);

            RouteData.Values.Add("controller", GetType().Name.ToLower().Replace("controller", ""));

            var response = new HttpResponse(new StringWriter());

            ControllerContext.HttpContext = new HttpContextWrapper(new HttpContext(request, response));

            var routes = new RouteCollection();

            RouteConfig.RegisterRoutes(routes);
            Url = new System.Web.Mvc.UrlHelper(ControllerContext.RequestContext, routes);

            System.Web.HttpContext.Current = new HttpContext(request, response);

            var fullContext = new FullRequestContext(this);

            FullRequestContext.Current = fullContext;

            DbContext = fullContext.DbContext;

            if (accountId.HasValue)
            {
                var accountDbContext = DbContext.GetAccountDbContext(accountId.Value);
                if (userId.HasValue)
                {
                    var user = accountDbContext.GetUserRepository().GetById(userId.Value);
                    CurrentUser = UserHelper.UserInfoByUser(user, accountId.Value);
                    fullContext.SetUser(CurrentUser);
                }
            }
        }
Example #49
0
        /// <summary>
        /// Builds the view model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="view">The view.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="controlPath">The control path.</param>
        /// <param name="useForm">if set to <c>true</c> [use form].</param>
        /// <param name="conf">The conf.</param>
        public static void BuildViewModel <T>(System.Web.Mvc.UrlHelper url, EntityBaseViewModel view, T entity, string controllerName, string controlPath, bool useForm, IDictionary conf) where T : IEntity
        {
            string baseurl   = string.Empty;
            var    editUrl   = url.Link("edit", controllerName, null);
            var    deleteUrl = url.Link("delete", controllerName, null);
            var    indexUrl  = url.Link("index", controllerName, null);
            var    manageUrl = url.Link("manage", controllerName, null);
            var    copyUrl   = url.Link("copy", controllerName, null);
            bool   allowEdit = false;

            if (entity != null)
            {
                copyUrl   += entity.Id;
                editUrl   += entity.Id;
                deleteUrl += entity.Id;
                allowEdit  = Auth.IsUserOrAdmin(entity.CreateUser);
            }
            view.Name           = controllerName;
            view.ControllerName = controllerName;
            view.UrlEdit        = editUrl;
            view.UrlCopy        = copyUrl;
            view.UrlDelete      = deleteUrl;
            view.UrlIndex       = indexUrl;
            view.UrlManage      = manageUrl;
            view.UrlCancel      = manageUrl;
            view.AllowDelete    = allowEdit;
            view.AllowDelete    = allowEdit;
            view.ControlPath    = controlPath;
            view.Config         = conf;
            if (view is EntityDetailsViewModel)
            {
                ((EntityDetailsViewModel)view).Entity = entity;
            }
            else if (view is EntityFormViewModel)
            {
                ((EntityFormViewModel)view).Entity = entity;
            }
        }
        /// <summary>
        /// If specific route can be found, return that route with the parameter tokens in route string.
        /// </summary>
        public static string JavaScriptReplaceableUrl(this UrlHelper urlHelper, ActionResult result)
        {
            var    rvd  = result.GetRouteValueDictionary();
            string area = string.Empty;
            object token;

            if (rvd.TryGetValue("area", out token))
            {
                area = token.ToString();
            }

            if (!rvd.TryGetValue("controller", out token))
            {
                throw new Exception("T4MVC JavascriptReplacableUrl could not locate controller in source dictionary");
            }
            string controller = token.ToString();

            if (!rvd.TryGetValue("SecureAction", out token))
            {
                throw new Exception("T4MVC JavascriptReplacableUrl could not locate SecureAction in source dictionary");
            }
            string SecureAction = token.ToString();

            // This matches the ActionResult to a specific route (so we can get the exact URL)
            string specificSecureActionUrl = RouteTable.Routes.OfType <Route>()
                                             .Where(r => r.DataTokens.CompareValue("area", area) &&
                                                    r.Defaults.CompareValue("controller", controller) &&
                                                    r.Defaults.CompareValue("SecureAction", SecureAction))
                                             .Select(r => r.Url)
                                             .FirstOrDefault();

            if (String.IsNullOrEmpty(specificSecureActionUrl))
            {
                return(urlHelper.RouteUrl(null, result.GetRouteValueDictionary()));
            }

            return(urlHelper.Content("~/" + specificSecureActionUrl));
        }
        /// <summary>
        /// 是否有访问指定controller的action权限
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public static bool UrlPermission(string actionName, string controllerName)
        {
            List <ViewPermissionGroup> permissionGroups;
            List <ViewPermissionLine>  permissionLines;


            GetPermission(out permissionGroups, out permissionLines);

            UrlHelper url = new System.Web.Mvc.UrlHelper();

            if (actionName == null && controllerName == null)
            {
                return(false);
            }
            var path = "/" + controllerName + "/" + actionName; //url.Action(actionName, controllerName);

            var i = permissionGroups != null?permissionGroups.Where(m => m.Url.ToLower().Contains(path.ToLower())).Count() : 0;

            i += permissionLines != null?permissionLines.Where(m => m.Url.ToLower().Contains(path.ToLower())).Count() : 0;

            return(i > 0);
            //return true;
        }
Example #52
0
        public static string FormParameters(this System.Web.Mvc.UrlHelper urlHelper, string url)
        {
            var request = urlHelper.RequestContext.HttpContext.Request;

            UriBuilder uriBuilder = new UriBuilder(new Uri(request.Url, url));

            var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);

            if (string.Equals(request.HttpMethod, HttpMethod.Get.Method, StringComparison.InvariantCultureIgnoreCase))
            {
                request.QueryString.CopyTo(queryParameters, false);
            }

            if (string.Equals(request.HttpMethod, HttpMethod.Post.Method, StringComparison.InvariantCultureIgnoreCase))
            {
                request.Form.CopyTo(queryParameters, false);
            }

            RemoveValueIsNullOrEmptyEntries(queryParameters);

            uriBuilder.Query = queryParameters.ToString();

            return(uriBuilder.Uri.PathAndQuery);
        }
Example #53
0
 public static string Action <TController>(this System.Web.Mvc.UrlHelper helper, Expression <Func <TController, ActionResult> > func) where TController : Controller
 {
     return(new UrlHelperWrapper(helper).Action <TController>(func));
 }
        public static string AbsoluteRouteUrl(this System.Web.Mvc.UrlHelper urlHelper, string routeName, object routeValues = null)
        {
            string scheme = urlHelper.RequestContext.HttpContext.Request.Url.Scheme;

            return(urlHelper.RouteUrl(routeName, routeValues, scheme));
        }
Example #55
0
 public static string RouteCultureUrl(this System.Web.Mvc.UrlHelper UrlHelper, RouteValueDictionary RouteValueDictionary, string Lang)
 {
     return(UrlHelper.RouteUrl(new { controller = RouteValueDictionary["controller"], action = RouteValueDictionary["action"], culture = Lang }));
 }
Example #56
0
        public static string Minify(System.Web.Mvc.UrlHelper urlHelper, MatchEvaluator urlReplacer, string cssContent, int columnWidth)
        {
            // BSD License http://developer.yahoo.net/yui/license.txt
            // New css tests and regexes by Michael Ash
            MatchEvaluator rgbDelegate            = new MatchEvaluator(RGBMatchHandler);
            MatchEvaluator shortColorNameDelegate = new MatchEvaluator(ShortColorNameMatchHandler);
            MatchEvaluator shortColorHexDelegate  = new MatchEvaluator(ShortColorHexMatchHandler);

            cssContent = RemoveCommentBlocks(cssContent);
            cssContent = Regex.Replace(cssContent, @"\s+", " ");                                           //Normalize whitespace
            cssContent = Regex.Replace(cssContent, @"\x22\x5C\x22}\x5C\\x22\x22", "___PSEUDOCLASSBMH___"); //hide Box model hack

            /* Remove the spaces before the things that should not have spaces before them.
             * But, be careful not to turn "p :link {...}" into "p:link{...}"
             */
            cssContent = Regex.Replace(cssContent, @"(?#no preceding space needed)\s+((?:[!{};>+()\],])|(?<={[^{}]*):(?=[^}]*}))", "$1");
            cssContent = Regex.Replace(cssContent, @"([!{}:;>+([,])\s+", "$1");                            // Remove the spaces after the things that should not have spaces after them.
            cssContent = Regex.Replace(cssContent, @"([^;}])}", "$1;}");                                   // Add the semicolon where it's missing.
            cssContent = Regex.Replace(cssContent, @"(\d+)\.0+(p(?:[xct])|(?:[cem])m|%|in|ex)\b", "$1$2"); // Remove .0 from size units x.0em becomes xem
            cssContent = Regex.Replace(cssContent, @"([\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)\b", "$1$2");    // Remove unit from zero
            //New test
            //Font weights
            cssContent = Regex.Replace(cssContent, @"(?<=font-weight:)normal\b", "400");
            cssContent = Regex.Replace(cssContent, @"(?<=font-weight:)bold\b", "700");
            //Thought this was a good idea but properties of a set not defined get element defaults. This is reseting them. css = ShortHandProperty(css);
            cssContent = ShortHandAllProperties(cssContent);
            //css = Regex.Replace(css, @":(\s*0){2,4}\s*;", ":0;"); // if all parameters zero just use 1 parameter
            // if all 4 parameters the same unit make 1 parameter
            //css = Regex.Replace(css, @":\s*(inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))(\s+\1){1,3};", ":$1;", RegexOptions.IgnoreCase); //if background-position:500px 500px; replaced to background-position:500px;, that will parsed to background-position:500px 50% at the client.
            // if has 4 parameters and top unit = bottom unit and right unit = left unit make 2 parameters
            cssContent = Regex.Replace(cssContent, @":\s*((inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(inherit|auto|0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2\s+\3;", ":$1;", RegexOptions.IgnoreCase);
            // if has 4 parameters and top unit != bottom unit and right unit = left unit make 3 parameters
            cssContent = Regex.Replace(cssContent, @":\s*((?:(?:inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+)?(inherit|auto|0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(?:0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2;", ":$1;", RegexOptions.IgnoreCase);
            //// if has 3 parameters and top unit = bottom unit make 2 parameters
            //css = Regex.Replace(css, @":\s*((0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(?:0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2;", ":$1;", RegexOptions.IgnoreCase);
            cssContent = Regex.Replace(cssContent, "background-position:0;", "background-position:0 0;");
            cssContent = Regex.Replace(cssContent, @"(:|\s)0+\.(\d+)", "$1.$2");
            //  Outline-styles and Border-sytles parameter reduction
            cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)(?:\s+\2){1,3};", "$1-style:$2;", RegexOptions.IgnoreCase);

            cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3)(?:\s+\4);", "$1-style:$2;", RegexOptions.IgnoreCase);

            cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((?:(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+)?(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset )\s+(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3);", "$1-style:$2;", RegexOptions.IgnoreCase);

            cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3);", "$1-style:$2;", RegexOptions.IgnoreCase);

            //  Outline-color and Border-color parameter reduction
            cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*((?:\#(?:[0-9A-F]{3}){1,2})|\S+)(?:\s+\2){1,3};", "$1-color:$2;", RegexOptions.IgnoreCase);

            cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*(((?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+((?:\#(?:[0-9A-F]{3}){1,2})|\S+))(?:\s+\3)(?:\s+\4);", "$1-color:$2;", RegexOptions.IgnoreCase);

            cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*((?:(?:(?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+)?((?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+(?:(?:\#(?:[0-9A-F]{3}){1,2})|\S+))(?:\s+\3);", "$1-color:$2;", RegexOptions.IgnoreCase);

            // Shorten colors from rgb(51,102,153) to #336699
            // This makes it more likely that it'll get further compressed in the next step.
            cssContent = Regex.Replace(cssContent, @"rgb\s*\x28((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*\x29", rgbDelegate);
            cssContent = Regex.Replace(cssContent, @"(?<![\x22\x27=]\s*)\#(?:([0-9A-F])\1)(?:([0-9A-F])\2)(?:([0-9A-F])\3)", "#$1$2$3", RegexOptions.IgnoreCase);
            // Replace hex color code with named value is shorter
            cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*.*)\#(?<hex>f00)\b", "red", RegexOptions.IgnoreCase);
            cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*.*)\#(?<hex>[0-9a-f]{6})", shortColorNameDelegate, RegexOptions.IgnoreCase);
            cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*)\b(Black|Fuchsia|LightSlateGr[ae]y|Magenta|White|Yellow)\b", shortColorHexDelegate, RegexOptions.IgnoreCase);

            // replace URLs
            if (urlReplacer != null)
            {
                cssContent = Regex.Replace(cssContent, @"(?<=url\(\s*([""']?))(?<url>[^'""]+?)(?=\1\s*\))", urlReplacer, RegexOptions.IgnoreCase);
                cssContent = Regex.Replace(cssContent, @"(?<=@import\s*([""']))(?<url>[^'""]+?)(?=\1\s*;)", urlReplacer, RegexOptions.IgnoreCase);
            }

            // Remove empty rules.
            cssContent = Regex.Replace(cssContent, @"[^}]+{;}", "");
            //Remove semicolon of last property
            cssContent = Regex.Replace(cssContent, ";(})", "$1");
            if (columnWidth > 0)
            {
                cssContent = BreakLines(cssContent, columnWidth);
            }
            return(cssContent);
        }
Example #57
0
 public static Uri Absolute(this System.Web.Mvc.UrlHelper url, string relative, bool escapeDataParts = false)
 {
     return(UriHelper.Absolute(relative, escapeDataParts: escapeDataParts));
 }
Example #58
0
 public static Uri Absolute(this System.Web.Mvc.UrlHelper url)
 {
     return(url.Absolute(string.Empty));
 }
 public FormFactoryUrlHelper(System.Web.Mvc.UrlHelper mvcUrlHelper)
 {
     _mvcUrlHelper = mvcUrlHelper;
 }
Example #60
0
        /// <summary>
        /// ResizeImage图片地址生成
        /// </summary>
        /// <param name="url">图片地址</param>
        /// <param name="w">最大宽度</param>
        /// <param name="h">最大高度</param>
        /// <param name="quality">质量0~100</param>
        /// <param name="image">占位图类别</param>
        /// <returns>地址为空返回null</returns>
        public static string ResizeImage(string url, int?w = null, int?h = null,
                                         int?quality       = null,
                                         DummyImage?image  = DummyImage.Default,
                                         ResizerMode?mode  = null,
                                         ReszieScale?scale = null
                                         )
        {
            var Url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            else
            {
                if (Url.IsLocalUrl(url))
                {
                    var t = new Uri(HttpContext.Current.Request.Url, Url.Content(url)).AbsoluteUri;
                    Dictionary <string, string> p = new Dictionary <string, string>();
                    if (w.HasValue)
                    {
                        p.Add("w", w.ToString());
                    }
                    if (h.HasValue)
                    {
                        p.Add("h", h.ToString());
                    }
                    if (scale.HasValue)
                    {
                        p.Add("scale", scale.Value.ToString());
                    }
                    if (quality.HasValue)
                    {
                        p.Add("quality", quality.ToString());
                    }
                    if (image.HasValue)
                    {
                        p.Add("404", image.ToString());
                    }
                    if (mode.HasValue)
                    {
                        p.Add("mode", mode.ToString());
                    }
                    return(t + p.ToParam("?"));
                }
                else if (url.Contains(QinQiuApi.ServerLink))
                {
                    var fileType = System.IO.Path.GetExtension(url);

                    StringBuilder sbUrl = new StringBuilder(url);
                    if (fileType == ".mp4")
                    {
                        sbUrl.Append("?vframe/jpg/offset/1");
                        if (w.HasValue)
                        {
                            sbUrl.Append($"/w/{w}");
                        }
                        if (h.HasValue)
                        {
                            sbUrl.Append($"/h/{h}");
                        }
                        return(sbUrl.ToString());
                    }
                    else
                    {
                        sbUrl.Append("?imageView2");
                        switch (mode)
                        {
                        case ResizerMode.Pad:
                        default:
                        case ResizerMode.Crop:
                            sbUrl.Append("/1");
                            break;

                        case ResizerMode.Max:
                            sbUrl.Append("/0");
                            break;
                        }
                        if (w.HasValue)
                        {
                            sbUrl.Append($"/w/{w}");
                        }
                        if (h.HasValue)
                        {
                            sbUrl.Append($"/h/{h}");
                        }
                        quality = quality ?? 100;
                        sbUrl.Append($"/q/{quality}");
                        return(sbUrl.ToString());
                    }
                }
                else
                {
                    return(url);
                }
            }
        }