Пример #1
0
        public void GatewaysUrl_WithFilters_Locale()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl, "ES");

                // Act
                var url = provider.GatewaysUrl("NL", "EUR", 100);

                // Assert
                Assert.AreEqual(String.Format("{0}/gateways?country=NL&currency=EUR&amount=100&locale=es", baseUrl.TrimTrailingSlash()), url);
            }
        }
Пример #2
0
        public void GatewaysUrl_Default_Locale()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl, "ES");

                // Act
                var url = provider.GatewaysUrl();

                // Assert
                Assert.AreEqual(String.Format("{0}/gateways?locale=es", baseUrl.TrimTrailingSlash()), url);
            }
        }
Пример #3
0
        public void GatewayUrl()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl);
                const string name = " test";

                // Act
                var url = provider.GatewayUrl(name);

                // Assert
                Assert.AreEqual(String.Format("{0}/gateways/{1}", baseUrl.TrimTrailingSlash(), name), url);
            }
        }
        public static IMapList GetTree(
            Guid selectedId, 
            UrlProvider roomUrlProvider,
            UrlProvider mapUrlProvider,
            UrlProvider buildingUrlProvider,
            UrlProvider campusUrlProvider,
            UrlProvider equipmentUrlProvider,
            UrlProvider roomTypesUrlProvider)
        {
            var parentIds = new Stack<Guid>();
            FindParentIds(parentIds, selectedId);

            var tuples = parentIds
                .Select(id => Data.GetChildren(id));

            var levels = new Dictionary<Level, IEnumerable<Tuple<Guid, string, bool>>>();
            var currentLevel = Level.Campus;

            foreach (var tuplesForLevel in tuples)
            {
                levels.Add(currentLevel, tuplesForLevel);
                currentLevel += 1;
            }

            var emptyTuples = new Tuple<Guid, string, bool>[0];

            var roomTuples = levels.ContainsKey(Level.Room) ? levels[Level.Room] : emptyTuples;
            var mapTuples = levels.ContainsKey(Level.Map) ? levels[Level.Map] : emptyTuples;
            var buildingTuples = levels.ContainsKey(Level.Building) ? levels[Level.Building] : emptyTuples;
            var campusTuples = levels.ContainsKey(Level.Campus) ? levels[Level.Campus] : emptyTuples;

            var rooms = roomTuples
                .Select(i => new Room(i.Item1, i.Item2, roomUrlProvider.GetDetailsUrl(i.Item1)))
                .ToArray();

            var maps = mapTuples
                .Select(i => parentIds.Contains(i.Item1)
                                 ? new Map(i.Item1, i.Item2, mapUrlProvider.GetDetailsUrl(i.Item1), rooms)
                                 : new Map(i.Item1, i.Item2, mapUrlProvider.GetDetailsUrl(i.Item1),
                                           i.Item3, mapUrlProvider.GetChildrenUrl(i.Item1)))
                .ToArray();

            var buildings = buildingTuples
                .Select(i => parentIds.Contains(i.Item1)
                                 ? new Building(i.Item1, i.Item2, buildingUrlProvider.GetDetailsUrl(i.Item1), maps)
                                 : new Building(i.Item1, i.Item2, buildingUrlProvider.GetDetailsUrl(i.Item1),
                                           i.Item3, buildingUrlProvider.GetChildrenUrl(i.Item1)))
                .ToArray();

            var campuses = campusTuples
                .Select(i => parentIds.Contains(i.Item1)
                                 ? new Campus(i.Item1, i.Item2, campusUrlProvider.GetDetailsUrl(i.Item1), buildings)
                                 : new Campus(i.Item1, i.Item2, campusUrlProvider.GetDetailsUrl(i.Item1),
                                           i.Item3, campusUrlProvider.GetChildrenUrl(i.Item1)))
                .Cast<ITreeItem>()
                .ToArray();

            var equipment = new Equipment(equipmentUrlProvider.GetDetailsUrl(Guid.Empty));

            var roomTypes = new RoomTypes(roomTypesUrlProvider.GetDetailsUrl(Guid.Empty));

            var rootItems = new ITreeItem[] {equipment, roomTypes}
                .Union(campuses);

            return new MapList(rootItems, selectedId);
        }
Пример #5
0
        public static void ReplaceFormsSources(ref string htmlCodes,
                                               string pageUrlNoQuery,
                                               string newPageFormat,
                                               string pagePath,
                                               string siteRootUrl,
                                               bool encodeUrl,
                                               bool changeMethod,
                                               string extraAttributeFormat)
        {
            TextRange methodResult;            // = new TextRange();
            TextRange actionResult;            // = new TextRange();
            int       cursorPos = 0;
            string    newAttribute = "";
            string    formMethod = "";
            string    tmp, actionSrc = "";
            string    orgValue = "";

            bool addNewAttribute = false;
            bool hasNewAttribute = false;

            if (!string.IsNullOrEmpty(extraAttributeFormat))
            {
                addNewAttribute = true;
                hasNewAttribute = true;
            }


            do
            {
                addNewAttribute = hasNewAttribute;

                if (changeMethod)
                {
                    methodResult = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, "<form", "method", cursorPos);
                    if (methodResult.Start > -1 && methodResult.End > -1)
                    {
                        // get the method
                        formMethod = htmlCodes.Substring(methodResult.Start, 2);

                        // validate the method
                        formMethod = WebMethods.DetectMethod(formMethod, WebMethods.DefaultMethods.GET);

                        htmlCodes = htmlCodes.Remove(methodResult.Start, methodResult.End - methodResult.Start);
                        htmlCodes = htmlCodes.Insert(methodResult.Start, "POST");
                    }
                    else
                    {
                        int formPos = StringCompare.IndexOfIgnoreCase(ref htmlCodes, "<form", cursorPos);
                        int tagEnd;
                        if (formPos != -1)
                        {
                            tagEnd = StringCompare.IndexOfMatchCase(ref htmlCodes, '>', formPos);
                            if (tagEnd != -1)
                            {
                                htmlCodes = htmlCodes.Insert(tagEnd, " method=POST ");
                            }
                        }

                        formMethod = WebMethods.GET;
                    }
                }

                actionResult = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, "<form", "action", cursorPos);

                if (actionResult.Start == -1)
                {
                    break;
                }

                if (actionResult.Start > -1 && actionResult.End > -1)
                {
                    cursorPos = actionResult.Start;


                    //====== Correct value position according to quotes existence=======
                    // actionResult = ASProxyFunctions.CorrectValueIfQuoteExists(ref pageHtml, actionResult);

                    // Get the value
                    actionSrc = htmlCodes.Substring(actionResult.Start, actionResult.End - actionResult.Start);

                    // BUG fixed in v5 beta 2
                    // now supports forms with javascript
                    if (UrlProvider.IsClientSitdeUrl(actionSrc) == false)
                    {
                        //====== Convert virtual url to absolute ======
                        actionSrc = UrlProvider.JoinUrl(actionSrc, pageUrlNoQuery, pagePath, siteRootUrl);

                        //====== Delete invalid character such as tab and line feed ======
                        actionSrc = UrlProvider.IgnoreInvalidUrlCharctersInHtml(actionSrc);

                        orgValue = actionSrc;

                        //===== If another site url, has bookmark=====
                        if (actionSrc.IndexOf('#') != -1)
                        {
                            actionSrc = UrlBuilder.RemoveUrlBookmark(actionSrc, out tmp);
                        }

                        //=====Get desired address=======
                        actionSrc = HttpUtility.HtmlDecode(actionSrc);

                        //====== Encode url to make unknown it ======
                        if (encodeUrl)
                        {
                            actionSrc = UrlProvider.EncodeUrl(actionSrc);
                        }
                        else
                        {
                            // just url safe
                            actionSrc = UrlProvider.EscapeUrlQuery(actionSrc);
                        }

                        //====== Add it to our url ======
                        actionSrc = string.Format(newPageFormat, actionSrc);

                        if (changeMethod)
                        {
                            //actionSrc = UrlBuilder.AddUrlQuery(actionSrc, Consts.qIsPostForm, ((int)method).ToString());
                            actionSrc = UrlBuilder.AddUrlQueryToEnd(actionSrc, Consts.Query.WebMethod, formMethod);
                        }


                        // Make it html safe
                        actionSrc = HttpUtility.HtmlEncode(actionSrc);

                        //====== Replace it with old url ======
                        htmlCodes = htmlCodes.Remove(actionResult.Start, actionResult.End - actionResult.Start);
                        htmlCodes = htmlCodes.Insert(actionResult.Start, actionSrc);
                    }
                    else
                    {
                        // this is client side url
                        addNewAttribute = false;
                    }


                    if (addNewAttribute)
                    {
                        // Apply orginal value and encoded value to format
                        newAttribute = string.Format(extraAttributeFormat, orgValue, actionSrc, "POST");

                        // Locate end of tag
                        cursorPos = StringCompare.IndexOfMatchCase(ref htmlCodes, '>', actionResult.Start);
                        if (htmlCodes[cursorPos - 1] == '/')
                        {
                            cursorPos--;
                        }

                        // Insert to it
                        htmlCodes = htmlCodes.Insert(cursorPos, newAttribute);
                    }
                }
                else
                {
                    if (actionResult.Start != -1)
                    {
                        cursorPos = actionResult.Start;
                    }
                    cursorPos = StringCompare.IndexOfMatchCase(ref htmlCodes, ">", cursorPos);
                }
            }while (actionResult.Start != -1);
        }
