How to remove the domain name? - c#

I have one sharepoint application, in this i have to show the current user, i used SPContext.Current.Web.CurrentUser.LoginName. then it returns XXXXXX\abida. But i want only the username like abida. How to achieve this requirement?

Note that we have to escape the slash...
string loginName = SPContext.Current.Web.CurrentUser.LoginName;
string[] loginNameParts = loginName.Split('\\');
string loginNameWithoutDomain = nameParts[1];
I presume you are doing this in order to use the name-only for some reason and that you aren't relying on the user name being unique in its own right. You could have DOMAIN1\BobSmith and DOMAIN2\BobSmith - so if you were using "BobSmith" as a unique user name, you could come unstuck.

you do not. The name is not guaranteed to be unique without the domain prefix. If you erally want to show it without, then just remove it - split the string at the "\" and use the second element. There are multiple ways do do that, from the Split method on the string to using IndexOf for the "\" and then substring to extract the reminder.

Related

Regex to find a user UPN inside a string

I want to find User Principal names inside all sort of strings for a C# tool to anonymize customer specific data.
I found this one:
(?[^#]+)#(?(?:[a-z0-9]+.)+[a-z]+)
But in a string like this:
f-4af0-86e8-01439a0ae52a\",,\"Active\",\"10/30/2018 9:05:35
AM\",\"SingleSession\",\"Desktop\",,\"10/29/2018 2:35:06
PM\",,\"655952\",\"DOM\na010318\",\"na010318\",\"DOM\n010318\",\"S-1-5-21-2052699199-3915784498-1582209984-1157056\",\"user.a#domain.acc.local\",\"Primary\",\"c46b084c-6df3-47dd-9d3e-8e17f855c7fe\""
It matches the entire part before the UPN (the first space, because it matches the word I guess.
How can I re-write the regular expression to only find the e-mail/UPN within this string?
Thanks
If a UPN effectively has the same format as an email address - try some of the answers from this question:
regex extract email from strings
The following regex works for your example:
([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)
https://regex101.com/r/ijG8Xr/2

Extract second section of string

I will have always an string like this:
"/FirstWord/ImportantWord/ThirdWord"
How can I extract the ImportantWord? Words can contain at most one space and they are separated by forward slashlike I put above, for example:
"/Folder/Second Folder/Content"
"/Main folder/Important/Other Content"
I always want to get the second word(Second Folder and Important considering above examples)
how about this:
string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word
I hope you need not to use the String.Split option either with specific characters or with some regular expressions. Since the inputs are well qualified paths to a directory you can use Directory.GetParent method of the System.IO.Directory class, which will give you the parent Directory as DirectoryInfo. From that you can take the Name of Directory which will be the required text.
You can use like this :
string pathFirst = "/Folder/Second Folder/Content";
string pathSecond = "/Main folder/Important/Other Content";
string reqWord1 = Directory.GetParent(pathFirst ).Name; // will give you Second Folder
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important
Additional note: The method Directory.GetParent can be nested if you need to get a name in another level.
Also you may try this:
var stringValue = "/FirstWord/ImportantWord/ThirdWord";
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord
There are several ways to solve this. The simplest one is using String.split
Char delimiter = '/';
String[] substrings = value.Split(delimiter);
String secondWord = substrings[1];
(you may want to do some input check to make sure the input is in the right format or else you will get some exception)
Other way is using regex when the pattern is simple /
If you are sure this is a path you can use other answer mention here

string format custom parameter

Is there a (simple/predefined) way to use the same string.format mechanism but use names instead of numbers? I want to use the same formatting system but make it more end-user friendly. Right now my users are putting in {0} {1:Minutes} after selecting what parameters they want to use from a list but it becomes quite unreadable and confusing once you start using more then say 2 parameters.
For example want to do {Now} and {Now:Minutes} and have it replaced with DateTime.Now for {Now} and DateTime.Now.Minutes using the IFormattable for {Now:Minutes}. So that the users won't need to select items from a list anymore but rather just type/insert the names of the parameters.
In c#-6.0 you can use
string result = $"Time: {DateTime.Now}";
On previous versions see
How to replace tokens on a string template?

How do I get the current windows user's name in username#domain format?

I know that the following function returns the current Windows user's name in domain\username format.
Convert.ToString( WindowsIdentity.GetCurrent().Name );
But how do I obtain the user's name in username#domain format?
EDIT:
I'm responding in this edit as everyone who has replied has the same basic idea.
From what I've been given to understand, parsing the name from domain\username format and constructing it as username#domain is not safe or advised. I believe this is so because there is no guarantee that the two domain names are the same in the different formats. For example, in the company where I work, the domain part of the domain\username format is based upon deparment, but in the username#domain, it's the company name. It's the kind of thing that requires a DNS lookup.
I was hoping that there was an API that did this DNS lookup. I guess I should have put this information into my original question. Sorry.
Something like this should work...
string[] temp = Convert.ToString(WindowsIdentity.GetCurrent().Name).Split('\\');
string userName = temp[1] + "#" + temp[0];
var input = WindowsIdentity.GetCurrent().Name ;
string[] tab = input.Split('\\');
var result = tab[1] + "#" + tab[0];
You could split the name using \ as the delimiter, then reverse the order like so:
string[] splitName = WindowsIdentity.GetCurrent().Name.Split('\\');
//check that splitName contains at least 2 values before using
string name = (splitName.Length > 1) ? splitName[1] + "#" + splitName[0] : null;
It's important to note that a double backslash \\ is required because a backslash is a special character. We add the second backslash in the above example to escape the special character and use it as a regular character.
All of the code to take the name in Domain\user name format and parse it will not work in all situations. The answer is you have to make calls to Active Directory to get the User Principal Name. It turns out that I can't rely on Active Directory being installed on the desktop, since many police departments don't install the directory on their laptops in case it is stolen while a cop is not in the car. (Talk about gutsy, stealing a computer out of a police vehicle!)
We have come up with our own solution for our situation. We store the user names in our database in Domain\user name format. When the program starts up, it checks to see if the current windows user name (in the same format) is in the database. If it is, the program uses that user as the current user and runs. If the current Windows user is not in our database, the program falls back to our previous code.
This way, the user can log into the machine using any format for their user name and they authenticate with Windows. Our program always gets the user name in the same format and it always checks the user name in that format. Windows authenticates the user and not us.
Use
System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName
This returns the UPN of the current user. Requires a reference to System.DirectoryServices.AccountManagement.
Something along these lines.
var nameParts = WindowsIdentity.GetCurrent().Name.Split(#"\");
string name = nameParts.Length == 1
? nameParts
: string.format("{0}#{1}",nameParts[1],nameParts[0]);
I've seen so many variations of the same, why not put it into a function like:
string GetUserName()
{
var currentName = WindowsIdentity.GetCurrent()?.Name;
if (string.IsNullOrEmpty(currentName)) return null;
var nameSplit = currentName.Split(#"\");
string name = (nameSplit.Length > 1)
? $"{nameSplit[1]}#{nameSplit[0]}" : currentName;
return name;
}

Splitting two strings and rejoining

I am currently working on an address selector for a checkout process, this currently has a function that adds a comma after all fields that are found on the check out like this.
This is done using,
ddl.Items.Add(new ListItem(string.Join(", ", lines.ToArray()), address.ID.ToString()));
This is fine until you add a name in, which is a must have so they may use their account to delivery to a different person in the case of gifts or if you wish to order something and have someone else sign for the product. I wish for my first/last name to not have a comma between them, however... I can't simply do this by not adding a comma on the first two fields as there is many cases in which a name would not be entered on the delivery address.
This is how it displays currently
I was thinking the best way to do this was to split the name into a separate string and then the rest of the address into another, add the commas in and then rejoin the strings into one.
If anyone could think of a better way to do this, please share your ideas.
1 You can also use
string.Concat(lines.ToArray()).Replace(" ",",");
2 Or iterate with foreach and build stringBuilder
I have used this method,
StringBuilder fullName = new StringBuilder();
List<string> lines = new List<string>();
if (!string.IsNullOrEmpty(address.Name))
fullName.AppendFormat("{0} ", address.Name);
if (!string.IsNullOrEmpty(address.Name1))
fullName.AppendFormat("{0} ", address.Name1);
if (!string.IsNullOrEmpty(address.Name2))
fullName.Append(address.Name2);
if (!string.IsNullOrEmpty(fullName.ToString()))
lines.Add(fullName.ToString());
String = String.Replace(","," ");
or
String = String.Replace(","," ");
This will do what you want.

Categories