How to to find a domain name inside a query string value - asp.net

I think regular expressions might be able to accomplish this, if not then string manipulation is also a viable solution.
I need to turn the following inputs:
"http://open.thumbshots.org/image.pxf?url=www.party.com"
"http://www.xclicks.net/sc/ct.php?s=9971&l=http%3A//www.google.com/imgres%3F"
"http://whos.amung.us/pingjs/?k=yvybju40twbs&t=Mudswimmer%3A%20Spam%20%26%20Crap%3A%20Http%3AUniversity.com%3A%20No%20Animals%20Allowed..&c=c&y=htt"
into the following outputs:
"party.com"
"google.com"
"University.com"
I am not trying to get the host name of the URL, I want the the second domain, the one in the query string.

With everything that involves regular expressions there is a degree of uncertainty, for me at least, but giving your three inputs the following code works:
string[] urls = new string[]
{
"http://open.thumbshots.org/image.pxf?url=www.party.com",
"http://www.xclicks.net/sc/ct.php?s=9971&l=http%3A//www.google.com/imgres%3F",
"http://whos.amung.us/pingjs/?k=yvybju40twbs&t=Mudswimmer%3A%20Spam%20%26%20Crap%3A%20Http%3AUniversity.com%3A%20No%20Animals%20Allowed..&c=c&y=htt"
};
foreach (var url in urls)
{
var result = HttpUtility.ParseQueryString(new Uri(url, UriKind.Absolute).Query);
foreach (string item in result)
{
string value = result.GetValues(item).Single();
const string DomainNamePattern = "(?:www\\.|\\b)(?<domain>([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)+((a[cdefgilmnoqrstuwxz]|aero|arpa)|(b[abdefghijmnorstvwyz]|biz)|(cat|com|coop|c[acdfghiklmnorsuvxyz])|d[ejkmoz]|(e[ceghrstu]|edu)|f[ijkmor]|(g[abdefghilmnpqrstuwy]|gov)|h[kmnrtu]|(i[delmnoqrst]|info|int)|(j[emop]|jobs)|k[eghimnprwyz]|l[abcikrstuvy]|(m[acdghklmnopqrstuvwxyz]|mil|mobi|museum)|(n[acefgilopruz]|name|net)|(om|org)|(p[aefghklmnrstwy]|pro)|qa|r[eouw]|s[abcdeghijklmnortvyz]|(t[cdfghjklmnoprtvwz]|travel)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))";
var match = Regex.Match(
value,
DomainNamePattern,
RegexOptions.IgnoreCase);
if (match.Success)
{
string domain = match.Groups["domain"].Value;
Console.WriteLine(domain);
}
}
}
The regular expression used was adapted from here.
If you run this you get the following output:
// party.com
// google.com
// University.com

If your link always contain the url querystring key then you can simple get this by
String url = Request.QueryString["url"].ToString();
This will retrun the value of url.

Related

How to break url into multiple string parts

