Sunday 30 November 2014

C# Active Directory fuctions

//Check user exist in a group
public static bool IfUserExistInGroup(string username, string groupname)
       {
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
 
           // find a user
           UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
 
           // find the group in question
           GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
 
           // check if user is member of that group
           if (user.IsMemberOf(group))
           {
               return true;
           }
           else
               return false;
 
       }
//Check if group exist
public static bool ifGroupExist(string groupname)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "Password");
 
            GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       groupname);
 
 
            if (grp != null)
            {
                grp.Dispose();
                ctx.Dispose();
                return true;
 
            }
            else
            {
                ctx.Dispose();
                return false;
            }
 
 
        }
//if user exist
 public static bool ifUserExist(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "password");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
 
            if (usr != null)
            {
                usr.Dispose();
                ctx.Dispose();
                return true;
 
            }
            else
            {
                ctx.Dispose();
                return false;
            }
 
 
        }

//Find if user is administrator
 
public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
 
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
 
            return false;
        }
//set home directory 
public static string setHomeDir(string username, string homeDir)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                         "",
                                         "",
                                         "");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
            if (usr != null)
            {
                if (usr.Enabled == false)
                    usr.Enabled = true;
                usr.HomeDirectory = homeDir;
                try
                {
                    usr.Save();
                }
                catch (Exception e)
                {
                    return e.ToString();
                }
                usr.Dispose();
 
            }
            else { return "cant find user"; }
            ctx.Dispose();
            return ("succssful");
 
 
        }
//Create user
public static void createUser(string username, string password, string firstname, string surname, string yearlevel, string homegroup)
        {
            if (ifUserExist(username))
                writeToLogs("user:" + username + " already exist", ADUserlogs);
            else
            {
                PrincipalContext pc = new PrincipalContext(ContextType.Domain,
                                                       "DomainName",
                                                       "AdminName",
                                                       "");
                UserPrincipal up = new UserPrincipal(pc);
                up.SamAccountName = username;
                up.HomeDirectory = "\\\\FileServer$\\" + username;
                if (!Directory.Exists(up.HomeDirectory))
                {
                    Directory.CreateDirectory(up.HomeDirectory);
                    AddDirectorySecurity(up.HomeDirectory, username, FileSystemRights.FullControl);
                }
 
                up.EmailAddress = username + "@Email.com";
 
                up.SetPassword(password);
                up.Enabled = true;
                up.ExpirePasswordNow();
                up.GivenName = firstname;
                up.Surname = surname;
                up.DisplayName = firstname + " " + firstname;
                up.HomeDrive = "U:";
                up.Description = "Year " + yearlevel + " 2014";
 
                try
                {
                    up.Save();
                    up.Dispose();
                    pc.Dispose();
                }
                catch (Exception E)
                {
                    Console.WriteLine(E.ToString());
                    up.Dispose();
                    pc.Dispose();
 
                }
                writeToLogs("user:" + username + "at yearlevel:" + yearlevel + "successfully created with password:" + password, ADUserlogs);
                string studentOU;
                if (homegroup != "condition1")
                    studentOU = "OU1"
                else
                    studentOU = "";
                moveOU(getDN(username), studentOU);
 
         }
        }

// create ou
public static void createou(string ou, string rootou)
        {
            string rootOU = rootou;
            DirectoryEntry objAD = new DirectoryEntry(rootOU, "i", "");
            DirectoryEntry objOU = objAD.Children.Add(ou, "OrganizationalUnit");
            objOU.CommitChanges();
        }

//Change group scope
public static void changeGroupScope(string s, GroupScope gp)
        {
            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, s);
                group.GroupScope = gp;
                group.Save();
            }
            catch (Exception E)
            {
                writeToLogs(E.ToString() + " --- when try to make changes on group name: " + s, ADGrouplogs);
            }
 
 
        }

//Remove Directory Security
 public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
        {
            // Create a new DirectoryInfo object.
            DirectoryInfo dInfo = new DirectoryInfo(FileName);
 
            // Get a DirectorySecurity object that represents the  
            // current security settings.
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
 
            // Add the FileSystemAccessRule to the security settings. 
            dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                            Rights,
                                                            ControlType));
 
            // Set the new access settings.
            dInfo.SetAccessControl(dSecurity);
 
        }

//Add  AD security
public static bool AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights)
        {
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(FileName);
 
                // Get a DirectorySecurity object that represents the  
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
 
                // Add the FileSystemAccessRule to the security settings. 
                dSecurity.ResetAccessRule(new FileSystemAccessRule(Account,
           Rights, AccessControlType.Allow));
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
            Rights,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow));
 
                /*
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                                Rights,
                                                                ControlType));
                */
 
 
                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
                return true;
            }
            catch (Exception E)
            {
                return false;
            }
 
 
        }

// move OU
 public static string moveOU(string userDN, string ou)
        {
            try
            {
                DirectoryEntry NewUser = new DirectoryEntry("LDAP://" + userDN);
                // Use the MoveTo property to define the new container you want to move the object to.
                NewUser.MoveTo(new DirectoryEntry("LDAP://" + ou));
            }
            catch (Exception e)
            {
                writeToLogs("when move :" + userDN + " to " + ou + " , this happened" + e.ToString(), ADOUlogs);
            }
            return ("success");
        }

//get Distinguish Name
public static string getDN(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "",
                                           "",
                                           "Password");
 
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
 
 
            if (usr != null)
            {
                string temp = usr.DistinguishedName.ToString();
                usr.Dispose();
                ctx.Dispose();
                return temp;
 
            }
            else
            {
 
                ctx.Dispose();
                return "cant find user";
            }
 
 
 
        }