Пример #6
0
        public static void ReplaceTwoAttributeTagsValue(ref string htmlCodes,
                                                        string newValueFormat,
                                                        bool encodeUrl,
                                                        string tagName,
                                                        string attr1,
                                                        string attr1Value,
                                                        string attr2)
        {
            TextRange attr1Result = new TextRange(-1, -1);
            TextRange attr2Result = new TextRange(-1, -1);
            int       cursorPos   = 0;
            string    actionSrc   = "";

            do
            {
                attr1Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tagName, attr1, cursorPos);
                if (attr1Result.Start > -1 && attr1Result.End > -1)
                {
                    string tmpRelType = htmlCodes.Substring(attr1Result.Start, attr1Result.End - attr1Result.Start);
                    if (tmpRelType.Trim().ToLower() != attr1Value.Trim().ToLower())
                    {
                        if (attr1Result.Start != -1)
                        {
                            cursorPos         = attr1Result.Start;
                            attr2Result.Start = attr1Result.Start;
                        }
                        continue;
                    }
                }
                else
                {
                    break;
                }

                attr2Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tagName, attr2, cursorPos);

                if (attr2Result.Start == -1)
                {
                    break;
                }

                if (attr2Result.Start > -1 && attr2Result.End > -1)
                {
                    cursorPos = attr2Result.Start;

                    //====== Correct value position according to quotes existence=======
                    attr2Result = HtmlTags.CorrectValueIfQuoteExists(ref htmlCodes, attr2Result);

                    // Get the value
                    actionSrc = htmlCodes.Substring(attr2Result.Start, attr2Result.End - attr2Result.Start);

                    // Get clear url
                    actionSrc = HttpUtility.HtmlDecode(actionSrc);

                    //====== Encode url to make it unknown ======
                    if (encodeUrl)
                    {
                        actionSrc = UrlProvider.EncodeUrl(actionSrc);
                    }
                    else
                    {
                        // just url safe
                        actionSrc = UrlProvider.EscapeUrlQuery(actionSrc);
                    }

                    //====== Add it to our url ======
                    actionSrc = string.Format(newValueFormat, actionSrc);

                    // Make it safe
                    actionSrc = HttpUtility.HtmlEncode(actionSrc);

                    //====== Replace it with old url ======
                    htmlCodes = htmlCodes.Remove(attr2Result.Start, attr2Result.End - attr2Result.Start);
                    htmlCodes = htmlCodes.Insert(attr2Result.Start, actionSrc);
                }
                else
                {
                    if (attr2Result.Start != -1)
                    {
                        cursorPos = attr2Result.Start;
                    }
                    cursorPos = StringCompare.IndexOfMatchCase(ref htmlCodes, ">", cursorPos);
                }
            }while (attr2Result.Start != -1);
        }
Пример #7
0
 public string GetSingleResourceLink(string id)
 {
     return(UrlProvider.UriStringFor <BookController>(c => c.GetByIdAsync(id, null)));
 }
Пример #8
0
        public static List <ViewCartItem> GetByCartID(int cartID, string userID)
        {
            using (var db = OnlineStoreDbContext.Entity)
            {
                var query = from item in db.CartItems
                            where item.CartID == cartID
                            select new ViewCartItem()
                {
                    ID = item.ID,

                    ProductVarientID = item.ProductVarientID,
                    ProductID        = item.ProductID,
                    PackageID        = item.PackageID,

                    Quantity = item.Quantity
                };

                var result = query.ToList();
                foreach (var item in result)
                {
                    if (item.ProductVarientID.HasValue || item.ProductID.HasValue)
                    {
                        var priceItem = new PriceItem();

                        if (item.ProductVarientID.HasValue)
                        {
                            var productVarient = ProductVarients.GetByID(item.ProductVarientID.Value);

                            item.CartProductID = productVarient.ProductID;
                            item.Price         = ProductVarientPrices.GetPriceByProductVarientID(item.ProductVarientID.Value);

                            priceItem.ID = item.ProductVarientID.Value;
                        }
                        else if (item.ProductID.HasValue)
                        {
                            item.CartProductID = item.ProductID.Value;
                        }

                        var product = Products.GetByID(item.CartProductID);
                        var group   = Groups.GetByID(product.GroupID.Value);

                        product.Title    = group.Perfix + " " + product.Title;
                        product.Title_En = product.Title_En + " " + group.Perfix_En;

                        item.Title = product.DisplayTitle;

                        item.Image = (from img in db.ProductImages
                                      where img.ProductID == item.CartProductID &&
                                      img.ProductImagePlace == ProductImagePlace.Home
                                      select img.Filename).FirstOrDefault();

                        item.HasVarients = product.HasVarients;

                        item.Image = UrlProvider.GetProductImage(item.Image, StaticValues.MiniCartProductImageSize);

                        item.Url = UrlProvider.GetProductUrl(item.CartProductID, group.UrlPerfix, product.UrlPerfix);

                        #region Prices

                        if (item.ProductVarientID.HasValue)
                        {
                            item.VarientTitle = ProductVarientAttributes.GetVarients(item.ProductVarientID.Value);
                        }
                        else if (item.ProductID.HasValue)
                        {
                            item.Price = (from price in db.ProductPrices
                                          where price.ProductID == item.CartProductID &&
                                          price.PriceType == PriceType.Sell
                                          orderby price.LastUpdate descending
                                          select price.Price).FirstOrDefault();
                        }

                        priceItem.Price = item.Price;
                        var prices = new List <PriceItem>()
                        {
                            priceItem
                        };

                        var productID = (item.ProductID.HasValue ? item.ProductID.Value : ProductVarients.GetProductID(item.ProductVarientID.Value));

                        Products.SetDiscounts(userID, product.ID, product.HasVarients, prices);

                        item.DiscountPercent = priceItem.DiscountPercent;
                        item.DiscountPrice   = priceItem.DiscountPrice;

                        #endregion Prices

                        DateTime now = DateTime.Now;

                        var gifts = (from gift in db.ProductGifts
                                     where ((item.ProductID != null && gift.ProductID == item.ProductID) ||
                                            (item.ProductID == null && gift.ProductID == item.CartProductID)) &&
                                     gift.StartDate <= now && gift.EndDate >= now
                                     select new ViewCartItemGift
                        {
                            ID = gift.ID,
                            ProductID = gift.ProductID,
                            GiftTitle = gift.Gift.Title,
                            GiftID = gift.GiftID
                        }).ToList();

                        foreach (var gift in gifts)
                        {
                            var gProduct = Products.GetByID(gift.GiftID);
                            var gGroup   = Groups.GetByID(gProduct.GroupID.Value);
                            gift.Url = UrlProvider.GetProductUrl(gProduct.ID, gGroup.UrlPerfix, gProduct.UrlPerfix);

                            var giftPrices = Products.GetProductPrices(gift.GiftID, false, PriceType.Sell);
                            var price      = giftPrices.LastOrDefault();

                            if (price != null)
                            {
                                gift.Price = price.Price;
                            }
                        }

                        item.Gifts = gifts;

                        item.IsFreeDelivery = product.IsFreeDelivery;
                    }
                    else if (item.PackageID.HasValue)
                    {
                        var package = Packages.GetByID(item.PackageID.Value);

                        item.Title = package.Title;

                        item.Image = (from img in db.PackageImages
                                      where img.PackageID == package.ID &&
                                      img.PackageImagePlace == ProductImagePlace.Home
                                      select img.Filename).FirstOrDefault();

                        item.Image = UrlProvider.GetPackageImage(item.Image, StaticValues.MiniCartProductImageSize);

                        item.Url = UrlProvider.GetPackageUrl(item.Title, item.PackageID.Value);

                        #region Prices

                        var products = PackageProducts.GetProducts(item.PackageID.Value);

                        item.Price           = products.Sum(a => a.OldPrice);
                        item.DiscountPrice   = products.Sum(a => a.NewPrice);
                        item.DiscountPercent = (item.Price * 100) / item.DiscountPrice;

                        #endregion Prices
                    }
                }

                return(result);
            }
        }
Пример #9
0
 public SimpleComposition(int width, int height, int totalSubjects, String searchText, UrlProvider urlProvider)
     : base(width, height, totalSubjects, searchText, urlProvider)
 {
 }
Пример #10
0
 public NewsBusinessModule(BusinessModuleFactory businessModuleFactory, UrlProvider urlProvider) : base(businessModuleFactory)
 {
     _urlProvider = urlProvider;
 }
 public UmbracoContextFullUrlResolverService(UmbracoContext umbracoContext)
 {
     _urlProvider = umbracoContext.UrlProvider;
     _leftPart    = umbracoContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
 }