I have a url that is hold the complete path of my SSRS Report . In C# i want to break the url in multiple string
http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF
Here i want to break this url into part-1 http://Mydatabase-live/ReportServer part-2 ADMIN/STATS-SCHEDULE and part-3 TEAMNM
I thought about this and one way to do it is to define some delimiters for the program to know where to break the URL.
Before we do this, we need to replace the special characters first.
So let's start:
string searchFor;
string replaceWith;
static void Main(string[] args)
{
// First we need to replace the special characters:
ReplaceSubstrings replace = new ReplaceSubstrings();
string s = "http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF";
// We need to replace:
// "%2f" with "/"
// "+-+" with "-"
// using System.Text.RegularExpressions
replace.searchFor = "%2f";
replace.replaceWith = "/";
s = Regex.Replace(s, replace.searchFor);
replace.searchFor = "+-+";
replace.replaceWith = "-";
s = Regex.Replace(s, replace.searchFor);
// Your URL will now look like this:
Console.WriteLine(s);
// Output: http://Mydatabase-live/ReportServer?/ADMIN/STATS-SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF
// Add the delimiters
char[] delimiters = {'?', '&', '='};
string[] words = s.Split(delimiters);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
// Output:
// http://Mydatabase-live/ReportServer
// /ADMIN/STATS-SCHEDULE
// TEAMNM
// 2015 TERRIER JV
// rs:Command
// Render
// rs:Format
// PDF
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Your URL will be separated in much more places than you specified, but this is how you should do it. You could delete the last part from the string where the first = sign is located, and then execute the string separation.
I hope this helped you.
This is dynamic way of splitting the URL using Uri Class.
Uri class has the feature to get absolute path,query and etc. You can use them and construct your requirement.
string path = "http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF";
Uri uri = new Uri(path);
Console.WriteLine(uri.AbsolutePath); //Absolute path
Console.WriteLine(uri.Query); //Query

change query string values without redirect in c#

I have a query string that looks something like this:
"somename1=123&QueryString=PlaceHolder%3dNothing%26anotherid%3dsomevalue&somename=somevalue"
but I want the query string to be something like the query string below and replace the whole query string with the updated one is there any way to do that without redirection?
"somename1=somevalue1&PlaceHolder=Nothing&somename2=somevalue2&somename3=somevalue3"
basically need to remove:
"QueryString=" with empty string
"%3d" with "&"
"%26" with "="
So far I've done is:
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
strQueryString = strQueryString.Replace("QueryString=", "");
if (strQueryString.Contains("%26")) strQueryString = strQueryString.Replace("%26", "&");
if (strQueryString.Contains("%3d")) strQueryString = strQueryString.Replace("%3d", "=");
string x = strQueryString;
}
and:
// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
if (this.Request.QueryString.ToString().Contains("QueryString="))
{
this.Request.QueryString.ToString().Replace("QueryString=", "");
if (this.Request.QueryString.ToString().Contains("%26")) this.Request.QueryString.ToString().Replace("%26", "&");
if (this.Request.QueryString.ToString().Contains("%3d")) this.Request.QueryString.ToString().Replace("%3d", "=");
string x = this.Request.QueryString.ToString();
}
// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
The second part of the code is not replacing the characters and I don't know how after removing all character or replacing them change the query string to new query string.
Any help is greatly appreciated.
Changing the query string of the current request is not supported. Using private Reflection to edit some in-memory state will most likely break ASP.NET because it assumes that the query string is immutable. The only way to change the query string is to issue a new request, either by doing a redirect, or by doing a sort of sub-request, such as by making a new HTTP request to the same page but with a different query string.
May I suggest a not very well known built in key/value dictionary, Context.Items.
With this you very like get a better performance than toggle the readonly QueryString object, and it also last throughout a request so you can share it between module, handlers, etc.
Create
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
HttpContext.Current.Items("qs") = strQueryString.Replace("QueryString=", "").Replace("%26", "&").Replace("%3d", "=");
}
Use
string x = HttpContext.Current.Items("qs_d").ToString();
Side note: I shortened you code some, as there is no need to first check if anything contains and if so, replace, just run replace, it will be faster

changing the Request.QueryString value

