why is my parameter value not being passed in QueryString - c#

I have a parameter:
string custName = "";
custName = AddressDT.Rows[0]["first_name"].ToString() + " " + AddressDT.Rows[0]["last_name"].ToString();
I am performing my Response.Redirect
Response.Redirect("~/Account/EmailError.aspx?parm1=custName");
and I am retrieving the parameter value:
custName = Request.QueryString["parm1"];
when I run debug: ... custName = "custName"
what am I doing wrong? I have done this before with no issue.

Your Response.Redirect is passing the string "custName", not the value of the variable.
This will fix it for you:
Response.Redirect("~/Account/EmailError.aspx?param1=" + custName);

That is because you're using a String Constant as the value for the parameter.
Response.Redirect("~/Account/EmailError.aspx?parm1=custName");
That would always cause the URL to be set with the string custName.
Try using the variable name as:
Response.Redirect("~/Account/EmailError.aspx?parm1=" + custName);
Now the variable would be appended to the request.
Now when you'll run the code, it would produce the value in the Variable and you'll get the code running fine.
Always remember to finish the string and then adding the variable values. Everything inside the double qoutes is considered to be a string and not a variable name or a keyword.

If you already know that QueryString value is string, you need to use UrlEncode.
In addition, you want to use String.Format as much as possible for good design practice instead of +.
string custName = String.Format("{0} {1}",
AddressDT.Rows[0]["first_name"].ToString(),
AddressDT.Rows[0]["last_name"].ToString());
string url = String.Format("~/Account/EmailError.aspx?parm1={0}",
Server.UrlEncode(custName));
Response.Redirect(url);

Related

Get substring in between two other strings?

I am trying to get a string in between two sub strings, but I am running into an issue.
I am trying to use Selenium to automate a web test, and extract the profile ID from the javascript in the page source. I am running into an ArgumentOutOfRangeException?
It doesn't matter with I'm searching for the correct or wrong values and passing them to GetInbetween, it throws this exception. I cannot see anything wrong with my code, so here I am.
Code:
var source = GetSource();
var username = "username1";
Console.WriteLine("Here: " + source.GetInbetween("window.__additionalDataLoaded('/" + username + "/',{\"logging_page_id\":\"", "\","));
Source (truncated for readability):
window.__additionalDataLoaded('/username1/',{"logging_page_id":"profilePage_10216","logging_page_username": "username1"})
Exception:
ArgumentOutOfRangeException
Length cannot be less than zero. (Parameter 'length')
It throws the exception in this method
public static string GetInbetween(this string s, string start, string end)
{
return s[(s.IndexOf(start) + start.Length)..s.IndexOf(end)];
}
LinqPad test:
void Main()
{
var source = "window.__additionalDataLoaded('/username1/',{\"logging_page_id\":\"profilePage_10216\",\"logging_page_username\":\"username1\"})";
var username = "username1";
Console.WriteLine(source.IndexOf("window.__additionalDataLoaded('/" + username + "/',{\"logging_page_id\":\""));
Console.WriteLine(source.IndexOf("\","));
Console.WriteLine($"[{source}]");
Console.WriteLine($"[{"window.__additionalDataLoaded('/" + username + "/',{\"logging_page_id\":\""}]");
Console.WriteLine("Here: " + source.GetInbetween("window.__additionalDataLoaded('/" + username + "/',{\"logging_page_id\":\"", "\"."));
}
You might get this error if end exists in s before start. So try using s.LastIndexOf(end).
It says 'Length cannot be less than zero.' which means IndexOf is returning -1, which it does if the substring is not found in the search string... So you are looking for a substring which doesn't exist in the string. Make sure you have case-sensitivity correct, or use an IndexOf overload which ignores case.
Edit -- Your GetSource() method must not be returning the string you think it is returning... See, works fine explicitly searching that string:
Passing a start index to IndexOf(end) like this seems to fix it.
return s[(s.IndexOf(start) + start.Length)..s.IndexOf(end, s.IndexOf(start))];
The final method looks like this:
public static string GetInbetween(this string s, string start, string end)
{
return s[(s.IndexOf(start) + start.Length)..s.IndexOf(end, s.IndexOf(start))];
}

Variable decimal formating in string interpolation

I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";

Get value off querystring by it's position

I have a URL that's going to have one parameter on it but the 'name' of this parameter will, in some cases, be different eg.
www.mysite.com/blog/?name=craig
www.mysite.com/blog/?city=birmingham
and what I'm trying to do is always get the value (craig / birmingham) of the first (and only) parameter on the string regardless of it's name (name/ city). Is there any code that will do that or will I have to check the possible options?
thanks,
Craig
Try something like this:
string valueOfFirstQueryStringParameter = "";
string nameOfFirstQueryStringParameter = "";
NameValueCollection n = Request.QueryString;
if (n.HasKeys())
{
nameOfFirstQueryStringParameter = n.GetKey(0);
valueOfFirstQueryStringParameter = n.Get(0);
}

Pass parameters through URL in C# ASP.net

I have the following code for a Button click event where I open a new Tab for a Report and I need to pass a parameter to that from the code behind,
String classname = txt_classname.SelectedValue;
String teachername = "Some name";
string url = "Report_Classwise.aspx";
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
I need to pass classname & teachername to Report_Classwise.aspx page, I have tried setting
string url = "Report_Classwise.aspx?classname='"+classname+"'&teachername='"+teachername+"'";
But it didn't work
You dont need to add additional single quote in URL
string url = "Report_Classwise.aspx?classname=" + classname + "&teachername="
+ teachername;
You single quotes might interfere with your parameter names, are you sure you really want to have them there?
You might want to encode your parameters to make sure that they don't contain some special characters etc, and drop your single quotes:
string url = "Report_Classwise.aspx?classname=" + encodeURIComponent(classname) +"&teachername=" + ncodeURIComponent(teachername);
Use string.Format for more readability and avoid confusions.
string url = string.Format("Report_Classwise.aspx?classname={0}&teachername={1}", classname, teachername);

Convert HTML query to normal string

I have a webmethod and get my queryString with this code:
string name = "";
int pos7 = context.Request.UrlReferrer.PathAndQuery.IndexOf("name");
if (pos7 >= 0)
name = context.Request.UrlReferrer.PathAndQuery.Substring(pos7 + 5);
The problem is the adresse "www.test.com?name=tiki song" will be end up in "tiki%20song" on my string.
How to avoid that?
(Yes I could replace the %20 to " " but there are a lot of more of that kind, right?"
Consider using Uri.UnescapeDataString
http://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx
As per this previous you could create a URI and extract it using "UnescapeDataString" (post). Referencing this MSDN page.
Or alternatively, you can use some of the HtmlDecode methods as MikeBarkemeyer had mentioned in the comments.

Categories

Resources