Built-in helper to parse User.Identity.Name into Domain\Username

965

Solution 1

This is better (easier to use, no opportunity of NullReferenceExcpetion and conforms MS coding guidelines about treating empty and null string equally):

public static class Extensions
{
    public static string GetDomain(this IIdentity identity)
    {
        string s = identity.Name;
        int stop = s.IndexOf("\\");
        return (stop > -1) ?  s.Substring(0, stop) : string.Empty;
    }

    public static string GetLogin(this IIdentity identity)
    {
        string s = identity.Name;
        int stop = s.IndexOf("\\");
        return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
    }
}

Usage:

IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();

This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.

Solution 2

System.Environment.UserDomainName gives you the domain name only

Similarly, System.Environment.UserName gives you the user name only

Solution 3

var components = User.Identity.Name.Split('\\');

var userName = components.Last() 

var domainName = components.Reverse().Skip(1).FirstOrDefault()

Solution 4

You guys might also consider parsing a string input like "[email protected]", or "user@domain".

This is what I'm currently doing:
If string contains '\' then split string at '\' and extract username and domain
Else If string contains '@' then split string at '@' and extract username and domain
Else treat string as username without a domain

I'm still hunting for a better solution in the case where the input string isn't in an easily predicted format, i.e. "domain\user@domain". I'm thinking RegEx...

Update: I stand corrected. My answer is a bit of out context, it refers to the general case of parsing username and domains out of user input, like in user login/logon prompt. Hope it still helps someone.

Solution 5

I think No too, because I asked myself the same question the other day :D

You can try:

public static string GetDomain(string s)
{
    int stop = s.IndexOf("\\");
    return (stop > -1) ? s.Substring(0, stop + 1) : null;
}

public static string GetLogin(string s)
{
    int stop = s.IndexOf("\\");
    return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
}
Share:
965

Related videos on Youtube

mp3por
Author by

mp3por

Updated on December 19, 2020

