Getting a string from url split after a character c# - c#

I'm trying to use a url to post a username back and fourth from another page. My current code (which gives an error "StartIndex cannot be less than zero.".
if (Convert.ToString(Context.Request.QueryString).StartsWith("username"))
{
string username = Convert.ToString(Context.Request.QueryString);
string input = username.Substring(username.LastIndexOf(":"));
txt_username.Text = input;
}
the url looks like 192.168.1.1/p/login.aspx?username:textIwantintxtbox
Obviously just trying to put the last bit into a text box.

You seem to be taking a longer way to get the value you actually want. Since you start with a QueryString, you should just use that.
txt_username.Text = Context.Request.QueryString['username'];
As for your actual error, Substring needs to start from at least index 0, LastIndexOf seems to be returning -1, indicating it hasn't found the colon, probably because get parameters normally use an = instead of a :

Related

Encode URL querystring from database

I am trying to encode searches that are sent as querystrings (Response.Redirect("/Find/" + TextBoxSearch.Text);). There is a row in the database with names including / and +, and when that enters the URL things stop working properly. I have tried encoding like this:
String encode = HttpUtility.UrlEncode(TextBoxSearch.Text);
Response.Redirect("/Find/" + encode);
But can' get it to work, what am I missing? Pretend the search value is ex/ex 18+. How could I get this to work as a querystring?
Don't know if this is important but here is how I get the querysting in my Find-page:
IList<string> segments = Request.GetFriendlyUrlSegments();
string val = "";
for (int i = 0; i < segments.Count; i++)
{
val = segments[i];
}
search = val;
I can't even encode spaces properly.
I try:
String encoded = Uri.EscapeDataString(TextBoxSearch.Text);
Response.Redirect("/Find/" + encoded);
But this does not turn spaces in the querystring in to %20. It does transform "/" though.
EDIT: At this point I would be happy to just turn this url localhost/Find/here are spaces in to localhost/Find/here+are+spaces
EDIT: I have been searching and trying solutions for over 5 hours now.
Can anyone just tell me this:
If I redirect like this Response.Redirect("/Find/" + search);
And I make a search like this Social media
I then Get the queryString as the code above using segments.
Now I want to display info about Social media from my database
but at the same time I want the url to say Find/Social+media
PS: Do I need to encode every url-string? or just where I use signs and spaces.
Instead of HttpUtility.UrlEncode use HttpUtility.UrlPathEncode. From the documentation of UrlEncode:
You can encode a URL using with the UrlEncode method or the
UrlPathEncode method. However, the methods return different results.
The UrlEncode method converts each space character to a plus character
(+). The UrlPathEncode method converts each space character into the
string "%20", which represents a space in hexadecimal notation. Use
the UrlPathEncode method when you encode the path portion of a URL in
order to guarantee a consistent decoded URL, regardless of which
platform or browser performs the decoding.
The + character does represent a space in query strings but not in the address part.

C# Open Google Search With Search Request

I have an InputTextbox that will have text in it such as:
"search google for test"
And this is the code I have at the moment:
String searchRequest = InputTextbox.Text;
searchRequest = searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1);
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);
What I am trying to do is search the "InputTextbox.Text" for the word "for" and use anything after it as the search term.
Can someone tell me what I'm doing wrong with this please.
One error is in the SubString. The second parameter is meant to be the length of the substring, not the index of the end of the substring. You need to change this to:
searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1 - (searchRequest.IndexOf("for ") + 4));
If that makes sense.
I would avoid using substring here anyway because it can be quite unpredictable. For example, if "for" is not typed into the textbox, you'll get an error and if two "for"s are typed in, I don't even know what will happen. You should try usin RegExp (http://www.regular-expressions.info/) instead:
String searchRequest = InputTextbox.Text;
searchRequest = new System.Text.RegularExpressions.Regex("(?<=for ?).+$").Match(searchRequest).Value;
System.Diagnostics.Process.Start("http://www.google.com.au/search?q=" + System.Uri.EscapeDataString(searchRequest));
Note that I have removed the "iexplore" bit from the process.start routine. This is ok for people who use internet explorer, but it is best not to specify a browser here so as the default browser can be used instead. Note also that I have used System.Uri.EscapeDataString. This will cover you incase the user enters an ampersand into the search box.
If the error says "StartIndex cannot be less than zero" then there will be probably something wrong here:
searchRequest.Length-1
For example, searchRequest.Length may be zero and you're subtracting 1 from it.
Problem : you are giving complete String Length as second parameter for Substring() function.
Solution : You should provide the substring Length (number of characters to be extracted out of the string) as second Parameter for Substring()
function.
Syntax of Substring() from MSDN
Substring(Int32, Int32) : Retrieves a substring from this instance.
The substring starts at a specified character position and has a
specified length.
Try This:
String searchRequest = "search google for test";
int index = searchRequest.IndexOf("for ") + 4;
searchRequest = searchRequest.Substring(index,searchRequest.Length-index);
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);

