Not sure how to ask this or if it can be done.
I have an ID number, that I want to test if it matches an ID in a URL query string that is stored in an API I am working with.
So if the URL i want to search contains a http://www.testurl.com/page?key=55555, I just want to put in my http request if that url 'contains' that number. Testing if the url is exactly equal has proved problematic as there is a lot of other info the stored query string.
Are wildcards within query strings even possible, considering I am encoding the html already? Any help is appreciated. Thank you!
string[] myUrls = new string[] {
"http://www.testurl.com/page?key=55555",
"http://www.testurl.com/page?key=555556789",
"http://www.testurl.com/page?foo=bar&key=55555&baz=938355555"};
string myToken = "key=55555";
bool exists;
foreach(string url in myUrls)
{
System.Uri uri = new System.Uri(url);
string q = uri.GetComponents(UriComponents.Query, UriFormat.Unescaped);
if (q.Split('&').Any(x=>x== myToken))
{
Console.WriteLine(string.Format("found it in '{0}'", url));
}
}
If you can access the QueryString, you could just do this:
if (HttpContext.Current.Request.QueryString["key"].ToLower() == "5555")
//do something
Related
I'm trying to figure out the best way to get everything before the / character in a string. Some example strings are below.
var url = dr.FindElements(By.XPath("//*[#id=\"u_0_3\"]/div/h1/a"));
foreach (var item in url)
{
if (item.GetAttribute("href").ToString().Contains("https://www.facebook.com/"))
{
listBox4.Items.Add("here");
}
}
the href is like that = "http://facebook.com/xxx"
want the xxx which is username want to get it alone in my listbox without the rest of the url
If you're at the point where you've got the string you want to work with, here are two ways to do this:
Split the string by / and take the last part
var stringToProcess = "https://www.facebook.com/ProfileName";
var partsOfString = stringToProcess.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var profileName = partsOfString.Last();
Use the Uri class to extract the last part
var stringToProcess = "https://www.facebook.com/ProfileName";
var stringToProcessAsUri = new Uri(stringToProcess);
var profileNameFromUri = stringToProcessAsUri.Segments.Last();
This is the "strictly better" way as it will give you a clean result even if the profile address has a query string attached to it, i.e:
var stringToProcess = "https://www.facebook.com/ProfileName?abc=def";
var stringToProcessAsUri = new Uri(stringToProcess);
var profileNameFromUri = stringToProcessAsUri.Segments.Last();
You'll still have the variable profileNameFromUri returned containing only ProfileName
I have a redirect:
string linkedInLogin = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=ID&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Flinkedin&state=ZEKNI&scope=r_basicprofile";
Response.Redirect(linkedInLogin);
This results in a redirect in my browser to
https://www.example.com/auth/linkedin?code=CODE_I_NEED&state=STATE
How do I retrieve the value of the code paramater?
Request.Querystring["code"] gives me a null value. The problem is that the browser "thinks" the current URL was /home/MyController.
try:
HttpContext.Current.Request.Params["code"]
this way you can get a combined collection of QueryString, Form, Cookies, and ServerVariables items.
here you can read more: HttpRequest.Params Property
Do you have that link stored somewhere or are you asking for how to retrieve it as well?
Assuming you already have it:
var s = "https://www.example.com/auth/linkedin?
code=CODE_I_NEED&state=ROB962242SMUT"
You can either do:
string s = "https://www.example.com/auth/linkedin?code=CODE_I_NEED&state=ROB962242SMUT";
var code = s.Substring((s.IndexOf("code=") + 5), (s.IndexOf('&') - (s.IndexOf("code=") + 5)));
//CODE_I_NEED
Or
String sourcestring = "https://www.example.com/auth/linkedin?
code=CODE_I_NEED&state=ROB962242SMUT";
Regex re = new Regex(#"code=(.*)&");
var result =Match m = re.Match(sourcestring).Value;
//CODE_I_NEED
edit: based on the other two answers i may not have understood your question properly xd
I have a Url as shown below
http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com
I would like to have the email address from the url
Note
The email address may have the escape character of # sometimes.
ie it may be myname%40gmail.com or myname#gmail.com
Is there any way to get the email address from a url, such that if the that have the matching regx for an email patten and retrieve the value.
Here is the code that i have tried
string theRealURL = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";
string emailPattern = #"^([\w\.\-]+)(((%40))|(#))([\w\-]+)((\.(\w){2,3})+)$";
Match match = Regex.Match(theRealURL, emailPattern);
if (match.Success)
string campaignEmail = match.Value;
If anyone helps what went wrong here?
Thanks
If possible, don't use a regular expression when there are domain-specific tools available.
Unless there is a reason not to reference System.Web, use
var uri = new Uri(
"http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com");
var email = HttpUtility.ParseQueryString(uri.Query).Get("emailAddress");
Edit: If (for some reason) you don't know the name of the parameter containing the address, use appropriate tools to get all the query values and then see what looks like an email address.
var emails = query
.AllKeys
.Select(k => query[k])
.Where(v => Regex.IsMatch(v, emailPattern));
If you want to improve your email regex too, there are plenty of answers about that already.
Starting with Rawling's answer in response to the comment
The query string parameter can vary.. How can it possible without using the query string parameter name.
The follwing code will produce a list (emails) of the emails in the supplied input:
var input = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";
var queryString = new Uri(input).Query;
var parsed = HttpUtility.ParseQueryString(queryString);
var attribute = new EmailAddressAttribute();
var emails = new List<string>();
foreach (var key in parsed.Cast<string>())
{
var value = parsed.Get(key);
if (attribute.IsValid(value))
emails.Add(value);
}
Console.WriteLine(String.Join(", ", emails)); // prints: myname#gmail.com
See also this answer for email parsing technique.
I have a query that contains a string that looks like this: .
When I put this into my query hardcoded it does return results and as a variable it doesn't.
var myresult = RepositoryQuery.Where(a => a.Account== #"domain\\user");
Works.
string account= "domain\\user";
var user = RepositoryQuery.Where(a => a.Account == account);
Does not work.
Account GetAccount(account){
return RepositoryQuery.Where(a => a.Account == account);
}
Does not work.
Account GetAccount(account){
return RepositoryQuery.Where(a => a.Account == #account);
}
Does not work.
My guess is that it would have to do with the backslashes, but I can't any answers.
I found someone with the same problem but I couldn't get a solution out of it.
What am I doing wrong?
[edit]
Updated the typo var name.
account.Replace("\\", "\\\\");
If I replace it like this it works.
Looks ugly though..
[Solution]
So the account string I get from my session has already been escaped. I decided to replace the backslashes at session creation to keep the databases in line and not have one with double backslashes and one with single.
Sometimes you have to be aware of what you are looking at might have been changed by the IDE visually, when debugging, for example you could get confused when looking at filepaths in visual studio. where a string "c:\something\file.bla" could be shown as "c:\\something\\file.bla"
this also happens in connection strings and other things.
In your case #"domain\\user" is really "domain\\user"
whereas if you don't use the verbatim string
"domain\\user" would be "domain\user" when querying the database.
Use:
string accountid = #"domain\user"
Or
string accountid = "domain\\user"
On a second note:
the # in front of a variable is used to allow you to use reserved words as your variable names.
something like:
string #class = "1st. class";
Or
bool #if = true;
if(#if)
{
Console.WriteLine("If is: "+ #if); //would print "If is: true"
}
Your first mistake: you filter with account variable instead of accountid.
Maybe it behaves as an escape character, try with verbatim string:
string accountid = #"domain\\user";
or if you store it with single backslash:
string accountid = #"domain\user";
I think this could work:
string accountid = #"domain\user";
var user = RepositoryQuery.Where(a => a.Account == accountid );
or this (but I don't suggest):
string accountid = "domain\\user";
var user = RepositoryQuery.Where(a => a.Account == accountid );
To be more precise I will be working with example...
Clean query is: (type:77 AND (zipCode:12345 OR name:OR))
When querying on Solr Admin page this throws exception:
org.apache.lucene.queryParser.ParseException: Cannot parse...
So on Solr Admin page I changed query to:
(type:"77" AND (zipCode:"12345" OR name:"OR"))
which worked as a charm
Now I have a problem to do the same stuff with solrnet. I am using SolrQueryByField class for querying. When I am working with
new SolrQueryByField("name", "OR")
I get Solrnet.Exceptions.InvalidFieldException which is in accordance with Solr Admin page, but when I am working with
new SolrQueryByField("name", "\"OR\"")
I get wrong results. By inspecting network traffic I found out that http get request is different (for brevity only name field name and value are given):
name%3A%22OR%22 => from Solr Admin page
name%3a%5c%22OR%5c%22 => from solrnet
My question is: what sholud I do to prevent solrnet from adding %5C (backslash) to query string?
Thanks in advance
SolrQueryByField produces quoted/escaped values. If you have some special case where this is not desirable (such as this case) you can use SolrQuery, e.g. :
Query.Field("type").Is(77) && (Query.Field("zipCode").Is("12345") || Query.Simple("name:\"OR\""))
Please try to pass the string array that contains multiple field names and search text in the below method. It will return the solrnet query for search with multiple filed name with OR condition.
public ISolrQuery BuildQuery(string[] SearchFields, string SearchText)
{
try
{
AbstractSolrQuery firstQuery = new SolrQueryByField(SearchFields[0], SearchText) { Quoted = false };
for (var i = 1; i < parameters.SearchFields.Length; i++)
{
firstQuery = firstQuery || new SolrQueryByField(SearchFields[i], SearchText) { Quoted = false };
}
return firstQuery;
}