//add user to a group
public static string AddUserToGroup(string userId, string groupName)
        {
            if (ifUserExist(userId))
            {
                if (!IfUserExistInGroup(userId, groupName))
                {
                    try
                    {
 
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                        // find the group in question
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userId);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                        user.Dispose();
                        ctx.Dispose();
 
                    }
                    catch (System.DirectoryServices.AccountManagement.PrincipalExistsException)
                    {
                        return userId + " is already a member of " + groupName;
                    }
                    catch (System.DirectoryServices.DirectoryServicesCOMException E)
                    {
                        return E.Message.ToString() + "WHen try to add: " + userId + " to group:" + groupName;
 
                    }
                    return userId + " is successfully added to " + groupName;
                }
                else
                    return userId + " is already a member of " + groupName;
            }
            else
                return userId + " is not exist";
 
        }
//empty active directory group 
 public static string emptyGroup(string groupname)
        {
            string output = "Empty Group started";
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // find the group in question
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
            // if found....
            if (group != null)
            {
                // iterate over members
                foreach (Principal p in group.GetMembers())
                {
 
                    UserPrincipal theUser = p as UserPrincipal;
                    if (theUser != null)
                    {
                        group.Members.Remove(theUser);
                        try
                        {
                            group.Save();
 
                        }
                        catch (Exception e)
                        {
                            output = e.ToString();
                        }
                        finally { }
                    }
 
                }
            }
            return output;
        }
//create active directory group
public static string createGroup(string Path, string name)
        {
            if (!DirectoryEntry.Exists(Path))
            {
                try
                {
                    DirectoryEntry entry = new DirectoryEntry(Path);
                    DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
                    group.Properties["sAmAccountName"].Value = name;
                    group.CommitChanges();
                    return "group: " + name + " has been created ";
                }
                catch (Exception e)
                {
                    return e.Message.ToString();
                }
            }
            else
            {
                return emptyGroup(name);
            }
        }
 

C# File System

//Count lines in file
 public static int CountLinesInFile(string f)
        {
            int count = 0;
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    count++;
                }
            }
            return count;
        }

//Create Folder
  public static string createDir(string s)
        {
            try
            {
                // Determine whether the directory exists. 
                if (Directory.Exists(s))
                {
                    return ("That path:" + s + " exists already.");
 
                }
 
                // Try to create the directory.
                DirectoryInfo di = Directory.CreateDirectory(s);
                return ("The directory :" + s + "was created successfully at " + Directory.GetCreationTime(s));
 
 
            }
            catch (Exception e)
            {
                return ("The process failed: " + e.ToString() + " when create:" + s);
            }
            finally { }
        }

C# run DOS command

public static void LaunchCommandLineApp(string command, string args)
        {
 
            // Use ProcessStartInfo class
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            startInfo.FileName = command;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.Arguments = args;
 
            try
            {
                // Start the process with the info we specified.
                // Call WaitForExit and then the using statement will close.
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch
            {
                // Log error.
            }
        }

get date time in YYYYYMMDDHHMMSS format

public static string getDateTime()
        {
            return (DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString());
        }     

C# Fix Internet Explorer with wpad proxy

 public static void IEFix()
        {
            foreach (Process proc in Process.GetProcessesByName("iexplore.exe"))
            {
                proc.Kill();
            }
 
            RegistryKey startPageKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
            startPageKey.SetValue("Start Page", "http://");
            startPageKey.Close();
 
            RegistryKey startPageKey2 = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            startPageKey2.SetValue("AutoConfigURL", "http:///wpad.dat");
            startPageKey2.Close();
            Tools.LaunchCommandLineApp("C:\\Program Files\\Internet Explorer\\iexplore.exe", "");
        }

C# Get Serial Number

import System.Management;
public static string getSN()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor");
            string collectedInfo = ""; // here we will put the informa
 
            searcher.Query = new ObjectQuery("select * from Win32_BIOS");
            foreach (ManagementObject share in searcher.Get())
            {
                //then, the serial number of BIOS
                collectedInfo += share.GetPropertyValue("SerialNumber").ToString();
            }
            return collectedInfo;
        }

C# SQL Server Examples

This is for a quick reference whenever I need use some data from SQL server:
1. From SQL to DataTable:
SqlConnection myConnection = new SqlConnection("user id=;" +
                                      "password=;server=;" +
                                      "database=; " +
                                      "connection timeout=30");
        myConnection.Open();
        SqlCommand command = new SqlCommand("Select xxx from xxx here xxx =xxx order by xxx", myConnection);
        // Creates a SqlDataReader instance to read data from the table.
        SqlDataReader dataReader = command.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(dataReader);


2. From DataTable to String Builder
var sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast().
                                  Select(column => column.ColumnName).
                                  ToArray();
        sb.AppendLine(string.Join(",", columnNames));
 
        foreach (DataRow row in dt.Rows)
        {
            string[] fields = row.ItemArray.Select(field => field.ToString()).
                                            ToArray();
            sb.AppendLine(string.Join(",", fields));
        }
3. From DataTable to GridView
this.GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
4.From DataTable to CSV
StringBuilder sb = new StringBuilder();  
string[] columnNames = dt.Columns.Cast().
                                  Select(column => column.ColumnName).
                                  ToArray();
sb.AppendLine(string.Join(",", columnNames));
 
foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
    sb.AppendLine(string.Join(",", fields));
} 
File.WriteAllText("test.csv", sb.ToString())

Reference: http://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv