Beispiel #1
0
    /// <summary>
    /// Event raises when we click on any contextmenu item
    /// And then performs the specified action
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void cm_OnMenuClick(object sender, EventArgs e)
    {
        // assure that the sender is a MenuItem
        MenuItem mi = sender as MenuItem;

        //Help
        if (mi != null && mi.Text.Equals("Help"))
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.UseShellExecute = true;
            psi.FileName = CommonResources.GetString("LAC_Help");
            psi.Verb = "open";
            psi.WindowStyle = ProcessWindowStyle.Normal;
            Process.Start(psi);
            return;
        }

        ADUCDirectoryNode dirnode = mi.Tag as ADUCDirectoryNode;

        if (dirnode == null && lvChildNodes.SelectedItems.Count == 1)
        {
            return;
        }

        int ret = -1;

        if (dirnode != null)
        {
            string[] attrs = { null };

            List<LdapEntry> ldapEntries = null;

            ret = dirnode.LdapContext.ListChildEntriesSynchronous(
            dirnode.DistinguishedName,
            Likewise.LMC.LDAP.Interop.LdapAPI.LDAPSCOPE.ONE_LEVEL,
            "(objectClass=*)",
            attrs,
            false,
            out ldapEntries);

            if (ret == (int)Likewise.LMC.Utilities.ErrorCodes.LDAPEnum.LDAP_NO_SUCH_OBJECT)
            {
                return;
            }
        }

        //Refresh the dirnode (redo a ldap query at the current dirnode)
        if (mi != null && mi.Text.Equals("Refresh"))
        {
            if (dirnode != null)
            {
                dirnode.Refresh();
                if (dirnode.Nodes.Count == 0)
                {
                    return;
                }
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
        }

        //Add New User
        if (mi != null && mi.Text.Equals("User"))
        {
            if (dirnode != null)
            {
                AddNewUser(dirnode);
            }
        }
        //Add new computer
        if (mi != null && mi.Text.Equals("Computer"))
        {
            if (dirnode != null)
            {
                AddNewComputer(dirnode, null);
            }
        }
        //Add new group
        if (mi != null && mi.Text.Equals("Group"))
        {
            if (dirnode != null)
            {
                AddNewGroup(dirnode);
            }
        }
        //Add new OU
        if (mi != null && mi.Text.Equals("Organizational Unit"))
        {
            if (dirnode != null)
            {
                AddNewOU(dirnode);
            }
        }

        //Add a generic Object
        if (mi != null && mi.Text.Equals("Other"))
        {
            if (dirnode != null)
            {
                AddNewObject(dirnode);
            }
        }

        //Delete an object (user, computer, group and OU
        if (mi != null && mi.Text.Equals("Delete"))
        {
            LACTreeNode parentNode = null;
            ret = -1;

            DialogResult dlg = container.ShowMessage(
           "Are you sure you want to delete this object(s)?",
           MessageBoxButtons.YesNo,
           MessageBoxIcon.Exclamation);

            if (dlg == DialogResult.Yes)
            {
                if (mi.Tag != null)
                {
                    parentNode = dirnode.Parent == null ? treeNode as ADUCDirectoryNode : dirnode.Parent as ADUCDirectoryNode;

                    ret = DODeleteADObjects(dirnode);
                }
                else
                {
                    parentNode = (LACTreeNode)treeNode;

                    foreach (ListViewItem item in lvChildNodes.SelectedItems)
                    {
                        ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                        if (dn != null)
                        {
                            ret = DODeleteADObjects(dn);
                            if (ret != 0)
                            {
                                break;
                            }
                        }
                    }
                }

                if (ret == 0)
                {
                    int length = CommonResources.GetString("Caption_Console").Length + 24;
                    string msgToDisplay = "Object(s) is deleted!";
                    if (length > msgToDisplay.Length)
                    {
                        msgToDisplay = msgToDisplay.PadRight(length - msgToDisplay.Length, '�');
                    }
                    container.ShowError(msgToDisplay);

                    if ((parentNode != null) && (parentNode is ADUCDirectoryNode))
                    {
                        ADUCPlugin plugin = treeNode.Plugin as ADUCPlugin;
                        ADUCDirectoryNode parentdirnode = parentNode as ADUCDirectoryNode;
                        parentdirnode.Refresh();
                        parentdirnode.IsModified = true;
                        base.treeNode = parentdirnode;
                    }
                }
            }
        }

        //Copy ...
        if (mi != null && mi.Text.Equals("Copy..."))
        {
            if (dirnode != null)
            {
                string obj_type = dirnode.ObjectClass;

                if (obj_type.Equals("top", StringComparison.InvariantCultureIgnoreCase) ||
                obj_type.Equals("user", StringComparison.InvariantCultureIgnoreCase))
                {
                    string sText = "Copy Object - User";
                    DirectoryContext dirContext = dirnode.LdapContext;

                    try
                    {
                        //first obtain the current userAccountControl value
                        DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
                        int userCtrlInt = Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());
                        long pwdLastSet = Convert.ToInt64(de.Properties["pwdLastSet"].Value.ToString());
                        string copyfrom = "Copy from: " + de.Properties["name"].Value.ToString();

                        bool bAcountDisable = false, bNeverExpiresPwd = false, bMustChangePwd = false, bUserCannotChange = false;

                        string userCtrlBinStr = UserGroupUtils.DecimalToBase(userCtrlInt, 2);

                        if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 10] == '1'
                            && pwdLastSet == 0)
                        {
                            bMustChangePwd = true;
                        }
                        if (userCtrlBinStr.Length >= 17 && userCtrlBinStr[userCtrlBinStr.Length - 17] == '1')
                        {
                            bNeverExpiresPwd = true;
                            bMustChangePwd = false;
                        }
                        if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 7] == '1'
                        && pwdLastSet != 0)
                        {
                            bUserCannotChange = true;
                        }
                        if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 2] == '1')
                        {
                            bAcountDisable = true;
                        }

                        ADUserAddDlg f = new ADUserAddDlg(base.container, this, sText, treeNode as ADUCDirectoryNode, bAcountDisable, bNeverExpiresPwd, bMustChangePwd, bUserCannotChange, copyfrom);

                        f.ShowDialog(this);
                        //the user information is gather in f.userInfo before "finish" button is clicked
                        if (f.userInfo.commit == true)
                        {
                            Hashtable htUserInfo = new Hashtable();
                            if (f.userInfo.fName != "")
                            {
                                htUserInfo.Add("givenName", f.userInfo.fName);
                            }
                            if (f.userInfo.initials != "")
                            {
                                htUserInfo.Add("initials", f.userInfo.initials);
                            }
                            if (f.userInfo.lName != "")
                            {
                                htUserInfo.Add("sn", f.userInfo.lName);
                            }
                            if (f.userInfo.fullName != "")
                            {
                                htUserInfo.Add("cn", f.userInfo.fullName);
                                htUserInfo.Add("displayName", f.userInfo.fullName);
                                htUserInfo.Add("name", f.userInfo.fullName);
                            }
                            if (f.userInfo.logonName != "")
                            {
                                htUserInfo.Add("userPrincipalName", f.userInfo.logonName);
                            }
                            if (f.userInfo.userPrelogonname != "")
                            {
                                htUserInfo.Add("sAMAccountName", f.userInfo.userPrelogonname);
                            }
                            //use logon name to set "sAMAaccountname"
                            AddNewObj_User(treeNode as ADUCDirectoryNode, htUserInfo, false, f.userInfo.passWord, f.userInfo.bAcountDisable, f.userInfo.bNeverExpiresPwd, f.userInfo.bMustChangePwd, f.userInfo.bCannotChangePwd);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException("ADUCPage.cm_OnMenuClick", ex);
                    }
                }
            }
        }

        //Move...
        if (mi != null && mi.Text.Equals("Move..."))
        {
            DoMoveObjectWork(dirnode);
        }

        //Rename
        if (mi != null && mi.Text.Equals("Rename"))
        {
            if (dirnode != null)
            {
                DirectoryContext dirContext = dirnode.LdapContext;
                string obj_type = dirnode.ObjectClass;

                if (obj_type.Equals("top", StringComparison.InvariantCultureIgnoreCase) ||
                    obj_type.Equals("user", StringComparison.InvariantCultureIgnoreCase))
                {
                    LACTreeNode parentnode = dirnode.Parent == null ? treeNode as LACTreeNode : dirnode.Parent as LACTreeNode;
                    ADUCDirectoryNode parentdirnode = parentnode as ADUCDirectoryNode;

                    ADRenameUserDlg f = new ADRenameUserDlg(dirnode, parentdirnode.DistinguishedName);
                    f.ShowDialog(this);

                    if (f.renameUserInfo.commit == true)
                    {
                        string basedn = dirnode.DistinguishedName;
                        string newdn = f.renameUserInfo.fullName;

                        newdn = string.Concat(CN_PREFIX, newdn);

                        ret = dirContext.RenameSynchronous(basedn, newdn, null);

                        if (ret == 0)
                        {
                            Hashtable htUserInfo = new Hashtable();
                            if (f.renameUserInfo.fName != "")
                            {
                                htUserInfo.Add("givenName", f.renameUserInfo.fName);
                            }
                            if (f.renameUserInfo.initials != "")
                            {
                                htUserInfo.Add("initials", f.renameUserInfo.initials);
                            }
                            if (f.renameUserInfo.lName != "")
                            {
                                htUserInfo.Add("sn", f.renameUserInfo.lName);
                            }
                            if (f.renameUserInfo.displayName != "")
                            {
                                htUserInfo.Add("displayName", f.renameUserInfo.displayName);
                            }
                            if (f.renameUserInfo.logonName != "")
                            {
                                htUserInfo.Add("userPrincipalName", f.renameUserInfo.logonName);
                            }
                            if (f.renameUserInfo.userPrelogonname != "")
                            {
                                htUserInfo.Add("sAMAccountName", f.renameUserInfo.userPrelogonname);
                            }

                            string cn = string.Empty;
                            string smamAccount = string.Empty;
                            List<LDAPMod> userinfo = new List<LDAPMod>();

                            foreach (string key in htUserInfo.Keys)
                            {
                                string[] objectClass_values = new string[] { htUserInfo[key].ToString(), null };

                                LDAPMod ldapMod_Info =
                                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, key, objectClass_values);

                                userinfo.Add(ldapMod_Info);
                            }

                            LDAPMod[] renameinfo = new LDAPMod[userinfo.Count];
                            userinfo.CopyTo(renameinfo);

                            string dn = string.Concat(newdn, DN_SEPARATOR);
                            string ou = parentdirnode.DistinguishedName;
                            dn = string.Concat(dn, ou);

                            ret = dirContext.ModifySynchronous(dn, renameinfo);

                            if (ret == 0)
                            {
                                int length = CommonResources.GetString("Caption_Console").Length + 24;
                                string msgToDisplay = "Object is renamed!";
                                if (length > msgToDisplay.Length)
                                {
                                    msgToDisplay = msgToDisplay.PadRight(length - msgToDisplay.Length, '�');
                                }
                                container.ShowMessage(msgToDisplay);
                            }
                            else
                            {
                                container.ShowError(ErrorCodes.LDAPString(ret));
                                return;
                            }
                        }
                        else
                        {
                            container.ShowError(ErrorCodes.LDAPString(ret));
                            return;
                        }

                        if (parentdirnode != null)
                        {
                            parentdirnode.Refresh();
                            parentdirnode.IsModified = true;
                            base.treeNode = parentdirnode;
                        }
                    }
                }
                else
                {
                    ADRenameDlg f = new ADRenameDlg(base.container, this, dirnode.Text, dirnode.ObjectClass);
                    f.ShowDialog(this);

                    //OK clicked
                    if (f.rename != null)
                    {
                        //the following portion of code uses openldap "ldap_rename_s"
                        string basedn = dirnode.DistinguishedName;
                        LACTreeNode parentnode = dirnode.Parent == null ? treeNode as LACTreeNode : dirnode.Parent as LACTreeNode;

                        ADUCDirectoryNode parentdirnode = parentnode as ADUCDirectoryNode;
                        string newdn = f.rename;

                        //rename an object
                        if (obj_type.Equals("organizationalUnit", StringComparison.InvariantCultureIgnoreCase))
                        {
                            newdn = string.Concat(OU_PREFIX, newdn);
                        }
                        else
                        {
                            newdn = string.Concat(CN_PREFIX, newdn); //Renaming any object(user, group, computer, container etc...)
                        }

                        ret = dirContext.RenameSynchronous(basedn, newdn, null);

                        if (ret == 0)
                        {
                            int length = CommonResources.GetString("Caption_Console").Length + 24;
                            string msgToDisplay = "Object is renamed!";
                            if (length > msgToDisplay.Length)
                            {
                                msgToDisplay = msgToDisplay.PadRight(length - msgToDisplay.Length, '�');
                            }
                            container.ShowMessage(msgToDisplay);
                        }

                        else
                        {
                            container.ShowError(ErrorCodes.LDAPString(ret));
                            return;
                        }

                        if (parentdirnode != null)
                        {
                            parentdirnode.Refresh();
                            parentdirnode.IsModified = true;
                            base.treeNode = parentdirnode;
                        }
                    }
                }//if f.name == null, there is no rename performed
            }
        }

        //in Computer Or user
        if (mi != null && mi.Text.Equals("Disable Account"))
        {
            ret = -1;
            ADUCDirectoryNode parentNode = null;
            if (mi.Tag != null)
            {
                parentNode = dirnode.Parent == null ? treeNode as ADUCDirectoryNode : dirnode.Parent as ADUCDirectoryNode;
                string obj_type = dirnode.ObjectClass;
                DialogResult dlg =
                MessageBox.Show(this, "Are you sure you want to disable this account?",
                CommonResources.GetString("Caption_Console"), MessageBoxButtons.YesNo,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
                if (dlg == DialogResult.Yes)
                {
                    if (obj_type.Equals("user", StringComparison.InvariantCultureIgnoreCase))
                    {
                        dlg = DialogResult.Yes;
                    }
                    if (obj_type.Equals("computer", StringComparison.InvariantCultureIgnoreCase))
                    {
                        dlg = MessageBox.Show(this, "Disabling the computer account " + dirnode.Text + " prevents users on that computer from logging on to this domain\n " +
                                              "Do you want to disable this computer account?",
                        CommonResources.GetString("Caption_Console"), MessageBoxButtons.YesNo,
                        MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
                    }
                    if (dlg == DialogResult.Yes || dlg == DialogResult.OK)
                    {
                        ret = DoDisableADObjects(dirnode);
                    }
                    if (ret == 0)
                    {
                        MessageBox.Show(this, string.Format("Object {0} has been disabled.", dirnode.Text),
                        CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                bool bAlertMsg = true;
                parentNode = treeNode as ADUCDirectoryNode;
                foreach (ListViewItem item in lvChildNodes.SelectedItems)
                {
                    ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                    if (dn != null)
                    {
                        if (!dn.IsDisabled)
                        {
                            bAlertMsg = false;
                            break;
                        }
                    }
                }
                if (bAlertMsg)
                {
                    MessageBox.Show(this, "All of the selected objects are disabled",
                    CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                    return;
                }
                foreach (ListViewItem item in lvChildNodes.SelectedItems)
                {
                    ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                    if (dn != null)
                    {
                        ret = DoDisableADObjects(dn);
                        if (ret != 0)
                        {
                            return;
                        }
                    }
                }
                if (ret == 0)
                {
                    MessageBox.Show(this, string.Format("All of the selected objects have been disabled."),
                    CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                }
            }
            if (ret == 0)
            {
                if (parentNode != null)
                {
                    parentNode.Refresh();
                    parentNode.IsModified = true;
                    base.treeNode = parentNode;
                }
            }
            else if (ret != -1)
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowMessage(sMsg);
            }
        }

        //Enable Account
        if (mi != null && mi.Text.Equals("Enable Account"))
        {
            ret = -1;
            ADUCDirectoryNode parentNode = null;
            if (mi.Tag != null)
            {
                parentNode = dirnode.Parent == null ? treeNode as ADUCDirectoryNode : dirnode.Parent as ADUCDirectoryNode;
                DialogResult dlg =
                MessageBox.Show(this, "Are you sure you want to enable this account?",
                CommonResources.GetString("Caption_Console"), MessageBoxButtons.YesNo,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
                if (dlg == DialogResult.Yes)
                {
                    ret = DoEnableAccount(dirnode);
                    if (ret == 0)
                    {
                        MessageBox.Show(this, string.Format("Object {0} has been enabled.", dirnode.Text),
                        CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                bool bAlertMsg = true;
                parentNode = treeNode as ADUCDirectoryNode;
                foreach (ListViewItem item in lvChildNodes.SelectedItems)
                {
                    ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                    if (dn != null)
                    {
                        if (dn.IsDisabled)
                        {
                            bAlertMsg = false;
                            break;
                        }
                    }
                }
                if (bAlertMsg)
                {
                    MessageBox.Show(this, "All of the selected objects are enabled",
                    CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                    return;
                }
                foreach (ListViewItem item in lvChildNodes.SelectedItems)
                {
                    ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                    if (dn != null)
                    {
                        ret = DoEnableAccount(dn);
                        if (ret != 0)
                        {
                            return;
                        }
                    }
                }
                if (ret == 0)
                {
                    MessageBox.Show(this, string.Format("All of the selected objects have been enabled."),
                    CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                }
            }
            if (ret == 0)
            {
                if (parentNode != null)
                {
                    parentNode.Refresh();
                    parentNode.IsModified = true;
                    base.treeNode = parentNode;
                }
            }
            else if (ret == -2)
            {
                string sMsg = string.Format("Windows cannot enable object {0} becuase\n" +
                              "Unanle to update the password. The value provided for the new passoword does not meeth\n" +
                              "length, complexity, or history requirement of the domain", dirnode.Text);
                MessageBox.Show(this, sMsg, CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (ret != -1)
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowMessage(sMsg);
            }
        }

        //in User only
        if (mi != null && mi.Text.Equals("Reset Password"))
        {
            if (dirnode != null)
            {
                DirectoryContext dirContext = dirnode.LdapContext;

                //first obtain the current userAccountControl value
                DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
                int userCtrlInt = int.Parse(de.Properties["userAccountControl"].Value.ToString());
                int useraccountCtr_decimalVal = 512;
                bool bNeverExpiresPwd = false;
                ret = 0;

                string userCtrlBinStr = UserGroupUtils.DecimalToBase(userCtrlInt, 2);

                if ((userCtrlBinStr.Length >= 17 && userCtrlBinStr[userCtrlBinStr.Length - 17] == '1') ||
                    (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 7] == '1'))
                {
                    bNeverExpiresPwd = true;
                }

                ResetPassword f = new ResetPassword(base.container, this, bNeverExpiresPwd, dirnode.Text);
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    //first, change the password
                    //first obtain the current userAccountControl value
                    //DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
                    string username = de.Properties["sAMAccountName"].Value.ToString();
                    if (String.IsNullOrEmpty(f.passwordinfo.password))
                    {
                        return;
                    }
                    bool retValue = false;
                    try
                    {
                        ADUCPlugin plugin = pi as ADUCPlugin;
                        Hostinfo hn = ctx as Hostinfo;

                        retValue = !Convert.ToBoolean(LUGAPI.NetChangePassword(hn.domainName, username, f.passwordinfo.password));
                    }
                    catch (Exception)
                    {
                        retValue = false;
                    }
                    List<LDAPMod> attrlist = new List<LDAPMod>();

                    //second, we need to set up to make sure that user shall change his password next time he logs in.
                    if (f.passwordinfo.MustChangePwNextLogon && !bNeverExpiresPwd && retValue)
                    {
                        //int userCtrlInt = (int)de.Properties["msDS-User-Account-Control-Computed"].Value;
                        //userCtrlInt = Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());
                        if (userCtrlInt != 546)
                        {
                            string newUserCtrl_val = Convert.ToString(useraccountCtr_decimalVal + 8388608);

                            string[] userControl_values = { newUserCtrl_val, null };
                            LDAPMod userControl_Info =
                            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userAccountControl", userControl_values);
                            attrlist.Add(userControl_Info);
                        }

                        string[] pwdLastSet_values = { "0", null };
                        LDAPMod pwdLastSet_attr = new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "pwdLastSet", pwdLastSet_values);
                        attrlist.Add(pwdLastSet_attr);
                    }

                    if (attrlist.Count != 0)
                    {
                        LDAPMod[] attrinfo = new LDAPMod[attrlist.Count];
                        attrlist.CopyTo(attrinfo);

                        ret = dirnode.LdapContext.ModifySynchronous(dirnode.DistinguishedName, attrinfo);
                    }

                    if (retValue && ret == 0)
                    {
                        int length = CommonResources.GetString("Caption_Console").Length + 28;
                        string msgToDisplay = "Password has been reset successfully.";
                        if (length > msgToDisplay.Length)
                        {
                            msgToDisplay = msgToDisplay.PadRight(length - msgToDisplay.Length, '�');
                        }
                        container.ShowMessage(msgToDisplay);
                        return;
                    }
                    else
                    {
                        container.ShowError("Failed to reset password.");
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }

        //Add to Group
        if (mi != null && mi.Text.Equals("Add to Group"))
        {
            if (dirnode == null)
            {
                dirnode = lvChildNodes.SelectedItems[0].Tag as ADUCDirectoryNode;
            }
            string sLdapPath = string.Format("LDAP://{0}/{1}", dirnode.LdapContext.DomainName, dirnode.DistinguishedName);
            string sProtocol;
            string sServer;
            string sCNs;
            string sDCs;

            System.DirectoryServices.SDSUtils.CrackPath(sLdapPath, out sProtocol, out sServer, out sCNs, out sDCs);
            System.DirectoryServices.Misc.DsPicker f = new System.DirectoryServices.Misc.DsPicker();
            f.SetData(System.DirectoryServices.Misc.DsPicker.DialogType.SELECT_GROUPS, sProtocol, sServer, sDCs, false);

            if (f.waitForm != null && f.waitForm.bIsInterrupted)
            {
                return;
            }

            if (f.ShowDialog(this) == DialogResult.OK)
            {
                List<ListViewItem> itemlist = new List<ListViewItem>();
                ADUCDirectoryNode parentNode = null;
                string sDN = f.ADobjectsArray[0].de.Properties["distinguishedName"].Value as string;

                if (mi.Tag != null)
                {
                    parentNode = dirnode.Parent == null ? treeNode as ADUCDirectoryNode : dirnode.Parent as ADUCDirectoryNode;
                    ret = DoAddtoGroup(dirnode, sDN, true, f.ADobjectsArray[0].Name, ref itemlist);
                    if (ret == 0)
                    {
                        container.ShowMessage("The Add to Group operation was successfully completed");
                    }
                }
                else
                {
                    parentNode = treeNode as ADUCDirectoryNode;
                    foreach (ListViewItem item in lvChildNodes.SelectedItems)
                    {
                        ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                        if (dn != null)
                        {
                            ret = DoAddtoGroup(dn, sDN, false,null, ref itemlist);
                        }
                    }
                    if (itemlist != null && itemlist.Count != 0)
                    {
                        ADAddtoGroupErrorEditor errorDailog = new ADAddtoGroupErrorEditor(itemlist);
                        errorDailog.ShowDialog(this);
                    }
                    else if (ret == 0)
                    {
                        container.ShowMessage("The Add to Group operation was successfully completed");
                    }
                }
                if (ret != 0 && ret != -1)
                {
                    string sMsg = ErrorCodes.LDAPString(ret);
                    container.ShowError(sMsg);
                    return;
                }
            }
        }

        //Reset Computer Account

        if (mi != null && mi.Text.Equals("Reset Account"))
        {
            DirectoryContext dirContext = dirnode.LdapContext;
            DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
            int iPrimaryGroupID = Convert.ToInt32(de.Properties["primaryGroupID"].Value.ToString());
            //  string DCResetacc = de.Properties["cn"].Value.ToString() + "$";
            if (iPrimaryGroupID == 516)
            {
                string sMsg = string.Format(
                "Server {0} is a domain controller.You cannot reset " +
                "the password on this object.",
                dirnode.Text);
                MessageBox.Show(sMsg);
                return;
            }
            if (dirnode != null)
            {
                DialogResult dlg =
                MessageBox.Show(this, "Are you sure you want to reset this computer account?",
                CommonResources.GetString("Caption_Console"), MessageBoxButtons.YesNo,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
                if (dlg == DialogResult.Yes)
                {
                    string computername = de.Properties["sAMAccountName"].Value.ToString();
                    //It will give the DistinguishedName for the computer is nothing but getting 'cn' attribute
                    string compResetpawd = de.Properties["cn"].Value.ToString() + "$"; //dirnode.DistinguishedName.Split(',')[0].Substring(3) + "$";
                    try
                    {
                        ADUCPlugin plugin = pi as ADUCPlugin;
                        Hostinfo hn = ctx as Hostinfo;

                        bool retValue = !Convert.ToBoolean(LUGAPI.NetChangePassword(hn.domainName, computername, compResetpawd));
                        if (retValue)
                        {
                            string sMsg = string.Format(
                            "Account {0} was successfully reset.",
                            dirnode.Text);
                            container.ShowMessage(sMsg);
                            return;
                        }
                        else
                        {
                            string sMsg = string.Format(
                            "Resetting account for {0} was unsuccessful.",
                            dirnode.Text);
                            container.ShowMessage(sMsg);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        string sMsg = string.Format(
                        "Resetting account for {0} was unsuccessful. Becuase {1}",
                        dirnode.Text,
                        ex.Message);
                        container.ShowError(sMsg);
                        Logger.LogException("ADUCPage", ex);
                        return;
                    }
                }
            }
        }

        //Refreshing the Aduc page after performing any of the aduc functionalities
		RefreshPluginPage();

        //Properties...
        if (mi != null && mi.Text.Equals("Properties"))
        {

            if (lvChildNodes.SelectedItems.Count > 1)
            {
                ADUCPlugin plugin = treeNode.Plugin as ADUCPlugin;
                ADUCDirectoryNode dnNode = treeNode as ADUCDirectoryNode;

                List<object> dirnodes = new List<object>();
                bool bIsuserType = false;
                bool bIsgroupType = false;
                bool bIsOUType = false;
                bool bIsOthers = false;
                ADObjectType = string.Empty;

                foreach (ListViewItem item in lvChildNodes.SelectedItems)
                {
                    ADUCDirectoryNode dn = item.Tag as ADUCDirectoryNode;
                    if (dn != null)
                    {
                        if (dn.ObjectClass.Trim().Equals("user", StringComparison.InvariantCultureIgnoreCase))
                        {
                            bIsuserType = true;
                        }
                        else if (dn.ObjectClass.Trim().Equals("group", StringComparison.InvariantCultureIgnoreCase))
                        {
                            bIsgroupType = true;
                        }
                        else if (dn.ObjectClass.Trim().Equals("organizationalUnit", StringComparison.InvariantCultureIgnoreCase))
                        {
                            bIsOUType = true;
                        }
                        else
                        {
                            bIsOthers = true;
                            ADObjectType = string.Empty;
                        }
                        dirnodes.Add(dn);
                    }
                }
                if (bIsgroupType && !bIsOthers && !bIsuserType && !bIsOUType)
                {
                    ADObjectType = "group";
                }
                else if (bIsuserType && !bIsOthers && !bIsgroupType && !bIsOUType)
                {
                    ADObjectType = "user";
                }
                else if (bIsOUType && !bIsOthers && !bIsuserType && !bIsgroupType)
                {
                    ADObjectType = "organizationalUnit";
                }
                MultiItemPropertiesDlg propertiesDlg = new MultiItemPropertiesDlg(base.container, this, base.pi as ADUCPlugin, dirnodes);
                propertiesDlg.SetData(plugin.HostInfo.creds, plugin.HostInfo.hostName, "", dnNode, dnNode.LdapContext.SchemaCache);
                propertiesDlg.Show();
            }
            else
            {
                DoPropertyPagesWork(dirnode);
            }
        }
    }
        private void lvGPOs_MouseUp(object sender, MouseEventArgs e)
        {
            ListView lvSender = sender as ListView;
            if (lvSender != null && e.Button == MouseButtons.Right)
            {
                ListViewHitTestInfo hti = lvSender.HitTest(e.X, e.Y);
                if (hti != null && hti.Item != null)
                {
                    ListViewItem lvItem = hti.Item;
                    ContextMenu menu = null;
                    if (!lvItem.Selected)
                    {
                        lvItem.Selected = true;
                    }
                    if (lvItem.Tag != null)
                    {
                        menu = GetListViewMouseUpContextMenu(lvItem.Tag as string);
                    }
                    if (menu != null)
                    {
                        menu.Show(lvSender, new Point(e.X, e.Y));
                    }
                    else
                    {
                        Logger.Log(
                            "ObjectsListPage::lvGPOs_MouseUp, menu == null",
                            Logger.manageLogLevel);
                    }
                }
            }
            else if (lvSender != null && e.Button == MouseButtons.Left)
            {
                if (bIsLabelEdited && lvGPOs.Items.Count != 0)
                {
                    if (lvGPOs.Items[lvGPOs.Items.Count - 1].Text.Trim().Equals(string.Empty))
                        lvGPOs.Items[lvGPOs.Items.Count - 1].Text = "New Group Policy Object";

                    sNewGPODN = lvGPOs.Items[lvGPOs.Items.Count - 1].Text;
                    if (!AddNewGPO(sNewGPODN, false))
                        bIsLabelEdited = false;

                    if (lvGPOs.SelectedItems.Count == 0)
                        return;

                    ListViewItem selectedItem = lvGPOs.SelectedItems[0];
                    sDistinguishedName = selectedItem.Tag as string;
                    sGPODisplayName = selectedItem.Text;

                    btnOk.Enabled = true;
                }
                else if (bIsRenameEdited && lvGPOs.Items.Count != 0)
                {
                    if (lvGPOs.SelectedItems.Count == 0)
                        return;

                    if (lvGPOs.SelectedItems[0].Text.Trim().Equals(string.Empty))
                    {
                        lvGPOs.SelectedItems[0].Text = sGPODisplayName;
                        return;
                    }

                    string rename = lvGPOs.SelectedItems[0].Text;
                    bIsRenameEdited = false;

                    ListViewItem selectedItem = lvGPOs.SelectedItems[0];
                    sDistinguishedName = selectedItem.Tag as string;
                    sGPODisplayName = selectedItem.Text;

                    string[] displayname_values = new string[] { rename, null };

                    LDAPMod displayname_Info =
                       new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "displayName",
                                   displayname_values);
                    LDAPMod[] attrinfo = new LDAPMod[] { displayname_Info };

                    int ret = dirContext.ModifySynchronous(sDistinguishedName, attrinfo);

                    btnOk.Enabled = true;
                }
            }
        }
        private void DeleteGPO(string DistinguishedName)
        {
            List<LdapEntry> ldapEntries = new List<LdapEntry>();
            int ret = dirContext.ListChildEntriesSynchronous
                                     (dirContext.RootDN,
                                     LdapAPI.LDAPSCOPE.SUB_TREE,
                                     "(objectClass=organizationalUnit)",
                                     new string[] { "dummy", "objectClass", "distinguishedName", "userAccountControl", null },
                                     false,
                                     out ldapEntries);

            if (ldapEntries != null && ldapEntries.Count != 0)
            {
                List<LdapEntry> rootldapEntries = new List<LdapEntry>();
                ret = dirContext.ListChildEntriesSynchronous
                                       (dirContext.RootDN,
                                       LdapAPI.LDAPSCOPE.BASE,
                                       "(objectClass=*)",
                                       new string[] { "dummy", "objectClass", "distinguishedName", "userAccountControl", null },
                                       false,
                                       out rootldapEntries);

                if (rootldapEntries != null && rootldapEntries.Count != 0)
                {
                    foreach (LdapEntry ldapentry in rootldapEntries)
                        ldapEntries.Add(ldapentry);
                }

                foreach (LdapEntry ldapNextEntry in ldapEntries)
                {
                    string currentDN = ldapNextEntry.GetDN();

                    DirectoryEntry deEntry = new DirectoryEntry(currentDN);

                    if (deEntry != null)
                    {
                        string gpLinkEntries = null;

                        if (deEntry.Properties["gpLink"].Value != null)
                            gpLinkEntries = deEntry.Properties["gpLink"].Value.ToString();

                        if (gpLinkEntries != null)
                        {
                            string[] gplinkTokens = gpLinkEntries.Split(']');
                            if (gplinkTokens == null)
                                return;
                            List<string> gpoLinksList = new List<string>();
                            bool IsLinkExists = false;

                            foreach (string gpLink in gplinkTokens)
                            {
                                if (gpLink.Trim().Length == 0)
                                    continue;

                                string gpoLink = gpLink.Substring(1, gpLink.IndexOf(';') - 1);
                                string currentGPO = "LDAP://" + DistinguishedName;

                                if (gpoLink.Trim().Equals(currentGPO.Trim(), StringComparison.InvariantCultureIgnoreCase))
                                    IsLinkExists = true;
                                else
                                {
                                    gpoLinksList.Add(gpLink + "]");
                                }
                            }
                            if (IsLinkExists)
                            {
                                string gpLink_Value = "";
                                foreach (string value in gpoLinksList)
                                {
                                    gpLink_Value += value;
                                }
                                string[] gpLink_values = { gpLink_Value, null };

                                LDAPMod gpLink_Info =
                                   new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "gpLink",
                                               gpLink_values);
                                LDAPMod[] attrinfo = new LDAPMod[] { gpLink_Info };

                                ret = dirContext.ModifySynchronous(currentDN, attrinfo);
                            }
                        }
                    }
                }
            }
            ret = dirContext.DeleteChildren_Recursive(DistinguishedName);

            if (ret == 0)
            {
                string baseDn = "CN=Policies,CN=System,";
                baseDn = string.Concat(baseDn, dirContext.RootDN);
                ListGPOChildren(baseDn);
                RefreshlvItems();
            }
            else
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowMessage(sMsg);
                return;
            }
        }
        /// <summary>
        /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
        /// </summary>
        /// <returns></returns>
        public bool OnApply()
        {
            List<LDAPMod> ldapAttrlist = new List<LDAPMod>();
            List<LDAPMod> attrlist = new List<LDAPMod>();

            if (dirnode == null ||
                String.IsNullOrEmpty(dirnode.DistinguishedName) ||
                dirnode.LdapContext == null)
            {
                return true;
            }

			if (ListUserOptions.GetItemChecked(0) && ListUserOptions.GetItemChecked(1))
            {
                string Msg = "You cannot select both 'User must change passowrd at next logon' and 'User cannot change password'\nfor the same user";
                MessageBox.Show(this, Msg, CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                ListUserOptions.SetItemChecked(1, false);
                return false;
            }

            if (ListUserOptions.GetItemChecked(0) && ListUserOptions.GetItemChecked(2))
            {
                string Msg = "You have selected 'Password never expires'. \nThe user will not be required to change the password at next logon.";
                MessageBox.Show(this, Msg, CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                ListUserOptions.SetItemChecked(0, false);
                return false;
            }

            //the following portion of code uses openldap "ldap_Modify_s"
            string basedn = dirnode.DistinguishedName;
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = null;

            if (Logonname != null && !(Logonname.Trim().Equals(txtlogon.Text.Trim())))
            {
                objectClass_values = new string[] { txtlogon.Text.Trim(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userPrincipalName",
                objectClass_values);
                attrlist.Add(attr);
            }

            if (txtpreLogonname.Text.Trim().Length > 0 && !(PreLogonname.Trim().Equals(txtpreLogonname.Text.Trim())))
            {
                objectClass_values = new string[] { txtpreLogonname.Text.Trim(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "sAMAccountName",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (dateTimePicker.Enabled && dateTimePicker.Value != null)
            {
                objectClass_values = new string[] { ConvertToUnixTimestamp(dateTimePicker.Value).ToString(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "accountExpires",
                objectClass_values);
                attrlist.Add(attr);
            }

            if (!String.IsNullOrEmpty(pwdLastSet))
            {
                objectClass_values = new string[] { pwdLastSet, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "pwdLastSet",
                objectClass_values);
                attrlist.Add(attr);
            }

            //userWorkstations attribute
            if (String.IsNullOrEmpty(sUserWorkStations))
                objectClass_values = new string[] { null };
            else
                objectClass_values = new string[] { sUserWorkStations, null };
            LDAPMod attri =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userWorkstations",
            objectClass_values);
            attrlist.Add(attri);

            if (ListUserOptions.SelectedIndices.Count > 0)
            {
                objectClass_values = new string[] { CalculateUserAccountControl().ToString(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userAccountControl",
                objectClass_values);
                attrlist.Add(attr);
            }

            LDAPMod[] attrArry = attrlist.ToArray();
            int ret = -1;
            if (attrArry != null && attrArry.Length != 0)
            {
                ret = dirContext.ModifySynchronous(basedn, attrArry);
            }
            else
            {
                return true;
            }
            if (ret != 0)
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowError(sMsg);
                return false;
            }
            else
            {
                DirectoryEntry de = new DirectoryEntry(dirnode.DistinguishedName);
                de.Properties["pwdLastSet"].Value = pwdLastSet;
                de.CommitChanges();
            }
            return true;
        }
    /// <summary>
    /// Modifies the "member" attribute for the selected "user" or "group" in AD schema template
    /// </summary>
    /// <param name="changedGroups"></param>
    /// <param name="_dirnode"></param>
    /// <param name="page"></param>
    /// <param name="operation"></param>
    /// <returns></returns>
    private static bool OnApply_inner(List<string> changedGroups, ADUCDirectoryNode _dirnode, MPPage page, int operation)
    {
        bool retVal = true;
        int ret = -1;
        string AdminGroupDN = string.Concat("CN=Administrators,CN=Builtin,", _dirnode.LdapContext.RootDN);

        if (changedGroups != null && changedGroups.Count > 0)
        {
            foreach (string newGroupname in changedGroups)
            {
                List<string> members = new List<string>();
                members = GetMemberAttrofGroup(newGroupname.Trim(), _dirnode);

                bool existingMember = false;

                //if we want to add, we need check whether it is already a member of the group
                if (operation == ADDING)
                {
                    foreach (string str in members)
                    {
                        if (str.Equals(_dirnode.DistinguishedName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            existingMember = true;
                            break;
                        }
                    }
                }

                if (!existingMember)
                {
                    if (operation == ADDING)
                    {
                        members.Add(_dirnode.DistinguishedName);
                    }
                    if (operation == REMOVING)
                    {
                        members.Remove(_dirnode.DistinguishedName);
                    }

                    if (newGroupname.Trim().ToLower().Equals(AdminGroupDN.Trim().ToLower()))
                    {
                        string userlogonName = OnApply_GetObjectRealmName(_dirnode);
                        LUGAPI.NetAddGroupMember(_dirnode.LdapContext.DomainControllerName, "Administrators", userlogonName);
                    }
                    else
                    {
                        string[] members_values = new string[members.Count + 1];
                        members.CopyTo(members_values);
                        members_values[members.Count] = null;

                        LDAPMod memberattr_Info =
                        new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "member",
                        members_values);

                        LDAPMod[] attrinfo = new LDAPMod[] { memberattr_Info };

                        if (_dirnode != null)
                        {
                            ret = _dirnode.LdapContext.ModifySynchronous(newGroupname.Trim(), attrinfo);

                            if (ret == 0)
                            {
                                retVal = true;
                            }
                            else
                            {
                                string sMsg = ErrorCodes.LDAPString(ret);
                                MessageBox.Show(page, sMsg, "Likewise Management Console",
                                MessageBoxButtons.OK);
                                retVal = false;
                            }
                        }
                    }
                }
            }
            if (ret == 0)
            {
                if (operation == ADDING)
                {
                    MessageBox.Show(
                    page,
                    "User/Computer/Group list is added to new groups!",
                    CommonResources.GetString("Caption_Console"),
                    MessageBoxButtons.OK);
                }
                if (operation == REMOVING)
                {
                    MessageBox.Show(
                    page,
                    "User/Computer/Group list is removed from chose groups!",
                    CommonResources.GetString("Caption_Console"),
                    MessageBoxButtons.OK);
                }
            }
        }
        return retVal;
    }
    private void HandleLVDefault(ListViewItem lvItem, ref bool dnIsChanged, ref int ret)
    {
        string basedn = dirnode.DistinguishedName;
        DirectoryContext dirContext = dirnode.LdapContext;
        string value = lvItem.SubItems[2].Text;
        if (String.Equals(value, "<Not Set>", StringComparison.InvariantCultureIgnoreCase))
        {
            string[] objectClass_values = { null };
            LDAPMod attr_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, lvItem.SubItems[0].Text,
            objectClass_values);
            LDAPMod[] attrinfo = new LDAPMod[] { attr_Info };
            ret = dirContext.ModifySynchronous(basedn, attrinfo);

            //need recover the previous value
            if (ret != 0)
            {
                lvItem.SubItems[2].Text = lvItem.SubItems[2].Tag as string;
            }
        }
        else
        {
            //application crashes for single digit value
            if (value.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
            {
                value = value.Replace("ox", "-");
                value = value.Substring(1);
            }

            string[] objectClass_values = { value, null };
            LDAPMod attr_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, lvItem.SubItems[0].Text,
            objectClass_values);
            LDAPMod[] attrinfo = new LDAPMod[] { attr_Info };
            ret = dirContext.ModifySynchronous(basedn, attrinfo);
        }
    }
    /// <summary>
    /// Modifies the specified attributes for the selected Domain
    /// </summary>
    /// <returns></returns>
    public bool OnApply()
    {
        Description = this.txtDescription.Text.Trim();
        List<LDAPMod> attrlist = new List<LDAPMod>();
        //the following portion of code uses openldap "ldap_Modify_s"
        string basedn = dirnode.DistinguishedName;
        DirectoryContext dirContext = dirnode.LdapContext;
        string[] objectClass_values = null;

        if (!String.IsNullOrEmpty(Description))
        {
            objectClass_values = new string[] { Description, null };
        }
        else
        {
            objectClass_values = new string[] { null };
        }
        
        LDAPMod attr =
        new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "description",
        objectClass_values);
        
        LDAPMod[] attrArry = new LDAPMod[] { attr };
        int ret = -1;
        if (attrArry != null && attrArry.Length != 0)
        {
            ret = dirContext.ModifySynchronous(basedn, attrArry);
        }
        else
        {
            return true;
        }
        if (ret != 0)
        {           
            string sMsg = ErrorCodes.LDAPString(ret);
            container.ShowError(sMsg);
            return false;
        }
        this.ParentContainer.DataChanged = false;
        this.ParentContainer.btnApply.Enabled = false;
        return true;
    }
Beispiel #8
0
    /// <summary>
    /// Helper function that saves the new OU information in AD by
    /// defining the attributes "ou", "ObjectClass" as user for the new object
    /// Here we can say that ObjectClass,cn is mandatory attributes that has to be set while creating the new OU
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="cn"></param>
    /// <param name="htAttributesList"></param>
    /// <param name="IsObjectItem"></param>
    private void AddNewObj_OU(ADUCDirectoryNode dirnode, string cn,Hashtable htAttributesList,bool IsObjectItem)
    {
        if (dirnode != null)
        {
            DirectoryContext dirContext = dirnode.LdapContext;
            List<LDAPMod> listattr = new List<LDAPMod>();
            string[] objectClass_values = { "organizationalUnit", null };

            if (IsObjectItem)
            {
                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("ou") || key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    if (key.Trim().ToLower().Equals("objectclass"))
                    {
                        continue;
                    }

                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };
                    LDAPMod ouinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    listattr.Add(ouinfo_attr1);
                }
                objectClass_values = new string[] { "organizationalUnit", null };
                LDAPMod ouinfo_attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                listattr.Add(ouinfo_attr);
            }
            else
            {
                objectClass_values = new string[] { "organizationalUnit", null };
                LDAPMod ouinfo_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                listattr.Add(ouinfo_attr1);
            }

            LDAPMod[] ouinfo = new LDAPMod[listattr.Count];
            listattr.CopyTo(ouinfo);

            string dn = string.Concat(OU_PREFIX, cn, DN_SEPARATOR);
            string ou = dirnode.DistinguishedName;
            dn = string.Concat(dn, ou);

            //Returns the ret=0 if adding new OU is successfull
            int ret = dirContext.AddSynchronous(dn, ouinfo);

            if (ret == 0)
            {
                //int length = CommonResources.GetString("Caption_Console").Length + 24;
                string msgToDisplay = "New OrganizationalUnit Object is added!";
                MessageBox.Show(this, msgToDisplay, CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK);

                dirnode.Refresh();
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
            else
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }
    }
Beispiel #9
0
    /// <summary>
    /// Helper function that saves the new object information in AD by
    /// defining the attributes "ObjectClass" as selected object type for the new object
    /// Here we can say that the values getting from "systemMustContain" attribute have to be set while creating the new object
    /// New object may be any of the class schema attribute from AD Schema template
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="choosenclass"></param>
    /// <param name="cn"></param>
    /// <param name="htAttributesList"></param>
    private void AddNewObj(ADUCDirectoryNode dirnode, string choosenclass, string cn, Hashtable htAttributesList)
    {
        if (dirnode != null)
        {
            LDAPMod[] info = null;

            DirectoryContext dirContext = dirnode.LdapContext;

            string[] objectClass_values = { choosenclass, null };

            if (htAttributesList != null)
            {
                info = new LDAPMod[htAttributesList.Count];
            }

            int i = 0;
            foreach (string key in htAttributesList.Keys)
            {
                if (key.Trim().ToLower().Equals("cn"))
                {
                    cn = htAttributesList[key].ToString();
                    continue;
                }
                objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                LDAPMod info_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);

                info[i] = info_attr1;
                i++;
            }
            if (!htAttributesList.Contains("ObjectClass"))
            {
                objectClass_values = new string[] { choosenclass, null };
                LDAPMod info_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

                info[i] = info_attr1;
            }

            string dn = string.Concat(CN_PREFIX, cn, DN_SEPARATOR);
            string ou = dirnode.DistinguishedName;
            dn = string.Concat(dn, ou);

            int ret = dirContext.AddSynchronous(dn, info);

            if (ret == 0)
            {
                container.ShowMessage("New Object is added!");
                dirnode.Refresh();
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
            else if (ret == (int)ErrorCodes.LDAPEnum.LDAP_INSUFFICIENT_RIGHTS)
            {
                string showmsg = "You do not have sufficient access rights";
                container.ShowError(showmsg);
            }
            else
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }
    }
Beispiel #10
0
    /// <summary>
    /// Helper function that saves the new user information in AD by
    /// defining the attributes "cn", "sAMAccountName", "ObjectClass" as user for the new object
    /// Here we can say that ObjectClass,sAMAccountName is mandatory attribute that has to be set while creating the new user
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="cn"></param>
    /// <param name="smamAccount"></param>
    /// <param name="htAttributesList"></param>
    /// <param name="IsObjectItem"></param>
    /// <param name="password"></param>
    /// <param name="IsDisabled"></param>
    private void AddNewObj_User(ADUCDirectoryNode dirnode, Hashtable htAttributesList, bool IsObjectItem, string password, bool IsDisabled, bool NeverExpiredPW, bool MustChangePWNxtLogon, bool CannotChangePW)
    {
        if (dirnode != null)
        {
            string cn = string.Empty;
            string smamAccount = string.Empty;
            List<LDAPMod> userinfo = new List<LDAPMod>();
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = { "user", null };

            if (IsObjectItem)
            {
                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    else if (key.Trim().ToLower().Equals("sAMAccountName".Trim().ToLower()))
                    {
                        smamAccount = htAttributesList[key].ToString();
                    }
                    else if (key.Trim().ToLower().Equals("objectclass"))
                    {
                        continue;
                    }
                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                    LDAPMod userinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    userinfo.Add(userinfo_attr1);
                }

                objectClass_values = new string[] { "user", null };
                LDAPMod userinfo_attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                userinfo.Add(userinfo_attr);
            }
            else
            {
                LDAPMod userinfo_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                userinfo.Add(userinfo_attr1);

                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    else if (key.Trim().ToLower().Equals("sAMAccountName".ToLower()))
                    {
                        smamAccount = htAttributesList[key].ToString();
                    }
                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                    userinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    userinfo.Add(userinfo_attr1);
                }
            }

            int useraccountCtr_decimalVal = 512;

            if (IsObjectItem)
            {
                useraccountCtr_decimalVal = 546;
            }
            else
            {
                if (IsDisabled)
                {
                    useraccountCtr_decimalVal += 2;
                }

                if (NeverExpiredPW)
                {
                    useraccountCtr_decimalVal += 65536;
                }
                ////user password needs to be set in another way instead of using "userPassword" attribute
                //if (MustChangePWNxtLogon)
                //{
                //    useraccountCtr_decimalVal += 8388608;
                //}
                if (CannotChangePW)
                {
                    useraccountCtr_decimalVal += 64;
                }
            }

            string useraccountCtr_decimalStr = Convert.ToString(useraccountCtr_decimalVal);

            string[] useraccountCtr_values = { useraccountCtr_decimalStr, null };

            LDAPMod[] userinfos = new LDAPMod[userinfo.Count];
            userinfo.CopyTo(userinfos);

            string dn = string.Concat(CN_PREFIX, cn, DN_SEPARATOR);
            string ou = dirnode.DistinguishedName;
            dn = string.Concat(dn, ou);

            Logger.Log(string.Format("New user DN :" + dn));
            foreach (LDAPMod key in userinfos)
            {
                Logger.Log(string.Format(string.Format("New user keys {0}, {1} :", key.ldapmod.mod_type, key.modv_strvals[0])));
            }

            //returns ret=0 if adding user is successfull
            int ret = dirContext.AddSynchronous(dn, userinfos);

            if (ret == 0)
            {
                bool retValue = false;
                if (!IsDisabled)
                {
                    container.ShowMessage("New User Object is added!");
                }
                else
                {
                    container.ShowMessage("New (disabled) User Object is added!");
                }

                //need to make sure the interop is working correctly, comment it for now
                try
                {
                    if (!String.IsNullOrEmpty(password))
                    {
                        ADUCPlugin plugin = pi as ADUCPlugin;
                        Hostinfo hn = ctx as Hostinfo;

                        retValue = !Convert.ToBoolean(LUGAPI.NetChangePassword(hn.domainName, smamAccount, password));
                        Logger.Log(string.Format("hn.domainName is {0} : userName is {1} and password is {2}", hn.domainName, smamAccount, password));
                    }
                }
                catch (Exception ex)
                {
                    container.ShowError("Filed to set the password for this new user because " + ex.Message);
                }
            }
            else if (ret == (int)ErrorCodes.LDAPEnum.LDAP_UNWILLING_TO_PERFORM)
            {
                string accessDenied = "Indicates that the Active Directory server cannot process the request because of server-defined restrictions. \n This error is returned for the following reasons:\n  - The add entry request violates the server's structure rules.\n  - The modify attribute request specifies attributes that users cannot modify.\n  - Password restrictions prevent the action.\n  - Connection restrictions prevent the action.";

                string returnedErrMsg = ErrorCodes.LDAPString(ret);

                if (accessDenied.Equals(returnedErrMsg, StringComparison.InvariantCultureIgnoreCase))
                {
                    returnedErrMsg = "The password could not be set for the new user object.\n\nThe the Active Directory server cannot process the request because of server-defined restrictions.\nThis error is returned for the following reasons:\n  - The add entry request violates the server's structure rules.\n  - The modify attribute request specifies attributes that users cannot modify.\n  - Password restrictions prevent the action.\n  - Connection restrictions prevent the action.\n\nLikewise Console will attempt to disable this account.\nBefore this user can log on, the password should be set and the account must be enabled.";

                    container.ShowError(returnedErrMsg);
                }
                //returns ret=0 if adding user is successfull
                ret = dirContext.AddSynchronous(dn, userinfos);

                if (!IsDisabled)
                {
                    container.ShowMessage("New User Object is added!");
                }
                else
                {
                    container.ShowMessage("New (disabled) User Object is added!");
                }
            }
            else if (ret == (int)ErrorCodes.LDAPEnum.LDAP_INSUFFICIENT_RIGHTS)
            {
                string showmsg = "You do not have sufficient access rights";
                container.ShowError(showmsg);
            }
            else
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }

            if (ret == 0)
            {
                DirectoryEntry de = new DirectoryEntry(dn, dirContext.UserName, dirContext.Password);
                int userCtrlInt = Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());
                de.CommitChanges();

                //string newUserCtrl_val = Convert.ToString(userCtrlInt - 2);
                //in order to disable an user, we need to add 2 to the existing userControl value
                //string[] userControl_values = { newUserCtrl_val, null };
                LDAPMod userControl_Info =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userAccountControl",
                useraccountCtr_values);
                LDAPMod[] attrinfo = new LDAPMod[] { userControl_Info };
                ret = dirContext.ModifySynchronous(dn, attrinfo);

                if (ret.ToString() == ((int)ErrorCodes.LDAPEnum.LDAP_UNWILLING_TO_PERFORM).ToString())
                {
                    //string accessDenied = "Indicates that the Active Directory server cannot process the request because of server-defined restrictions. \n This error is returned for the following reasons:\n  - The add entry request violates the server's structure rules.\n  - The modify attribute request specifies attributes that users cannot modify.\n  - Password restrictions prevent the action.\n  - Connection restrictions prevent the action.";
                    //string returnedErrMsg = ErrorCodes.LDAPString(ret);
                    //if (accessDenied.Equals(returnedErrMsg, StringComparison.InvariantCultureIgnoreCase))
                    //{
                    string returnedErrMsg = "The password could not be set for the new user object.\n\nThe the Active Directory server cannot process the request because of server-defined restrictions.\nThis error is returned for the following reasons:\n  - The add entry request violates the server's structure rules.\n  - The modify attribute request specifies attributes that users cannot modify.\n  - Password restrictions prevent the action.\n  - Connection restrictions prevent the action.\n\nLikewise Console will attempt to disable this account.\nBefore this user can log on, the password should be set and the account must be enabled.";

                    container.ShowError(returnedErrMsg);
                }

                if (MustChangePWNxtLogon)
                {
                    de.Properties["pwdLastSet"].Value = "0";
                    de.CommitChanges();
                }
                else
                {
                    de.Properties["pwdLastSet"].Value = ConvertToUnixTimestamp(DateTime.Now).ToString();
                    de.CommitChanges();
                }

                dirnode.Refresh();
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
        }
    }
Beispiel #11
0
    /// <summary>
    /// Helper function that saves the new group information in AD by
    /// defining the attributes "cn", "grouptype", "ObjectClass" as user for the new object
    /// Here we can say that ObjectClass,grouptype is mandatory attributes that has to be set while creating the new group
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="cn"></param>
    /// <param name="smamAccount"></param>
    /// <param name="groupType"></param>
    /// <param name="htAttributesList"></param>
    /// <param name="IsObjectItem"></param>
    private void AddNewObj_Group(ADUCDirectoryNode dirnode,Hashtable htAttributesList,bool IsObjectItem)
    {
        if (dirnode != null)
        {
            string cn = string.Empty;
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = { "group", null };
            List<LDAPMod> ldapAttrlist = new List<LDAPMod>();
            if (IsObjectItem)
            {
                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    else if (key.Trim().ToLower().Equals("objectclass"))
                    {
                        continue;
                    }

                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                    LDAPMod groupinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    ldapAttrlist.Add(groupinfo_attr1);
                }

                objectClass_values = new string[] { "group", null };
                LDAPMod groupinfo_attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                ldapAttrlist.Add(groupinfo_attr);
            }
            else
            {
                LDAPMod groupinfo_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                ldapAttrlist.Add(groupinfo_attr1);

                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }

                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                    groupinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    ldapAttrlist.Add(groupinfo_attr1);
                }
            }

            LDAPMod[] groupinfo = new LDAPMod[ldapAttrlist.Count];
            ldapAttrlist.CopyTo(groupinfo);

            string dn = string.Concat(CN_PREFIX, cn, DN_SEPARATOR);
            string ou = dirnode.DistinguishedName;
            dn = string.Concat(dn, ou);

            //Returns ret=0 if adding group is successfull
            int ret = dirContext.AddSynchronous(dn, groupinfo);

            if (ret == 0)
            {
                container.ShowMessage("New Group Object is added!");
                dirnode.Refresh();
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
            else if (ret == (int)ErrorCodes.LDAPEnum.LDAP_INSUFFICIENT_RIGHTS)
            {
                string showmsg = "You do not have sufficient access rights";
                container.ShowError(showmsg);
            }
            else
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }
    }
Beispiel #12
0
    /// <summary>
    /// Helper function that saves the new computer information in AD by
    /// defining the attributes "cn", "ObjectClass" as computer for the new object
    /// Here we can say that ObjectClass is mandatory attribute that has to be set while creating the new computer
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="cn"></param>
    /// <param name="smamAccount"></param>
    /// <param name="htAttributesList"></param>
    /// <param name="IsObjectItem"></param>
    private void AddNewObj_Computer(ADUCDirectoryNode dirnode, Hashtable htAttributesList, bool IsObjectItem, bool IsBackupDC,bool IsPreWindowsComp)
    {
        if (dirnode != null)
        {
            string cn = string.Empty;
            List<LDAPMod> ldapattrlst = new List<LDAPMod>();
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = { "computer", null };
            int ret = 0;

            if (IsObjectItem)
            {
                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    else if (key.Trim().ToLower().Equals("objectclass") ||
                    key.Trim().ToLower().Equals("useraccountcontrol"))
                    {
                        continue;
                    }

                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };
                    LDAPMod ouinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    ldapattrlst.Add(ouinfo_attr1);
                }

                objectClass_values = new string[] { "computer", null };
                LDAPMod ouinfo_attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                ldapattrlst.Add(ouinfo_attr);

                string compuserAccountControl = Convert.ToString(546);
                objectClass_values = new string[] { compuserAccountControl, null };
                ouinfo_attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "userAccountControl", objectClass_values);
                ldapattrlst.Add(ouinfo_attr);
            }
            else
            {
                LDAPMod userinfo_attr1 =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);
                ldapattrlst.Add(userinfo_attr1);

                foreach (string key in htAttributesList.Keys)
                {
                    if (key.Trim().ToLower().Equals("cn"))
                    {
                        cn = htAttributesList[key].ToString();
                    }
                    objectClass_values = new string[] { htAttributesList[key].ToString(), null };

                    userinfo_attr1 =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, key, objectClass_values);
                    ldapattrlst.Add(userinfo_attr1);
                }
            }

            string dn = string.Concat(CN_PREFIX, cn, DN_SEPARATOR);
            string ou = dirnode.DistinguishedName;
            dn = string.Concat(dn, ou);

            LDAPMod[] computerinfo = new LDAPMod[ldapattrlst.Count];
            ldapattrlst.CopyTo(computerinfo);

            //returns ret=0 if adding computer is successfull
            ret = dirContext.AddSynchronous(dn, computerinfo);
            if (ret == 0)
            {
                container.ShowMessage("New Computer Object is added!");

                dirnode.Refresh();
                dirnode.IsModified = true;
                base.treeNode = dirnode;
            }
            else if (ret == (int)ErrorCodes.LDAPEnum.LDAP_INSUFFICIENT_RIGHTS)
            {
                string showmsg = "You do not have sufficient access rights";
                container.ShowError(showmsg);
            }
            else
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }
    }
Beispiel #13
0
    private int DoDisableADObjects(ADUCDirectoryNode dirnode)
    {
        int ret = -1;
        if (dirnode != null && !dirnode.IsDisabled)
        {
            DirectoryContext dirContext = dirnode.LdapContext;
            string obj_type = dirnode.ObjectClass;

            //first obtain the current userAccountControl value
            DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
            int userCtrlInt = Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());

            string newUserCtrl_val = Convert.ToString(userCtrlInt + 2);
            //in order to disable an user, we need to add 2 to the existing userControl value
            string[] userControl_values = { newUserCtrl_val, null };
            LDAPMod userControl_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userAccountControl",
            userControl_values);

            LDAPMod[] attrinfo = new LDAPMod[] { userControl_Info };

            ret = dirnode.LdapContext.ModifySynchronous(dirnode.DistinguishedName, attrinfo);
        }
        else
        {
            return ret;
        }
        return ret;
    }
Beispiel #14
0
    private int DoAddtoGroup(ADUCDirectoryNode dirnode,
                             string sDN,
                             bool IsSingleObject,
                             string group,
                             ref List<ListViewItem> itemsList)
    {
        int ret = -1;
        string errorMsg = "The specified account name is already a member of the local group";

        string[] groupDns = UserGroupUtils.GetGroupsforUser(dirnode);

        foreach (string dn in groupDns)
        {
            string aPartName = string.Empty;
            if (dn.Trim().ToLower().Equals(sDN.Trim().ToLower()))
            {
                if (IsSingleObject)
                {
                    string sMsg = string.Format(
                    "Object {0} cannot be added to group {1} becuase:\n " +
                    "The specified user is already member to that group",
                    dirnode.Text,
                    group);
                    container.ShowError(sMsg);
                    return ret;
                }
                else
                {
                    string[] values = new string[] { dirnode.Text, errorMsg };
                    ListViewItem item = new ListViewItem(values);
                    itemsList.Add(item);
                    return ret;
                }
            }
        }
        string AdminGroupDN = string.Concat("CN=Administrators,CN=Builtin,", dirnode.LdapContext.RootDN);
        if (sDN.Trim().ToLower().Equals(AdminGroupDN.Trim().ToLower()))
        {
            string userlogonName = string.Empty;
            DirectoryEntry de = new DirectoryEntry(dirnode.DistinguishedName);

            if (de != null && de.Properties["userPrincipalName"].Value != null)
            {
                userlogonName = de.Properties["userPrincipalName"].Value as string;
            }
            LUGAPI.NetAddGroupMember(dirnode.LdapContext.DomainControllerName, "Administrators", userlogonName);
        }
        else
        {
            List<string> members = new List<string>();

            members = MemOfPages.GetMemberAttrofGroup(sDN, dirnode);
            members.Add(dirnode.DistinguishedName);

            string[] members_values = new string[members.Count + 1];
            members.CopyTo(members_values);
            members_values[members.Count] = null;

            LDAPMod memberattr_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "member",
            members_values);

            LDAPMod[] attrinfo = new LDAPMod[] { memberattr_Info };
            ret = dirnode.LdapContext.ModifySynchronous(sDN, attrinfo);
        }

        return ret;
    }
    /// <summary>
    /// when adding a user to a new group, we need modify the group's "member" attribute to include this user,
    /// we cannot modify the user's "memberof" attribute
    /// </summary>
    /// <returns></returns>
    public bool OnApply()
    {
        bool retVal = true;
        if (IsPrimaryGroupChanged)
        {
            List<LDAPMod> attrlist = new List<LDAPMod>();
            //the following portion of code uses openldap "ldap_Modify_s"
            string basedn = _dirnode.DistinguishedName;
            string[] objectClass_values = null;

            //first obtain the current primaryGroupID value
            DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", _dirnode.LdapContext.DomainName, ChangedPrimaryGroup));
            if (de.Properties["primaryGroupToken"].Value != null)
            {
                int iPrimaryGroupToken = Convert.ToInt32(de.Properties["primaryGroupToken"].Value.ToString());

                objectClass_values = new string[] { iPrimaryGroupToken.ToString(), null };
                LDAPMod attr_info =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "primaryGroupID",
                objectClass_values);

                LDAPMod[] attrinfo = new LDAPMod[] { attr_info };
                int ret = _dirnode.LdapContext.ModifySynchronous(basedn, attrinfo);
                Logger.Log("Modify primaryGroupID returns " + ret);
                if (ret == 0)
                {
                    string[] Items = UserGroupUtils.splitDn(ChangedPrimaryGroup);
                    if (!string.IsNullOrEmpty(Items[0]))
                    {
                        DomainUserlabel.Text = Items[0];
                    }
                }
                else
                    retVal = false;
            }
        }

        retVal = MemOfPages.OnApply_helper(MemofDnList, AddedGroups, RemovedGroups, _dirnode, this);

        return retVal;
    }
