Look at this statement :
messageBox.show( System.Security.Principal.WindowsIdentity.GetCurrent().Name);
the output of this statement is :
Roshan\mohdibrahim.tasal
but i want to display me only :
mohdibrhaim.tasal
how can i do this?
You can just split the name on the "\" and retrieve the 2nd item.
e.g.
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1]
Edit:
You'll want to make this safe by first checking for the existence of a backslash - if there isn't one, you just want to take the Name as-is.
Why don't you trim returned value until '\' is reached,
following code does the trick
WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
if(current!=null)
{
string name = current.Name;
string value = name.Substring(name.IndexOf('\\') + 1);
}
Environment.UserName should work without any splitting or additional logic.
Related
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}
Not sure my brain has completely started today...
I would need to escape defined quotation marks (" or ') in a string provided by the user, so depending on selected char the transformation should look like follows:
"I'm not so \"stupid\", am I?" => "I\\'m not so \"stupid\", am I?"
"I'm not so \"stupid\", am I?" => "I'm not so \\\"stupid\\\", am I?"
Trying to use string.Replace(string, string) drives me a little bit crazy, because it still refuses to perform the desired replacements (no additional backslashes are inserted to the result). And I still refuse to do it manually via loop ;)
Dictionary<Type, char> qString; // ...
valueStr = "I'm not so \"stupid\", am I?"; // Illustation only, in reality there is some user input used
// ...
string escFrom = qString[type].ToString(); // Make string from the quotation mark
string escTo = "\\" + escFrom; // Add the escape to it
valueStr.Replace(escFrom, escTo); // Try to replace it
Could you please help me with the mentioned startup completion?
Is there any obvious error I'm doing and not seeing?
Is there any hack like "safe" strings or any "culture" related stuff?
The Replace method doesn't change the string, you have to assign the result of the method call to a string.
You need to escape backslashes also, so it would be:
string escFrom = qString[type].ToString();
string escTo = "\\" + escFrom;
valueStr = valueStr.Replace("\\", "\\\\").Replace(escFrom, escTo);
you need to assign the result back:
valueStr=valueStr.Replace(escFrom, escTo);
If you just wand to replace characters, it could be done with the Replace method, where you would have to use its return value; however I second the comments above that the approach might not be suitable, of course depending on what you are finally trying to achieve.
I would like to give a document I've created programmatically a name which contains the returned value of DateTime.Now.ToString();
The trial failed when ":" symbol is a content of the file name.
Any Idea?
Avoid problemw with culture like this
DateTime.Now.ToString("yyyy-MMdd-HH-mm", CultureInfo.InvariantCulture)
also you can try out
string n = string.Format("typeoffile-{0:yyyy-MM-dd_hh-mm-ss-tt}.ext",
DateTime.Now);
try this will work for you
String.Replace(".","_")
turn in
DateTime.Now.ToString().Replace(".","_")
I would specify a format for DateTime.ToString(), for example:
DateTime.Now.ToString("yyyyMMddhhmmss") //results in "20131127103249"
If you want to go the String.Replace route, I suggest leveraging a useful method called Path.GetInvalidFileNameChars():
string s = DateTime.Now.ToString();
foreach (char c in Path.GetInvalidFileNameChars()) // replace all invalid characters with an underscore
{
s = s.Replace(c, '_');
}
Or, if you're into the whole brevity thing, you can do the same thing in a one-liner using LINQ:
var s = new String(DateTime.Now.ToString().Select(ch => Path.GetInvalidFileNameChars().Any(invalid => invalid == ch) ? '_' : ch).ToArray());
You can use the replace function to replace the : with for example _
DateTime.Now.ToString().Replace(":","_");
Why don't you try removing the ":" symbol, i.e. filename will be:
20131127_0530
DateTime.Now.ToString("yyyyddMM_HHmm")
you should be using the custom ToString method specify a formatter i.e:
DateTime.Now.ToString("ddMMyyyy") - shows daymonthyear
So I have a few file extensions in my C# projects and I need to remove them from the file name if they are there.
So far I know I can check if a Sub-string is in a File Name.
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
So if say stringValue is test.asm, and then it contains .asm, I want to somehow remove the .asm from stringValue.
How can I do this?
if you want a "blacklist" approach coupled with the Path library:
// list of extensions you want removed
String[] badExtensions = new[]{ ".asm" };
// original filename
String filename = "test.asm";
// test if the filename has a bad extension
if (badExtensions.Contains(Path.GetExtension(filename).ToLower())){
// it does, so remove it
filename = Path.GetFileNameWithoutExtension(filename);
}
examples processed:
test.asm = test
image.jpg = image.jpg
foo.asm.cs = foo.asm.cs <-- Note: .Contains() & .Replace() would fail
You can use Path.GetFileNameWithoutExtension(filepath) to do it.
if (Path.GetExtension(stringValue) == anotherStringValue)
{
stringValue = Path.GetFileNameWithoutExtension(stringValue);
}
No need for the if(), just use :
stringValue = stringValue.Replace(anotherStringValue,"");
if anotherStringValue is not found within stringValue, then no changes will occur.
One more one-liner approach to getting rid of only the ".asm" at the end and not any "asm" in the middle of the string:
stringValue = System.Text.RegularExpressions.Regex.Replace(stringValue,".asm$","");
The "$" matches the end of the string.
To match ".asm" or ".ASM" or any equivlanet, you can further specify Regex.Replace to ignore case:
using System.Text.RegularExpresions;
...
stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase);
I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}