You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AD及AD组计算机验证C#代码异常修复求助

AD计算机状态勾选逻辑错误修复

问题根源分析

原代码存在以下核心问题:

  1. CheckMachine_ADGroup方法逻辑错误:当计算机不存在于AD(cp == null)时,错误返回true,导致不在AD的机器被标记为在组内。
  2. 变量名大小写不一致:Room_code和Room_Code混用,导致StartsWith判断失效,计算机名拼接逻辑混乱。
  3. 主逻辑分支漏洞:
    • 初始AD检查通过时,若计算机名不符合前缀规则,仅在拼接后AD检查通过时才设置组状态;若拼接后检查失败,组状态保持初始false,忽略了原始计算机名本身可能在AD内的情况。
    • 初始AD检查不通过时,错误调用组检查方法,违背“不在AD则两列都不勾选”的需求。
  4. 分支覆盖不全:当计算机名符合前缀规则时,完全未设置组状态,导致组列始终为false。

修复方案

1. 修正组检查方法逻辑

修改CheckMachine_ADGroup,确保只有计算机存在于AD且属于目标组时才返回true,其余情况返回false:

private bool CheckMachine_ADGroup(string ComputerName, string GroupName)
{
    try
    {
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
        {
            ComputerPrincipal cp = ComputerPrincipal.FindByIdentity(ctx, ComputerName);
            if (cp != null)
            {
                GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, GroupName);
                return gp != null && cp.IsMemberOf(gp);
            }
            // 计算机不在AD,直接返回false
            return false;
        }
    }
    catch
    {
        return false;
    }
}

2. 统一变量名,修复拼接逻辑

将Room_code统一为Room_Code,避免大小写判断错误;重构计算机名尝试逻辑:先试原始名称,再试加前缀,最后试加前缀+ID,直到找到存在于AD的名称或确定所有组合都不存在。

3. 重构主逻辑,严格遵循需求

重新梳理combo_box_SelectionChanged内的逻辑,完全匹配以下规则:

  • 计算机不存在于AD:两列均为false
  • 存在于AD但不在目标组:仅AD列为true
  • 存在于目标组:两列均为true

完整修复代码

private bool MachineADCheck(string ComputerName)
{
    try
    {
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
        {
            ComputerPrincipal cp = ComputerPrincipal.FindByIdentity(ctx, ComputerName);
            return cp != null;
        }
    }
    catch
    {
        return false;
    }
}

private bool CheckMachine_ADGroup(string ComputerName, string GroupName)
{
    try
    {
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
        {
            ComputerPrincipal cp = ComputerPrincipal.FindByIdentity(ctx, ComputerName);
            if (cp != null)
            {
                GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, GroupName);
                return gp != null && cp.IsMemberOf(gp);
            }
            return false;
        }
    }
    catch
    {
        return false;
    }
}

private void combo_box_SelectionChanged(object sender, RoutedEventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    if (cbx != null && cbx.SelectedValue != null && cbx.Name == "combo_box")
    {
        string Room_Code = cbx.SelectedValue.ToString();
        DataTable ComputerData = ComputerWorkStation(Room_Code);
        ComputerData.Columns.Add("Member in AD", typeof(bool));
        ComputerData.Columns.Add("AD Group", typeof(bool));

        foreach (DataRow row in ComputerData.Rows)
        {
            string originalComputerName = row["Computer_Name"].ToString();
            string computerId = row["Computer_ID"].ToString();
            bool isInAD = false;
            bool isInGroup = false;
            string validADComputerName = null;

            // 尝试原始名称
            if (MachineADCheck(originalComputerName))
            {
                validADComputerName = originalComputerName;
                isInAD = true;
            }
            // 尝试加Room_Code前缀
            else if (!originalComputerName.StartsWith(Room_Code))
            {
                string prefixedName = Room_Code + originalComputerName;
                if (MachineADCheck(prefixedName))
                {
                    validADComputerName = prefixedName;
                    isInAD = true;
                }
                // 尝试加前缀+ID
                else
                {
                    string prefixedWithId = prefixedName + computerId;
                    if (MachineADCheck(prefixedWithId))
                    {
                        validADComputerName = prefixedWithId;
                        isInAD = true;
                    }
                }
            }

            // 仅当计算机在AD中时,检查组状态
            if (isInAD && !string.IsNullOrEmpty(validADComputerName))
            {
                isInGroup = CheckMachine_ADGroup(validADComputerName, "Authorized Computers");
            }

            row["Member in AD"] = isInAD;
            row["AD Group"] = isInGroup;
        }

        results2.ItemsSource = ComputerData.DefaultView;
        results2.Visibility = Visibility.Visible;
    }
}

public DataTable ComputerWorkStation(string RoomCodes)
{
    DataTable table = new DataTable();
    using (SqlConnection con = new SqlConnection(Authorized_DB))
    {
        // 注意:此处存在SQL注入风险,建议改用参数化查询
        string sql = $"SELECT Computer_Name, Computer_ID FROM Computer_Workstation WITH (NOLOCK) WHERE Room_Codes = '{RoomCodes}'";
        SqlDataAdapter ComputerWorkStationAdapter = new SqlDataAdapter(sql, con);

        try
        {
            con.Open();
            ComputerWorkStationAdapter.Fill(table);
        }
        catch (Exception ex)
        {
            MessageBox.Show("错误:" + ex.Message);
        }
        // using块会自动关闭连接,无需手动Close
    }
    return table;
}

额外提示

原ComputerWorkStation方法中的SQL语句存在SQL注入风险,建议改为参数化查询,示例如下:

string sql = "SELECT Computer_Name, Computer_ID FROM Computer_Workstation WITH (NOLOCK) WHERE Room_Codes = @RoomCodes";
SqlDataAdapter ComputerWorkStationAdapter = new SqlDataAdapter(sql, con);
ComputerWorkStationAdapter.SelectCommand.Parameters.AddWithValue("@RoomCodes", RoomCodes);

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 13:15:05