Beispiel #16
0
    /// <summary>
    /// takes a leaf node as input, perform a rename operation (delete and then add)
    /// </summary>
    /// <param name="dirnode"></param>
    /// <param name="newName"></param>
    private void DelAndAddLeaf(ADUCDirectoryNode dirnode, string newName)
    {
        int ret;

        LACTreeNode parentnode = dirnode.Parent == null ? treeNode as LACTreeNode : dirnode.Parent as LACTreeNode;

        ADUCDirectoryNode parentdirnode = parentnode as ADUCDirectoryNode;

        string newDn = parentdirnode.DistinguishedName;

        string obj_type = dirnode.ObjectClass;

        DirectoryContext dirContext = dirnode.LdapContext;
        //rename leaf user
        if (obj_type.Equals("top", StringComparison.InvariantCultureIgnoreCase) ||
        obj_type.Equals("user", StringComparison.InvariantCultureIgnoreCase))
        {
            //User
        }
        {
            ret = dirContext.DeleteSynchronous(dirnode.DistinguishedName);

            if (ret!=0)
            {

                container.ShowError(ErrorCodes.LDAPString(ret));
                return;
            }

            string[] objectClass_values = { "user", null };

            LDAPMod userinfo_attr1 =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

            LDAPMod[] userinfo = new LDAPMod[] { userinfo_attr1 };

            newDn = string.Concat(CN_PREFIX, newName, DN_SEPARATOR, newDn);

            ret = dirContext.AddSynchronous(newDn, userinfo);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }

        //rename leaf computer
        if (obj_type.Equals("computer", StringComparison.InvariantCultureIgnoreCase))
        {
            ret = dirContext.DeleteSynchronous(dirnode.DistinguishedName);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
                return;
            }

            string[] objectClass_values = { "user", null }; //need to be fixed, computer is now treated as user (person)

            LDAPMod userinfo_attr1 =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

            LDAPMod[] userinfo = new LDAPMod[] { userinfo_attr1 };

            newDn = string.Concat(CN_PREFIX, newName, DN_SEPARATOR, newDn);

            ret = dirContext.AddSynchronous(newDn, userinfo);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }

        //rename leaf ou
        if (obj_type.Equals("organizationalUnit", StringComparison.InvariantCultureIgnoreCase))
        {

        }
        {
            ret = dirContext.DeleteSynchronous(dirnode.DistinguishedName);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
                return;
            }

            string[] objectClass_values = { "organizationalUnit", null };

            LDAPMod userinfo_attr1 =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

            LDAPMod[] userinfo = new LDAPMod[] { userinfo_attr1 };

            newDn = string.Concat(OU_PREFIX, newName, DN_SEPARATOR, newDn);

            ret = dirContext.AddSynchronous(newDn, userinfo);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }

        //rename a group
        if (obj_type.Equals("group", StringComparison.InvariantCultureIgnoreCase))
        {
            ret = dirContext.DeleteSynchronous(dirnode.DistinguishedName);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
                return;
            }

            string[] objectClass_values = { "group", null };

            LDAPMod userinfo_attr1 =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

            LDAPMod[] userinfo = new LDAPMod[] { userinfo_attr1 };

            newDn = string.Concat(CN_PREFIX, newName, DN_SEPARATOR, newDn);

            ret = dirContext.AddSynchronous(newDn, userinfo);

            if (ret != 0)
            {
                container.ShowError(ErrorCodes.LDAPString(ret));
            }
        }

        parentdirnode.Refresh();

    }
