private string GetUpnFromSelection(UnsafeNativeMethods.DsSelection selection) { if (!string.IsNullOrEmpty(selection.pwzUPN)) { return(selection.pwzUPN); } const string sidPropertyName = "objectSid"; string upn = selection.pwzADsPath; // Try to get the UPN value from AD path try { using (DirectoryEntry entry = new DirectoryEntry(upn)) { if (entry.Properties.Contains(sidPropertyName)) { SecurityIdentifier sid = new SecurityIdentifier((byte[])entry.Properties[sidPropertyName].Value, 0); if (sid.IsAccountSid()) { NTAccount acc = (NTAccount)sid.Translate(typeof(NTAccount)); upn = acc.Value; } } } } catch (Exception e) { Trace.TraceError(e.Message); } return(upn); }
private List <DsObjectPickerItem> ProcessSelections(System.Runtime.InteropServices.ComTypes.IDataObject dataObj) { List <DsObjectPickerItem> selections = new List <DsObjectPickerItem>(); if (dataObj == null) { return(selections); } STGMEDIUM stg = new STGMEDIUM(); stg.tymed = TYMED.TYMED_HGLOBAL; stg.unionmember = IntPtr.Zero; stg.pUnkForRelease = null; FORMATETC fe = new FORMATETC(); if (!this.DesignMode) { fe.cfFormat = (short)System.Windows.Forms.DataFormats.GetFormat(CfstrDsopDsSelectionList).Id; } fe.ptd = IntPtr.Zero; fe.dwAspect = DVASPECT.DVASPECT_CONTENT; fe.lindex = -1; fe.tymed = TYMED.TYMED_HGLOBAL; dataObj.GetData(ref fe, out stg); IntPtr pDsSL = UnsafeNativeMethods.GlobalLock(stg.unionmember); try { IntPtr current = pDsSL; int cnt = Marshal.ReadInt32(current); if (cnt > 0) { current = (IntPtr)((int)current + (Marshal.SizeOf(typeof(uint)) * 2)); for (int i = 0; i < cnt; i++) { UnsafeNativeMethods.DsSelection selection = (UnsafeNativeMethods.DsSelection)Marshal.PtrToStructure(current, typeof(UnsafeNativeMethods.DsSelection)); Marshal.DestroyStructure(current, typeof(UnsafeNativeMethods.DsSelection)); current = (IntPtr)((int)current + Marshal.SizeOf(typeof(UnsafeNativeMethods.DsSelection))); DsObjectPickerItem item = new DsObjectPickerItem(); item.Name = selection.pwzName; item.Upn = GetUpnFromSelection(selection); item.ClassName = selection.pwzClass.ToLowerInvariant(); item.Sid = GetSidFromUpn(item.Upn); selections.Add(item); } } } finally { if (stg.unionmember != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnlock(stg.unionmember); } UnsafeNativeMethods.ReleaseStgMedium(ref stg); } return(selections); }