Joseph Michael Pesch
VP Programming

C# ArrayList to Delimited String

by 31. May 2011 09:18
// Convert ArrayList to comma delimited string...
string myListString = string.Join(","
        , ((myArrayList.ToArray(typeof(string)) as string[]);

Tags:

C#

LDAP Query to Find a Users Manager Using C#

by 28. May 2011 11:46

Method 1:

DirectoryEntry deUserRootEntry = new DirectoryEntry("LDAP://impaccompanies.com");
DirectorySearcher dsUserSearcher = new DirectorySearcher();
dsUserSearcher.SearchRoot = deUserRootEntry;
//dsUserSearcher.Filter = "name=User Name";
dsUserSearcher.Filter = "userprincipalname=userid@domain.com";
if (dsUserSearcher.FindOne().GetDirectoryEntry() != null)
{
  DirectoryEntry deUser = dsUserSearcher.FindOne().GetDirectoryEntry();

  if (dsUserSearcher.FindOne().GetDirectoryEntry().Properties["manager"].Value != null)
  {
    ///you get manager here...
  }
}

Method 2:

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

// Get specific user in domain...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com");
UserPrincipal usp = UserPrincipal.FindByIdentity(ctx, "userid@domain.com");

// Call the GetManager method and get the managers user id...
UserPrincipal mgp = GetManager(ctx, usp);
System.Diagnostics.Debug.WriteLine(mgp.UserPrincipalName);

// Method to find the manager for a specific user...
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user)
{
  if (user != null)
  {
    // Get the DirectoryEntry object of the UserPrincipal object
    var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry;

    if (dirEntryForUser != null)
    {
      // See if the user has a manager assigned and if so return it...
      if (dirEntryForUser.Properties["manager"] != null 
          && dirEntryForUser.Properties["manager"].Count > 0)
      {
        string mgrDN = dirEntryForUser.Properties["manager"][0].ToString();
        // Get the manager UserPrincipal via the DN 
        return UserPrincipal.FindByIdentity(ctx, mgrDN);
      }
    }
  }
  return null;
}

Tags:

C#

LDAP Query to Find a Users Manager Using C#

by 28. May 2011 11:28

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

// Get specific user in domain...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com");
UserPrincipal usp = UserPrincipal.FindByIdentity(ctx, "userid@domain.com");

// Call the GetManager method and get the managers user id...
UserPrincipal mgp = GetManager(ctx, usp);
System.Diagnostics.Debug.WriteLine(mgp.UserPrincipalName);

// Method to find the manager for a specific user...
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user)
{
  if (user != null)
  {
    // Get the DirectoryEntry object of the UserPrincipal object
    var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry;

    if (dirEntryForUser != null)
    {
      // See if the user has a manager assigned and if so return it...
      if (dirEntryForUser.Properties["manager"] != null 
          && dirEntryForUser.Properties["manager"].Count > 0)
      {
        string mgrDN = dirEntryForUser.Properties["manager"][0].ToString();
        // Get the manager UserPrincipal via the DN 
        return UserPrincipal.FindByIdentity(ctx, mgrDN);
      }
    }
  }
  return null;
}

Tags:

C# | LDAP

LDAP Queries

by 28. May 2011 09:03
DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=YourCorp,dc=com");

if(deUser != null)
{
   
// check if the manager property is set - it could be NULL (no manager defined)
   
if(deUser.Properties["manager"] != null)
   
{
     
string managerDN = deUser.Properties["manager"][0].ToString();
   
}
}

Properties:
[0]: "homemdb"

    [1]: "countrycode"

    [2]: "cn"

    [3]: "msexchuseraccountcontrol"

    [4]: "mailnickname"

    [5]: "msexchhomeservername"

    [6]: "msexchhidefromaddresslists"

    [7]: "msexchalobjectversion"

    [8]: "usncreated"

    [9]: "objectguid"

    [10]: "msexchrequireauthtosendto"

    [11]: "whenchanged"

    [12]: "memberof"

    [13]: "accountexpires"

    [14]: "displayname"

    [15]: "primarygroupid"

    [16]: "badpwdcount"

    [17]: "objectclass"

    [18]: "instancetype"

    [19]: "msmqdigests"

    [20]: "objectcategory"

    [21]: "samaccounttype"

    [22]: "whencreated"

    [23]: "lastlogon"

    [24]: "useraccountcontrol"

    [25]: "msmqsigncertificates"

    [26]: "samaccountname"

    [27]: "userparameters"

    [28]: "mail"

    [29]: "msexchmailboxsecuritydescriptor"

    [30]: "adspath"

    [31]: "lockouttime"

    [32]: "homemta"

    [33]: "description"

    [34]: "msexchmailboxguid"

    [35]: "pwdlastset"

    [36]: "logoncount"

    [37]: "codepage"

    [38]: "name"

    [39]: "usnchanged"

    [40]: "legacyexchangedn"

    [41]: "proxyaddresses"

    [42]: "userprincipalname"

    [43]: "admincount"

    [44]: "badpasswordtime"

    [45]: "objectsid"

    [46]: "msexchpoliciesincluded"

    [47]: "mdbusedefaults"

    [48]: "distinguishedname"

    [49]: "showinaddressbook"

    [50]: "givenname"

    [51]: "textencodedoraddress"

    [52]: "lastlogontimestamp"