Пример #12
0
 /// <summary>
 /// Constructor used to create a new handler for multi-tenency with domains and ids
 /// </summary>
 /// <param name="itemsForRoute"></param>
 public CategoryRouteHandler(UrlProvider umbracoUrlProvider, int blogId)
 {
     _blogRootNode = UmbracoContext.Current.ContentCache.GetById(blogId);
 }
Пример #13
0
        public void OrderRefundsUrl()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl);
                const string orderId = " test";

                // Act
                var url = provider.OrderRefundsUrl(orderId);

                // Assert
                Assert.AreEqual(String.Format("{0}/orders/{1}/refunds", baseUrl.TrimTrailingSlash(), orderId), url);
            }
        }
Пример #14
0
 /// <summary>
 /// Gets the url of a content identified by its identifier, in a specified mode.
 /// </summary>
 /// <param name="contentId">The content identifier.</param>
 /// <param name="mode">The mode.</param>
 /// <returns>The url for the content.</returns>
 public string Url(int contentId, UrlProviderMode mode, string culture = null)
 {
     return(UrlProvider.GetUrl(contentId, mode, culture));
 }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var redirectRoute = UrlProvider <ErrorsController> .GetRouteValues(c => c.UnauthorizedError());

            filterContext.Result = new RedirectToRouteResult(redirectRoute);
        }
        public static void MapRoutes(RouteCollection routes, ContextualPublishedCache umbracoCache, UrlProvider umbracoUrlProvider)
        {
            //find all dialogue root nodes
            var dialogueNodes = umbracoCache.GetByXPath(string.Concat("//", DialogueConfiguration.Instance.DocTypeForumRoot)).ToArray();

            LogHelper.Info(typeof(DialogueRoutes), () => $"Mapping routes for {dialogueNodes.Length} Dialogue root nodes");

            //NOTE: need to write lock because this might need to be remapped while the app is running if
            // any articulate nodes are updated with new values
            using (routes.GetWriteLock())
            {
                //clear the existing articulate routes (if any)
                RemoveExisting(routes);

                // For each articulate root, we need to create some custom route, BUT routes can overlap
                // based on multi-tenency so we need to deal with that.
                // For example a root articulate node might yield a route like:
                //      /
                // and another articulate root node that has a domain might have this url:
                //      http://mydomain/
                // but when that is processed through RoutePathFromNodeUrl, it becomes:
                //      /
                // which already exists and is already assigned to a specific node ID.
                // So what we need to do in these cases is use a special route handler that takes
                // into account the domain assigned to the route.
                var groups = dialogueNodes
                             .GroupBy(x => RouteCollectionExtensions.RoutePathFromNodeUrl(x.Url))
                             //This is required to ensure that we create routes that are more specific first
                             // before creating routes that are less specific
                             .OrderByDescending(x => x.Key.Split('/').Length);
                foreach (var grouping in groups)
                {
                    var nodesAsArray = grouping.ToArray();

                    MapTopicRoute(routes, umbracoUrlProvider, grouping.Key, nodesAsArray);
                    MapDialoguePages(routes, umbracoUrlProvider, grouping.Key, nodesAsArray);
                    MapMemberRoute(routes, umbracoUrlProvider, grouping.Key, nodesAsArray);
                }
            }
        }
 public override FrontendBehavior GetOwnReference(string context, ChallengeType challengeType)
 {
     return(new(StepType, challengeType,
                new CallAction(UrlProvider.GetSwitchAuthTypeUrl(context, ConnectionAuthType.Passcode))));
 }
Пример #18
0
        public void OrdersUrl()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl);

                // Act
                var url = provider.OrdersUrl();

                // Assert
                Assert.AreEqual(String.Format("{0}/orders", baseUrl.TrimTrailingSlash()), url);
            }
        }
Пример #19
0
        /// <summary>
        /// Process the styles and replace them
        /// </summary>
        public static void ReplaceCSSClassStyleUrl(ref string htmlCode, string currentUrlWithoutParameters, string newUrl, string replacmentBasePath, string siteAddress, bool encodeUrl, bool forImportRule)
        {
            int       index = 0;
            TextRange position;
            string    oldValue, newValue;
            string    bookmarkPart = "";

            do
            {
                if (forImportRule)
                {
                    // do not find "Import Rule"s with url option, it will done by other codes. Since v4.0
                    position = CSSParser.FindImportRuleUrlPosition(ref htmlCode, index, false, false);
                }
                else
                {
                    position = CSSParser.FindCSSClassStyleUrlValuePosition(ref htmlCode, index);
                }

                if (position.Start == -1)
                {
                    break;
                }

                if (position.Start != -1 && position.End != -1)
                {
                    bool shouldAddQuote = false;
                    //======OK. go to end of tag=============
                    index = position.End;

                    //========================================================//
                    //====================Replace new address=================//
                    //========================================================//

                    //====== Correct value position according to quotes existence=======
                    position = HtmlTags.CorrectValueIfQuoteExists(ref htmlCode, position);


                    //====== Get the attribute value ======
                    oldValue = htmlCode.Substring(position.Start, position.End - position.Start);

                    // Trim!
                    oldValue = oldValue.Trim();

                    // Removes URL attribute if there is any
                    if (HtmlTags.RemoveUrlAttribCssLocation(oldValue, out oldValue))
                    {
                        shouldAddQuote = true;
                    }

                    oldValue = HtmlTags.RemoveQuotesFromTagAttributeValue(oldValue);
                    //===== If link is a bookmark don't change it=====
                    if (oldValue.StartsWith("#"))
                    {
                        continue;
                    }

                    //====== Convert virtual url to absolute ======
                    oldValue = UrlProvider.JoinUrl(oldValue, currentUrlWithoutParameters, replacmentBasePath, siteAddress);

                    //====== Delete invalid character such as tab and line feed ======
                    oldValue = UrlProvider.IgnoreInvalidUrlCharctersInHtml(oldValue);

                    //===== If another site url, has bookmark=====
                    if (StringCompare.IndexOfMatchCase(ref oldValue, '#') != -1)
                    {
                        oldValue = UrlBuilder.RemoveUrlBookmark(oldValue, out bookmarkPart);
                    }

                    //==== Make it clear=========
                    oldValue = HttpUtility.HtmlDecode(oldValue);

                    //====== Encode url to make it unknown ======
                    if (encodeUrl)
                    {
                        oldValue = UrlProvider.EncodeUrl(oldValue);
                    }
                    else
                    {
                        // just url safe
                        oldValue = UrlProvider.EscapeUrlQuery(oldValue);
                    }


                    //====== Add it to our url ======
                    newValue = string.Format(newUrl, oldValue);

                    //===== Add bookmark to last url =====
                    if (bookmarkPart.Length > 0)
                    {
                        newValue    += bookmarkPart;
                        bookmarkPart = "";
                    }

                    // Make it safe
                    //newValue = HttpUtility.HtmlEncode(newValue);

                    if (shouldAddQuote)
                    {
                        newValue = "\"" + newValue + "\"";
                    }

                    //====== Replace it with old url ======
                    htmlCode = htmlCode.Remove(position.Start, position.End - position.Start);
                    htmlCode = htmlCode.Insert(position.Start, newValue);

                    //========================================================//
                    //==============End of Replace new address================//
                    //========================================================//
                }
                else
                {
                    if (position.Start != -1)
                    {
                        index = position.Start;
                    }
                    index = StringCompare.IndexOfMatchCase(ref htmlCode, ' ', index);
                }
            }while ((index != -1));
        }
Пример #20
0
 public AddSiteBusinessModule(UrlProvider urlHelper, BusinessModuleFactory businessModuleFactory) : base(businessModuleFactory)
 {
     _urlHelper = urlHelper;
 }
