/// <summary> /// Returns the QueryString for a specified url /// </summary> /// <param name="url">The Url to pull the QueryString from</param> /// <returns>QueryString</returns> public static QueryString FromUrl(string url) { string[] parts = url.Split("?".ToCharArray()); QueryString qs = new QueryString(); qs.document = parts[0]; if (parts.Length == 1) return qs; string[] keys = parts[1].Split("&".ToCharArray()); foreach (string key in keys) { string[] part = key.Split("=".ToCharArray()); if (part.Length == 1) qs.Add(part[0], ""); else if (part.Length > 1) qs.Add(part[0], part[1]); } return qs; }
private void CreateLanguageDropDownList() { var redirectQs = new QueryString(Page); redirectQs.RemoveParameter("lang"); var jsRedirect = redirectQs.AllUrl; if (redirectQs.Parameters.Count == 0) jsRedirect += "?lang="; else jsRedirect += "&lang="; jsRedirect = HttpUtility.HtmlEncode(jsRedirect); var sb = new StringBuilder(); sb.Append("<form method=\"get\" action=\"" + redirectQs.AllUrl + "\">"); foreach (string key in redirectQs.Parameters.Keys) { sb.Append("<input type=\"hidden\" name=\"" + key + "\" value=\"" + redirectQs[key] + "\" />"); } sb.Append("<select id=\"LanguageDropDownList\" name=\"lang\" onchange=\"javascript:location='" + jsRedirect + "' + this.options[this.selectedIndex].value\" >"); foreach (var language in AvailableLanguages) { var selected = string.Empty; if (language.ISOCode.ToLower() == SelectedLanguage.ToLower()) selected = " selected=\"selected\" "; sb.Append(string.Format("<option value=\"{0}\"" + selected + ">{1}</option>", language.ISOCode, language.Description)); } sb.Append("</select>"); sb.Append("<noscript><input type=\"submit\" value=\">\" /></noscript>"); sb.Append("</form>"); LanguageDropDownListLiteral.Text = sb.ToString(); }
/// <summary> /// Create a new http request header. /// </summary> public HTTPRequest() { QueryString = new QueryString(); }
//// TODO: Add option to include the current querystring //// TODO: Figure out a neat way to provide names arguments public LinkArguments(IEnumerable<string> arguments, bool useLinkName, params string[] switches) : this() { foreach (string sw in switches) this.Switches.Add(sw, false); List<string> parameters = arguments.ToArray().ToList(); if (useLinkName) { this.LinkName = parameters.ElementAt(0); parameters.RemoveAt(0); } foreach (string parameter in parameters) { var temp = new QueryString(parameter); if (temp.Count == 1 && switches.Contains(temp.Keys.Get(0))) { string name = temp.Keys.Get(0); this.Switches[name] = temp[name].ToLower().ContainsAnyOf("yes", "true", "1"); } if (this.QueryString.Count != 0 && this.HashString == null) { this.HashString = parameter.Trim('#'); break; } if (parameter.IndexOf("#") == 0) this.HashString = parameter.Trim('#'); else this.QueryString.Merge(new QueryString(parameter, parameterSeparators)); } }
/// <summary> /// Formats and rewrites the link pattern with the specified <paramref name="linkName" />. /// </summary> /// <param name="linkName">Name of the link.</param> /// <param name="parameters">The parameters.</param> /// <param name="hashString">The hash string.</param> /// <param name="qualify">If set to <c>true</c> the resulting URL will be prefixed with <see cref="ServerPrefix"/>.</param> /// <returns>The full rewritten Url, ready to use</returns> /// <exception cref="ConfigurationError">Current configuration doesn't contain a link with name specified with /// <paramref name="linkName" />.</exception> internal string FormatAndRewriteUrl(string linkName, NameValueCollection parameters, string hashString = null, bool qualify = false) { if (!this.Links.ContainsKey(linkName)) { log.ErrorFormat("The url configuration doesn't contain a url with name '{0}'", linkName); return string.Format("javascript:alert('Unresolved link: {0}')", linkName); } string linkPattern = this.Links[linkName].Value; QueryString formatValues = new QueryString { { "locale", context.Locale }, { "category", context.Category } }; if (parameters != null) formatValues.Merge(parameters); string resultUrl = this.FormatPattern(linkPattern, formatValues); formatValues.Remove("locale"); formatValues.Remove("category"); string queryString = formatValues.ToString(); if (queryString != string.Empty) { string join = resultUrl.Contains("?") ? "&" : "?"; resultUrl = string.Concat(resultUrl, join, queryString); } if (!string.IsNullOrWhiteSpace(hashString)) { string join = resultUrl.Contains("#") ? string.Empty : "#"; resultUrl = string.Concat(resultUrl, join, hashString); } if (qualify) resultUrl = string.Concat(this.ServerPrefix, resultUrl); return resultUrl; }
internal static string GetSelfFunction(SageContext context, params string[] arguments) { var linkArguments = new LinkArguments(arguments, false, "encode", "absolute"); var currentUrl = linkArguments.Switches["absolute"] ? context.Url.RawUrl : context.Url.RawPathAndQuery; var paramQuery = new QueryString(parameterSeparators); if (currentUrl.Contains("?")) { var questionIndex = currentUrl.IndexOf("?", StringComparison.Ordinal); paramQuery.Parse(currentUrl.Substring(questionIndex + 1)); currentUrl = currentUrl.Substring(0, questionIndex); } paramQuery.Merge(linkArguments.QueryString); var result = string.Concat(currentUrl, paramQuery.ToString("?"), string.IsNullOrEmpty(linkArguments.HashString) ? string.Empty : string.Concat("#", linkArguments.HashString)); if (linkArguments.Switches["encode"] && !string.IsNullOrEmpty(result)) result = HttpUtility.UrlEncode(result); return result; }
protected void Page_Load(object sender, EventArgs e) { _queryString = new QueryString(Page); _nodeId = _queryString["NodeID"].ToInt(); var currentDocument = new Document(_nodeId); DocumentDescription.Text = currentDocument.Text; var status = DocumentTranslation.CheckTranslationInfrastructure(_nodeId); if (status == "ok") { if (!IsPostBack) { var languagesToDisplay = Languages.GetLanguages(true); var hideDefaultLanguage = ConfigurationManager.AppSettings["PolyglotHideDefaultLanguageCheckbox"]; if (!string.IsNullOrEmpty(hideDefaultLanguage) && hideDefaultLanguage.ToLower() == "true") { languagesToDisplay.Remove( languagesToDisplay.Single(x => x.CultureAlias == Languages.GetDefaultCulture())); } CheckBoxList1.DataSource = languagesToDisplay; CheckBoxList1.DataValueField = "ISOCode"; CheckBoxList1.DataTextField = "Description"; CheckBoxList1.DataBind(); foreach (ListItem li in CheckBoxList1.Items) { if (DocumentTranslation.TranslationNodeExists(_nodeId, li.Value)) { li.Selected = false; li.Enabled = false; } else { if (li.Value.ToLower() != Languages.GetDefaultLanguage().ToLower()) li.Selected = true; li.Enabled = true; } } } var savedParam = _queryString["saved"].ToStr(); if (!string.IsNullOrEmpty(savedParam)) { switch (savedParam) { case "ok": { ((BasePage) HttpContext.Current.Handler).ClientTools.ShowSpeechBubble( speechBubbleIcon.save, "Successful creation", "Translation documents created. Please reload nodes."); break; } case "NoLangProp": { ((BasePage) HttpContext.Current.Handler).ClientTools.ShowSpeechBubble( speechBubbleIcon.error, "Error", "Creation failed because there is no Label field with the alias 'language' in the translation document type"); break; } default: { ((BasePage) HttpContext.Current.Handler).ClientTools.ShowSpeechBubble( speechBubbleIcon.error, "Error", "There was an error creating the translation documents"); break; } } } } else { PropertyPanel1.Visible = false; PropertyPanel2.Visible = true; ((BasePage) HttpContext.Current.Handler).ClientTools.ShowSpeechBubble(speechBubbleIcon.warning, "Infrastructure issue", status); } }
private static void OnApplicationRequestStart(object sender, EventArgs e) { try { HttpApplication application = (HttpApplication) sender; SageContext context = new SageContext(application.Context); if (File.Exists(context.Request.PhysicalPath)) return; QueryString query = new QueryString(HttpContext.Current.Request.Url.Query); string view = query.GetString(MetaViewDictionary.ParamNameMetaView); if (view != null && !context.ProjectConfiguration.MetaViews.ContainsKey(view)) view = null; //// \.(html|xml|xmlx|htmlx)$ //// Meta view extension gets removed from the path //// Path is rewritten with ?view=$1 string path = MetaExtensionRewriter.MetaViewExpression.Replace(context.Request.Path, delegate(Match m) { if (view == null) view = m.Groups[1].Value; return string.Empty; }); if (view != null) { query.Remove(MetaViewDictionary.ParamNameMetaView); query.Add(MetaViewDictionary.ParamNameMetaView, view); string newUri = new Uri(path + query.ToString("?"), UriKind.RelativeOrAbsolute).ToString(); log.DebugFormat("Rewriting the context path from '{0}' to '{1}'.", context.Request.Path, newUri); application.Context.RewritePath(newUri); } } catch (Exception ex) { log.ErrorFormat("Failed to rewrite path: {0}", ex.Message); } }
public virtual void ProcessRequest(HttpContext HttpContext) { if (!this.IsHttpGet(HttpContext)) { this.RespondForbidden(HttpContext); return; } _HttpContext = HttpContext; _HttpContext.Response.Headers["DataServiceVersion"] = DataServiceVersion; _HttpContext.Response.CacheControl = "no-cache"; _QueryString = new QueryString(); this.CheckDataServiceHeader("DataServiceVersion"); this.CheckDataServiceHeader("MaxDataServiceVersion"); }
/// <summary> /// Substitutes any placeholders in the specified <paramref name="templatePath"/> with values from the current /// <see cref="ProjectConfiguration"/> and the specified <paramref name="values"/>. /// </summary> /// <param name="templatePath">The template path to resolve.</param> /// <param name="values">The name/value collection of values to use</param> /// <returns> /// The substituted version of the specified template with placeholders substituted. /// </returns> public string Substitute(string templatePath, QueryString values) { Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(templatePath)); Contract.Requires<ArgumentNullException>(values != null); if (values["category"] == null) values.Add("category", context.Category); if (values["locale"] == null) values.Add("locale", context.Locale); if (values["assetpath"] == null) values.Add("assetpath", this.GetAssetPath(values["category"])); string result = templatePath; foreach (string key in values) result = result.Replace(string.Format("{{{0}}}", key), values[key]); return result; }
/// <summary> /// Substitutes any placeholders in the specified <paramref name="templatePath"/> with values from the current /// <see cref="ProjectConfiguration"/>, the current <see cref="SageContext"/> and the specified /// <paramref name="category"/>. /// </summary> /// <param name="templatePath">The path to resolve.</param> /// <param name="category">The category to use instead of the current context's category when resolving.</param> /// <returns>The substituted version of the specified <paramref name="templatePath"/>.</returns> public string Substitute(string templatePath, string category) { Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(templatePath)); Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(category)); QueryString values = new QueryString(); values.Add("category", category); values.Add("resourcepath", this.GetAssetPath(category)); return this.Substitute(templatePath, values); }
/// <summary> /// Substitutes any placeholders in the specified <paramref name="templatePath"/> with values from the current /// <see cref="ProjectConfiguration"/> and the specified <paramref name="values"/> and returns an absolute path. /// </summary> /// <param name="templatePath">The template path to resolve.</param> /// <param name="values">The name/value collection of values to use</param> /// <returns> /// The resolved version of the specified template with placeholders substituted. /// </returns> public string Resolve(string templatePath, QueryString values) { var physicalPath = context.MapPath(this.Substitute(templatePath, values)); if (!File.Exists(physicalPath) && !Directory.Exists(physicalPath) && Project.Extensions.Count > 0) { string applicationPath = context.Request.PhysicalApplicationPath; string requestedFile = physicalPath.ToLower() .Replace(applicationPath.ToLower(), string.Empty) .Trim('\\'); foreach (string extensionId in Project.InstallOrder.Reverse()) { if (!Project.Extensions.ContainsKey(extensionId)) continue; string extensionName = Project.Extensions[extensionId].Name; string rewrittenPath = Path.Combine(this.ExtensionPath, extensionName, requestedFile); if (File.Exists(rewrittenPath)) { return rewrittenPath; } } } return physicalPath; }
/// <summary> /// Creates a Sage context using the specified <paramref name="category"/>, <paramref name="locale"/> and <paramref name="query"/>. /// </summary> /// <param name="category">The category to set on the context being created.</param> /// <param name="locale">The locale to set on the context being created.</param> /// <param name="query">The query string of the fake request to create.</param> /// <returns> /// A new <see cref="SageContext"/> instance. /// </returns> public static SageContext CreateSageContext(string category, string locale, QueryString query) { var result = CreateSageContext(string.Format("default.aspx?category={0}&locale={1}", category, locale), Mother.MapPath); result.Query.Merge(query); return result; }