Alternative to System.Web.HttpUtility.ParseQueryString that uses a case-insensitive comparer? - c#

If you include a query string on the HREF of the "Launch" link on the publish.htm page that ClickOnce generates when you publish a Windows desktop application:
HREF="MyWindowsApp.application?ARG1=sis&ARG2=boom&ARG3=bah"
then the query string can be accessed and parsed inside the Windows program:
if (ApplicationDeployment.IsNetworkDeployed)
{
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
nameValueColl = System.Web.HttpUtility.ParseQueryString(queryString);
}
But the NameValueCollection that the HttpUtility parser returns is case-sensitive. A parameter won't be found if you test for it using the wrong case:
if (ApplicationDeployment.IsNetworkDeployed)
{
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
nameValueColl = System.Web.HttpUtility.ParseQueryString(queryString);
if (nameValueColl.AllKeys.Contains("arg1") )
{
// we don't get here
} ​
​}
Is there an alternative to System.Web.HttpUtility.ParseQueryString that uses a case-insensitive comparer?

Related

Add prefix string in URL string

User input the url string in a textbox and I need to add a string "cmd" if not available .
Please suggest how to achieve this,
string cmdUrl = AddPrefix("https://google.com");
static string AddPrefix(string inputUrl)
{
return formattedUrl;// want to return https://cmd.google.com if the string cmd not added already in url
}
First, you can parse your url using var parsedUrl = new Uri(inputUrl).
Then check if the host includes your substring like this: parsedUrl.Host.StartsWith("cmd")
If it does, return your original url else build your new one: $"{parsedUrl.Scheme}://cmd.{parsedUrl.Host}{parsedUrl.PathAndQuery}"

How to use TeamCity parameters to swap out values from a .csx file

we are using a .csx file to store certain parameters for our UI Automation solution such as the browser we want the tests to run on and the Selenium Grid URL. We are also using TeamCity Enterprise 10.0.3 (build 42434) to build and run our tests. I've had a look on the TeamCity documentation but don't really understand how to do it.
Question: How do I configure the build to use parameters to swap out the values stored in the CSX file?
Here is my CSX file (called SettingsData.csx):
string BrowserValue = "chrome";
string BrowserMobileValue = "Samsung Galaxy S4";
string DeviceValue = "Samsung Galaxy S4";
string EnvironmentValue = "Live";
string FeatureBranchValue = "";
string FeatureIdValue = "";
string GridUrlValue = "http://IE-SLM-HUB:5555/wd/hub";
string PlatformValue = "";
string ResolutionValue = "default";
string ScreenWidthValue = "1280";
string ScreenHeightValue = "960";
Dictionary<string, object> SeleniumGridSetupValue = new Dictionary<string, object>
{
{"browserName", "chrome"}
};
Dictionary<string, object> SeleniumGridMobileSetupValue = new Dictionary<string, object>
{
{"browserName", "chrome"}
};
If anyone can provide an example of how I use parameters to swap out one of these values I would greatly appriciate it.
I have found out how to do this, this wouldn't be using parameters at all but would use Build Features and the File Content Replacer feature. Pretty simple to use, you set the file path of the file you want values replaced and a Regex of the initial value and the goal value.

How to update querystring in C#?