Пример #21
0
        /// <summary>
        /// Processes the html codes
        /// </summary>
        /// <param name="codes">Html codes</param>
        /// <param name="pageUrl">Page url. E.G. http://Site.com/users/profile.aspx?uid=90</param>
        /// <param name="rootUrl">Root path. E.G. http://Site.com/</param>
        public override void Execute(ref string codes, string pageUrl, string pageUrlNoQuery, string pagePath, string rootUrl)
        {
            try
            {
                // 1- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginHtmlProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginHtmlProcessor,
                                             PluginMethods.IPluginHtmlProcessor.BeforeExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }

                // ASProxy pages url formats generator
                ASProxyPagesFormat pages = new ASProxyPagesFormat(_UserOptions.EncodeUrl);

                // Original urls addistional codes option
                bool orginalUrlRequired = false;


                // Renames ASPDotNET standard ViewState name to a temporary name
                // This name will reset to default when the page posted back
                HtmlReplacer.ReplaceAspDotNETViewState(ref codes);


                // If remove scripts chosen, remove all the scripts.
                if (_UserOptions.RemoveScripts)
                {
                    HtmlReplacer.RemoveScripts(ref codes);
                }


                // If remove embeded objects is requested
                if (_UserOptions.RemoveObjects)
                {
                    // Removing <object> tag
                    HtmlParser.RemoveTagContent(ref codes, "object", true);

                    // Removing <embed> tag
                    HtmlParser.RemoveTagContent(ref codes, "embed", true);
                }

                // Applying the BASE tag to the URLs.
                string baseHref;
                if (HtmlReplacer.ReplaceBaseSources(ref codes, true, out baseHref))
                {
                    // changing page base path to specified Base in the document
                    pagePath = UrlProvider.AddSlashToEnd(baseHref);

                    // BUGFIX v4.6.1:: site root url should change also
                    rootUrl = UrlProvider.GetRootPath(rootUrl);
                }

                // processing style sheet links
                if (_UserOptions.Images)
                {
                    HtmlReplacer.ReplaceCssLinks(ref codes,
                                                 pageUrlNoQuery,
                                                 pages.PageAnyType,
                                                 pagePath,
                                                 rootUrl,
                                                 _UserOptions.EncodeUrl);

                    // TODO: CSSReplacer
                    // This function replaces "Import" rule and background images!
                    // So, this breaches to background option role. Since v4.0
                    CSSReplacer.ReplaceStyleTagStyleUrl(ref codes,
                                                        pageUrlNoQuery,
                                                        pages.PageAnyType,
                                                        pages.PageAnyType,
                                                        pagePath,
                                                        rootUrl,
                                                        _UserOptions.EncodeUrl);
                }

                // It seems with javascript encoding these methods are useless!!
                // The javascript may be disabled in browser so we have to this anyway
                if (_UserOptions.Links)
                {
                    string extraAttib = "";

                    // Add displaying orginal url address code
                    if (_UserOptions.OrginalUrl)
                    {
                        orginalUrlRequired = true;
                        extraAttib         = Resources.STR_OrginalUrl_TagAttributeFormat;
                    }

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib += Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceAnchors(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageDefault,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl,
                                                extraAttib);

                    HtmlReplacer.ReplaceHttpRefresh(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageDefault,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }
                else
                {
                    string extraAttib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib = Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceAnchors(ref codes,
                                                pageUrlNoQuery,
                                                "{0}",
                                                pagePath,
                                                rootUrl,
                                                false,
                                                extraAttib);

                    HtmlReplacer.ReplaceHttpRefresh(ref codes,
                                                    pageUrlNoQuery,
                                                    "{0}",
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }

                if (_UserOptions.Frames)
                {
                    string extraAttrib = Resources.STR_IFrame_ExtraAttribute;

                    // Encode <iframe> tags
                    HtmlReplacer.ReplaceIFrames(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageHtml,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl,
                                                extraAttrib);

                    // Encode <framset> tags
                    HtmlReplacer.ReplaceFrameSets(ref codes,
                                                  pageUrlNoQuery,
                                                  pages.PageHtml,
                                                  pagePath,
                                                  rootUrl,
                                                  _UserOptions.EncodeUrl);
                }

                // Encode <img> tags
                if (_UserOptions.Images)
                {
                    string extraAttrib = "";

                    // Add code to display orginal url address
                    if (_UserOptions.OrginalUrl)
                    {
                        orginalUrlRequired = true;
                        extraAttrib        = Resources.STR_OrginalUrl_TagAttributeFormat;
                    }

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib += Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceImages(ref codes,
                                               pageUrlNoQuery,
                                               pages.PageAnyType,
                                               pagePath,
                                               rootUrl,
                                               _UserOptions.EncodeUrl,
                                               extraAttrib);

                    // Encode background image of <body> , <table> and <td> tags
                    HtmlReplacer.ReplaceBackgrounds(ref codes,
                                                    pageUrlNoQuery,
                                                    pages.PageAnyType,
                                                    pagePath,
                                                    rootUrl,
                                                    _UserOptions.EncodeUrl);
                }
                else
                {
                    string extraAttrib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib = Consts.ClientContent.attrAlreadyEncodedAttributeWithValue;

                    HtmlReplacer.ReplaceImages(ref codes,
                                               pageUrlNoQuery,
                                               "{0}",
                                               pagePath,
                                               rootUrl,
                                               false,
                                               extraAttrib);
                }

                // Encodes script tags if RemoveScripts option is disabled
                if (_UserOptions.RemoveScripts == false)
                {
                    HtmlReplacer.ReplaceScripts(ref codes,
                                                pageUrlNoQuery,
                                                pages.PageAnyType,
                                                pagePath,
                                                rootUrl,
                                                _UserOptions.EncodeUrl);

                    // TODO: JSReplacer
                    JSReplacer.ReplaceScriptTagCodes(ref codes);

                    // V5.2: Replaces tags events using RegEx
                    HtmlReplacer.ReplaceTagsEvents(ref codes,
                                                   pageUrlNoQuery,
                                                   pages.PageAnyType,
                                                   pagePath,
                                                   pageUrl,
                                                   rootUrl,
                                                   _UserOptions.EncodeUrl);
                }

                // Encode <embed> tags
                HtmlReplacer.ReplaceEmbeds(ref codes,
                                           pageUrlNoQuery,
                                           pages.PageAnyType,
                                           pagePath,
                                           rootUrl,
                                           _UserOptions.EncodeUrl);

                // Encode <form> tags
                if (_UserOptions.SubmitForms)
                {
                    string extraAttrib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttrib =
                        Consts.ClientContent.attrAlreadyEncodedAttributeWithValue
                        + Resources.STR_SubmitForms_ExtraAttribute;

                    HtmlReplacer.ReplaceFormsSources(ref codes,
                                                     pageUrlNoQuery,
                                                     pages.PageDefault,
                                                     pagePath,
                                                     rootUrl,
                                                     _UserOptions.EncodeUrl,
                                                     _UserOptions.SubmitForms,
                                                     extraAttrib);
                }
                else
                {
                    string extraAttib;

                    // Add an attribute to determine that this tag already encoded and javascript encoder shouldn't encode it again.
                    extraAttib =
                        Consts.ClientContent.attrAlreadyEncodedAttributeWithValue
                        + Resources.STR_SubmitForms_ExtraAttribute;

                    HtmlReplacer.ReplaceFormsSources(ref codes,
                                                     pageUrlNoQuery,
                                                     "{0}",
                                                     pagePath,
                                                     pagePath,
                                                     false,
                                                     _UserOptions.SubmitForms,
                                                     extraAttib);
                }

                // Add dynamic encoding javascript codes
                string jsEncoderCodes = GenerateJsEncoderCodes(pageUrl,
                                                               pageUrlNoQuery,
                                                               pagePath,
                                                               rootUrl);


                // Add jsEncoder codes to page
                ExtraCodesForPage = jsEncoderCodes + ExtraCodesForPage;

                // OrginalUrl additional injection html codes
                if (orginalUrlRequired)
                {
                    // TODO: Check necessary
                    ExtraCodesForPage = Resources.STR_OrginalUrl_FloatBar + ExtraCodesForPage;

                    // Inject to html, right after the body element
                    ExtraCodesForBody = Resources.STR_OrginalUrl_Functions + ExtraCodesForBody;
                }


                // 2- executing plugins
                if (Plugins.IsPluginAvailable(PluginHosts.IPluginHtmlProcessor))
                {
                    Plugins.CallPluginMethod(PluginHosts.IPluginHtmlProcessor,
                                             PluginMethods.IPluginHtmlProcessor.AfterExecute,
                                             this, (object)codes, pageUrl, pageUrlNoQuery, pagePath, rootUrl);
                }
            }
            catch (Exception ex)
            {
                // error logs
                if (Systems.LogSystem.ErrorLogEnabled)
                {
                    Systems.LogSystem.LogError(ex, pageUrl);
                }

                codes = "<center><b>ASProxy has some errors! The delivered content may not work properly.</b></center>" + ex.Message + "<br />"
                        + codes;
            }
        }
        private JsonProductCompare GetJsonProductCompare(int productID, int groupID)
        {
            var product = Products.GetDetails(productID);

            var group = Groups.GetByID(groupID);

            product.Title    = group.Perfix + " " + product.Title;
            product.Title_En = product.Title_En + " " + group.Perfix_En;

            var url = UrlProvider.GetProductUrl(productID, group.UrlPerfix, product.UrlPerfix);

            #region Image File

            string fileName = "";

            var imageInfo = ProductImages.GetDefaultImage(productID);

            if (imageInfo != null)
            {
                fileName = imageInfo.Filename;
            }
            var image = UrlProvider.GetProductImage(fileName,
                                                    StaticValues.ThumbnailProductImageSize);

            #endregion Image File

            #region Scores

            float totalScore = Utilities.CalcRaty(product.SumScore.Value, product.ScoreCount, product.ProductScore);

            List <ScoresAverage> scoresAverages = ScoreParameterValues.CalculateAverage(productID);

            #endregion Scores

            #region Attributes

            var groups    = ProductGroups.GetByProductID(productID).Select(item => item.GroupID).ToList();
            var attrbutes = Attributes.GetByGroupIDs(groups);
            foreach (var item in attrbutes)
            {
                item.Value = AttributeValues.GetValue(productID, item.ID);

                if (item.Value != null)
                {
                    item.Value = AttributeValues.RenderValue(item);
                }
            }

            #endregion Attributes

            #region Prices

            product.Prices = Products.GetProductPrices(product.ID, product.HasVarients, PriceType.Sell);

            string userID = null;
            if (User.Identity.IsAuthenticated)
            {
                userID = UserID;
            }

            Products.SetDiscounts(userID, product.ID, product.HasVarients, product.Prices);

            #endregion Prices

            var productItem = new JsonProductCompare
            {
                ProductID        = productID,
                DisplayTitleType = product.DisplayTitleType,
                Title_Fa         = product.Title,
                Title_En         = product.Title_En,
                Url                = url,
                Prices             = product.Prices,
                Image              = image,
                Score              = totalScore,
                PreferentialsCount = product.ScoreCount + 1,
                Attributes         = attrbutes,
                ScoresAverages     = scoresAverages,
                GroupID            = groupID,
                IsUnavailable      = product.IsUnavailable
            };

            return(productItem);
        }
Пример #23
0
        /// <summary>
        /// Generate dynamic encoding javascript codes
        /// </summary>
        /// <param name="pageBasePath">base path of current request page</param>
        /// <returns>Javascript codes</returns>
        string GenerateJsEncoderCodes(
            string pageUrl,
            string pageUrlNoQuery,
            string pagePath,
            string rootUrl)
        {
            string userConfig;
            string reqInfo;
            string cookieNames;
            string locationObject;

            userConfig = string.Format(Consts.ClientContent.JSEncoder_UserConfig,
                                       _UserOptions.EncodeUrl.ToString().ToLower(),
                                       _UserOptions.OrginalUrl.ToString().ToLower(),
                                       _UserOptions.Links.ToString().ToLower(),
                                       _UserOptions.Images.ToString().ToLower(),
                                       _UserOptions.SubmitForms.ToString().ToLower(),
                                       _UserOptions.Frames.ToString().ToLower(),
                                       _UserOptions.Cookies.ToString().ToLower(),
                                       _UserOptions.RemoveScripts.ToString().ToLower(),
                                       _UserOptions.RemoveObjects.ToString().ToLower(),
                                       _UserOptions.TempCookies.ToString().ToLower()
                                       );

            reqInfo = string.Format(Consts.ClientContent.JSEncoder_RequestInfo,
                                    // V5.5b4 BUGFIX: page url should be encoded, it may contain unsecure chars.
                                    HtmlTags.EncodeJavascriptString(pageUrl, true),
                                    HtmlTags.EncodeJavascriptString(pageUrlNoQuery, true),
                                    HtmlTags.EncodeJavascriptString(pagePath, true),
                                    HtmlTags.EncodeJavascriptString(rootUrl, true),
                                    Systems.CookieManager.GetCookieName(pageUrl),
                                    Systems.CookieManager.GetCookieNameExt,
                                    UrlProvider.JoinUrl(UrlProvider.GetAppAbsolutePath(), Consts.FilesConsts.PageDefault_Dynamic),
                                    UrlProvider.GetAppAbsolutePath(),
                                    UrlProvider.GetAppAbsoluteBasePath(),
                                    Consts.FilesConsts.PageDefault_Dynamic,
                                    Consts.Query.Base64Unknowner
                                    );

            // Cookie names
            StringCollection strColl         = Systems.CookieManager.GetAppliedCookieNamesList(pageUrl);
            string           cookieNamesTemp = "";

            for (int i = 0; i < strColl.Count; i++)
            {
                string name = strColl[i];
                cookieNamesTemp += "'" + name + "'";
                if (i != strColl.Count - 1)
                {
                    cookieNamesTemp += ',';
                }
            }
            cookieNames = string.Format(Consts.ClientContent.JSEncoder_AppliedCookieNames,
                                        cookieNamesTemp);

            // Page uri
            Uri pageUri = new Uri(pageUrl);

            locationObject = string.Format(Consts.ClientContent.JSEncoder_RequestLocation,
                                           pageUri.Fragment,     // Hash
                                           pageUri.Authority,    // Host
                                           pageUri.Host,         // Hostname
                                           pageUri.AbsolutePath, // Pathname
                                           pageUri.Query,        // Search
                                           pageUri.Port,         // Port
                                           pageUri.Scheme        // Protocol
                                           );

            StringBuilder result = new StringBuilder();

            try
            {
                // ASProxy encoder variables
                result.Append(Resources.ASProxyJavaScriptTag(userConfig + reqInfo + locationObject + cookieNames, ""));

                // Base64 encoder
                result.Append(Resources.ASProxyJavaScriptTag("", Consts.FilesConsts.JSBase64));

                // ASProxy encoder
                result.Append(Resources.ASProxyJavaScriptTag("", Consts.FilesConsts.JSASProxyEncoder));

                // AJAX wrapper core, Usless since v5.5b4
                // result.Append(Resources.ASProxyJavaScriptTag("", Consts.FilesConsts.JSAJAXWrapperCore));

                return(result.ToString());
            }
            finally
            {
                // release the memory of stringBuilder
                result.Length = 0;
            }
        }
Пример #24
0
        public static void ReplaceTwoAttributeTagsValue(ref string htmlCodes,
                                                        string pageUrlNoQuery,
                                                        string newPageFormat,
                                                        string pagePath,
                                                        string siteRootUrl,
                                                        bool encodeUrl,
                                                        string tagName,
                                                        string attr1,
                                                        string attr1Value,
                                                        string attr2)
        {
            TextRange attr1Result = new TextRange(-1, -1);
            TextRange attr2Result = new TextRange(-1, -1);
            int       cursorPos = 0;
            string    tmp, actionSrc = "";

            do
            {
                attr1Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tagName, attr1, cursorPos);
                if (attr1Result.Start > -1 && attr1Result.End > -1)
                {
                    string tmpRelType = htmlCodes.Substring(attr1Result.Start, attr1Result.End - attr1Result.Start);
                    if (tmpRelType.Trim().ToLower() != attr1Value.Trim().ToLower())
                    {
                        if (attr1Result.Start != -1)
                        {
                            cursorPos = attr1Result.Start;
                        }
                        continue;
                    }
                }
                else
                {
                    break;
                }

                attr2Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tagName, attr2, cursorPos);

                if (attr2Result.Start == -1)
                {
                    break;
                }

                if (attr2Result.Start > -1 && attr2Result.End > -1)
                {
                    cursorPos = attr2Result.Start;

                    //====== Correct value position according to quotes existence=======
                    attr2Result = HtmlTags.CorrectValueIfQuoteExists(ref htmlCodes, attr2Result);

                    // Get the value
                    actionSrc = htmlCodes.Substring(attr2Result.Start, attr2Result.End - attr2Result.Start);


                    //====== Convert virtual url to absolute ======
                    actionSrc = UrlProvider.JoinUrl(actionSrc, pageUrlNoQuery, pagePath, siteRootUrl);

                    //====== Delete invalid character such as tab and line feed ======
                    actionSrc = UrlProvider.IgnoreInvalidUrlCharctersInHtml(actionSrc);

                    //===== If another site url, has bookmark=====
                    if (actionSrc.IndexOf('#') != -1)
                    {
                        actionSrc = UrlBuilder.RemoveUrlBookmark(actionSrc, out tmp);
                    }

                    // Get clear url
                    actionSrc = HttpUtility.HtmlDecode(actionSrc);

                    //====== Encode url to make it unknown ======
                    if (encodeUrl)
                    {
                        actionSrc = UrlProvider.EncodeUrl(actionSrc);
                    }
                    else
                    {
                        // just url safe
                        actionSrc = UrlProvider.EscapeUrlQuery(actionSrc);
                    }

                    //====== Add it to our url ======
                    actionSrc = string.Format(newPageFormat, actionSrc);

                    // Make it safe
                    actionSrc = HttpUtility.HtmlEncode(actionSrc);

                    //====== Replace it with old url ======
                    htmlCodes = htmlCodes.Remove(attr2Result.Start, attr2Result.End - attr2Result.Start);
                    htmlCodes = htmlCodes.Insert(attr2Result.Start, actionSrc);
                }
                else
                {
                    if (attr2Result.Start != -1)
                    {
                        cursorPos = attr2Result.Start;
                    }
                    cursorPos = StringCompare.IndexOfMatchCase(ref htmlCodes, ">", cursorPos);
                }
            }while (attr2Result.Start != -1);
        }
