SHARE
TWEET

Untitled

a guest Jun 18th, 2019 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.DirectoryServices;
  6. using System.DirectoryServices.AccountManagement;
  7. using System.IO;
  8. using AccountCheck;
  9. using Microsoft.ActiveDirectory.Management.Commands;
  10. using System.Data;
  11. using System.Data.SqlClient;
  12. using System.Configuration;
  13. using System.ComponentModel;
  14.  
  15. namespace testproj1
  16. {
  17.     class Class1
  18.     {
  19.         //private static DateTime LonTS1;
  20.  
  21.         //static void Main(string[] args)
  22.  
  23.         // public static int LoadADUsers()
  24.         static void Main(string[] args)
  25.         {
  26.  
  27.             int userCount = 0;
  28.             int maxPasswordAge = 90;
  29.             string LDAP_QUERY = "LDAP://DC=xyz,DC=com";
  30.             string LDAP_FILTER = "(&(objectClass=user)(objectCategory=person))";
  31.             //string LDAP_FILTER = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
  32.  
  33.  
  34.             DirectoryEntry objDirEntry = new DirectoryEntry(LDAP_QUERY);
  35.             string[] aryPropertiesToRetrieve =
  36.             {"sAMAccountName","Company","whenCreated","department","description","Enabled","displayName","distinguishedName","mail","employeeID","accountExpires", "extensionAttribute11", "extensionAttribute12",
  37.              "extensionAttribute13", "extensionAttribute14","extensionAttribute7", "extensionAttribute9","givenName" ,"Initials","title","location","sn","LastLogoff","LastLogon","manager","ChangePasswordAtLogon",
  38.              "physicalDeliveryOfficeName", "pwdLastSet","PasswordNeverExpires","PasswordNotRequired","nTSecurityDescriptor","ProtectedFromAccidentalDeletion","usercannotchangepassword","userAccountControl","userPrincipalName","lastlogontimestamp",
  39.             };
  40.             List<string> adPropertyList = new List<string>(aryPropertiesToRetrieve);
  41.             DirectorySearcher objSearch = new DirectorySearcher(objDirEntry, LDAP_FILTER, aryPropertiesToRetrieve);
  42.             objSearch.Asynchronous = true;
  43.             objSearch.PageSize = 500;
  44.             objSearch.SizeLimit = 1000;
  45.             objSearch.SearchScope = SearchScope.Subtree;
  46.             SearchResultCollection objResults = objSearch.FindAll();
  47.             User adUser = new User();
  48.             List<User> allUsers = new List<User>();
  49.             //NewADObjectParameterSet na = new NewADObjectParameterSet();
  50.             //string SQL = string.Empty;
  51.             int userAccountControl = 0;
  52.             DateTime accountExpiration = DateTime.Now;
  53.             //DateTime? accountExpiration;
  54.             DateTime passwordLastSet = DateTime.Now;
  55.             int daysUntilPasswordExpiration = 0;
  56.             DateTime passwordExpiration = DateTime.Now;
  57.             int daysUntilAccountExpiration = 0;
  58.             double passwordAge = 0;
  59.             DateTime? LLon=null;
  60.             string Mgr;
  61.             bool MCPANL;
  62.             string pfcd;
  63.             foreach (SearchResult result in objResults)
  64.             {
  65.                 PrincipalContext context = new PrincipalContext(ContextType.Domain);
  66.                 UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, GetPropertyValue(result, "sAMAccountName").ToString());
  67.  
  68.                 //accountExpiration = (DateTime)GetPropertyValue_name(result, "accountExpires", "displayName", "sAMAccountName");
  69.                 //accountExpiration = (DateTime)GetPropertyValue(result, "accountExpires");
  70.                 accountExpiration = (DateTime)GetPropertyValue(result, "accountExpires");
  71.                 //accountExpiration = user.AccountExpirationDate.HasValue ? (DateTime)user.AccountExpirationDate : (DateTime?)null;
  72.                 daysUntilAccountExpiration = accountExpiration.Subtract(DateTime.Now).Days;
  73.                 userAccountControl = (int)GetPropertyValue(result, "userAccountControl");
  74.                 passwordLastSet = (DateTime)GetPropertyValue(result, "pwdLastSet");
  75.                 pfcd = (string)GetPropertyValue(result, "ProtectedFromAccidentalDeletion");
  76.                 if (passwordLastSet == null)
  77.                 { MCPANL = true; }
  78.                 else { MCPANL = false; }
  79.                 Mgr = GetPropertyValue(result, "manager").ToString();
  80.                 if (Mgr == "" || Mgr == null)
  81.                 { Mgr = ""; }
  82.                 else
  83.                 { Mgr = Mgr.Substring(3, Mgr.IndexOf(",") - 3); }
  84.                 //LLoff = (string)GetPropertyValue(result, "LastLogoff");    
  85.                // LLon = user.LastLogon.HasValue ? (DateTime)user.LastLogon : (DateTime?) null;
  86.                 LLon = user.LastLogon;
  87.                 if (userAccountControl > 10000) //password never expires
  88.                 {
  89.                     daysUntilPasswordExpiration = daysUntilAccountExpiration;
  90.                     passwordExpiration = accountExpiration;
  91.                 }
  92.                 else
  93.                 {
  94.                     passwordAge = DateTime.Now.Subtract(passwordLastSet).TotalDays;
  95.                     daysUntilPasswordExpiration = maxPasswordAge - (int)Math.Round(passwordAge + 1);
  96.                     passwordExpiration = DateTime.Now.AddDays(daysUntilPasswordExpiration);
  97.                 }
  98.  
  99.                 adUser = new User()
  100.                 {
  101.                     Name = GetPropertyValue(result, "sAMAccountName").ToString(),
  102.                     Company = GetPropertyValue(result, "Company").ToString(),
  103.                     Creation_Date = GetPropertyValue(result, "whenCreated").ToString(),
  104.                     Department = GetPropertyValue(result, "department").ToString(),
  105.                     Description = GetPropertyValue(result, "description").ToString(),
  106.                     Enabled = user.Enabled,
  107.                     Display_Name = GetPropertyValue(result, "displayName").ToString(),
  108.                     Distinguished_Name = GetPropertyValue(result, "distinguishedName").ToString(),
  109.                     Email = GetPropertyValue(result, "mail").ToString(),
  110.                     EmployeeID = GetPropertyValue(result, "employeeID").ToString(),
  111.                     Expiration_Date = accountExpiration,
  112.                     extensionAttribute11 = GetPropertyValue(result, "extensionAttribute11").ToString(),
  113.                     extensionAttribute12 = GetPropertyValue(result, "extensionAttribute12").ToString(),
  114.                     extensionAttribute13_Room = GetPropertyValue(result, "extensionAttribute13").ToString(),
  115.                     extensionAttribute14_Ext = GetPropertyValue(result, "extensionAttribute14").ToString(),
  116.                     extensionAttribute7_IAM_ID = GetPropertyValue(result, "extensionAttribute7").ToString(),
  117.                     extensionAttribute9_CostCenter = GetPropertyValue(result, "extensionAttribute9").ToString(),
  118.                     First_Name = GetPropertyValue(result, "givenName").ToString(),
  119.                     Initials = GetPropertyValue(result, "Initials").ToString(),
  120.                     Job_Title = GetPropertyValue(result, "title").ToString(),
  121.                     //Last_Known_Location = GetPropertyValue(result, "location").ToString(),
  122.                     Last_Name = GetPropertyValue(result, "sn").ToString(),
  123.                     // lastLogoff = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(LLoff),
  124.                     //lastLogoff=
  125.                     lastLogon = LLon,
  126.                     Manager = Mgr,
  127.                     Must_Change_Password_At_Next_Logon = MCPANL,
  128.                     Office = GetPropertyValue(result, "physicalDeliveryOfficeName").ToString(),
  129.                     Password_Age_In_Days = passwordAge,
  130.                     Password_Expiration_Date = passwordExpiration,
  131.                     Password_Last_Changed = passwordLastSet,
  132.                     Password_Never_Expire = user.PasswordNeverExpires,
  133.                     Password_Not_Required = user.PasswordNotRequired,
  134.                     physicalDeliveryOfficeName = GetPropertyValue(result, "physicalDeliveryOfficeName").ToString(),
  135.                     //Protected_From_Accidental_Deletion = GetPropertyValue(result, "ProtectedFromAccidentalDeletion").ToString(),
  136.                     User_Cannot_Change_Password = user.UserCannotChangePassword,
  137.                     userAccountControl = GetPropertyValue(result, "userAccountControl").ToString(),
  138.                     Username = GetPropertyValue(result, "userPrincipalName").ToString(),
  139.                     Username_pre_2000 = GetPropertyValue(result, "sAMAccountName").ToString(),
  140.                     //lastLogon_value= LLonTS1
  141.                 };
  142.  
  143.                 allUsers.Add(adUser);
  144.  
  145.                 userCount++;
  146.                 //Console.WriteLine("the count is" + userCount);
  147.                 // Console.ReadLine();
  148.  
  149.  
  150.  
  151.             } // end foreach SearchResult loop
  152.  
  153.             string connectionstring = ConfigurationManager.ConnectionStrings["LDAP_ALLUSER"].ConnectionString;
  154.             using (SqlConnection conn = new SqlConnection(connectionstring))
  155.             {
  156.  
  157.  
  158.                 conn.Open();
  159.                 string query = "truncate table [dbo].[adlook] ";
  160.                 SqlCommand cmd1 = new SqlCommand(query, conn);
  161.                 cmd1.ExecuteNonQuery();
  162.                 SqlCommand cmd =
  163.                new SqlCommand(
  164.                    "INSERT INTO [dbo].[ADlook] (name, company, creation_date,department,description,enabled,display_name,distinguished_name,email,employeeid,expiration_date,extensionattribute11,extensionattribute12,extensionattribute13_room,extensionattribute14_ext,extensionattribute7_iam_id,extensionattribute9_costcenter,first_name,initials,job_title,last_name,lastlogon,manager,must_change_password_at_next_logon,office,password_age_in_days,password_expiration_date,password_last_changed,password_never_expire,password_not_required,physicaldeliveryofficename,user_cannot_change_password,useraccountcontrol,username,username_pre_2000) " +
  165.                    " VALUES (@name,@company,@creation_date,@department,@description,@enabled,@display_name,@distinguished_name,@email,@employeeid,@expiration_date,@extensionattribute11,@extensionattribute12,@extensionattribute13_room,@extensionattribute14_ext,@extensionattribute7_iam_id,@extensionattribute9_costcenter,@first_name,@initials,@job_title,@last_name,@lastlogon,@manager,@must_change_password_at_next_logon,@office,@password_age_in_days,@password_expiration_date,@password_last_changed,@password_never_expire,@password_not_required,@physicaldeliveryofficename,@user_cannot_change_password,@useraccountcontrol,@username,@username_pre_2000)");
  166.                 cmd.CommandType = CommandType.Text;
  167.                 cmd.Connection = conn;
  168.                 cmd.Parameters.Add("@name",DbType.String); cmd.Parameters.Add("@company",DbType.String); cmd.Parameters.Add("@creation_date",DbType.DateTime); cmd.Parameters.Add("@department",DbType.String); cmd.Parameters.Add("@description",DbType.String); cmd.Parameters.Add("@enabled",DbType.Boolean);
  169.                 cmd.Parameters.Add("@display_name",DbType.String); cmd.Parameters.Add("@distinguished_name",DbType.String); cmd.Parameters.Add("@email",DbType.String); cmd.Parameters.Add("@employeeid",DbType.String); cmd.Parameters.Add("@expiration_date",DbType.DateTime); cmd.Parameters.Add("@extensionattribute11",DbType.String);
  170.                 cmd.Parameters.Add("@extensionattribute12",DbType.String); cmd.Parameters.Add("@extensionattribute13_room",DbType.String); cmd.Parameters.Add("@extensionattribute14_ext",DbType.String); cmd.Parameters.Add("@extensionattribute7_iam_id",DbType.String); cmd.Parameters.Add("@extensionattribute9_costcenter",DbType.String); cmd.Parameters.Add("@first_name",DbType.String);
  171.                 cmd.Parameters.Add("@initials",DbType.String); cmd.Parameters.Add("@job_title",DbType.String); cmd.Parameters.Add("@last_name",DbType.String); cmd.Parameters.Add("@lastlogon",DbType.DateTime); cmd.Parameters.Add("@manager",DbType.String); cmd.Parameters.Add("@must_change_password_at_next_logon",DbType.Boolean);
  172.                 cmd.Parameters.Add("@office",DbType.String); cmd.Parameters.Add("@password_age_in_days",DbType.Int32); cmd.Parameters.Add("@password_expiration_date",DbType.DateTime); cmd.Parameters.Add("@password_last_changed",DbType.DateTime); cmd.Parameters.Add("@password_never_expire",DbType.Boolean); cmd.Parameters.Add("@password_not_required",DbType.Boolean);
  173.                 cmd.Parameters.Add("@physicaldeliveryofficename",DbType.String); cmd.Parameters.Add("@user_cannot_change_password",DbType.Boolean); cmd.Parameters.Add("@useraccountcontrol",DbType.String); cmd.Parameters.Add("@username",DbType.String); cmd.Parameters.Add("@username_pre_2000",DbType.String);
  174.  
  175.                 foreach (var item in allUsers)
  176.                 {
  177.                     cmd.Parameters[0].Value = item.Name; cmd.Parameters[1].Value = item.Company; cmd.Parameters[2].Value = item.Creation_Date; cmd.Parameters[3].Value = item.Department; cmd.Parameters[4].Value = item.Description;
  178.                     cmd.Parameters[5].Value = item.Enabled; cmd.Parameters[6].Value = item.Display_Name; cmd.Parameters[7].Value = item.Distinguished_Name; cmd.Parameters[8].Value = item.Email; cmd.Parameters[9].Value = item.EmployeeID;
  179.                     cmd.Parameters[10].Value = item.Expiration_Date; cmd.Parameters[11].Value = item.extensionAttribute11; cmd.Parameters[12].Value = item.extensionAttribute12; cmd.Parameters[13].Value = item.extensionAttribute13_Room; cmd.Parameters[14].Value = item.extensionAttribute14_Ext;
  180.                     cmd.Parameters[15].Value = item.extensionAttribute7_IAM_ID; cmd.Parameters[16].Value = item.extensionAttribute9_CostCenter; cmd.Parameters[17].Value = item.First_Name; cmd.Parameters[18].Value = item.Initials; cmd.Parameters[19].Value = item.Job_Title;
  181.                     cmd.Parameters[20].Value = item.Last_Name;cmd.Parameters[21].Value = (object)item.lastLogon ?? DBNull.Value;cmd.Parameters[22].Value = item.Manager; cmd.Parameters[23].Value = item.Must_Change_Password_At_Next_Logon; cmd.Parameters[24].Value = item.Office;
  182.                     cmd.Parameters[25].Value = item.Password_Age_In_Days; cmd.Parameters[26].Value = item.Password_Expiration_Date; cmd.Parameters[27].Value = item.Password_Last_Changed; cmd.Parameters[28].Value = item.Password_Never_Expire; cmd.Parameters[29].Value = item.Password_Not_Required;
  183.                     cmd.Parameters[30].Value = item.physicalDeliveryOfficeName; cmd.Parameters[31].Value = item.User_Cannot_Change_Password; cmd.Parameters[32].Value = item.userAccountControl; cmd.Parameters[33].Value = item.Username; cmd.Parameters[34].Value = item.Username_pre_2000;
  184.  
  185.  
  186.                     cmd.ExecuteNonQuery();
  187.                 }
  188.  
  189.                 conn.Close();
  190.  
  191.             }
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.         }
  200.  
  201.  
  202.         ///////////////////////////////////////// 1st method starts
  203.         private static object GetPropertyValue(SearchResult result, string propertyName)
  204.         {
  205.             object propValue = null;
  206.  
  207.  
  208.             if (result.Properties.Contains(propertyName))
  209.             {
  210.                 if (result.Properties[propertyName].Count > 0)
  211.                 {
  212.                     propValue = result.Properties[propertyName][0];
  213.  
  214.                     if (propertyName == "accountExpires" || propertyName == "pwdLastSet")
  215.                     {
  216.                         long dateValue = (long)propValue;
  217.                         long maxDate = DateTime.MaxValue.ToFileTime();
  218.  
  219.                         if (dateValue == 0 || dateValue > maxDate || dateValue == null) //never expires
  220.                         {
  221.                             propValue = Convert.ToDateTime("12/31/2100"); //new DateTime(2100, 12, 31);
  222.                         }
  223.                         else //expires
  224.                         {
  225.                             propValue = DateTime.FromFileTime(dateValue);
  226.                         }
  227.                     }
  228.                 }
  229.             }
  230.             else
  231.             {
  232.                 propValue = string.Empty;
  233.  
  234.             }
  235.  
  236.             return propValue;
  237.         }
  238.         ////////////////////////////// 1st method ends
  239.     }
  240.  
  241. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top