private string PreProcess(XhtmlString xhtmlString) { // The store value of an XhtmlString contains placeholder content for certain dynamic content. We want to // pre-load this data to before we send it off to the app. In order to load personalized content, dynamic controls, etc., // we use the following methods to get the "rendered results" of the XhtmlString property var htmlHelper = Helpers.MvcHelper.GetHtmlHelper(); string mvcHtmlResults = EPiServer.Web.Mvc.Html.XhtmlStringExtensions.XhtmlString(htmlHelper, xhtmlString).ToHtmlString(); // replace image URLs with a full URL path string workingResults = Regex.Replace(mvcHtmlResults, "<img(.+?)src=[\"\']/(.+?)[\"\'](.+?)>", "<img $1 src=\"http://ascend-dev.adagetechnologies.com/$2\" $3>"); // find all internal href items var regexMatches = Regex.Matches(mvcHtmlResults, "href=[\"\'](.*?)[\"\']"); var resolver = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<UrlResolver>(); // for each item attempt to determine if they are an internal page link foreach(Match eachUrlMatch in regexMatches) { UrlBuilder eachUrl = new UrlBuilder(eachUrlMatch.Groups[1].Value); var currentRoute = resolver.Route(eachUrl); if (currentRoute != null) { string internalContentLink = string.Format("href=\"index.html#/app/content/{0}\"", currentRoute.ContentLink.ID); workingResults = workingResults.Replace(eachUrlMatch.Value, internalContentLink); } } return workingResults; }
public static SitemapEntry ToSitemapEntry(this PageData page, LanguageSelector language, string bundle) { if (page == null) { return SitemapEntry.Empty; } var urlRewriter = ServiceLocator.Current.GetInstance<IUrlRewriteProviderWrapper>(); var hostBindingsService = ServiceLocator.Current.GetInstance<IHostBindingsService>(); Uri baseUri; baseUri = hostBindingsService.AllBindings().TryGetValue(language.LanguageBranch, out baseUri) ? baseUri : hostBindingsService.DefaultHost(); var location = new UrlBuilder(new Uri(baseUri, page.LinkURL.ToLower())); urlRewriter.GetFriendlyUrl(location, null, Encoding.UTF8); return new SitemapEntry { IsEmpty = false, Location = location.Uri, LastModified = page.Changed, ChangeFrequency = Frequency.Weekly, Priority = 0.5F, Language = language.LanguageBranch, Bundle = !string.IsNullOrWhiteSpace(bundle) ? bundle : Constants.Bundles.Default }; }
/// <summary> /// Handles the AfterSubmitPostedData event of the XFormControl. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EPiServer.XForms.WebControls.SaveFormDataEventArgs"/> instance containing the event data.</param> public void XForm_AfterSubmitPostedData(object sender, SaveFormDataEventArgs e) { XFormControl control = (XFormControl)sender; if (control.FormDefinition.PageGuidAfterPost != Guid.Empty) { PermanentContentLinkMap pageMap = PermanentLinkMapStore.Find(control.FormDefinition.PageGuidAfterPost) as PermanentContentLinkMap; if (pageMap != null) { string internalUrl = pageMap.MappedUrl.ToString(); internalUrl = UriSupport.AddLanguageSelection(internalUrl, ContentLanguage.PreferredCulture.Name); UrlBuilder urlBuilder = new UrlBuilder(internalUrl); //Rewrite the url to make sure that it gets the friendly url if such a provider has been configured. Global.UrlRewriteProvider.ConvertToExternal(urlBuilder, null, Encoding.UTF8); //Always cast UrlBuilders to get a correctly encoded url since ToString() is for "human" readability. control.Page.Response.Redirect((string)urlBuilder); return; } } //After the form has been posted we remove the form elements and add a "thank you message". control.Controls.Clear(); Label label = new Label(); label.CssClass = "thankyoumessage"; label.Text = LocalizationService.Current.GetString("/form/postedmessage"); control.Controls.Add(label); }
public string ConvertUrlToExternal(PageData pageData = null, PageReference p = null) { if (pageData == null && p == null) { return string.Empty; } var page = pageData ?? _repository.Get<PageData>(p); var pageUrlBuilder = new UrlBuilder(page.LinkURL); Global.UrlRewriteProvider.ConvertToExternal(pageUrlBuilder, page.PageLink, Encoding.UTF8); string pageURL = pageUrlBuilder.ToString(); UriBuilder uriBuilder = new UriBuilder(SiteDefinition.Current.SiteUrl); uriBuilder.Path = pageURL; var jj = ServiceLocator.Current.GetInstance<UrlResolver>().GetUrl(p); if (uriBuilder.Path == "/") return uriBuilder.Uri.AbsoluteUri; string[] words = uriBuilder.Uri.AbsoluteUri.Split(new char[] {':', '/', '.'}, StringSplitOptions.RemoveEmptyEntries); bool reoccurs = words.Count(q => q == "http") > 1; if (reoccurs) return uriBuilder.Uri.LocalPath.StartsWith("/") ? uriBuilder.Uri.LocalPath.Remove(0,1) : uriBuilder.Uri.LocalPath; return uriBuilder.Uri.AbsoluteUri; }
/// <summary> /// Serialize to XElement /// </summary> /// <returns></returns> public override XElement Serialize(XNamespace namespaceXForms) { var builder = new UrlBuilder(GetFormAction()); if (this.RecipientEmailAddress != null) { builder.QueryCollection.Add("to", this.RecipientEmailAddress); } if (this.SenderEmailAddress != null) { builder.QueryCollection.Add("from", this.SenderEmailAddress); } if (this.EmailSubject != null) { builder.QueryCollection.Add("subject", this.EmailSubject); } var formElement = new XElement(namespaceXForms + "submit", new XAttribute("action", builder.ToString()), new XAttribute("method", string.Empty), new XAttribute("name", "ctl00$FullRegion$FormControl$ctl11")); var formLabelElement = new XElement(namespaceXForms + "label", this.ButtonText); formElement.Add(formLabelElement); return formElement; }
protected override void OnLoad(EventArgs e) { // We don't want to modify EPiServer's code if it's not a PostBack. if (!Page.IsPostBack) { base.OnLoad(e); return; } var linkinternalurl = Control.FindControlRecursive<InputPageReference>("linkinternalurl"); var linklanguages = Control.FindControlRecursive<DropDownList>("linklanguages"); var activeTab = Control.FindControlRecursive<HtmlInputHidden>("activeTab"); var linktypeinternal = Control.FindControlRecursive<HtmlInputRadioButton>("linktypeinternal"); var request = HttpContext.Current.Request; // Modified parts of EPiServer's HyperlinkProperties.aspx.cs load method below var function = "function CloseAfterPostback(e) {"; if (String.CompareOrdinal(activeTab.Value, "0") == 0 && linktypeinternal.Checked) { var urlBuilder = new UrlBuilder(DataFactory.Instance.GetPage(linkinternalurl.PageLink).StaticLinkURL); var linkLang = request.Form[linklanguages.UniqueID]; if (!string.IsNullOrEmpty(linkLang)) { urlBuilder.QueryCollection["epslanguage"] = linkLang; } var ddlSelectedBookmark = request["ddlBookmarkSelector"]; var bookmarkOrDefault = !BookmarkLocator.DefaultBookmark.Equals(ddlSelectedBookmark) ? string.Concat("#", ddlSelectedBookmark) : string.Empty; function = function + "EPi.GetDialog().returnValue.href = '" + urlBuilder + bookmarkOrDefault + "';"; } Page.ClientScript.RegisterClientScriptBlock(GetType(), "closeafterpostback", function + "EPi.GetDialog().Close(EPi.GetDialog().returnValue);}", true); ((PageBase)Page).ScriptManager.AddEventListener(Page, new CustomEvent(EventType.Load, "CloseAfterPostback")); }
public static string GetFriendlyURL(PageData pageData) { UrlBuilder pageURLBuilder = new UrlBuilder(pageData.LinkURL); EPiServer.Global.UrlRewriteProvider.ConvertToExternal(pageURLBuilder, pageData.PageLink, UTF8Encoding.UTF8); return GetSiteRoot() + pageURLBuilder.Path; }
public string GetNewUrl(string oldUrl) { if(!oldUrl.EndsWith("/")) { oldUrl += "/"; } // lookup Url in DDS var store = typeof(UrlRemapEntity).GetStore(); var foundItem = store.Items<UrlRemapEntity>().FirstOrDefault(i => i.OldUrl.Equals(oldUrl)); if(foundItem != null) { var reference = new PageReference(foundItem.PageId); var pageData = DataFactory.Instance.GetPage(reference); pageData = pageData.GetPageLanguage(foundItem.LanguageBranch); var builder = new UrlBuilder(UriSupport.AddLanguageSelection(pageData.LinkURL, pageData.LanguageBranch)); if(Global.UrlRewriteProvider.ConvertToExternal(builder, pageData.PageLink, Encoding.UTF8)) { return builder.Uri.ToString(); } } return null; }
/// <summary> /// Adds scheme and host to a relative url. /// </summary> /// <param name="input">Url</param> /// <returns>String</returns> public static string GetExternalUrl(this string input) { if (string.IsNullOrWhiteSpace(input)) { return string.Empty; } var siteUri = HttpContext.Current != null ? HttpContext.Current.Request.Url : SiteDefinition.Current.SiteUrl; if (!input.StartsWith("/")) { input = "/" + input; } var urlBuilder = new UrlBuilder(input) { Scheme = siteUri.Scheme, Host = siteUri.Host, Port = siteUri.Port }; return urlBuilder.ToString(); }
/// <summary>Retrieves an individual key from the gamer properties.</summary> /// <returns>Promise resolved when the operation has completed. The attached bundle contains the fetched property. /// As usual with bundles, it can be casted to the proper type you are expecting. /// In case the call fails, the bundle is not attached, the call is marked as failed with a 404 status.</returns> /// <param name="key">The name of the key to be fetched.</param> public Promise<Bundle> GetKey(string key) { UrlBuilder url = new UrlBuilder("/v2.6/gamer/property").Path(domain).Path(key); HttpRequest req = Gamer.MakeHttpRequest(url); return Common.RunInTask<Bundle>(req, (response, task) => { task.PostResult(response.BodyJson["properties"]); }); }
/// <summary>Retrieves an individual key from the key/value system.</summary> /// <returns>Promise resolved when the operation has completed. The attached bundle contains the fetched property. /// As usual with bundles, it can be casted to the proper type you are expecting. /// If the property doesn't exist, the call is marked as failed with a 404 status.</returns> /// <param name="key">The name of the key to be fetched.</param> public Promise<Bundle> GetKey(string key) { UrlBuilder url = new UrlBuilder("/v1/vfs").Path(domain).Path(key); HttpRequest req = Cloud.MakeUnauthenticatedHttpRequest(url); return Common.RunInTask<Bundle>(req, (response, task) => { task.PostResult(response.BodyJson); }); }
/// <summary> /// Retrieves the balance of the user. That is, the amount of "items" remaining after the various executed /// transactions. /// </summary> /// <returns>Promise resolved when the operation has completed. The attached bundle contains the balance. /// You can query the individual items by doing `result.Value["gold"]` for instance.</returns> public Promise<Bundle> Balance() { UrlBuilder url = new UrlBuilder("/v1/gamer/tx").Path(domain).Path("balance"); HttpRequest req = Gamer.MakeHttpRequest(url); return Common.RunInTask<Bundle>(req, (response, task) => { task.PostResult(response.BodyJson); }); }
public void Given_Empty_Parameter_Correct_Url_Is_Generated() { var url = new UrlBuilder(BaseUrl) .WithParameter("limit", null) .Build(); Assert.AreEqual("http://api.dotnetgroup.dev/", url); }
/// <summary>Removes a single key from the user properties.</summary> /// <returns>Promise resolved when the operation has completed.</returns> /// <param name="key">The name of the key to remove.</param> public Promise<Done> RemoveKey(string key) { UrlBuilder url = new UrlBuilder("/v2.6/gamer/property").Path(domain).Path(key); HttpRequest req = Gamer.MakeHttpRequest(url); req.Method = "DELETE"; return Common.RunInTask<Done>(req, (response, task) => { task.PostResult(new Done(response.BodyJson)); }); }
public void Given_Several_Parts_Correct_Url_Is_Generated() { var url = new UrlBuilder(BaseUrl) .WithPart("get") .WithPart(1) .Build(); Assert.AreEqual("http://api.dotnetgroup.dev/get/1", url); }
public void Given_Date_From_And_Limit_Parameter_Correct_Url_Is_Generated() { var url = new UrlBuilder(BaseUrl) .WithParameter("from", "2012-01-01 10:00:00") .WithParameter("limit", 10) .Build(); Assert.AreEqual("http://api.dotnetgroup.dev/?from=2012-01-01%2010:00:00&limit=10", url); }
/// <summary>Dismisses a pending invitation for the current user and the match. Fails if the user has not been invited.</summary> /// <returns>Promise resolved when the operation has completed.</returns> public Promise<Done> DismissInvitation() { UrlBuilder url = new UrlBuilder("/v1/gamer/matches").Path(MatchId).Path("invitation"); HttpRequest req = Gamer.MakeHttpRequest(url); req.Method = "DELETE"; return Common.RunInTask<Done>(req, (response, task) => { task.PostResult(new Done(true, response.BodyJson)); }); }
public Item GetItem(string objectId) { var url = new UrlBuilder(this.baseUrl) .WithPart("get") .WithPart(objectId) .Build(); return this.jsonClient.Get<Item>(url); }
/// <summary>Runs a batch on the server, authenticated as a gamer (gamer-scoped).</summary> /// <returns>Promise resolved when the operation has completed. The attached bundle is the JSON data returned /// by the batch.</returns> /// <param name="batchName">Name of the batch to run, as configured on the server.</param> /// <param name="batchParams">Parameters to be passed to the batch.</param> public Promise<Bundle> Run(string batchName, Bundle batchParams = null) { UrlBuilder url = new UrlBuilder("/v1/gamer/batch").Path(domain).Path(batchName); HttpRequest req = Gamer.MakeHttpRequest(url); req.BodyJson = batchParams ?? Bundle.Empty; return Common.RunInTask<Bundle>(req, (response, task) => { task.PostResult(response.BodyJson); }); }
public void UrlBuilder_TestUrlShouldRemainTheSame_NoAdditionalQueryParameters(string url, string expected) { //Arrange //Act var builder = new UrlBuilder(url); //Assert Assert.AreEqual(expected, builder.ToString()); }
private static void CleanNestedCollections(UrlBuilder current) { var facetQuery = current.QueryList[StorefrontConstants.QueryStrings.Facets]; if (facetQuery != null) { var decodedFacets = HttpUtility.UrlDecode(facetQuery); current.QueryList.AddOrSet(StorefrontConstants.QueryStrings.Facets, decodedFacets); } }
public void UrlBuilderWithVirtualPathUsesVirtualPathUtility() { // Arrange var pagePath = "~/page"; // Act var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null); // Assert Assert.Equal("page", builder.Path); }
public void AddToQueryString_AddsCompleteString_ReturnsValueUrl(string url, string expected, string query) { //Arrange var builder = new UrlBuilder(url); //Act builder.AddToQueryString(query); //Assert Assert.AreEqual(expected, builder.ToString()); }
public IEnumerable<Item> GetItems(StreamFilter filter) { var url = new UrlBuilder(this.baseUrl) .WithParameter("type", filter.Type) .WithParameter("from", filter.From) .WithParameter("to", filter.To) .WithParameter("limit", filter.Limit) .Build(); return this.jsonClient.Get<IEnumerable<Item>>(url); }
/// <exclude /> public static string GetUrl(IMediaFile file, bool isInternal, bool downloadableMedia) { string url = MediaUrls.BuildUrl(file, isInternal ? UrlKind.Internal : UrlKind.Public); if (!downloadableMedia) return url; var urlBuilder = new UrlBuilder(url); urlBuilder["download"] = "true"; return urlBuilder.ToString(); }
public void UrlBuilderConstructorEmptyTest() { UrlBuilder target = new UrlBuilder(); //NOTE: Verify non null construction Assert.IsNotNull(target); Assert.IsTrue(string.IsNullOrEmpty(target.Query)); Assert.IsNotNull(target.QueryString); Assert.AreEqual(0, target.QueryString.Count); }
public string TranslateV2(string word, string target) { const string api = "https://www.googleapis.com/language/translate/v2/languages"; UrlBuilder urlBuilder = new UrlBuilder(api); urlBuilder.Add("key","11111"); urlBuilder.Add("target","en"); urlBuilder.Add("q", word); string resJson = webHelper.Get(urlBuilder); NameValueCollection nameValue = JsonConvert.ToNameValue(resJson); return nameValue["responseData"]; }
public void UrlBuilderUsesPathAsIsIfPathIsAValidUri() { // Arrange var pagePath = "http://www.test.com/page-path"; // Act var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null); // Assert Assert.Equal("http://www.test.com/page-path", builder.Path); }
public string ResolveUrl(LinkItem linkItem) { var result = linkItem.Href; var url = new UrlBuilder(linkItem.ToMappedLink()); int id; if (int.TryParse(url.QueryCollection["id"], out id)) result = ResolveUrl(new ContentReference(id)); return result; }
public void UrlBuilderAppendsObjectParametersToPathWithQueryString() { // Arrange var pagePath = "http://www.test.com/page-path.vbhtml?param=value&baz=biz"; // Act var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { param2 = "param2val" }); // Assert Assert.Equal("http://www.test.com/page-path.vbhtml", builder.Path); Assert.Equal("?param=value&baz=biz¶m2=param2val", builder.QueryString); }
internal BrowserWindow(SessionConfiguration SessionConfiguration, ElementFinder elementFinder, Driver driver, TimingStrategy timingStrategy, Waiter waiter, UrlBuilder urlBuilder, DisambiguationStrategy disambiguationStrategy) : base(SessionConfiguration, elementFinder, driver, timingStrategy, waiter, urlBuilder, disambiguationStrategy) { }
/// <inheritdoc/> public IResponse InvokePOST(UrlBuilder url, HttpContent content, IBindingSession session) { return(Invoke(url, HttpMethod.Post, content, session, null, null, null)); }
public virtual void AddMyAccountMenu <THomePage, THeaderViewModel>(THomePage homePage, THeaderViewModel viewModel) where THeaderViewModel : HeaderViewModel, new() where THomePage : CmsHomePage { var commerceHomePage = homePage as CommerceHomePage; if (commerceHomePage == null) { return; } if (HttpContext.Current != null && !HttpContext.Current.Request.IsAuthenticated) { viewModel.UserLinks = new LinkItemCollection(); return; } var menuItems = new LinkItemCollection(); var filter = new FilterContentForVisitor(); var contact = _customerService.GetCurrentContact(); if (contact != null && contact.FoundationOrganization != null) { var orgLink = new LinkItem { Href = _urlResolver.GetUrl(commerceHomePage.OrganizationMainPage), Text = _localizationService.GetString("My Organization", "My Organization"), Title = _localizationService.GetString("My Organization", "My Organization") }; menuItems.Add(orgLink); } foreach (var linkItem in commerceHomePage.MyAccountCommerceMenu ?? new LinkItemCollection()) { if (!UrlResolver.Current.TryToPermanent(linkItem.Href, out var linkUrl)) { continue; } if (linkUrl.IsNullOrEmpty()) { continue; } var urlBuilder = new UrlBuilder(linkUrl); var content = _urlResolver.Route(urlBuilder); if (content == null || filter.ShouldFilter(content)) { continue; } linkItem.Title = linkItem.Text; menuItems.Add(linkItem); } var signoutText = _localizationService.GetString("/Header/Account/SignOut", "Sign Out"); var link = new LinkItem { Href = "/publicapi/signout", Text = signoutText, Title = signoutText }; link.Attributes.Add("css", "fa-sign-out"); menuItems.Add(link); viewModel.UserLinks.AddRange(menuItems); }
public void FormatRestApiUrl_Validate_Single_Param_Count() { UrlBuilder.FormatRestApiUrl("{0}", null); }
public void FormatRestApiUrl_Null_Url() { UrlBuilder.FormatRestApiUrl(null); }
public CloseIncidentActionLink(IPortalContext portalContext, GridMetadata gridMetadata, int languageCode, CloseIncidentAction action, bool enabled = true, UrlBuilder url = null, string portalName = null) : this(portalContext, languageCode, action, enabled, url, portalName) { if (gridMetadata.CloseIncidentDialog == null) { return; } Modal.CloseButtonCssClass = gridMetadata.CloseIncidentDialog.CloseButtonCssClass; Modal.CloseButtonText = gridMetadata.CloseIncidentDialog.CloseButtonText.GetLocalizedString(languageCode); Modal.CssClass = gridMetadata.CloseIncidentDialog.CssClass; Modal.DismissButtonSrText = gridMetadata.CloseIncidentDialog.DismissButtonSrText.GetLocalizedString(languageCode); Modal.PrimaryButtonCssClass = gridMetadata.CloseIncidentDialog.PrimaryButtonCssClass; Modal.PrimaryButtonText = gridMetadata.CloseIncidentDialog.PrimaryButtonText.GetLocalizedString(languageCode); Modal.Size = gridMetadata.CloseIncidentDialog.Size; Modal.Title = gridMetadata.CloseIncidentDialog.Title.GetLocalizedString(languageCode); Modal.TitleCssClass = gridMetadata.CloseIncidentDialog.TitleCssClass; }
public void FormatRestApiUrl_Empty_Url_Empty_RequestOptions_Null_Param() { UrlBuilder.FormatRestApiUrl(string.Empty, new RequestOptions(), null); }
private void RenderFolderCreator(HtmlTextWriter writer) { var controlMode = SPContext.Current.FormContext.FormMode; writer.AddAttribute(HtmlTextWriterAttribute.Id, "part1"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formtable"); writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.AddStyleAttribute(HtmlTextWriterStyle.MarginTop, "8px"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formlabel"); writer.AddAttribute(HtmlTextWriterAttribute.Width, "190px"); writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-standardheader"); writer.RenderBeginTag(HtmlTextWriterTag.H3); writer.Write("Name"); if (controlMode != SPControlMode.Display) { writer.AddAttribute(HtmlTextWriterAttribute.Title, "This is a required field."); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formvalidation"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(" *"); writer.RenderEndTag(); // span } writer.RenderEndTag(); // h3 writer.RenderEndTag(); // td // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formbody"); writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top"); writer.RenderBeginTag(HtmlTextWriterTag.Td); SPListItem folder = null; if (controlMode != SPControlMode.New) { folder = SPContext.Current.List.GetItemById(Convert.ToInt32(Page.Request.QueryString["ID"], CultureInfo.InvariantCulture)); } if (controlMode == SPControlMode.Display) { var viewUrl = Page.Request.QueryString["Source"]; if (string.IsNullOrEmpty(viewUrl)) { viewUrl = SPContext.Current.List.DefaultViewUrl; } var urlBuilder = new UrlBuilder(viewUrl); urlBuilder.ClearQueryString(); urlBuilder.AddQueryString("RootFolder", folder.Folder.ServerRelativeUrl); writer.AddAttribute(HtmlTextWriterAttribute.Rel, "sp_DialogLinkNavigate"); writer.AddAttribute(HtmlTextWriterAttribute.Href, urlBuilder.ToString()); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(SPEncode.HtmlEncode(folder.Name)); writer.RenderEndTag(); // a } else { writer.RenderBeginTag(HtmlTextWriterTag.Span); if (!Page.IsPostBack && SPContext.Current.FormContext.FormMode == SPControlMode.Edit) { writer.AddAttribute(HtmlTextWriterAttribute.Value, folder.Name); } else { writer.AddAttribute(HtmlTextWriterAttribute.Value, this.folderName); } writer.AddAttribute(HtmlTextWriterAttribute.Title, "Name"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-long"); writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + "$onetidIOFile"); writer.RenderBeginTag(HtmlTextWriterTag.Input); if (!IsValid) { writer.Write("<br/>"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formvalidation"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.AddAttribute("role", "alert"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(this.ErrorMessage); writer.RenderEndTag(); // span writer.RenderEndTag(); // span } writer.RenderEndTag(); // input writer.RenderEndTag(); // span } writer.RenderEndTag(); // td writer.RenderEndTag(); // tr writer.RenderEndTag(); // table // Table writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formline"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write("<img width=\"1\" height=\"1\" alt=\"\" src=\"/_layouts/images/blank.gif\" complete=\"complete\"/>"); writer.RenderEndTag(); // td writer.RenderEndTag(); // tr writer.RenderEndTag(); // table // Table writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingTop, "7px"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); writer.RenderBeginTag(HtmlTextWriterTag.Td); // Table writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-formtoolbar"); writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "2"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); // Td writer.RenderBeginTag(HtmlTextWriterTag.Td); if (controlMode == SPControlMode.New) { writer.Write(" "); } else { this.createdModifiedInfo.ControlMode = controlMode; this.createdModifiedInfo.RenderControl(writer); } writer.RenderEndTag(); // td // Td writer.AddAttribute(HtmlTextWriterAttribute.Width, "99%"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write("<img width=\"1\" height=\"18\" alt=\"\" src=\"/_layouts/images/blank.gif\" complete=\"complete\"/>"); writer.RenderEndTag(); // td if (controlMode == SPControlMode.Display) { // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar"); writer.RenderBeginTag(HtmlTextWriterTag.Td); RenderButton(writer, "Close", "C", "SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, null);"); writer.RenderEndTag(); // td } else { // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar"); writer.RenderBeginTag(HtmlTextWriterTag.Td); RenderButton(writer, "Save", "O", Page.ClientScript.GetPostBackEventReference(this, "ADD_OR_EDIT_FOLDER")); writer.RenderEndTag(); // td // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-separator"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(" "); writer.RenderEndTag(); // td // Td writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar"); writer.RenderBeginTag(HtmlTextWriterTag.Td); RenderButton(writer, "Cancel", "C", "SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, null);"); writer.RenderEndTag(); // td } writer.RenderEndTag(); // tr writer.RenderEndTag(); // table writer.RenderEndTag(); // td writer.RenderEndTag(); // tr writer.RenderEndTag(); // table writer.RenderEndTag(); // div writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.Write("SetUploadPageTitle();"); writer.RenderEndTag(); // script }
public void FormatRestApiUrl_Params_Require_UrlEncode() { string result = UrlBuilder.FormatRestApiUrl("url/{0}?t={1}", null, "f$2%=1+1", "{2nd}"); Assert.IsTrue(result.Equals("url/f%242%25%3D1%2B1?t=%7B2nd%7D", StringComparison.InvariantCultureIgnoreCase)); }
public ActionResult ListSearchPlace(int id, string slug, int?page) { var model = new SearchViewModel(); var places = CacheService.GetOrSet("places_v8", () => _db.PlaceRepository.GetAll().ToList()); var place = places.Where(p => p.Id == id).FirstOrDefault <Place>(); int pageIndex = page == 0 || page == null ? 1 : page.Value; int pageSize = 20; string sort = Request.QueryString["sort"]; string filterQuery = Request.QueryString["filter"]; string filter = SearchHelper.GetCompleteSearchFilter(filterQuery); if (place != null) { string placename = GetPlaceDisplayName(place, Request.Url.Host); string url = UrlBuilder.PlaceUrl(place.Id, placename.Trim().Replace(" ", "-").Replace("/", "-").ToLower(), Resources.Resources.Slug_Search_Start, sort, filterQuery); if (placename.Trim().Replace(" ", "-").Replace("/", "-").ToLower() != slug) { return(RedirectPermanent(url)); } model.PlaceName = placename; model.Url = string.Format("http://{0}{1}", Request.Url.Host, url); _placeIds.Add(place.Id.ToString()); GetPlaceIds(place.Id, places); var breadcrumbs = new List <BreadCrumbItem>(); breadcrumbs = GetBreadCrumbs(GetPlaceDisplayName(place, model.Host)); model.BreadCrumbs = breadcrumbs; model.Header = string.Format("{0} - {1}", Resources.Resources.Header_SearchPlace, GetPlaceHeader(place.Id)); model.PageTitle = Resources.Resources.Header_SearchPlace + ", " + GetPlaceHeader(place.Id); } else { return(Redirect("/" + Resources.Resources.Url_FindHouse)); } var countries = places.Where(c => c.PlaceTypeId == 1).OrderBy(c => c.Name); var listCountries = new List <PlaceItem>(); foreach (var c in countries) { string c_placename = GetPlaceDisplayName(c, Request.Url.Host); listCountries.Add(new PlaceItem() { Id = c.Id, DisplayName = c_placename, Url = UrlBuilder.PlaceUrl(c.Id, c_placename.Trim().Replace(" ", "-").Replace("/", "-").ToLower(), Resources.Resources.Slug_Search_Start) }); } model.Countries = listCountries; model.PlaceId = id; int skip = (pageIndex - 1) * pageSize; string sortIndex = string.Empty; if (!string.IsNullOrEmpty(sort)) { sortIndex = sort.Contains("_") ? sort.Replace("_", " ") : sort; model.SearchSort = sort; } if (!string.IsNullOrEmpty(filter)) { model.SearchFilter = filterQuery; } var searchResult = _productSearch.Search(_placeIds, skip, sortIndex, filter); var result = searchResult.Results; if (result != null && result.Count > 0) { foreach (var p in result) { _placeProducts.Add(SetProductData(p.Document)); } } int total = searchResult.Count.HasValue ? int.Parse(searchResult.Count.Value.ToString()) : 0; int pageStart = ((pageIndex - 1) * pageSize) + 1; int spanStop = pageIndex * pageSize; int pageStop = spanStop > total ? total : spanStop; model.PageSize = pageSize; model.PageIndex = pageIndex; model.Products = _placeProducts; model.ProductCount = total; model.PageStart = pageStart; model.PageStop = pageStop; model.MapObjects = GetMapObjects(_placeProducts); model.PlaceDescription = model.Host.Contains("mowido.se") ? GetPlaceDescriptionSV(place, places) : string.Empty; model.PlaceDescTitle = !string.IsNullOrEmpty(model.PlaceDescription) ? _placeDescTitle : string.Empty; return(View(model)); }
/// <inheritdoc/> public IResponse InvokeGET(UrlBuilder url, IBindingSession session) { return(Invoke(url, HttpMethod.Get, null, session, null, null, null)); }
private IResponse Invoke(UrlBuilder url, HttpMethod method, HttpContent content, IBindingSession session, long?offset, long?length, IDictionary <string, string> headers) { if (Logger.IsDebugEnabled) { Logger.Debug("HTTP: " + method.ToString() + " " + url.ToString()); } IPortableAuthenticationProvider authProvider = session.GetAuthenticationProvider() as IPortableAuthenticationProvider; HttpClient httpClient = session.GetValue(InvokerHttpClient) as HttpClient; if (httpClient == null) { lock (invokerLock) { httpClient = session.GetValue(InvokerHttpClient) as HttpClient; if (httpClient == null) { // create a HTTP client handler HttpClientHandler httpClientHandler = null; if (authProvider != null) { httpClientHandler = authProvider.CreateHttpClientHandler(); } if (httpClientHandler == null) { httpClientHandler = new HttpClientHandler(); } // redirects if (httpClientHandler.SupportsRedirectConfiguration) { httpClientHandler.AllowAutoRedirect = false; } // compression if (httpClientHandler.SupportsAutomaticDecompression) { string compressionFlag = session.GetValue(SessionParameter.Compression) as string; if (compressionFlag != null && compressionFlag.ToLowerInvariant().Equals("true")) { httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } } // authentication httpClientHandler.PreAuthenticate = true; httpClientHandler.UseDefaultCredentials = false; // authentication provider if (authProvider != null) { authProvider.PrepareHttpClientHandler(httpClientHandler); } // create HttpClient httpClient = new HttpClient(httpClientHandler, true); // timeouts int connectTimeout = session.GetValue(SessionParameter.ConnectTimeout, -2); if (connectTimeout >= -1) { httpClient.Timeout = TimeSpan.FromMilliseconds(connectTimeout); } session.PutValue(InvokerHttpClient, httpClient); } } } HttpRequestMessage request = new HttpRequestMessage(method, url.ToString()); // set additional headers string userAgent = session.GetValue(SessionParameter.UserAgent) as string; request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(userAgent ?? ClientVersion.UserAgent)); if (headers != null) { foreach (KeyValuePair <string, string> header in headers) { request.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // range if (offset != null && length != null) { long longOffset = offset.Value < 0 ? 0 : offset.Value; if (length.Value > 0) { request.Headers.Range = new RangeHeaderValue(longOffset, longOffset + length.Value - 1); } else { request.Headers.Range = new RangeHeaderValue(longOffset, null); } } else if (offset != null && offset.Value > 0) { request.Headers.Range = new RangeHeaderValue(offset, null); } // content if (content != null) { request.Headers.TransferEncodingChunked = true; request.Content = content; } // authentication provider if (authProvider != null) { authProvider.PrepareHttpRequestMessage(request); } Response response; try { Task <HttpResponseMessage> task = Send(httpClient, request); if (task.IsFaulted) { throw task.Exception; } else { HttpResponseMessage httpResponseMessage = task.Result; if (authProvider != null) { authProvider.HandleResponse(httpResponseMessage); } response = new Response(httpResponseMessage); } } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.Message, e); } return(response); }
/// <inheritdoc/> public IResponse InvokeDELETE(UrlBuilder url, IBindingSession session) { return(Invoke(url, HttpMethod.Delete, null, session, null, null, null)); }
/// <inheritdoc/> public IResponse InvokePUT(UrlBuilder url, IDictionary <string, string> headers, HttpContent content, IBindingSession session) { return(Invoke(url, HttpMethod.Put, content, session, null, null, headers)); }
/// <exclude /> public static bool GetPreviewInformation(HttpContext context, Guid pageId, Guid templateId, out string imageFilePath, out PlaceholderInformation[] placeholders) { int updateHash = BrowserRender.GetLastCacheUpdateTime(RenderingMode).GetHashCode(); string requestUrl = new UrlBuilder(context.Request.Url.ToString()).ServerUrl + ServiceUrl + "?p=" + pageId + "&t=" + templateId + "&hash=" + updateHash; BrowserRender.RenderingResult result = null; var renderTask = BrowserRender.RenderUrlAsync(context, requestUrl, RenderingMode); renderTask.Wait(10000); if (renderTask.Status == TaskStatus.RanToCompletion) { result = renderTask.Result; } if (result == null) { imageFilePath = null; placeholders = null; return(false); } if (result.Status != BrowserRender.RenderingResultStatus.Success) { Log.LogWarning("PageTemplatePreview", "Failed to build preview for page template '{0}'. Reason: {1}; Output:\r\n{2}", templateId, result.Status, result.Output); imageFilePath = null; placeholders = null; return(false); } imageFilePath = result.FilePath; string output = result.Output; var pList = new List <PlaceholderInformation>(); string templateInfoPrefix = "templateInfo:"; if (output.StartsWith(templateInfoPrefix)) { foreach (var infoPart in output.Substring(templateInfoPrefix.Length).Split('|')) { string[] parts = infoPart.Split(','); Verify.That(parts.Length == 5, "Incorrectly serialized template part info: " + infoPart); int left = Int32.Parse(parts[1]); int top = Int32.Parse(parts[2]); int width = Int32.Parse(parts[3]); int height = Int32.Parse(parts[4]); var zoom = 1.0; pList.Add(new PlaceholderInformation { PlaceholderId = parts[0], ClientRectangle = new Rectangle(left, top, width, height), ClientRectangleWithZoom = new Rectangle( (int)Math.Round(zoom * left), (int)Math.Round(zoom * top), (int)Math.Round(zoom * width), (int)Math.Round(zoom * height)) }); } } placeholders = pList.ToArray(); return(true); }
private static string ToQueryString(IEnumerable <KeyValuePair <string, string> > queryString) { var encodedPairs = new List <string>(); foreach (var qs in queryString) { encodedPairs.Add(string.Format("{0}={1}", UrlBuilder.EncodeParameter(qs.Key), UrlBuilder.EncodeParameter(qs.Value))); } return(string.Join("&", encodedPairs.ToArray())); }
/// <summary> /// Gets the modifications. /// </summary> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <returns></returns> /// <remarks></remarks> public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to) { var revisionData = NameValuePair.ToDictionary(from.SourceControlData); if (to.LastIntegrationStatus == IntegrationStatus.Unknown) { ((SvnHistoryParser)historyParser).IntegrationStatusUnknown = true; } string wd = Path.GetFullPath(to.BaseFromWorkingDirectory(WorkingDirectory)); if (WorkingFolderIsKnownAsSvnWorkingFolder(wd)) { if (CleanUp) { Execute(CleanupWorkingCopy(to)); } if (Revert) { Execute(RevertWorkingCopy(to)); } if (this.DeleteObstructions) { this.DeleteObstructionsFromWorking(to); } } else { Util.Log.Warning(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} is not a svn working folder", wd)); } List <Modification> modifications = new List <Modification>(); List <string> repositoryUrls = new List <string>(); repositoryUrls.Add(TrunkUrl); if (CheckExternals) { ProcessResult resultOfSvnPropget = Execute(PropGetProcessInfo(to)); List <string> externals = ParseExternalsDirectories(resultOfSvnPropget); foreach (string external in externals) { if (!repositoryUrls.Contains(external)) { repositoryUrls.Add(external); } } } foreach (string repositoryUrl in repositoryUrls) { var lastRepositoryRevisionName = "SVN:LastRevision:" + repositoryUrl; Modification[] modsInRepository; string lastRepositoryRevision = null; if (UseRevsionNumbers) { // Since we are using the last revision number, see if there is any number stored to use lastRepositoryRevision = revisionData.ContainsKey(lastRepositoryRevisionName) ? revisionData[lastRepositoryRevisionName] : null; ProcessResult result = Execute(NewHistoryProcessInfoFromRevision(lastRepositoryRevision, to, repositoryUrl)); modsInRepository = ParseModifications(result, lastRepositoryRevision); } else { // Use use the date range ProcessResult result = Execute(NewHistoryProcessInfo(from, to, repositoryUrl)); modsInRepository = ParseModifications(result, from.StartTime, to.StartTime); } // If there are modifications, get the number and add them to the output if (modsInRepository != null) { lastRepositoryRevision = Modification.GetLastChangeNumber(modsInRepository) ?? lastRepositoryRevision; modifications.AddRange(modsInRepository); revisionData[lastRepositoryRevisionName] = lastRepositoryRevision; } // Set the latest revision - this always need to be done just in case an external has triggered a build if (repositoryUrl == TrunkUrl) { latestRevision = int.Parse(lastRepositoryRevision ?? "0", CultureInfo.CurrentCulture); revisionData[lastRepositoryRevisionName] = lastRepositoryRevision; } } mods = modifications.ToArray(); if (UrlBuilder != null) { UrlBuilder.SetupModification(mods); } FillIssueUrl(mods); // Store the latest revision number to.SourceControlData.Clear(); NameValuePair.Copy(revisionData, to.SourceControlData); return(mods); }
public static UrlBuilder <T> NextPage <T>(this UrlBuilder <T> builder) where T : class, IPageable { return(builder.With(x => x.Page, builder.Request.Page + 1)); }
public void FormatRestApiUrl_Simple_Url_Empty_RequestOptions() { string result = UrlBuilder.FormatRestApiUrl("none", new RequestOptions()); Assert.AreEqual("none", result); }
public static Uri GetEndpointUrl(this IRabbitMQConfiguration configuration, Uri address, string queue) => UrlBuilder.GetEndpointUrl(address, UrlBuilder.GetRoute(configuration.RabbitMQName, queue));
public void FormatRestApiUrl_Validate_Multiple_Param_Count() { UrlBuilder.FormatRestApiUrl("{1}", null, "", "2nd"); }
/// <summary> /// Get relative url for global assets /// </summary> /// <param name="assetName"></param> /// <returns></returns> public string GetGlobalAssetAbsoluteUrl(string assetName) { return(UrlBuilder.ToAppAbsolute(_globalThemeAssetsRelativeUrl.TrimEnd('/') + "/" + assetName.TrimStart('/'), WorkContext.CurrentStore, WorkContext.CurrentLanguage)); }
public void FormatRestApiUrl_Empty_Url_Empty_RequestOptions() { string result = UrlBuilder.FormatRestApiUrl(string.Empty, new RequestOptions()); Assert.AreEqual(string.Empty, result); }
// For testing public virtual Task PerformConnect() { return(PerformConnect(UrlBuilder.BuildConnect(_connection, Name, _connectionData))); }
public void Test__Lifecycle() { IPatch[] patches = new IPatch[] { Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), Substitute.For <IPatch>(), }; UrlDir.UrlConfig urlConfig = UrlBuilder.CreateConfig("abc/def", new ConfigNode("NODE")); patches[00].PassSpecifier.Returns(new InsertPassSpecifier()); patches[01].PassSpecifier.Returns(new InsertPassSpecifier()); patches[02].PassSpecifier.Returns(new FirstPassSpecifier()); patches[03].PassSpecifier.Returns(new FirstPassSpecifier()); patches[04].PassSpecifier.Returns(new LegacyPassSpecifier()); patches[05].PassSpecifier.Returns(new LegacyPassSpecifier()); patches[06].PassSpecifier.Returns(new BeforePassSpecifier("mod1", urlConfig)); patches[07].PassSpecifier.Returns(new BeforePassSpecifier("MOD1", urlConfig)); patches[08].PassSpecifier.Returns(new ForPassSpecifier("mod1", urlConfig)); patches[09].PassSpecifier.Returns(new ForPassSpecifier("MOD1", urlConfig)); patches[10].PassSpecifier.Returns(new AfterPassSpecifier("mod1", urlConfig)); patches[11].PassSpecifier.Returns(new AfterPassSpecifier("MOD1", urlConfig)); patches[12].PassSpecifier.Returns(new LastPassSpecifier("mod1")); patches[13].PassSpecifier.Returns(new LastPassSpecifier("MOD1")); patches[14].PassSpecifier.Returns(new BeforePassSpecifier("mod2", urlConfig)); patches[15].PassSpecifier.Returns(new BeforePassSpecifier("MOD2", urlConfig)); patches[16].PassSpecifier.Returns(new ForPassSpecifier("mod2", urlConfig)); patches[17].PassSpecifier.Returns(new ForPassSpecifier("MOD2", urlConfig)); patches[18].PassSpecifier.Returns(new AfterPassSpecifier("mod2", urlConfig)); patches[19].PassSpecifier.Returns(new AfterPassSpecifier("MOD2", urlConfig)); patches[20].PassSpecifier.Returns(new LastPassSpecifier("mod2")); patches[21].PassSpecifier.Returns(new LastPassSpecifier("MOD2")); patches[22].PassSpecifier.Returns(new LastPassSpecifier("mod3")); patches[23].PassSpecifier.Returns(new FinalPassSpecifier()); patches[24].PassSpecifier.Returns(new FinalPassSpecifier()); patches[00].CountsAsPatch.Returns(false); patches[01].CountsAsPatch.Returns(false); patches[02].CountsAsPatch.Returns(true); patches[03].CountsAsPatch.Returns(true); patches[04].CountsAsPatch.Returns(true); patches[05].CountsAsPatch.Returns(true); patches[06].CountsAsPatch.Returns(true); patches[07].CountsAsPatch.Returns(true); patches[08].CountsAsPatch.Returns(true); patches[09].CountsAsPatch.Returns(true); patches[10].CountsAsPatch.Returns(true); patches[11].CountsAsPatch.Returns(true); patches[12].CountsAsPatch.Returns(true); patches[13].CountsAsPatch.Returns(true); patches[14].CountsAsPatch.Returns(true); patches[15].CountsAsPatch.Returns(true); patches[16].CountsAsPatch.Returns(true); patches[17].CountsAsPatch.Returns(true); patches[18].CountsAsPatch.Returns(true); patches[19].CountsAsPatch.Returns(true); patches[20].CountsAsPatch.Returns(true); patches[21].CountsAsPatch.Returns(true); patches[22].CountsAsPatch.Returns(true); patches[23].CountsAsPatch.Returns(true); patches[24].CountsAsPatch.Returns(true); IPatchProgress progress = Substitute.For <IPatchProgress>(); PatchList patchList = new PatchList(new[] { "mod1", "mod2" }, patches, progress); IPass[] passes = patchList.ToArray(); Assert.Equal(13, passes.Length); Assert.Equal(":INSERT (initial)", passes[0].Name); Assert.Equal(new[] { patches[0], patches[1] }, passes[0]); Assert.Equal(":FIRST", passes[1].Name); Assert.Equal(new[] { patches[2], patches[3] }, passes[1]); Assert.Equal(":LEGACY (default)", passes[2].Name); Assert.Equal(new[] { patches[4], patches[5] }, passes[2]); Assert.Equal(":BEFORE[MOD1]", passes[3].Name); Assert.Equal(new[] { patches[6], patches[7] }, passes[3]); Assert.Equal(":FOR[MOD1]", passes[4].Name); Assert.Equal(new[] { patches[8], patches[9] }, passes[4]); Assert.Equal(":AFTER[MOD1]", passes[5].Name); Assert.Equal(new[] { patches[10], patches[11] }, passes[5]); Assert.Equal(":BEFORE[MOD2]", passes[6].Name); Assert.Equal(new[] { patches[14], patches[15] }, passes[6]); Assert.Equal(":FOR[MOD2]", passes[7].Name); Assert.Equal(new[] { patches[16], patches[17] }, passes[7]); Assert.Equal(":AFTER[MOD2]", passes[8].Name); Assert.Equal(new[] { patches[18], patches[19] }, passes[8]); Assert.Equal(":LAST[MOD1]", passes[9].Name); Assert.Equal(new[] { patches[12], patches[13] }, passes[9]); Assert.Equal(":LAST[MOD2]", passes[10].Name); Assert.Equal(new[] { patches[20], patches[21] }, passes[10]); Assert.Equal(":LAST[MOD3]", passes[11].Name); Assert.Equal(new[] { patches[22] }, passes[11]); Assert.Equal(":FINAL", passes[12].Name); Assert.Equal(new[] { patches[23], patches[24] }, passes[12]); progress.Received(23).PatchAdded(); }
/// <summary> /// Gets the Game Starting Lineup. /// </summary> /// <param name="league">The league.</param> /// <param name="year">The year.</param> /// <param name="seasonType">Type of the season.</param> /// <param name="requestOptions">The request options.</param> /// <returns></returns> public async Task <GameStartingLineupResponse> Get(int year, SeasonType seasonType, RequestOptions requestOptions = null) { string requestUrl = UrlBuilder.FormatRestApiUrl(Url, year, seasonType, requestOptions); return(await _httpWorker.GetAsync <GameStartingLineupResponse>(requestUrl).ConfigureAwait(false)); }
public void UrlParseTest1() { var ub = new UrlBuilder(_url1); Assert.AreEqual("someplace.com", ub.Host); }
public async Task <ActionResult> BlogRssFeed(string blogName) { Blog blog = WorkContext.Blogs.FirstOrDefault(); if (!string.IsNullOrEmpty(blogName)) { WorkContext.CurrentBlog = WorkContext.Blogs.FirstOrDefault(x => x.Name.EqualsInvariant(blogName)); } if (blog == null) { return(NotFound()); } var feedItems = new List <SyndicationItem>(); foreach (var article in blog.Articles.OrderByDescending(a => a.PublishedDate)) { if (!string.IsNullOrEmpty(article.Url)) { var urlString = UriHelper.GetDisplayUrl(Request); var requestUri = new Uri(urlString); var baseUri = new Uri(requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host); var fullUrl = new Uri(baseUri, UrlBuilder.ToAppAbsolute(article.Url, WorkContext.CurrentStore, WorkContext.CurrentLanguage)); var syndicationItem = new SyndicationItem() { Title = article.Title, Description = article.Excerpt, Published = article.PublishedDate.HasValue ? new DateTimeOffset(article.PublishedDate.Value) : new DateTimeOffset() }; syndicationItem.AddLink(new SyndicationLink(fullUrl)); feedItems.Add(syndicationItem); } } var sw = new StringWriter(); using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(blog.Title); await writer.WriteDescription(blog.Title); await writer.Write(new SyndicationLink(new Uri(blog.Url, UriKind.Relative))); foreach (var item in feedItems) { await writer.Write(item); } xmlWriter.Flush(); } return(Content(sw.ToString(), "text/xml")); }
/// <inheritdoc/> public IResponse InvokeGET(UrlBuilder url, IBindingSession session, long?offset, long?length) { return(Invoke(url, HttpMethod.Get, null, session, offset, length, null)); }
public void FormatRestApiUrl_Empty_Url() { string result = UrlBuilder.FormatRestApiUrl(string.Empty); Assert.AreEqual(string.Empty, result); }