Пример #25
0
        public Result GetAll(Query query)
        {
            var items  = ProductRepository.GetAll();
            var sortBy = (Func <Product, object>)(c => TypeAccessor[c, query.SortBy ?? "Name"]);

            if (query.SortDirection == SortDirection.Descending)
            {
                items = items.OrderByDescending(sortBy);
            }
            else
            {
                items = items.OrderBy(sortBy);
            }

            return(new Result(
                       PageSize,
                       items.Skip(PageSize * (query.Page - 1)).Take(PageSize).Select(item => new { Item = item, Url = UrlProvider.GetUrl(item) }),
                       items.Count()
                       ));
        }
Пример #26
0
        private static void ReplaceTagSrcAttribute(ref string htmlCodes,
                                                   string pageUrlNoQuery,
                                                   string tagName,
                                                   string attributeName,
                                                   string pagePath,
                                                   string newPageFormat,
                                                   string siteRootUrl,
                                                   bool encodeUrl,
                                                   string extraAttributeFormat,
                                                   bool canEncloseWithTags)
        {
            int       index = 0;      //====== In first run, index must be Zero ======
            TextRange position;
            string    oldValue, newValue;
            string    orgValue        = "";
            string    bookmarkPart    = "";
            string    newAttribute    = "";
            bool      addNewAttribute = false;
            bool      hasNewAttribute = false;

            if (!string.IsNullOrEmpty(extraAttributeFormat))
            {
                addNewAttribute = true;
                hasNewAttribute = true;
            }

            do
            {
                addNewAttribute = hasNewAttribute;

                position = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tagName, attributeName, index);

                if (position.Start == -1)
                {
                    break;
                }

                // If requested, test statement that shouldn't enclose with specified tags
                bool continueLoop = true;

                // this causes heavy pressure
                //if (canEncloseWithTags && position.Start != -1 && position.End != -1)
                //    continueLoop = !HtmlTags.IsEnclosedBy(ref htmlCodes, position.Start, "<script", "</script>");

                if (continueLoop &&
                    position.Start != -1 &&
                    position.End != -1 &&
                    position.End > position.Start)
                {
                    //======OK. go to end of tag=============
                    index = StringCompare.IndexOfMatchCase(ref htmlCodes, '>', position.Start);

                    // Replace new address

                    //====== Correct value position according to quotes existence=======
                    //position = ASProxyFunctions.CorrectValueIfQuoteExists(ref pageHtml, position);

                    //====== Get the attribute value ======
                    oldValue = htmlCodes.Substring(position.Start, position.End - position.Start);

                    oldValue = HtmlTags.RemoveEscapeQuotesFromTagAttributeValue(oldValue);

                    oldValue = HtmlTags.RemoveQuotesFromTagAttributeValue(oldValue);

                    //===== If link is a bookmark don't change it=====
                    if (oldValue.StartsWith("#"))
                    {
                        continue;
                    }

                    if (UrlProvider.IsClientSitdeUrl(oldValue) == false)
                    {
                        //====== Convert virtual url to absolute ======
                        oldValue = UrlProvider.JoinUrl(oldValue, pageUrlNoQuery, pagePath, siteRootUrl);

                        //====== Delete invalid character such as tab and line feed ======
                        oldValue = UrlProvider.IgnoreInvalidUrlCharctersInHtml(oldValue);

                        // Save orginal value
                        orgValue = oldValue;

                        //===== If another site url, has bookmark
                        if (oldValue.IndexOf('#') != -1)
                        {
                            oldValue = UrlBuilder.RemoveUrlBookmark(oldValue, out bookmarkPart);
                        }


                        //====== Get desigred url addrress
                        oldValue = HttpUtility.HtmlDecode(oldValue);

                        //====== Encode url to make it unknown ======
                        if (encodeUrl)
                        {
                            oldValue = UrlProvider.EncodeUrl(oldValue);
                        }
                        else
                        {
                            // just url safe
                            oldValue = UrlProvider.EscapeUrlQuery(oldValue);
                        }

                        //====== Add it to our url ======
                        newValue = string.Format(newPageFormat, oldValue);

                        //===== Add bookmark to last url =====
                        if (bookmarkPart.Length > 0)
                        {
                            newValue    += bookmarkPart;
                            bookmarkPart = "";
                        }
                    }
                    else
                    {
                        newValue        = oldValue;
                        addNewAttribute = false;
                    }

                    //====== Make it safe
                    newValue = HttpUtility.HtmlEncode(newValue);

                    //====== Replace it with old url
                    htmlCodes = htmlCodes.Remove(position.Start, position.End - position.Start);
                    htmlCodes = htmlCodes.Insert(position.Start, newValue);


                    if (addNewAttribute)
                    {
                        // Apply original value and encoded value to format
                        // BUG: Problem with format string that contain (') or (") characters
                        // Bug Fixed since version 4.7
                        newAttribute = string.Format(extraAttributeFormat, orgValue, newValue);

                        // Locate end of tag
                        index = StringCompare.IndexOfMatchCase(ref htmlCodes, '>', position.Start);
                        if (htmlCodes[index - 1] == '/')
                        {
                            index--;
                        }

                        // Insert to tag
                        htmlCodes = htmlCodes.Insert(index, newAttribute);
                    }

                    //===============End of Replace new address =========
                }
                else
                {
                    if (position.Start != -1)
                    {
                        index = position.Start;
                    }
                    index = StringCompare.IndexOfMatchCase(ref htmlCodes, '>', index);
                }
            }while ((index != -1));
        }