Beispiel #17
0
    private void HandleLVMember(ListViewItem lvItem, ref bool dnIsChanged, ref int ret)
    {
        string basedn = dirnode.DistinguishedName;
        DirectoryContext dirContext = dirnode.LdapContext;
        string membersConcated = lvItem.SubItems[2].Text;

        if (membersConcated.Equals("<Not Set>", StringComparison.InvariantCultureIgnoreCase))
        {
            string[] members_values = { null };
            LDAPMod memberattr_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "member",
            members_values);

            LDAPMod[] attrinfo = new LDAPMod[] { memberattr_Info };

            ret = dirnode.LdapContext.ModifySynchronous(dirnode.DistinguishedName, attrinfo);
        }
        else
        {

            string[] members = membersConcated.Split(';');

            string[] members_values = new string[members.Length + 1];

            int i = 0;
            foreach (string member in members)
            {
                members_values[i] = member;
                i++;
            }
            members_values[i] = null;


            LDAPMod memberattr_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "member",
            members_values);

            LDAPMod[] attrinfo = new LDAPMod[] { memberattr_Info };

            ret = dirnode.LdapContext.ModifySynchronous(dirnode.DistinguishedName, attrinfo);
        }
    }
        public bool OnApply()
        {
            List<LDAPMod> attrlist = new List<LDAPMod>();
            LDAPMod attr = null;
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = null;

            string street = txtStreet.Text.Trim();
            if (street.Contains("\n"))
            {
                street = street.Replace("\n", "\r\n");
            }

            objectClass_values = street == string.Empty ? new string[] { null } : new string[] { street, null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "streetAddress",
            objectClass_values);
            if (bMultiUserSelected && chkStreet.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(txtStreet.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            objectClass_values = txtPOBox.Text.Trim() == string.Empty ? new string[] { null } : new string[] { txtPOBox.Text.Trim(), null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "postOfficeBox",
            objectClass_values);
            if (bMultiUserSelected && chkPO.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(txtPOBox.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            objectClass_values = txtCity.Text.Trim() == string.Empty ? new string[] { null } : new string[] { txtCity.Text.Trim(), null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "l",
            objectClass_values);
            if (bMultiUserSelected && chkCity.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(txtCity.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            objectClass_values = txtState.Text.Trim() == string.Empty ? new string[] { null } : new string[] { txtState.Text.Trim(), null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "st",
            objectClass_values);
            if (bMultiUserSelected && chkState.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(txtState.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            objectClass_values = txtZip.Text.Trim() == string.Empty ? new string[] { null } : new string[] { txtZip.Text.Trim(), null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "postalCode",
            objectClass_values);
            if (bMultiUserSelected && chkZip.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(txtZip.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            objectClass_values = cbCountry.Text.Trim() == string.Empty ? new string[] { null } : new string[] { cbCountry.Text.Trim(), null };
            attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "co",
            objectClass_values);
            if (bMultiUserSelected && chkCountry.Checked)
            {
                attrlist.Add(attr);
            }
            else if (!bMultiUserSelected && !String.IsNullOrEmpty(cbCountry.Text.Trim()))
            {
                attrlist.Add(attr);
            }

            SetControlStatus();

            LDAPMod[] attrArry = attrlist.ToArray();
            int ret = -1;
            if (attrArry != null && attrArry.Length != 0)
            {
                List<object> dirnodes = new List<object>();
                if (parentDlg is MultiItemPropertiesDlg)
                {
                    MPContainer _MultiItemPropertiesDlg = parentDlg as MPContainer;
                    dirnodes = _MultiItemPropertiesDlg.ObjectCounts;
                }
                else
                {
                    MPContainer _ADUserPropertiesDlg = parentDlg as MPContainer;
                    dirnodes = _ADUserPropertiesDlg.ObjectCounts;
                }
                foreach (ADUCDirectoryNode dn in dirnodes)
                {
                    if (dn != null)
                    {
                        ret = dirContext.ModifySynchronous(dn.DistinguishedName, attrArry);
                    }
                    if (ret != 0)
                    {
                        string sMsg = ErrorCodes.LDAPString(ret);
                        container.ShowError(sMsg);
                        return false;
                    }
                }
            }

            return true;
        }
        /// <summary>
        /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
        /// </summary>
        /// <returns></returns>
        public bool OnApply()
        {
            if (rbConnect.Checked)
            {
                string Connect = txtConnect.Text.Trim();
                bool IsValid = true;
                if (String.IsNullOrEmpty(Connect) ||
                    Connect.Length < 3)
                {
                    IsValid = false;
                }
                else if (Connect.Length == 3 && Connect.IndexOf(@"\\") == 0)
                {
                    MessageBox.Show(this, "The home folder could not be created because: The filename, directory name, or valume" +
                                          "label syntax is incorrect",
                          CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
                else
                {
                    string[] Slashsplits = Connect.Substring(2).Split('\\');
                    if (String.IsNullOrEmpty(Connect) ||
                        Slashsplits.Length != 2 ||
                        txtConnect.Text.Trim().IndexOf(@"\\") != 0 ||
                        Connect.EndsWith(@"\"))
                    {
                        IsValid = false;
                    }
                }
                if (!IsValid)
                {
                    MessageBox.Show(this, "The specified path is not valid. Enter a valid network server path using the form:\n\\\\server\\share\\folder",
                           CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }

            List<LDAPMod> ldapAttrlist = new List<LDAPMod>();
            List<LDAPMod> attrlist = new List<LDAPMod>();

            if (dirnode == null ||
                String.IsNullOrEmpty(dirnode.DistinguishedName) ||
                dirnode.LdapContext == null)
            {
                return true;
            }

            //the following portion of code uses openldap "ldap_Modify_s"
            string basedn = dirnode.DistinguishedName;
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = null;

            if (txtProfilePath.Text.Trim().Length > 0)
            {
                objectClass_values = new string[] { txtProfilePath.Text.Trim(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "profilePath",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (txtLogonScript.Text.Trim().Length > 0)
            {
                objectClass_values = new string[] { txtLogonScript.Text.Trim(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "scriptPath",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (rbConnect.Checked)
            {
                if (txtConnect.Text.Trim().Length > 0)
                {
                    objectClass_values = new string[] { txtConnect.Text.Trim(), null };
                    LDAPMod attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "homeDirectory",
                    objectClass_values);
                    attrlist.Add(attr);
                }
                if (cbDrive.SelectedItem != null)
                {
                    objectClass_values = new string[] { cbDrive.SelectedItem.ToString(), null };
                    LDAPMod attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "homeDrive",
                    objectClass_values);
                    attrlist.Add(attr);
                }
            }
            else
            {
                if (txtLocalPath.Text.Trim().Length > 0)
                {
                    objectClass_values = new string[] { txtLocalPath.Text.Trim(), null };
                    LDAPMod attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "homeDirectory",
                    objectClass_values);
                    attrlist.Add(attr);
                }
            }

            LDAPMod[] attrArry = attrlist.ToArray();
            int ret = -1;
            if (attrArry != null && attrArry.Length != 0)
            {
                ret = dirContext.ModifySynchronous(basedn, attrArry);
            }
            else
            {
                return true;
            }
            if (ret != 0)
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowError(sMsg);
                return false;
            }
            else
            {
                if (rbConnect.Checked)
                {
                    string sMsg = string.Empty;
                    if (!bIsOpened)
                    {
                        sMsg = string.Format("The {0} home folder was not created because the path was not found. This could be caused by listing\n" +
                                      "non-existent intermediate folders or by not finding the server or share. The user account has been updated" +
                                      "with the new home folder value but you must create the folder manually", txtConnect.Text.Trim());
                        bIsOpened = true;
                    }
                    else
                    {
                        sMsg = "The home folder could not be created becuase: The network location cannot be reached." +
                            "\nFor information about network troubleshooting, see the google map";
                    }

                    MessageBox.Show(this, sMsg,
                       CommonResources.GetString("Caption_Console"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            return true;
        }
        /// <summary>
        /// Modifies the specified attributes for the selected group in AD schema template
        /// </summary>
        /// <returns></returns>
        public bool OnApply()
        {
            bool retVal = true;

            if (!compareLists(ModifiedObjects, OriginalObjects))
            {
                string AdminGroupDN = string.Concat("CN=Administrators,CN=Builtin,", _dirnode.LdapContext.RootDN);
                if (ModifiedObjects.Contains(AdminGroupDN.ToLower()))
                {
                    string userlogonName = string.Empty;
                    DirectoryEntry de = new DirectoryEntry(_dirnode.DistinguishedName, _dirnode.LdapContext.UserName, _dirnode.LdapContext.Password);
                    if (de != null && de.Properties["sAMAccountName"].Value != null)
                    {
                        userlogonName = de.Properties["sAMAccountName"].Value as string;
                    }
                    LUGAPI.NetAddGroupMember(_dirnode.LdapContext.DomainControllerName, "Administrators", userlogonName);

                    ModifiedObjects.Remove(AdminGroupDN.ToLower());
                }

                string[] members_values = new string[ModifiedObjects.Count + 1];
                if (ModifiedObjects.Count > 0)
                {
                    ModifiedObjects.CopyTo(members_values);
                }
                members_values[ModifiedObjects.Count] = null;

                LDAPMod memberattr_Info =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "member",
                members_values);

                LDAPMod[] attrinfo = new LDAPMod[] { memberattr_Info };

                if (_dirnode != null)
                {
                    int ret = _dirnode.LdapContext.ModifySynchronous(_dirnode.DistinguishedName, attrinfo);

                    if (ret == 0)
                    {
                        container.ShowMessage("Group Memerbers have been modified successfully!");
                        retVal = true;
                    }
                    else
                    {
                        string sMsg = ErrorCodes.LDAPString(ret);
                        container.ShowError(sMsg);
                        retVal = false;
                    }
                }
            }
            return retVal;
        }
        /// <summary>
        /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
        /// </summary>
        /// <returns></returns>
        public bool OnApply()
        {
            if (checkBox.Checked)
            {
                List<LDAPMod> ldapAttrlist = new List<LDAPMod>();
                List<LDAPMod> attrlist = new List<LDAPMod>();
                //the following portion of code uses openldap "ldap_Modify_s"
                DirectoryContext dirContext = dirnode.LdapContext;
                string[] objectClass_values = null;

                objectClass_values = txtDescription.Text.Trim() == string.Empty ? new string[] { null } : new string[] { txtDescription.Text.Trim(), null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "description",
                objectClass_values);
                attrlist.Add(attr);

                LDAPMod[] attrArry = attrlist.ToArray();
                int ret = -1;
                if (attrArry != null && attrArry.Length != 0)
                {
                    foreach (ADUCDirectoryNode dn in this.parentDlg.ObjectCounts)
                    {
                        if (dn != null)
                        {
                            ret = dirContext.ModifySynchronous(dn.DistinguishedName, attrArry);
                        }
                        if (ret != 0)
                        {
                            string sMsg = ErrorCodes.LDAPString(ret);
                            container.ShowError(sMsg);
                            return false;
                        }
                    }
                }
                else
                {
                    return true;
                }

                checkBox.Checked = false;
            }
            return true;
        }
        /// <summary>
        /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
        /// </summary>
        /// <returns></returns>
        public bool OnApply()
        {
            List<LDAPMod> attrlist = new List<LDAPMod>();
            //the following portion of code uses openldap "ldap_Modify_s"
            string basedn = dirnode.DistinguishedName;
            DirectoryContext dirContext = dirnode.LdapContext;
            string[] objectClass_values = null;

            if (_editObject.Description != "" &&
            !(_editObject.Description.Equals(_originalObject.Description)))
            {
                objectClass_values = new string[] { _editObject.Description, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "description",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (_editObject.Street != "" &&
            !(_editObject.Street.Equals(_originalObject.Street)))
            {
                objectClass_values = new string[] { _editObject.Street, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "street",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (_editObject.City != "" &&
            !(_editObject.City.Equals(_originalObject.City)))
            {
                objectClass_values = new string[] { _editObject.City, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "l",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (_editObject.State != "" &&
            !(_editObject.State.Equals(_originalObject.State)))
            {
                objectClass_values = new string[] { _editObject.State, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "st",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (_editObject.PostalCode != "" &&
            !(_editObject.PostalCode.Equals(_originalObject.PostalCode)))
            {
                objectClass_values = new string[] { _editObject.PostalCode, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "postalCode",
                objectClass_values);
                attrlist.Add(attr);
            }
            if (_editObject.Country != "" &&
            !(_editObject.Country.Equals(_originalObject.Country)))
            {
                objectClass_values = new string[] { _editObject.Country, null };
                LDAPMod attr =
                new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "co",
                objectClass_values);
                attrlist.Add(attr);
            }


            LDAPMod[] attrArry = attrlist.ToArray();
            int ret = -1;
            if (attrArry != null && attrArry.Length != 0)
            {
                ret = dirContext.ModifySynchronous(basedn, attrArry);
            }
            else
            {
                return true;
            }
            if (ret != 0)
            {
                string sMsg = ErrorCodes.LDAPString(ret);
                container.ShowError(sMsg);
                return false;
            }
            UpdateOriginalData();
            return true;
        }
    /// <summary>
    /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
    /// </summary>
    /// <returns></returns>
    public bool OnApply()
    {
        List<LDAPMod> ldapAttrlist = new List<LDAPMod>();
        List<LDAPMod> attrlist = new List<LDAPMod>();      

        if (dirnode == null ||
            String.IsNullOrEmpty(dirnode.DistinguishedName) ||
            dirnode.LdapContext == null)
        {
            return true;
        }       

        //the following portion of code uses openldap "ldap_Modify_s"
        string basedn = dirnode.DistinguishedName;
        DirectoryContext dirContext = dirnode.LdapContext;
        string[] objectClass_values = null;        

        if (_editObject.FirstName != "" &&
        !(_editObject.FirstName.Equals(_originalObject.FirstName)))
        {
            objectClass_values = new string[] { _editObject.FirstName, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "givenName",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.Initails != "" &&
        !(_editObject.Initails.Equals(_originalObject.Initails)))
        {
            objectClass_values = new string[] { _editObject.Initails, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "initials",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.LastName != "" &&
        !(_editObject.LastName.Equals(_originalObject.LastName)))
        {
            objectClass_values = new string[] { _editObject.LastName, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "sn",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.Description != "" &&
        !(_editObject.Description.Equals(_originalObject.Description)))
        {
            objectClass_values = new string[] { _editObject.Description, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "description",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.DisplayName != "" &&
        !(_editObject.DisplayName.Equals(_originalObject.DisplayName)))
        {
            objectClass_values = new string[] { _editObject.DisplayName, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "displayName",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.Office != "" &&
        !(_editObject.Office.Equals(_originalObject.Office)))
        {
            objectClass_values = new string[] { _editObject.Office, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "physicalDeliveryOfficeName",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.Email != "" &&
        !(_editObject.Email.Equals(_originalObject.Email)))
        {
            objectClass_values = new string[] { _editObject.Email, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "mail",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.WebPage != "" &&
        !(_editObject.WebPage.Equals(_originalObject.WebPage)))
        {
            objectClass_values = new string[] { _editObject.WebPage, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "wWWHomePage",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.TelephoneNumber != "" &&
        !(_editObject.TelephoneNumber.Equals(_originalObject.TelephoneNumber)))
        {
            objectClass_values = new string[] { _editObject.TelephoneNumber, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "telephoneNumber",
            objectClass_values);
            attrlist.Add(attr);
        }
        if (_editObject.TelephoneNumberOther != "" &&
        !(_editObject.TelephoneNumberOther.Equals(_originalObject.TelephoneNumberOther)))
        {
            _editObject.TelephoneNumberOther += ";";
            string[] split = _editObject.TelephoneNumberOther.Split(';');
            split[split.Length - 1] = null;
            
            objectClass_values = split;
            
            LDAPMod TelephoneNumberOther =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "otherTelephone", objectClass_values);
            ldapAttrlist.Add(TelephoneNumberOther);
            
            attrlist.Add(TelephoneNumberOther);
        }
        
        if (_editObject.WebPageOther != "" &&
        !(_editObject.WebPageOther.Equals(_originalObject.WebPageOther)))
        {
            objectClass_values = new string[] { _editObject.WebPageOther, null };
            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "url",
            objectClass_values);
            attrlist.Add(attr);
        }
       
        LDAPMod[] attrArry = attrlist.ToArray();
        int ret = -1;
        if (attrArry != null && attrArry.Length != 0)
        {
            ret = dirContext.ModifySynchronous(basedn, attrArry);
        }
        else
        {
            return true;
        }
        if (ret !=0)
        {
            string sMsg = ErrorCodes.LDAPString(ret);
            container.ShowError(sMsg);
            return false;
        }        
        UpdateOriginalData();
       
        return true;
    }
        public int ModifySynchronous(string distinguishedName, LDAPMod[] userinfo)
        {
            int ret = 0;

            lock (lockThis_modSyn)
            {
                ret = _ldapHandle.Ldap_Modify_S(distinguishedName, userinfo);
            }

            return ret;
        }
        private void lvDomainOUs_MouseUp(object sender, MouseEventArgs e)
        {
            ListView lvSender = sender as ListView;
            if (lvSender != null && e.Button == MouseButtons.Right)
            {
                ListViewHitTestInfo hti = lvSender.HitTest(e.X, e.Y);
                if (hti != null && hti.Item != null)
                {
                    ListViewItem lvItem = hti.Item;
                    ContextMenu menu = null;
                    if (!lvItem.Selected)
                    {
                        lvItem.Selected = true;
                    }
                    if (lvItem.Tag != null)
                    {
                        DirectoryEntry de = new DirectoryEntry(lvItem.Tag as string);
                        if (de != null)
                        {
                            object[] asProp = de.Properties["objectClass"].Value as object[];
                            if (asProp != null)
                            {
                                List<string> liClasses = new List<string>();
                                foreach (string s in asProp)
                                    liClasses.Add(s);

                                if (liClasses.Contains("groupPolicyContainer"))
                                    menu = GetListViewMouseUpContextMenu(lvItem.Tag as string);
                            }
                        }
                    }
                    if (menu != null)
                    {
                        menu.Show(lvSender, new Point(e.X, e.Y));
                    }
                    else
                    {
                        Logger.Log(
                            "ObjectsListPage::lvDomainOUs_MouseUp, menu == null",
                            Logger.manageLogLevel);
                    }
                }
            }
            else if (lvSender != null && e.Button == MouseButtons.Left)
            {
                if (bIsLabelEdited && lvDomainOUs.Items.Count != 0)
                {
                    if (lvDomainOUs.Items[lvDomainOUs.Items.Count - 1].Text.Trim().Equals(string.Empty))
                        lvDomainOUs.Items[lvDomainOUs.Items.Count - 1].Text = "New Group Policy Object";

                    sNewGPODN = lvDomainOUs.Items[lvDomainOUs.Items.Count - 1].Text;

                    if (!AddNewGPO(sNewGPODN, true))
                    {
                        lvDomainOUs.Items.RemoveAt(lvDomainOUs.Items.Count - 1);
                        return;
                    }

                    bIsLabelEdited = false;

                    if (lvDomainOUs.SelectedItems.Count == 0)
                        return;

                    ListViewItem selectedItem = lvDomainOUs.SelectedItems[0];
                    sDistinguishedName = selectedItem.Tag as string;
                    sGPODisplayName = selectedItem.Text;

                    btnOk.Enabled = true;
                }
                else if (bIsRenameEdited && lvDomainOUs.Items.Count != 0)
                {
                    if (lvDomainOUs.SelectedItems.Count == 0)
                        return;

                    if (lvDomainOUs.SelectedItems[0].Text.Trim().Equals(string.Empty))
                    {
                        lvDomainOUs.SelectedItems[0].Text = sGPODisplayName;
                        return;
                    }

                    string rename = lvDomainOUs.SelectedItems[0].Text;
                    bIsRenameEdited = false;

                    ListViewItem selectedItem = lvDomainOUs.SelectedItems[0];
                    sDistinguishedName = selectedItem.Tag as string;
                    sGPODisplayName = selectedItem.Text;

                    string[] displayname_values = new string[] { rename, null };

                    LDAPMod displayname_Info =
                       new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "displayName",
                                   displayname_values);
                    LDAPMod[] attrinfo = new LDAPMod[] { displayname_Info };

                    int ret = dirContext.ModifySynchronous(sDistinguishedName, attrinfo);

                    btnOk.Enabled = true;
                }
            }
        }
Beispiel #26
0
        public static int AddNewObj(Likewise.LMC.LDAP.DirectoryContext dirContext, string choosenclass, string nodeDN)
        {
            if (dirContext != null)
            {
                LDAPMod[] info = new LDAPMod[1];

                string[] objectClass_values = new string[] { choosenclass, null };
                info[0] = new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "ObjectClass", objectClass_values);

                return dirContext.AddSynchronous(nodeDN, info);
            }

            return -1;
        }
        public bool AddNewGPO(string DN, bool bIsLinkable)
        {
            string baseDn = "CN=Policies,CN=System,";
            baseDn = string.Concat(baseDn, dirContext.RootDN);

            List<LDAPMod> listattr = new List<LDAPMod>();
            Guid guid = Guid.NewGuid();

            string[] attr_values = { "groupPolicyContainer", null };
            LDAPMod ouinfo_attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "objectClass", attr_values);
            listattr.Add(ouinfo_attr);

            attr_values = new string[] { DN, null };
            ouinfo_attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "displayName", attr_values);
            listattr.Add(ouinfo_attr);

            attr_values = new string[] { "0", null };
            ouinfo_attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "flags", attr_values);
            listattr.Add(ouinfo_attr);

            attr_values = new string[] { "2", null };
            ouinfo_attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "gPCFunctionalityVersion", attr_values);
            listattr.Add(ouinfo_attr);

            attr_values = new string[] { "0", null };
            ouinfo_attr =
                    new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "versionNumber", attr_values);
            listattr.Add(ouinfo_attr);

            string gPCFileSysPath = @"\\" + dirContext.DomainName + @"\SysVol\" + dirContext.DomainName + @"\Policies\" + "{" + guid.ToString().ToUpper() + "}";
            attr_values = new string[] { gPCFileSysPath, null };
            ouinfo_attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "gPCFileSysPath", attr_values);
            listattr.Add(ouinfo_attr);

            string ldapDN = "CN={" + guid.ToString() + "}," + baseDn;

            if (bIsLinkable)
            {
                lvDomainOUs.Items[lvDomainOUs.Items.Count - 1].Tag = ldapDN;
            }
            else
            {
                lvGPOs.Items[lvGPOs.Items.Count - 1].Tag = ldapDN;
            }

            LDAPMod[] gpoinfo = new LDAPMod[listattr.Count];
            listattr.CopyTo(gpoinfo);

            //Returns the ret=0 if adding new GPO is successfull
            int ret = dirContext.AddSynchronous(ldapDN.ToUpper(), gpoinfo);

            if (ret == 0)
            {
                int length = CommonResources.GetString("Caption_Console").Length + 24;
                string msgToDisplay = "New Group Policy Object is added!";
                if (length > msgToDisplay.Length)
                {
                    msgToDisplay = msgToDisplay.PadRight(length - msgToDisplay.Length, '�');
                }
                container.ShowMessage(msgToDisplay);

                //call of CreateGPOFolderInSysVol() function to make Folder generation in SysVol
                CreateGPOFolderInSysVol(guid.ToString().ToUpper(), DN);

                listattr.Clear();
                string machineDN = string.Concat("CN=Machine,", ldapDN.ToUpper());
                attr_values = new string[] { "container", null };
                ouinfo_attr =
                        new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "objectClass", attr_values);
                listattr.Add(ouinfo_attr);
                gpoinfo = new LDAPMod[listattr.Count];
                listattr.CopyTo(gpoinfo);
                //Returns the ret=0 if adding new Machine is successfull
                ret = dirContext.AddSynchronous(machineDN, gpoinfo);

                listattr.Clear();
                string UserDN = string.Concat("CN=User,", ldapDN.ToUpper());
                attr_values = new string[] { "container", null };
                ouinfo_attr =
                        new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_ADD, "objectClass", attr_values);
                listattr.Add(ouinfo_attr);
                gpoinfo = new LDAPMod[listattr.Count];
                listattr.CopyTo(gpoinfo);
                //Returns the ret=0 if adding new User is successfull
                ret = dirContext.AddSynchronous(UserDN, gpoinfo);

                #region Linking to slected OU
                if (bIsLinkable)
                {
                    DirectoryEntry rootDE = new DirectoryEntry(sParentDN);
                    if (rootDE != null)
                    {
                        Dictionary<string, string> gpoLinksList = new Dictionary<string, string>();
                        string gpLinkEntries = null;
                        if (rootDE.Properties["gpLink"].Value != null)
                            gpLinkEntries = rootDE.Properties["gpLink"].Value.ToString();

                        if (gpLinkEntries != null)
                        {
                            string[] gplinkTokens = gpLinkEntries.Split(']');
                            foreach (string gpLink in gplinkTokens)
                            {
                                if (gpLink.Trim().Length == 0)
                                    continue;

                                string gpoLink = gpLink.Substring(1, gpLink.IndexOf(';') - 1);

                                gpoLinksList.Add(gpoLink.Trim().ToLower(), gpLink + "]");
                            }
                        }
                        if (!gpoLinksList.ContainsKey(ldapDN.Trim().ToLower()))
                        {
                            string newgpoLink = "[LDAP://" + ldapDN.ToUpper() + ";1]";
                            gpoLinksList.Add(ldapDN, newgpoLink);
                        }

                        if (gpoLinksList.Count != 0)
                        {
                            string gpLink_Value = "";
                            foreach (string key in gpoLinksList.Keys)
                                gpLink_Value += gpoLinksList[key];

                            string[] gpLink_Values = new string[] { gpLink_Value, null };

                            LDAPMod gpLink_Info =
                            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "gpLink",
                                     gpLink_Values);
                            LDAPMod[] attrinfo = new LDAPMod[] { gpLink_Info };

                            ret = dirContext.ModifySynchronous(sParentDN, attrinfo);

                            if (ret == 0)
                            {
                                container.ShowMessage("Linked GPO object successful");
                                return true;
                            }
                            else
                            {
                                string sMsg = ErrorCodes.LDAPString(ret);
                                container.ShowMessage(sMsg);
                                return false;
                            }
                        }
                    }
                }
                #endregion
            }

            else
            {
                container.ShowMessage(Utilities.ErrorCodes.LDAPString(ret));
            }
            return true;
        }
Beispiel #28
0
        public static int ModifyProperty(Likewise.LMC.LDAP.DirectoryContext dirContext, string nodeDN, string propertyName, PropertyValueCollection propertyValue)
        {
            List<object> valueObjects = propertyValue.ValueCollection;

            string[] values;

            if (valueObjects == null || valueObjects.Count == 0)
                values = new string[] { null };
            else if (valueObjects.Count == 1)
            {
                values = new string[] { ParsingValueObj(valueObjects[0]), null };
                //Console.WriteLine("In SDSUtils::modifyPropertyvalue is " + ParsingValueObj(valueObjects[0]));
            }
            else
            {
                values = new string[valueObjects.Count + 1];
                int i;
                for (i = 0; i < valueObjects.Count; i++)
                {
                    values[i] = ParsingValueObj(valueObjects[i]);
                    //Console.WriteLine("In SDSUtils::modifyPropertyvalue " + i + "is " + values[i]);
                }
                values[i] = null;
            }

            LDAPMod[] attrinfo = new LDAPMod[] { new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, propertyName, values) };

            return dirContext.ModifySynchronous(nodeDN, attrinfo);
        }
        private void DeleteGPOLink(string DistinguishedName)
        {
            List<string> attrValues = new List<string>();

            DirectoryEntry parentDE = new DirectoryEntry(sParentDN);
            if (parentDE != null)
            {
                string gpLinkEntries = null;
                string[] gplinkTokens = null;

                if (parentDE.Properties["gpLink"].Value != null)
                    gpLinkEntries = parentDE.Properties["gpLink"].Value.ToString();

                if (gpLinkEntries != null)
                    gplinkTokens = gpLinkEntries.Split(']');

                if (gplinkTokens == null)
                    return;

                foreach (string gpLink in gplinkTokens)
                {
                    if (gpLink.Trim().Length == 0)
                        continue;
                    string gpoLink = gpLink.Substring(1, gpLink.IndexOf(';') - 1);
                    gpoLink = gpoLink.Substring(gpoLink.LastIndexOf('/') + 1);
                    if (!gpoLink.Trim().Equals(DistinguishedName, StringComparison.InvariantCultureIgnoreCase))
                        attrValues.Add(gpLink + "]");
                }

                string gpLink_Value = "";
                foreach (string value in attrValues)
                {
                    gpLink_Value += value;
                }

                string[] gpLink_values = null;
                if (String.IsNullOrEmpty(gpLink_Value))
                {
                    gpLink_values = new string[] { null };
                }
                else
                {
                    gpLink_values = new string[] { gpLink_Value, null };
                }

                LDAPMod gpLink_Info =
                   new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "gpLink",
                               gpLink_values);

                LDAPMod[] attrinfo = new LDAPMod[] { gpLink_Info };

                int ret = dirContext.ModifySynchronous(sParentDN, attrinfo);

                if (ret == 0)
                {
                    ListOUChildren(sParentDN);
                    RefreshlvItems();
                }
                else
                {
                    string sMsg = ErrorCodes.LDAPString(ret);
                    container.ShowMessage(sMsg);
                    return;
                }
            }
        }
    /// <summary>
    /// Modifies the specified attributes for the selected AD Object either "user" to AD Schema template
    /// </summary>
    /// <returns></returns>
    public bool OnApply()
    {
        List<LDAPMod> attrlist = new List<LDAPMod>();
        //the following portion of code uses openldap "ldap_Modify_s"
        string basedn = dirnode.DistinguishedName;
        DirectoryContext dirContext = dirnode.LdapContext;
        string[] objectClass_values = null;

        if (!(_editObject.Description.Equals(_originalObject.Description)))
        {
            if (String.IsNullOrEmpty(_editObject.Description))
                objectClass_values = new string[] { null };
            else
                objectClass_values = new string[] { _editObject.Description, null };

            LDAPMod attr =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "description",
            objectClass_values);
            attrlist.Add(attr);
        }

        if (!_editObject.DelegateTrust.Equals(_originalObject.DelegateTrust))
        {
            int userCtrlBinStr = _editObject.UserCtrlBinStr;

            if (_editObject.DelegateTrust)
            {
                userCtrlBinStr += 524288;
            }
            else
            {
                userCtrlBinStr -= 524288;
            }

            string[] userControl_values = { userCtrlBinStr.ToString(), null };
            LDAPMod userControl_Info =
            new LDAPMod((int)LDAPMod.mod_ops.LDAP_MOD_REPLACE, "userAccountControl", userControl_values);

            attrlist.Add(userControl_Info);
        }

        LDAPMod[] attrArry = attrlist.ToArray();
        int ret = -1;
        if (attrArry != null && attrArry.Length != 0)
        {
            ret = dirContext.ModifySynchronous(basedn, attrArry);
        }
        else
        {
            return true;
        }
        if (ret != 0)
        {
            string sMsg = ErrorCodes.LDAPString(ret);
            container.ShowMessage(sMsg);
            return false;
        }
        UpdateOriginalData();
        return true;
    }