Comments

  • mp3por
    mp3por over 3 years

    I am trying to dynamically set the maxLines on a TextView that is in a CardView which is in RecycleView.

    Here is my CardView_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
    
        <android.support.v7.widget.CardView
            android:id="@+id/fragment_advice_cardview_CV_cardview"
            android:layout_width="match_parent"
            android:layout_height="150sp"
            card_view:cardCornerRadius="5sp"
            card_view:cardElevation="5sp"
            card_view:contentPadding="2dp"
            card_view:cardUseCompatPadding="true">
    
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/green_background"
                android:padding="16sp">
    
                <ImageView
                    android:id="@+id/fragment_advice_cardview_IV_doctor_photo"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginEnd="16sp"
                    android:adjustViewBounds="true"
                    android:maxWidth="150sp"
                    android:scaleType="fitCenter"
                    android:src="@drawable/batman_logo" />
    
                <TextView
                    android:id="@+id/fragment_advice_cardview_TV_doctor_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_toEndOf="@+id/fragment_advice_cardview_IV_doctor_photo"
                    android:text="@string/omg"
                    android:textSize="30sp" />
    
                <TextView
                    android:id="@+id/fragment_advice_cardview_TV_doctor_advice"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@+id/fragment_advice_cardview_TV_doctor_name"
                    android:layout_toEndOf="@+id/fragment_advice_cardview_IV_doctor_photo"
                    android:text="@string/omg" />
    
            </RelativeLayout>
        </android.support.v7.widget.CardView>
    </LinearLayout>
    

    Here is my fragment_layout.xml:

    <ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment_advice_VS_view_switcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".android.fragments.AdviceFragment">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/fragment_advice_RV_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <TextView
            android:id="@+id/fragment_advice_TV_empty_error_message"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </ViewSwitcher>
    

    My adapter:

    public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DoctorViewHolder> {
        private final ArrayList<Doctor> doctors;
    
        public RVAdapter(ArrayList<Doctor> doctors) {
            this.doctors = doctors;
        }
    
    
        @Override
        public DoctorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_advice_cardview_layout, parent, false);
    
            final TextView doctorAdviceTV = (TextView) view.findViewById(R.id.fragment_advice_cardview_TV_doctor_advice);
            System.out.println("doctorAdviceTV.getId() : " + doctorAdviceTV.getId());
            System.out.println("doctorAdviceTV.getHeight() : " + doctorAdviceTV.getHeight());
    
    
            ViewTreeObserver doctorAdviceTVviewTreeObserver = doctorAdviceTV.getViewTreeObserver();
            doctorAdviceTVviewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    doctorAdviceTV.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    
                    int maxLines = doctorAdviceTV.getHeight() / doctorAdviceTV.getLineHeight();
                    BaseActivity.logD("RVAdapter", "maxLines : " + maxLines + " = " + doctorAdviceTV.getHeight() + " / " + doctorAdviceTV.getLineHeight());
                    doctorAdviceTV.setMaxLines(maxLines);
                    doctorAdviceTV.setEllipsize(TextUtils.TruncateAt.END);
                }
            });
    
            DoctorViewHolder dvh = new DoctorViewHolder(view);
            return dvh;
        }
    
        @Override
        public void onBindViewHolder(DoctorViewHolder holder, int position) {
            Doctor doctor = doctors.get(position);
            holder.doctorNameTV.setText(doctor.getSettingValue(Doctor.SETTINGS.NAME));
            holder.doctorAdviceTV.setText(doctor.getSettingValue(Doctor.SETTINGS.ADVICE));
    
            Bitmap profilePicture = doctor.getProfilePicture();
            if (profilePicture == null) {
                holder.doctorImageIV.setImageResource(R.drawable.batman_logo);
            } else {
                holder.doctorImageIV.setImageBitmap(profilePicture);
            }
        }
    
        @Override
        public int getItemCount() {
            return doctors.size();
        }
    
        public static class DoctorViewHolder extends RecyclerView.ViewHolder {
    
            CardView cv;
            TextView doctorNameTV;
            TextView doctorAdviceTV;
            ImageView doctorImageIV;
    
            public DoctorViewHolder(View itemView) {
                super(itemView);
                cv = (CardView) itemView.findViewById(R.id.fragment_advice_cardview_CV_cardview);
                doctorNameTV = (TextView) itemView.findViewById(R.id.fragment_advice_cardview_TV_doctor_name);
                doctorAdviceTV = (TextView) itemView.findViewById(R.id.fragment_advice_cardview_TV_doctor_advice);
                doctorImageIV = (ImageView) itemView.findViewById(R.id.fragment_advice_cardview_IV_doctor_photo);
            }
        }
    }
    

    And of course the result

    Before pic change:

    before pic change

    pic 1 change

    pic 2 change

    As you can see the first CardView TextView gets updated correctly to the correct amount of lines, the second however stays 1 even though there is clearly more space.

    Please help.

    Thank you

    • Torbjørn
      Torbjørn over 15 years
      It's the simple questions we always forget to ask ourselves. Will look forward to any useful answers to this question.
  • Simon Bastian
    Simon Bastian over 12 years
    > System.Environment.UserDomainName` gives you the domain name only > > Similarly, System.Environment.UserName gives you the user name only This will not work on ASP.NET
  • FMFF
    FMFF over 12 years
    I think it works if you use authentication=Windows and impersonation=true. See - stackoverflow.com/questions/8841816/…
  • Hassan Gulzar
    Hassan Gulzar almost 12 years
    Need an elegant solution for this. I agree. One answer to the domain\user part is this one: stackoverflow.com/a/185716/481656
  • Sam Harwell
    Sam Harwell almost 11 years
    Your return statement in GetLogin can be simplified to return s.Substring(stop + 1);
  • abatishchev
    abatishchev almost 11 years
    Isn't using regex an overkill here when simple string manipulating may be used instead?
  • abatishchev
    abatishchev almost 11 years
    Sounds like: I have a problem. Let's use regex. Now I have two problems :)
  • Adam Cooper
    Adam Cooper almost 11 years
    A regex solves the problem in one simple line. They're not the right tool for every job but I think in this case the regex solution is more elegant.
  • Ed Greaves
    Ed Greaves over 6 years
    What if the username has multiple back-slashes? What if the user wants to use the UPN format of [email protected]? I ended up using the Win32 function CredUIParseUserName. See pinvoke.net/default.aspx/credui.creduiparseusername