Пример #27
0
        protected virtual DirectoryContent GetDirectoryContent(Entity entity)
        {
            if (entity == null)
            {
                return(null);
            }

            string url;

            try
            {
                url = UrlProvider.GetUrl(ServiceContext, entity);
            }
            catch (Exception e)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error getting URL for entity [{0}:{1}]: {2}", entity.LogicalName, entity.Id, e.ToString()));

                return(null);
            }

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

            bool canWrite;

            try
            {
                if (!SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Read))
                {
                    return(null);
                }

                canWrite = SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Change);
            }
            catch (InvalidOperationException e)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for entity [{0}:{1}]: {2}", entity.LogicalName, entity.Id, e.ToString()));

                return(null);
            }

            var content = new DirectoryContent
            {
                url  = url,
                date = FormatDateTime(entity.GetAttributeValue <DateTime?>("modifiedon")),
                read = true,
                rm   = false,
            };

            DirectoryType directoryType;

            if (FileSystem.EntityDirectoryTypes.TryGetValue(entity.LogicalName, out directoryType))
            {
                content.hash  = new DirectoryContentHash(entity, true).ToString();
                content.name  = directoryType.GetDirectoryName(entity);
                content.mime  = DirectoryMimeType;
                content.size  = 0;
                content.write = directoryType.SupportsUpload && SecurityProvider.TryAssert(ServiceContext, entity, CrmEntityRight.Change);

                return(content);
            }

            content.write = canWrite;
            content.name  = entity.GetAttributeValue <string>("adx_name");
            content.hash  = new DirectoryContentHash(entity).ToString();

            if (entity.LogicalName != "adx_webfile")
            {
                content.mime = "application/x-{0}".FormatWith(entity.LogicalName);
                content.size = 0;

                return(content);
            }

            var fileNote = ServiceContext.GetNotes(entity)
                           .Where(e => e.GetAttributeValue <bool?>("isdocument").GetValueOrDefault())
                           .OrderByDescending(e => e.GetAttributeValue <DateTime?>("createdon"))
                           .FirstOrDefault();

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

            content.mime = fileNote.GetAttributeValue <string>("mimetype");
            content.size = fileNote.GetAttributeValue <int?>("filesize").GetValueOrDefault();
            content.rm   = canWrite;

            return(content);
        }