how can i modified the querystring?
I have capture the query string like this
qs = Request.QueryString["flag"].ToString();
and then rebuilt the query string with modified values
and response.redirect(url & qs) to it
While I'm not sure I'd suggest using this approach liberally, if you wanted to reconstruct the path and query string with a few changes... you could convert the query string to an editable collection, modify it, then rebuild it from your new collection.
Goofy example...
// create dictionary (editable collection) of querystring
var qs = Request.QueryString.AllKeys
.ToDictionary(k => k, k => Request.QueryString[k]);
// modify querystring
qs["flag"] = "2";
// rebuild querystring
var redir = string.Format("{0}{1}", Request.Path,
qs.Aggregate(new StringBuilder(),
(sb, arg) => sb.AppendFormat("{0}{1}={2}",
sb.Length > 0 ? "&" : "?", arg.Key, arg.Value)));
// do something with it
Response.Redirect(redir);
While I definitely wouldn't recommend the below for production code, for testing purposes you can use reflection to make the querystring collection editable.
// Get the protected "IsReadOnly" property of the collection
System.Reflection.PropertyInfo prop = Request.QueryString.GetType()
.GetProperty("IsReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
// Set the property false (writable)
prop.SetValue(Request.QueryString, false, null);
// Have your way with it.
Request.QueryString.Add("flag", "2");
To combine the required destination URL based on the Request’s properties, use something like this:
string destUrl = string.Format("{0}://{1}{2}/", Request.Url.Scheme, Request.Url.Authority, Request.Url.AbsolutePath);
if (destUrl.EndsWith("/"))
destUrl = destUrl.TrimEnd(new char[] { '/' });
if (!string.IsNullOrEmpty(Request.QueryString["paramName"])) {
destUrl = string.Format("{0}?paramName={1}", destUrl, "paramValueHere");
Response.Redirect(destUrl);
}
i am not sure if I understand your question. You can just alter the string qs and use.
qs = qs + "modification"
Response.Redirect("this.aspx?flag=" + qs )
The stuff in the Request class deals with the request that got you to the page. You can't edit it because the client constructed it, not the server.

Change Single URL query string value

I have an ASP.NET page which takes a number of parameters in the query string:
search.aspx?q=123&source=WebSearch
This would display the first page of search results. Now within the rendering of that page, I want to display a set of links that allow the user to jump to different pages within the search results. I can do this simply by append &page=1 or &page=2 etc.
Where it gets complicated is that I want to preserve the input query string from the original page for every parameter except the one that I'm trying to change. There may be other parameters in the url used by other components and the value I'm trying to replace may or may not already be defined:
search.aspx?q=123&source=WebSearch&page=1&Theme=Blue
In this case to generate a link to the next page of results, I want to change page=1 to page=2 while leaving the rest of the query string unchanged.
Is there a builtin way to do this, or do I need to do all of the string parsing/recombining manually?
You can't modify the QueryString directly as it is readonly. You will need to get the values, modify them, then put them back together. Try this:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("page", "2");
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
Response.Redirect(url + updatedQueryString);
The ParseQueryString method returns a NameValueCollection (actually it really returns a HttpValueCollection which encodes the results, as I mention in an answer to another question). You can then use the Set method to update a value. You can also use the Add method to add a new one, or Remove to remove a value. Finally, calling ToString() on the name NameValueCollection returns the name value pairs in a name1=value1&name2=value2 querystring ready format. Once you have that append it to the URL and redirect.
Alternately, you can add a new key, or modify an existing one, using the indexer:
nameValues["temp"] = "hello!"; // add "temp" if it didn't exist
nameValues["temp"] = "hello, world!"; // overwrite "temp"
nameValues.Remove("temp"); // can't remove via indexer
You may need to add a using System.Collections.Specialized; to make use of the NameValueCollection class.
You can do this without all the overhead of redirection (which is not inconsiderable). My personal preference is to work with a NameValueCollection which a querystring really is, but using reflection:
// reflect to readonly property
PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isReadOnly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
// modify
this.Request.QueryString.Set("bar", "123");
// make collection readonly again
isReadOnly.SetValue(this.Request.QueryString, true, null);
Using this QueryStringBuilder helper class, you can grab the current QueryString and call the Add method to change an existing key/value pair...
//before: "?id=123&page=1&sessionId=ABC"
string newQueryString = QueryString.Current.Add("page", "2");
//after: "?id=123&page=2&sessionId=ABC"
Use the URIBuilder Specifically the link textQuery property
I believe that does what you need.
This is pretty arbitrary, in .NET Core at least. And it all boils down to asp-all-route-data
Consider the following trivial example (taken from the "paginator" view model I use in virtually every project):
public class SomeViewModel
{
public Dictionary<string, string> NextPageLink(IQueryCollection query)
{
/*
* NOTE: how you derive the "2" is fully up to you
*/
return ParseQueryCollection(query, "page", "2");
}
Dictionary<string, string> ParseQueryCollection(IQueryCollection query, string replacementKey, string replacementValue)
{
var dict = new Dictionary<string, string>()
{
{ replacementKey, replacementValue }
};
foreach (var q in query)
{
if (!string.Equals(q.Key, replacementKey, StringComparison.OrdinalIgnoreCase))
{
dict.Add(q.Key, q.Value);
}
}
return dict;
}
}
Then to use in your view, simply pass the method the current request query collection from Context.Request:
<a asp-all-route-data="#Model.NextPageLink(Context.Request.Query)">Next</a>

Use variable name in StringUtil.substitue in Actionscript

If I have the following code:
var value : String = StringUtil.substitute("The value {0} requested is {1}", user, value);
How can I use the variable name instead of using {0} and {1} in the code.
Please advice. Thanks.
Edit:
The above code is quoted from http://www.rialvalue.com/blog/2010/05/10/string-templating-in-flex/.
It says that "Also note that we’re substituting the parameters using the order, it’d would fairly easy to do a named-parameter subsitution instead (i.e. using tokens like ${var1})". Therefore, I think it may be very easy to do that, but I don't know how to do.
Looks like it's not possible. And kind of makes sense that it allows zero based ints only, since you're passing a variable number of parameters that you're not identifying (except for their relative position in the params list).
Here's a piece of code that will replace tokens by name:
public static function replacePlaceholders(input:String,replacementMap:Object):String {
// '${', followed by any char except '}', ended by '}'
return input.replace(/\${([^}]*)}/g,function():String {
return replaceEntities(arguments,replacementMap);
});
}
private static function replaceEntities(regExpArgs:Array,map:Object):String {
var entity:String = String(regExpArgs[0]);
var entityBody:String = String(regExpArgs[1]);
return (map[entityBody]) ? map[entityBody] : entity;
}
Use:
var test:String = "Hello there ${name}, how is the ${noun} today?";
var replacementMap:Object = {
name : "YOUR_NAME_HERE",
noun : "YOUR_NOUN_HERE"
};
trace(StringUtils.replacePlaceholders(test,replacementMap));
The format I'm using for the placeholders is ${placeholdername}, since it's safer, I think. But if you want to remove the dollar sign, change the regexp accordingly.

Resources