passing multiline string variable from c# to javascript

I have a webpage that checks login credentials. The page calls a function which then makes a connection to a table in a oracle database and checks to see that this user is allow to see the application. This is all done using c# however if their is a fatal error from the database, i would like to notify the user using javascript. in my c# code i have a string variable that will basically print the javascript function into the webpage. it looks like this.
string javaScript =
"<script>"+
"var find = ':';"+
"var re = new RegExp(find, 'g');" +
"str='#"+CheckAccess[0]._ERROR.ToString().Replace(":"," ")+"';"+
"str = str.replace(re, '');"+
"if ($('#login_error').css('display') == 'none') {" +
"$('#login_error').text(str).show(); }" +
"else {Return;}</script>";
When the database return an error it return a multiline error the looks like this.
ORA-06550 line 1, column 7
PLS-00306 wrong number or types of arguments in call to 'GETUSERACCESS'
ORA-06550 line 1, column 7
PL/SQL Statement ignored at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure, Boolean bCheck)
All the examples Ive seen on the web say to break it up with "/" so that i dont continue to get the "unterminated string literal" error. However i don't see an efficient way to do this. Could there be a better way to achieve what I'm trying to accomplish or do i have to some how figured out a way to parse this string and guess where the line breaks are going to be. Any help would be most appreciated.
Thanks
Miguel
I wouldn't recommend trying to do it the way you are right now. Something smells about having JS code written out in a C# string like that, e.g. it looks like it'd be possible for an injection attack to occur, if the error message string doesn't include what you expected it to.
Instead of trying to pass JS code to the client when an error occurs, you could include the JS code to handle errors in the page to start with, then just pass a JSON-serialized data structure containing your error string. That should allow multiline strings and other special characters to pass from the server to the client correctly.
E.g. if your class is something like this:
public class MyClass
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
Then your controller method might look like:
public JsonResult TryToValidate(...)
{
MyClass myClass = // result
return Json(myClass);
}
With pseudo-JS on the login page that looks like:
MakeAjaxCallToTryToValidate(...)
.whenThatsDone(function ...() {
if !result.Success
alert(result.ErrorMessage);
});
Or, since you shouldn't really be exposing error details to average users anyway, you could just log the error's details on the server where the admin can see it, and give the user a generic error message. If it was something invalid that you might expect the user to do, (e.g. type in a wrong password) then the error message should tell them so, and how to fix it themselves, but a "wrong number or types of arguments" error isn't usually in that category.
You do not have to "guess" where the line breaks will be. The are usually represented by one or two special escape characters:
\r (CR = carriage return), and
\n (NL = new line).
(MS Windows usually use CRLF, Unix-based systems have traditionally used only LF, but this may vary). For example, you can find them with CheckAccess[0]._ERROR.ToString().IndexOf("\r\n"), and use the same technique to replace them.
Since you know you will be pushing error text directly to HTML element, you can replace the \r\n (CRLF) with <br/> (HTML line break).
Code:
CheckAccess[0]._ERROR.ToString().Replace(":"," ").Replace("\r\n", "<br/>")
Since Oracle can run on Unix machines also (for example) and may return just LF in the error message instead of CRLF you may want to be extra safe and be generic, first try to replace CRLF, then CR, then LF:
CheckAccess[0]._ERROR.ToString().Replace(":"," ")
.Replace("\r\n", "<br/>")
.Replace("\r", "<br/>")
.Replace("\n", "<br/>")
Then your javascript will not inject the whitespace from the CRLF, and will instead render the html to create the line breaks.