Tags:

Sharepoint Get User Information from within Workflow/Application Page

by 27. May 2011 14:39

// Workflow member variable declarations...
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

private void SomeMethod()
{
  // This method failed: SPList userList = SPContext.Current.Web.SiteUserInfoList;
  SPList userList = workflowProperties.Site.RootWeb.SiteUserInfoList;
  SPUser user = SPContext.Current.Web.EnsureUser(@"domain\userid");
  SPListItem userItem = userList.Items.GetItemById(user.ID);
  foreach(SPField fld in userItem.Fields) 
  {
    System.Diagnostics.Debug.WriteLine(string.Format("{0} >>> {1}", fld.Title, fld.InternalName)); 
  }
}

OUTPUT FROM MY SAMPLE TEST:
ID >>> ID
Content Type ID >>> ContentTypeId
Content Type >>> ContentType
Name >>> Title
Modified >>> Modified
Created >>> Created
Created By >>> Author
Modified By >>> Editor
Has Copy Destinations >>> _HasCopyDestinations
Copy Source >>> _CopySource
owshiddenversion >>> owshiddenversion
Workflow Version >>> WorkflowVersion
UI Version >>> _UIVersion
Version >>> _UIVersionString
Attachments >>> Attachments
Approval Status >>> _ModerationStatus
Approver Comments >>> _ModerationComments
Edit >>> Edit
Name >>> LinkTitleNoMenu
Title >>> LinkTitle
Title >>> LinkTitle2
Select >>> SelectTitle
Instance ID >>> InstanceID
Order >>> Order
GUID >>> GUID
Workflow Instance ID >>> WorkflowInstanceID
URL Path >>> FileRef
Path >>> FileDirRef
Modified >>> Last_x0020_Modified
Created >>> Created_x0020_Date
Item Type >>> FSObjType
Sort Type >>> SortBehavior
Effective Permissions Mask >>> PermMask
Name >>> FileLeafRef
Unique Id >>> UniqueId
Client Id >>> SyncClientId
ProgId >>> ProgId
ScopeId >>> ScopeId
File Type >>> File_x0020_Type
HTML File Type >>> HTML_x0020_File_x0020_Type
Edit Menu Table Start >>> _EditMenuTableStart
Edit Menu Table Start >>> _EditMenuTableStart2
Edit Menu Table End >>> _EditMenuTableEnd
Name >>> LinkFilenameNoMenu
Name >>> LinkFilename
Name >>> LinkFilename2
Type >>> DocIcon
Server Relative URL >>> ServerUrl
Encoded Absolute URL >>> EncodedAbsUrl
File Name >>> BaseName
Property Bag >>> MetaInfo
Level >>> _Level
Is Current Version >>> _IsCurrentVersion
Item Child Count >>> ItemChildCount
Folder Child Count >>> FolderChildCount
Account >>> Name
E-Mail >>> EMail
Mobile Number >>> MobilePhone
About Me >>> Notes
SIP Address >>> SipAddress
Locale >>> Locale
Calendar Type >>> CalendarType
AdjustHijriDays >>> AdjustHijriDays
TimeZone >>> TimeZone
Time Format >>> Time24
Alternate Calendar Type >>> AltCalendarType
CalendarView Options >>> CalendarViewOptions
WorkDays >>> WorkDays
WorkDay StartHour >>> WorkDayStartHour
WorkDay EndHour >>> WorkDayEndHour
Is Site Admin >>> IsSiteAdmin
Deleted >>> Deleted
Picture >>> Picture
Department >>> Department
Job Title >>> JobTitle
Is Active >>> IsActive
Group >>> GroupLink
Edit >>> GroupEdit
Name >>> ImnName
Picture >>> PictureDisp
Name >>> NameWithPicture
Name >>> NameWithPictureAndDetails
Edit >>> EditUser
Selection Checkbox >>> UserSelection
Content Type >>> ContentTypeDisp
 
 

Tags:

C# | Sharepoint

Sharepoint Get User Information from within Workflow/Application Page

by 27. May 2011 13:51

SPList userList = SPContext.Current.Web.SiteUserInfoList;

SPUser user = SPContext.Current.Web.EnsureUser(@"domain\userid");

SPListItem userItem = userList.Items.GetItemById(user.ID);

 

 

Tags:

C# | Sharepoint

Linq to Sharepoint DataContext Binding

by 27. May 2011 07:32