Somewhere in the url there is a &sortBy=6 . How do I update this to &sortBy=4 or &sortBy=2 on a button click? Do I need to write custom string functions to create the correct redirect url?
If I just need to append a query string variable I would do
string completeUrl = HttpContext.Current.Request.Url.AbsoluteUri + "&" + ...
Response.Redirect(completeUrl);
But what I want to do is modify an existing querystring variable.
To modify an existing QueryString value use this approach:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly
I go into more detail in another response.
Retrieve the querystring of sortby, then perform string replace on the full Url as follow:
string sUrl = *retrieve the required complete url*
string sCurrentValue = Request.QueryString["sortby"];
sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue);
Let me know how it goes :)
Good luck
private void UpdateQueryString(string queryString, string value)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Set(queryString, value);
isreadonly.SetValue(this.Request.QueryString, true, null);
}
If you really want this you need to redirect to new same page with changed query string as already people answered. This will again load your page,loading page again just for changing querystring that is not good practice.
But Why do you need this?
If you want to change the value of sortBy from 6 to 4 to use everywhere in the application, my suggession is to store the value of query string into some variable or view state and use that view state everywhere.
For e.g.
in Page_Load you can write
if (!IsPostBack)
{
ViewState["SortBy"] = Request.QueryString["sortBy"];
}
and everywhere else ( even after postback ) you can use ViewState["SortBy"]
Based on Ahmad Solution I have created following Method that can be used generally
private string ModifyQueryStringValue(string p_Name, string p_NewValue)
{
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set(p_Name, p_NewValue);
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
return url + updatedQueryString;
}
and then us it as follows
Response.Redirect(ModifyQueryStringValue("SortBy","4"));
You need to redirect to a new URL. If you need to do some work on the server before redirecting there you need to use Response.Redirect(...) in your code. If you do not need to do work on the server just use HyperLink and render it in advance.
If you are asking about constructing the actual URL I am not aware of any built-in functions that can do the job. You can use constants for your Paths and QueryString arguments to avoid repeating them all over your code.
The UriBuilder can help you building the URL but not the query string
You can do it clientside with some javascript to build the query string and redirect the page using windows.open.
Otherwise you can use Response.Redirect or Server.Transfer on the server-side.
SolrNet has some very helpful Url extension methods. http://code.google.com/p/solrnet/source/browse/trunk/SampleSolrApp/Helpers/UrlHelperExtensions.cs?r=512
/// <summary>
/// Sets/changes an url's query string parameter.
/// </summary>
/// <param name="helper"></param>
/// <param name="url">URL to process</param>
/// <param name="key">Query string parameter key to set/change</param>
/// <param name="value">Query string parameter value</param>
/// <returns>Resulting URL</returns>
public static string SetParameter(this UrlHelper helper, string url, string key, string value) {
return helper.SetParameters(url, new Dictionary<string, object> {
{key, value}
});
}
The only way you have to change the QueryString is to redirect to the same page with the new QueryString:
Response.Redirect("YourPage.aspx?&sortBy=4")
http://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.100).aspx
I think you could perform a replacement of the query string in the following fashion on your server side code.
NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("SortBy");
filtered.Add("SortBy","4");
The query string is passed TO the server. You can deal with the query string as a string all you like - but it won't do anything until the page is ready to read it again (i.e. sent back to the server). So if you're asking how to deal with the value of a query string you just simply access it Request.QueryString["key"]. If you're wanting this 'change' in query string to be considered by the server you just need to effectively reload the page with the new value. So construct the url again page.aspx?id=30 for example, and pass this into a redirect method.

How to build a elegant customized URL

i am working on a dashboard page where user will have a multiple choices to select properties and based on the selected properties it will generatea final URL and render.
so let say i have 10 different proprites:
ShowImage=true/false
ShowWindow=true/false
ShowAdmin = true/false
ShowAccounts = true/false
.............
..........
...........
my URL will be static which will be hitting the produciton so there is no change in terms of HOSTNAME.
so here is what i come-up with:
const string URL = "http://www.hostname.com/cont.aspx?id={0}&link={1}&link={2}........";
string.Format(URL, "123","aaa123", "123"............);
but the problem with the above solution is that, regardless it will generate me a long url whether i select or not...
any optimized solution?
You could use the StringBuilder class (System.Text namespace):
StringBuilder sbUrl = new StringBuilder();
sbUrl.AppendFormat("http://www.hostname.com/cont.aspx?id={0}", 123);
if (ShowImage) {
sbUrl.AppendFormat("&link1={0}", "aaa123");
}
if (ShowWindow) {
sbUrl.AppendFormat("&link2={0}", "aaa123");
}
string url = sbUrl.ToString();

Path equivalent in asp.net (C#)?

Whats the equivalent to System.IO.Path ?
I got this url: http://www.website.com/category1/category2/file.aspx?data=123
How can i break this down, like
var url = ASPNETPATH("http://www.website.com/category1/category2/file.aspx?data=123");
url.domain <-- this would then return http://www.website.com
url.folder <-- would return category1/category2
url.file <-- would return file.aspx
url.queryString <-- would return the querystring in some format
Use the UriBuilder class:
http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
UriBuilder uriBuilder = new UriBuilder("http://www.somesite.com/requests/somepage.aspx?i=123");
string host = uriBuilder.Host; // www.somesite.com
string query = uriBuilder.Query; // ?i=123
string path = uriBuilder.Path; // /requests/somepage.aspx
Check out the URI Class you can get all of that information using that class.
Regular expressions are perfect to use for this.
Here's a link that has some nice info on using them.
http://www.regular-expressions.info/
Edit : I forgot C# has a URI class which you can use for this as well.

Categories