RouteUrl replace "&" with "&" in query string parameters - c#

I have the following code:
#Url.RouteUrl("NewMessage", new { parentThreadId = Model.thread.id, cacheBustParam = currentUserId })
When the page get rendered the page source looks like:
/somepath/newMessage/12345?cacheBustParam=123&param1=value1&param2=value2
As you can see instead of plain ampesands & it places & in the query string params and that makes them unusable.
How can i instruct the #Url.RouteUrl not to encode the querystring?

Try using
#Html.Raw(Url.RouteUrl("NewMessage", new { parentThreadId = Model.thread.id, cacheBustParam = currentUserId }))

Related

Get everything after Slash c#

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

Get email address from the url with and without escape character of # in c#

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.

How do I create a query string in a C# Windows Store App (a.k.a. WinRT/Metro)?

I want to access a web resource with an HTTP GET query string, ex.:
http://stackoverflow.com/search?q=search%20example&tab=relevance
In a regular .NET Framework 4.5 application, you can use System.Net.WebClient.QueryString:
Remarks
The QueryString property contains a NameValueCollection instance containing name/value pairs that are appended to the URI as a query string. The contents of the QueryString property are preceded by a question mark (?), and name/value pairs are separated from one another by an ampersand (&).
For Store Apps, you can even parse them with Windows.Foundation.WwwFormUrlDecoder.
But for creating a query string, the best snippet I could find in MSDN was this:
UriBuilder baseUri = new UriBuilder("http://www.contoso.com/default.aspx?Param1=7890");
string queryToAppend = "param2=1234";
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
(from: http://msdn.microsoft.com/en-us/library/system.uribuilder.query(v=vs.110).aspx)
Is Microsoft really implying I should join my parameters with "=" and "&" myself? Isn't there a better way?
Currently, there isn't one available that I'm aware of.
It's easy enough to create something that mirrors the original .NET functionality:
public static class UriExtensions
{
public static Uri CreateUriWithQuery(Uri uri, NameValueCollection values)
{
var queryStr = new StringBuilder();
// presumes that if there's a Query set, it starts with a ?
var str = string.IsNullOrWhiteSpace(uri.Query) ?
"" : uri.Query.Substring(1) + "&";
foreach (var value in values)
{
queryStr.Append(str + value.Key + "=" + value.Value);
str = "&";
}
// query string will be encoded by building a new Uri instance
// clobbers the existing Query if it exists
return new UriBuilder(uri)
{
Query = queryStr.ToString()
}.Uri;
}
}
public class NameValueCollection : Dictionary<string, string>
{
}
Using like:
var uri = UriExtensions.CreateUriWithQuery(new Uri("http://example.com"),
new NameValueCollection { { "key1", "value1" }, { "key2", "value2" }});
Results:
http://localhost/?key1=value1&key2=value2

deleteing a list of values sent from client

I am trying to delete a list of values from database.I create a list with JQ and send it to server. my problem is how can I extract the values with request method my JQ code looks like this :
$("#del").click(function () {
var dellist = "";
$(".del:checked").each(function () {
dellist += "'" + $(this).val() + "',";
})
dellist += "''";
$.get("mem.aspx?cmd=del&dellist=" + dellist, function () { });
})
and the C# part is like this :
if(CMD == "del")
{
}
I use entity framework.
You have to use Request.QueryString as you are making query string in get method.
string del = Request.QueryString["del"].ToString();
string dellist = Request.QueryString["dellist"].ToString();
You can use string.Split to extract values from server.
string []listValues = Request.QueryString["dellist"].ToString().Split(',');
you can use
string cmd=Request["cmd"];
string dellist = Request["dellist"];
try this
String[] dellist = Request.QueryString["dellist"].Split(',');
since you have string with comma separated you can split that string with , character as above. String.Split method return array of strings.

javascript Request.QueryString

How do I request querystring using javascript from URL
e.g : http://localhost:1247/portal/alias__MySite/lang__en/tabid__3381/default.aspx
I want to get tabid...
var tabid = '<%= Request.QueryString["tabid"] %> ';
Above code works only in aspx page
but i dont need it, any ideas? thanks
There is now a new api URLSearchParams. Use that in conjunction with window.location.search
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('tabid'));
If your browser does not support URLSearchParams, you can create a custom fallback function:
function getParam(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log(getParam('tabid'));
Don't know why but I've always found the javascript for querystring data fetching a bit hacky. if you don't need this value on the initial page load then perhaps you could use Request.QueryString in the code and set the value to a hidden field, which your javascript will read from?
Try this, It is working perfectly for me.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var tabId=getParameterByName("tabid");
I bet there is a server-side rewrite (DotNetNuke?), so the aspx.cs "sees" the redirection target which contains the correct QueryString.
For the client, you have to use another mechanism because the browser only "sees" the public URL. In this case, a Regex that picks the number behind 'tabid_' and before the next slash should work. This would be the same number (page id?) that the aspx page "sees".
This is what I used:
<script type="text/javascript">
function QueryString(key) {
//Get the full querystring
fullQs = window.location.search.substring(1);
//Break it down into an array of name-value pairs
qsParamsArray = fullQs.split("&");
//Loop through each name-value pair and
//return value in there is a match for the given key
for (i=0;i<qsParamsArray.length;i++) {
strKey = qsParamsArray[i].split("=");
if (strKey[0] == key) {
return strKey[1];
}
}
}
//Test the output (Add ?fname=Cheese&lname=Pizza to your URL)
//You can change the variable to whatever it is you need to do for example, you could
//change firstname to id and lastname to userid and just change the reference in the
//document.write/alert box
var firstname = QueryString("fname");
var lastname = QueryString("lname");
document.write("You are now logged in as " + firstname + " " + lastname + "!");
</script>
You can replace document.write with alert and it would give you an alert box instead!
I used this on my website. Its not done yet but when it is it will be at zducttapestuff.com
The output will look like this: You are now logged in as Cheese Pizza!
This is very unsecure for Passwords though since the password will be shown in the url.

Categories

Resources