// Get DataContext from application page

SPMetalDataContext data = new SPMetalDataContext(SPContext.GetContext(this.Context).Web.Url);

 

// Get DataContext from workflow

public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

// The workflowProperties variable would be declared in the workflow class

SPMetalDataContext data = new SPMetalDataContext(workflowProperties.Item.Web.Url); 

 

OR

SPMetalDataContext data = new SPMetalDataContext(SPContext.Current.Web.Url);

 

Tags:

C# | Sharepoint

Linq Child/Nested Entity Join to Master Table Entity

by 26. May 2011 10:13
    private void LoadList_AssignedResources(int RequestId)
    {
      using (SPMetalDataContext dc = new SPMetalDataContext(this.Web.Url))
      {

        ResourceRequestsItem req = dc.ResourceRequests
          .Where(x => x.Id.Equals(RequestId)).FirstOrDefault();
        
        var qry = from rs in dc.Resources
                  join rx in req.Resources on rs.Id equals rx.Id
                  select new
                  {
                    Title = rs.Title,
                    Id = rs.Id
                  };

        AssignedResourcesList.DataTextField = "Title";
        AssignedResourcesList.DataValueField = "Id";
        AssignedResourcesList.DataSource = qry;
        AssignedResourcesList.DataBind();
      }
    }

Tags:

C# | LINQ to SQL

Add Author, Created, Editor and Modified Fields to SPMetal Generated C# Class for Sharepoint

by 26. May 2011 09:29
public partial class Item : Microsoft.SharePoint.Linq.ITrackEntityState
  , Microsoft.SharePoint.Linq.ITrackOriginalValues
  , System.ComponentModel.INotifyPropertyChanged
  , System.ComponentModel.INotifyPropertyChanging
{
  // Add the following to the Item class in the SPMetal generated class...
  string _CreatedBy;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Author", Storage = "_CreatedBy"
    , ReadOnly = true, FieldType = "User", IsLookupValue = true)]
  public string CreatedBy
  {
    get
    { return this._CreatedBy; }
    set
    {
      if ((value != this._CreatedBy))
      {
        this.OnPropertyChanging("CreatedBy"this._CreatedBy);
        this._CreatedBy = value;
        this.OnPropertyChanged("CreatedBy");
      }
    }
  }

  DateTime _CreatedOn;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Created", Storage = "_CreatedOn"
    , ReadOnly = true, FieldType = "DateTime", IsLookupValue = false)]
  public DateTime CreatedOn
  {
    get
    { return this._CreatedOn; }
    set
    {
      if ((value != this._CreatedOn))
      {
        this.OnPropertyChanging("CreatedOn"this._CreatedOn);
        this._CreatedOn = value;
        this.OnPropertyChanged("CreatedOn");
      }
    }
  }

  string _ModifiedBy;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Editor", Storage = "_ModifiedBy"
    , ReadOnly = true, FieldType = "User", IsLookupValue = true)]
  public string ModifiedBy
  {
    get
    {
      return this._ModifiedBy;
    }
    set
    {
      if ((value != this._ModifiedBy))
      {
        this.OnPropertyChanging("ModifiedBy"this._ModifiedBy);
        this._ModifiedBy = value;
        this.OnPropertyChanged("ModifiedBy");
      }
    }
  }

  DateTime _ModifiedOn;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Modified", Storage = "_ModifiedOn"
    , ReadOnly = true, FieldType = "DateTime", IsLookupValue = false)]
  public DateTime ModifiedOn
  {
    get
    {
      return this._ModifiedOn;
    }
    set
    {
      if ((value != this._ModifiedOn))
      {
        this.OnPropertyChanging("ModifiedOn"this._ModifiedOn);
        this._ModifiedOn = value;
        this.OnPropertyChanged("ModifiedOn");
      }
    }
  }

Tags:

C# | Sharepoint

Hide/Remove Title Column from Sharepoint List

by 25. May 2011 10:08

Tags:

Sharepoint

Simple Linq In Clause Example

by 25. May 2011 09:43
      // Sample using array and string converted to array...
      string[] ValueArray = new string[] { "11""13" };
      string ValueList = "1;3;5;9;15";
      using (SPMetalDataContext dc = new SPMetalDataContext(this.Web.Url))
      {
        var query =
          from res in dc.Resources
          where ValueList.Split(';').Contains(res.Id.ToString())
             || ValueArray.Contains(res.Id.ToString())
          select new
          {
            res.Title,
            res.Id
          };

Tags:

C#

C# Application to Toggle Between Multiple Windows for Specified Time Interval

by 19. May 2011 08:12

This application allows you to define windows with intervals and then when started it will toggle between those windows at the specified interval.

 

ToggleWindows.zipx (70.15 kb)

Tags:

C# | Windows

JavaScript Drop Down Menu Example

by 18. May 2011 08:31

Tags:

CSS | HTML | JavaScript