Пример #28
0
        /// <summary>
        /// Replaces head http refresh codes
        /// </summary>
        public static void ReplaceHttpRefresh(ref string htmlCodes,
                                              string pageUrlNoQuery,
                                              string newPageFormat,
                                              string pagePath,
                                              string rootUrl,
                                              bool encodeUrl)
        {
            const string tag           = "<meta";
            const string attr1         = "http-equiv";
            const string attr1Value    = "refresh";
            const string attr2         = "content";
            const string contentUrlTag = "url=";

            TextRange attr1Result = new TextRange(-1, -1);
            TextRange attr2Result = new TextRange(-1, -1);
            int       cursorPos = 0;
            string    tmp, actionSrc = "";

            do
            {
                // Find position of Meta tag and HTTP-EQUIV attribute
                attr1Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tag, attr1, cursorPos);
                if (attr1Result.Start > -1 && attr1Result.End > -1)
                {
                    string tmpRelType = htmlCodes.Substring(attr1Result.Start, attr1Result.End - attr1Result.Start);
                    if (tmpRelType.Trim().ToLower() != attr1Value.Trim().ToLower())
                    {
                        if (attr1Result.Start != -1)
                        {
                            cursorPos = attr1Result.Start;
                        }
                        continue;
                    }
                }
                else
                {
                    break;
                }

                // Find position of CONTENT attribute
                attr2Result = HtmlParser.GetTagAttributeValuePos(ref htmlCodes, tag, attr2, cursorPos);

                if (attr2Result.Start == -1)
                {
                    break;
                }

                if (attr2Result.Start > -1 && attr2Result.End > -1)
                {
                    cursorPos = attr2Result.Start;

                    // Get CONTENT attribute
                    actionSrc = htmlCodes.Substring(attr2Result.Start, attr2Result.End - attr2Result.Start);

                    // Some time CONTENT contains url address and refresh time, take them apart
                    string[] contentParts = actionSrc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    // If the CONTENT does not contain any url address, no changes needed!
                    if (contentParts.Length < 2)
                    {
                        cursorPos = attr2Result.Start;
                        // next one!!
                        continue;
                    }

                    // remove Url= from CONTENT
                    actionSrc = contentParts[1].Trim();
                    if (actionSrc.ToLower().StartsWith(contentUrlTag))
                    {
                        actionSrc = actionSrc.Substring(contentUrlTag.Length, actionSrc.Length - contentUrlTag.Length);
                    }

                    // Convert virtual url to absolute
                    actionSrc = UrlProvider.JoinUrl(actionSrc, pageUrlNoQuery, pagePath, rootUrl);

                    // Delete invalid character such as tab and line feed ======
                    actionSrc = UrlProvider.IgnoreInvalidUrlCharctersInHtml(actionSrc);

                    // If there is a bookmark
                    if (actionSrc.IndexOf('#') != -1)
                    {
                        actionSrc = UrlBuilder.RemoveUrlBookmark(actionSrc, out tmp);
                    }

                    // Get clear url
                    actionSrc = HttpUtility.HtmlDecode(actionSrc);

                    // Encode url to make it unknown
                    if (encodeUrl)
                    {
                        actionSrc = UrlProvider.EncodeUrl(actionSrc);
                    }
                    else
                    {
                        // just url safe
                        actionSrc = UrlProvider.EscapeUrlQuery(actionSrc);
                    }

                    // Add it to our url
                    actionSrc = string.Format(newPageFormat, actionSrc);

                    // Make CONTENT attribute state
                    actionSrc = contentParts[0] + ';' + contentUrlTag + actionSrc;

                    // Make it safe
                    actionSrc = HttpUtility.HtmlEncode(actionSrc);

                    // Replace it with old url
                    htmlCodes = htmlCodes.Remove(attr2Result.Start, attr2Result.End - attr2Result.Start);
                    htmlCodes = htmlCodes.Insert(attr2Result.Start, actionSrc);
                }
                else
                {
                    if (attr2Result.Start != -1)
                    {
                        cursorPos = attr2Result.Start;
                    }
                    cursorPos = StringCompare.IndexOfMatchCase(ref htmlCodes, ">", cursorPos);
                }
            }while (attr2Result.Start != -1);
        }
        protected override async Task <ITransitionResult> ExecuteInternalAsync(TransitionInput <AcceptStartRequest> input,
                                                                               CacheItem relatedItem)
        {
            var composeInfo = new BaseJwtComposeInfo(input)
            {
                IncludeFido2FallbackBehavior = true
            };

            if (input.Data.AuthType.HasValue)
            {
                switch (input.Data.AuthType)
                {
                case ConnectionAuthType.Basic:
                    if (String.IsNullOrEmpty(input.Data.ExtAuthPayload))
                    {
                        composeInfo.Behavior = GetNextBehaviorFunc(input, relatedItem);
                    }
                    else
                    {
                        composeInfo.Behavior = new FrontendBehavior(StepType.UpgradeToFido2, ChallengeType.Login,
                                                                    new CallAction(UrlProvider.GetSwitchAuthTypeUrl(relatedItem.Context,
                                                                                                                    ConnectionAuthType.Fido2)));
                    }
                    break;

                case ConnectionAuthType.Passcode:
                    composeInfo.Behavior = NavigateToEnterPasscode(input, relatedItem);
                    break;

                case ConnectionAuthType.Fido2:
                    if (string.IsNullOrEmpty(input.Data.ExtAuthPayload))
                    {
                        composeInfo.Behavior = await NavigateToPasswordlessPageAsync(input, relatedItem);
                    }
                    else
                    {
                        var switchResult =
                            await _trySwitchToFido2FlowCommand.ExecuteAsync(relatedItem, input.Data.ExtAuthPayload);

                        if (switchResult == null &&
                            _coreConfiguration.Fido2FallbackBehavior == Fido2FallbackBehavior.Block)
                        {
                            return(CreateErrorResponse(input, ErrorType.RequiresBiometricInput));
                        }

                        composeInfo.Behavior = switchResult ?? GetNextBehaviorFunc(input, relatedItem);
                    }

                    return(new JwtContainer(JwtComposer.GenerateBaseStepJwt(composeInfo)));

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else if (_coreConfiguration.TFAEnabled)
            {
                if (input.Data.SupportsFido2 && _coreConfiguration.Fido2.IsEnabled)
                {
                    // check if fido2 page response available
                    if (string.IsNullOrWhiteSpace(input.Data.ExtAuthPayload))
                    {
                        composeInfo.Behavior = await NavigateToPasswordlessPageAsync(input, relatedItem);
                    }
                    else
                    {
                        var switchResult =
                            await _trySwitchToFido2FlowCommand.ExecuteAsync(relatedItem, input.Data.ExtAuthPayload);

                        if (switchResult == null &&
                            _coreConfiguration.Fido2FallbackBehavior == Fido2FallbackBehavior.Block)
                        {
                            return(CreateErrorResponse(input, ErrorType.RequiresBiometricInput));
                        }

                        composeInfo.Behavior = switchResult ?? GetNextBehaviorFunc(input, relatedItem);
                    }

                    return(new JwtContainer(JwtComposer.GenerateBaseStepJwt(composeInfo)));
                }

                // if FIDO2 flow or there is no way to login (with/without recovery with previously created creds)
                if (relatedItem.IsFido2Flow ||
                    _coreConfiguration.Fido2FallbackBehavior == Fido2FallbackBehavior.Block &&
                    relatedItem.ChallengeType != ChallengeType.Login && (!input.Data.AuthType.HasValue ||
                                                                         !string.IsNullOrEmpty(relatedItem
                                                                                               .RecoveryToken)))
                {
                    return(CreateErrorResponse(input, ErrorType.RequiresBiometricInput));
                }

                // go to passcode if such behavior enabled and check if create
                if (_coreConfiguration.Fido2FallbackBehavior == Fido2FallbackBehavior.Passcode &&
                    (relatedItem.AuthCookieType == CookieType.Passcode ||
                     relatedItem.ChallengeType != ChallengeType.Login))
                {
                    composeInfo.Behavior = NavigateToEnterPasscode(input, relatedItem);
                }
            }

            if (composeInfo.Behavior == null && (!_coreConfiguration.TFAEnabled ||
                                                 _coreConfiguration.Fido2FallbackBehavior
                                                 == Fido2FallbackBehavior.Basic))
            {
                composeInfo.Behavior = GetNextBehaviorFunc(input, relatedItem);
            }

            if (!string.IsNullOrWhiteSpace(relatedItem.EncKey))
            {
                composeInfo.EncKey    = relatedItem.EncKey;
                composeInfo.EncVector = relatedItem.EncVector;
            }
            else
            {
                var updatedItem = await _setNewEncryptionTokenCommand.ExecuteAsync(relatedItem.Context);

                composeInfo.EncKey    = updatedItem.EncKey;
                composeInfo.EncVector = updatedItem.EncVector;
                // TODO: rework
                relatedItem = updatedItem;
            }

            composeInfo.CanBeRecovered = !string.IsNullOrEmpty(relatedItem.RecoveryToken);

            return(new JwtContainer(JwtComposer.GenerateBaseStepJwt(composeInfo,
                                                                    relatedItem.DID ?? _identitiesProvider.GenerateUserId())));
        }
Пример #30
0
 /// <summary>
 /// Parses the string looking for the {localLink} syntax and updates them to their correct links.
 /// </summary>
 /// <param name="text"></param>
 /// <param name="urlProvider"></param>
 /// <returns></returns>
 public static string ParseInternalLinks(string text, UrlProvider urlProvider) =>
 ParseInternalLinks(text, urlProvider, Current.UmbracoContext.MediaCache);
Пример #31
0
 public static UmbracoHelper GetUmbracoHelper(UmbracoContext context, ICultureDictionary cultureDictionary = null, MembershipHelper membershipHelper = null, UrlProvider urlProvider = null,
                                              IPublishedContent content = null, ITypedPublishedContentQuery typedQuery = null, IDynamicPublishedContentQuery dynamicQuery            = null, ITagQuery tagQuery = null, IDataTypeService typeService = null,
                                              IUmbracoComponentRenderer componentRenderer = null)
 {
     return(new UmbracoHelper(context,
                              content ?? Mock.Of <IPublishedContent>(),
                              typedQuery ?? Mock.Of <ITypedPublishedContentQuery>(),
                              dynamicQuery ?? Mock.Of <IDynamicPublishedContentQuery>(),
                              tagQuery ?? Mock.Of <ITagQuery>(),
                              typeService ?? Mock.Of <IDataTypeService>(),
                              urlProvider ?? GetUmbracoUrlProvider(context),
                              cultureDictionary ?? Mock.Of <ICultureDictionary>(),
                              componentRenderer ?? Mock.Of <IUmbracoComponentRenderer>(),
                              membershipHelper ?? GetUmbracoMembershipHelper(context)));
 }
Пример #32
0
 /// <summary>
 /// Gets the absolute url of a content identified by its identifier.
 /// </summary>
 /// <param name="contentId">The content identifier.</param>
 /// <returns>The absolute url for the content.</returns>
 public string UrlAbsolute(int contentId, string culture = null)
 {
     return(UrlProvider.GetUrl(contentId, true, culture));
 }
Пример #33
0
        /// <summary>
        /// Initializes the request info. This method should be called when
        /// Initializing the class directly from the request.
        /// </summary>
        protected virtual void IntializeRequestInfo(HttpRequest httpRequest)
        {
            // If Modified Since
            // BUG: v5beta4 custom headers doesn't support at this moment
            // RequestInfo.CustomHeaders = GetHeadersFromRequest(httpRequest);
            RequestInfo.IfModifiedSince = GetIfModifiedSinceHeader(httpRequest);


            bool tmpBool = false;

            // Get requested url
            string url = httpRequest.QueryString[Consts.Query.UrlAddress];

            // if url is provided
            if (!string.IsNullOrEmpty(url))
            {
                string decode = httpRequest.QueryString[Consts.Query.Decode];
                if (!string.IsNullOrEmpty(decode))
                {
                    try
                    {
                        tmpBool = Convert.ToBoolean(Convert.ToInt32(decode));
                    }
                    catch
                    {
                        tmpBool = false;
                    }
                }

                // If url is encoded, decode it
                if (tmpBool)
                {
                    url = UrlProvider.DecodeUrl(url);
                }

                RequestInfo.RequestUrl = UrlProvider.CorrectInputUrl(url);
            }

            url = httpRequest.QueryString[Consts.Query.Redirect];

            if (!string.IsNullOrEmpty(url))
            {
                // If url is encoded, decode it
                if (tmpBool)
                {
                    url = UrlProvider.DecodeUrl(url);
                }

                RequestInfo.RedirectedFrom = url;
            }

            // Get request post method state
            string reqMethod;

            if (UrlProvider.GetRequestQuery(httpRequest.QueryString, Consts.Query.WebMethod, out reqMethod))
            {
                //RequestInfo.RequestMethod = WebMethods.ValidateMethod(reqMethod, WebMethods.DefaultMethods.GET);
                RequestInfo.RequestMethod = WebMethods.OmitInvalidCharacters(reqMethod);
            }
            else
            {
                RequestInfo.RequestMethod = WebMethods.GET;
            }
        }
Пример #34
0
 public override FrontendBehavior GetOwnReference(string context, ChallengeType challengeType)
 {
     return(new(StepType, challengeType, new CallAction(UrlProvider.GetStopFlowUrl(context))));
 }
Пример #35
0
        public IActionResult ExportDictionaries(string id, [FromBody] ExportDictionariesSettings settings, [FromServices] UrlProvider urlProvider)
        {
            //SERVICE VALIDATION
            var service = serviceQuery.Get(id);

            if (service == null)
            {
                return(new HttpStatusCodeWithErrorResult(StatusCodes.Status404NotFound, ServiceResources.InvalidIdNotExistingService));
            }
            if (service.Type != (int)ServiceTypeEnum.Prc)
            {
                return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest, string.Format(ServiceResources.InvalidServiceTypeOnly_0_ServicesAreValidForThisRequest, "Prc")));
            }
            if (service.Status != (int)ServiceStatusEnum.Active && service.Status != (int)ServiceStatusEnum.Prepared)
            {
                return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest, ServiceResources.InvalidStatusOnlyTheServicesWithPreparedOrActiveStatusCanBeExported));
            }

            var prcSettings = serviceQuery.GetSettings <PrcSettingsElastic>(service.Id);

            //TAGS VALIDATION
            var           tagQuery = queryFactory.GetTagQuery(prcSettings.DataSetName);
            List <string> tagIds;

            if (settings?.TagIdList?.Any() == true)
            {
                tagIds = prcSettings.Tags.Select(t => t.Id).Intersect(settings.TagIdList).ToList();
                if (tagIds.Count < settings.TagIdList.Count)
                {
                    var missingTagIds = settings.TagIdList.Except(tagIds).ToList();
                    return(new HttpStatusCodeWithErrorResult(StatusCodes.Status400BadRequest,
                                                             string.Format(ServiceResources.TheFollowingTagIdsNotExistInTheService_0, string.Join(", ", missingTagIds))));
                }
            }
            else
            {
                tagIds = prcSettings.Tags.Select(t => t.Id).ToList();
            }

            var process = processHandler.Create(
                ProcessTypeEnum.PrcExportDictionaries,
                service.Id, settings,
                string.Format(ServiceResources.ExportingDictionariesFrom_0_Service_1, ServiceTypeEnum.Prc, service.Name));

            service.ProcessIdList.Add(process.Id);
            serviceQuery.Update(service.Id, service);

            processHandler.Start(process, (tokenSource) => prcHandler.ExportDictionaries(process.Id, prcSettings, tagIds, tokenSource.Token, urlProvider.GetHostUrl()));

            return(new HttpStatusCodeWithObjectResult(StatusCodes.Status202Accepted, process.ToProcessModel()));
        }