How do get the first occurrence of a char in Substring

I'm trying to get the first occurrence in my substring start point:
string dir = Request.MapPath(Request.ApplicationPath) + "\\App_GlobalResources\\";
foreach (var file in Directory.EnumerateFiles(dir, "*.resx"))
{
ddlResources.Items.Add(new ListItem { Text = file.Substring(firstoccuranceof("."), file.LastIndexOf(".")), Value = file });
}
if I do file.Substring(file.IndexOf("."), file.LastIndexOf(".")) I get an error
To answer your actual question - you can use string.IndexOf to get the first occurrence of a character. Note that you'll need to subtract this value from your LastIndexOf call, since Substring's second parameter is the number of characters to fetch, not a start and end index.
However... Instead of parsing the names, you can just use Path.GetFilenameWithoutExtension to get the filename directly.
First occurence
String.IndexOf('.')
Last occurence
String.LastIndexOf('.')
Use IndexOf and LastIndexOf string methods to get index of first and last occurrence of "search" string. You may use System.IO.Path.GetExtension(), System.IO.Path.GetFileNameWithoutExtension(), and System.IO.Path.GetDirectoryName() methods to parse the path.
For instance,
string file = #"c:\csnet\info.sample.txt";
Console.WriteLine(System.IO.Path.GetDirectoryName(file)); //c:\csnet
Console.WriteLine(System.IO.Path.GetFileName(file)); //info.sample.txt
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file));//info.sample
Console.WriteLine(System.IO.Path.GetExtension(file)); //.txt
file.IndexOf(".")
Should get you the first occurence of ".". Otherwise it will return -1 if not found.
I think that in your particular case you are NOT trying to get IndexOf... Instead you need to use 0 because you are trying to create a key based on filename if understand correctly:
`ddlResources.Items.Add(new ListItem(file.Substring(0, file.LastIndexOf(".")), file ));`
Also, you have '{}' in there as in new ListItem { ... } which is also going to cause a syntax error... Anyhow have a look..
Because the original question is marked with the [regex] tag, I'll provide the following solution, however the best answer for simple parsing of paths using .NET is not by regex.
//extracts "filename" from "filename.resx"
string name = Regex.Match("filename.resx", #"^(.*)\..+?$").Groups[1].Value;
Use an answer that relies on the Path class instead, for simplicity. Other answers contain that info.
Here you go!)
Using a string variable type
int index = str.IndexOf(#"\");
"C:\Users\somebody\Desktop\aFolder\someFile"
https://www.peachpit.com/articles/article.aspx?p=31938&seqNum=12#:~:text=To%20find%20the%20first%20or,string%20you%20are%20searching%20for.

Making an URL out of modified database fields

I have a button that when the user clicks it, it must go to a specified URL.
But I have to create my URL out of the values coming from database and most importantly, I need to modify the values coming from database before I make a URL out of it.
Suppose the values from database is
country- France
hotel - Hotel Movenpick
Now first I have to turn the capitals from above values to lowercase, then spaces to '-' sign.
Then i will have to create my URL with these modified values as below.
http://www.travel.com/france/hotel-movenpick
I have never done this before. Please provide me some reference for doing this task. I am coding in c#.
How about:
string fixedCountry = country.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string fixedHotel = hotel.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string url = "http://www.travel.com/" + fixedCountry + "/" + fixedHotel;
Note that this won't fix up any accented characters or other symbols. It becomes more complicated if you want to do that. It will depend on how much you trust your data to not contain that sort of thing.
If you need to make this any more complicated, or need to do it anywhere else, I suggest you create a "string fixing" method which munges it appropriately, then call it for each of your fields.
EDIT: Removing accented characters is interesting. .NET makes this fairly easy, but I don't know what it will do for your "ae" situation - you may need to special-case that. Try this though, as a starting point:
static string RemoveAccents (string input)
{
string normalized = input.Normalize(NormalizationForm.FormKD);
Encoding removal = Encoding.GetEncoding
(Encoding.ASCII.CodePage,
new EncoderReplacementFallback(""),
new DecoderReplacementFallback(""));
byte[] bytes = removal.GetBytes(normalized);
return Encoding.ASCII.GetString(bytes);
}

Categories

Resources