Пример #36
0
        // initializes a new instance of the UmbracoContext class
        // internal for unit tests
        // otherwise it's used by EnsureContext above
        // warn: does *not* manage setting any IUmbracoContextAccessor
        internal UmbracoContext(HttpContextBase httpContext,
                                IPublishedSnapshotService publishedSnapshotService,
                                WebSecurity webSecurity,
                                IUmbracoSettingsSection umbracoSettings,
                                IEnumerable <IUrlProvider> urlProviders,
                                IEnumerable <IMediaUrlProvider> mediaUrlProviders,
                                IGlobalSettings globalSettings,
                                IVariationContextAccessor variationContextAccessor)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }
            if (publishedSnapshotService == null)
            {
                throw new ArgumentNullException(nameof(publishedSnapshotService));
            }
            if (webSecurity == null)
            {
                throw new ArgumentNullException(nameof(webSecurity));
            }
            if (umbracoSettings == null)
            {
                throw new ArgumentNullException(nameof(umbracoSettings));
            }
            if (urlProviders == null)
            {
                throw new ArgumentNullException(nameof(urlProviders));
            }
            if (mediaUrlProviders == null)
            {
                throw new ArgumentNullException(nameof(mediaUrlProviders));
            }
            VariationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
            _globalSettings          = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings));

            // ensure that this instance is disposed when the request terminates, though we *also* ensure
            // this happens in the Umbraco module since the UmbracoCOntext is added to the HttpContext items.
            //
            // also, it *can* be returned by the container with a PerRequest lifetime, meaning that the
            // container *could* also try to dispose it.
            //
            // all in all, this context may be disposed more than once, but DisposableObject ensures that
            // it is ok and it will be actually disposed only once.
            httpContext.DisposeOnPipelineCompleted(this);

            ObjectCreated    = DateTime.Now;
            UmbracoRequestId = Guid.NewGuid();
            HttpContext      = httpContext;
            Security         = webSecurity;

            // beware - we cannot expect a current user here, so detecting preview mode must be a lazy thing
            _publishedSnapshot = new Lazy <IPublishedSnapshot>(() => publishedSnapshotService.CreatePublishedSnapshot(PreviewToken));

            // set the URLs...
            // NOTE: The request will not be available during app startup so we can only set this to an absolute URL of localhost, this
            // is a work around to being able to access the UmbracoContext during application startup and this will also ensure that people
            // 'could' still generate URLs during startup BUT any domain driven URL generation will not work because it is NOT possible to get
            // the current domain during application startup.
            // see: http://issues.umbraco.org/issue/U4-1890
            //
            OriginalRequestUrl = GetRequestFromContext()?.Url ?? new Uri("http://localhost");
            CleanedUmbracoUrl  = UriUtility.UriToUmbraco(OriginalRequestUrl);
            UrlProvider        = new UrlProvider(this, umbracoSettings.WebRouting, urlProviders, mediaUrlProviders, variationContextAccessor);
        }
Пример #37
0
        public void TransactionUrl()
        {
            foreach (var baseUrl in _baseUrls)
            {
                // Arrange
                var provider = new UrlProvider(baseUrl);
                const string transactionId = " test";

                // Act
                var url = provider.TransactionUrl(transactionId);

                // Assert
                Assert.AreEqual(String.Format("{0}/transactions/{1}", baseUrl.TrimTrailingSlash(), transactionId), url);
            }
        }