c#访问visualsvn server, 按照其 mof文件, 控制其服务端的功能,如建用户 设访问权限

阅读更多
https://yq.aliyun.com/articles/15964


摘要: VisualSVN Server可以用WMI接口管理(Windows Management Instrumentation)。 VisualSVN Server安装的计算机中,位于%VISUALSVN_SERVER%\WMI下的MOF文件描述了该接口。 


VisualSVN Server可以用WMI接口管理(Windows Management Instrumentation)。
VisualSVN Server安装的计算机中,位于%VISUALSVN_SERVER%\WMI下的MOF文件描述了该接口。可以用C#代码控制管理VisualSVN Server。

我机器VisualSVN安装在D盘,MOF文件存在位置:D:\Program Files\VisualSVN Server\WMI\VisualSVNServer.mof

下面一些代码供参考:


using System.Management;
using System.Management.Instrumentation;

并添加 System.Management,System.Management.Instrumentation这两个组件的引用。 

1)创建Subversion 用户 'user1',密码为'secret'


ManagementClass userClass = newManagementClass("root\\VisualSVN","VisualSVN_User",null);
// Obtain in-parameters for the method
ManagementBaseObject inParams =
userClass.GetMethodParameters("Create");
// Add the input parameters.
inParams["Name"] = "user1";
inParams["Password"] = "secret";
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
userClass.InvokeMethod("Create", inParams, null);

 2)创建新的repository 'Repo1' 


ManagementClass repoClass = newManagementClass("root\\VisualSVN","VisualSVN_Repository",null);
// Obtain in-parameters for the method
ManagementBaseObject inParams =
repoClass.GetMethodParameters("Create");
// Add the input parameters.
inParams["Name"] = "Repo1";
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
repoClass.InvokeMethod("Create", inParams, null);




  3)设置SID S-1-5-32-545 ('BUILTIN\Users') Windows用户组对'Test' repository的读/写权限. FYI: AccessLevel 值在MOF有描述: "0 - 无权限, 1 - 只读, 2 - 读/写". 


ManagementClass userClass = newManagementClass("root\\VisualSVN","VisualSVN_WindowsAccount",null);
ManagementClass authzClass = newManagementClass("root\\VisualSVN","VisualSVN_SecurityDescriptor",null);
ManagementClass permClass = newManagementClass("root\\VisualSVN","VisualSVN_PermissionEntry",null);
ManagementObject userObject = userClass.CreateInstance();
userObject.SetPropertyValue("SID","S-1-5-32-545");
ManagementObject permObject = permClass.CreateInstance();
permObject.SetPropertyValue("Account", userObject);
permObject.SetPropertyValue("AccessLevel", 2);
ManagementObject repo = newManagementObject("VisualSVN_Repository.Name='Test'");
ManagementBaseObject inParams =
authzClass.GetMethodParameters("SetSecurity");
inParams["Object"] = repo;
inParams["Permissions"] = newobject[] { permObject };
ManagementBaseObject outParams =
authzClass.InvokeMethod("SetSecurity", inParams, null);

封装后的Helper类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;//调用windows WMI需引入此类库

namespace Whir.Software.InteralServerManage.SVNManager
{
    /// 
    ///     Visual SVN 操作辅助类:使用WMI控制VisualSVN,MOF文件存在位置:C:\Program Files\VisualSVN Server\WMI\VisualSVNServer.mof
    /// 
    public class SVNHelper
    {
        #region 设置

        #region 设置仓库权限

        public enum AccessLevel : uint
        {
            NoAccess = 0,
            ReadOnly,
            ReadWrite
        }

        /// 
        ///     设置仓库权限(给用户授权)
        /// 
        /// 用户名
        /// SVN仓库
        public static bool SetRepositoryPermission(string userName, string repository)
        {
            return SetRepositoryPermission(userName, repository, 2);
        }

        /// 
        ///     设置仓库权限(给用户授权)
        /// 
        /// 用户名
        /// SVN仓库
        public static bool SetRepositoryPermission(List users, string repository)
        {
            string userNames = "";
            foreach (string user in users)
            {
                userNames += user + ",";
            }
            return SetRepositoryPermission(userNames, repository, 2);
        }

        /// 
        ///     设置仓库权限(给用户授权)
        /// 
        /// 用户名
        /// SVN仓库
        ///  权限码:0拒绝,1只读,2读写
        public static bool SetRepositoryPermission(string userName, string repository, int permission)
        {
            try
            {
                string[] users = userName.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
                IDictionary permissions = GetPermissions(repository, "/");
                foreach (string s in users)
                {
                    if (!permissions.ContainsKey(s))
                    {
                        permissions.Add(s, AccessLevel.ReadWrite);
                    }
                }
                SetPermissions(repository, "/", permissions);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// 
        ///     根据仓库名取得仓库实体
        /// 
        /// 
        /// 
        private static ManagementObject GetRepositoryObject(string name)
        {
            return new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_Repository.Name='{0}'", name), null);
        }

        /// 
        ///     读取权限实体
        /// 
        /// 
        /// 
        /// 
        private static ManagementObject GetPermissionObject(string sid, AccessLevel accessLevel)
        {
            var accountClass = new ManagementClass("root\\VisualSVN",
                                                   "VisualSVN_WindowsAccount", null);
            var entryClass = new ManagementClass("root\\VisualSVN",
                                                 "VisualSVN_PermissionEntry", null);
            ManagementObject account = accountClass.CreateInstance();
            if (account != null) account["SID"] = sid;
            ManagementObject entry = entryClass.CreateInstance();
            if (entry != null)
            {
                entry["AccessLevel"] = accessLevel;
                entry["Account"] = account;
                return entry;
            }
            return null;
        }

        /// 
        ///     设置仓库权限
        /// 
        /// 
        /// 
        /// 
        private static void SetPermissions(string repositoryName, string path,
                                           IEnumerable> permissions)
        {
            ManagementObject repository = GetRepositoryObject(repositoryName);
            ManagementBaseObject inParameters = repository.GetMethodParameters("SetSecurity");
            inParameters["Path"] = path;
            IEnumerable permissionObjects =
                permissions.Select(p => GetPermissionObject(p.Key, p.Value));
            inParameters["Permissions"] = permissionObjects.ToArray();
            repository.InvokeMethod("SetSecurity", inParameters, null);
        }

        /// 
        ///     读取仓库权限
        /// 
        /// 
        /// 
        /// 
        private static IDictionary GetPermissions(string repositoryName, string path)
        {
            ManagementObject repository = GetRepositoryObject(repositoryName);
            ManagementBaseObject inParameters = repository.GetMethodParameters("GetSecurity");
            inParameters["Path"] = path;
            ManagementBaseObject outParameters = repository.InvokeMethod("GetSecurity", inParameters, null);

            var permissions = new Dictionary();

            if (outParameters != null)
                foreach (ManagementBaseObject p in (ManagementBaseObject[]) outParameters["Permissions"])
                {
                    // NOTE: This will fail if VisualSVN Server is configured to use Subversion
                    // authentication.  In that case you'd probably want to check if the account
                    // is a VisualSVN_WindowsAccount or a VisualSVN_SubversionAccount instance
                    // and tweak the property name accordingly. 
                    var account = (ManagementBaseObject) p["Account"];
                    var sid = (string) account["SID"];
                    var accessLevel = (AccessLevel) p["AccessLevel"];

                    permissions[sid] = accessLevel;
                }

            return permissions;
        }

        #endregion

        #region 创建用户组

        /// 
        ///     创建用户组
        /// 
        public static bool CreatGroup(string groupName)
        {
            try
            {
                var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
                ManagementBaseObject @params = svn.GetMethodParameters("Create");
                @params["Name"] = groupName.Trim();
                @params["Members"] = new object[] {};
                svn.InvokeMethod("Create", @params, null);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        #region 创建用户

        /// 
        ///     创建用户
        /// 
        /// 
        /// 
        /// 
        public static bool CreateUser(string userName, string password)
        {
            try
            {
                var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_User", null);
                ManagementBaseObject @params = svn.GetMethodParameters("Create");
                @params["Name"] = userName.Trim();
                @params["Password"] = password.Trim();
                svn.InvokeMethod("Create", @params, null);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        #region  创建svn仓库

        /// 
        ///     创建svn仓库
        /// 
        /// 
        /// 
        public static bool CreateRepository(string name)
        {
            try
            {
                var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_Repository", null);
                ManagementBaseObject @params = svn.GetMethodParameters("Create"); //创建方法参数引用
                @params["Name"] = name.Trim(); //传入参数
                svn.InvokeMethod("Create", @params, null); //执行
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        #region  创建svn仓库目录

        /// 
        ///     创建svn仓库目录
        /// 
        ///  
        /// 
        /// 
        public static bool CreateRepositoryFolders(string repositories, string[] name)
        {
            try
            {
                var repository = new ManagementClass("root\\VisualSVN", "VisualSVN_Repository", null);
                ManagementObject repoObject = repository.CreateInstance();
                if (repoObject != null)
                {
                    repoObject.SetPropertyValue("Name", repositories);
                    ManagementBaseObject inParams = repository.GetMethodParameters("CreateFolders");
                    inParams["Folders"] = name;
                    inParams["Message"] = "";
                    repoObject.InvokeMethod("CreateFolders", inParams, null);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        //public static bool SetMemberGroup(string userName, string groupName)
        //{
        //    try
        //    {
        //        var userObj = GetGroupUsersArr(groupName);
        //        foreach (ManagementBaseObject baseObject in userObj)
        //        {
        //            if (baseObject["Name"].ToString().ToLower() == userName)
        //            {
        //                return false;
        //            }
        //        }
        //        var addUser = new ManagementClass("root\\VisualSVN", "VisualSVN_SubversionAccount", null).CreateInstance();
        //        if (addUser != null)
        //        {
        //            addUser.SetPropertyValue("Name", userName);
        //            userObj.Add(addUser);
        //        }

        //        var svnUser = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
        //        ManagementBaseObject inParams = svnUser.GetMethodParameters("SetMembers");
        //        inParams["Members"] = new object[] { userObj };
        //        svnUser.InvokeMethod("SetMembers", inParams, null);
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        return false;
        //    }
        //}

        #endregion

        #region 读取

        /// 
        ///     读取指定组里的用户
        /// 
        /// 
        /// 
        public static List GetGroupUsers(string groupName)
        {
            var listUsers = new List();
            var group = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
            ManagementObject instance = group.CreateInstance();
            if (instance != null)
            {
                instance.SetPropertyValue("Name", groupName.Trim());
                ManagementBaseObject outParams = instance.InvokeMethod("GetMembers", null, null); //通过实例来调用方法
                if (outParams != null)
                {
                    var members = outParams["Members"] as ManagementBaseObject[];
                    if (members != null)
                    {
                        foreach (ManagementBaseObject member in members)
                        {
                            object name = member["Name"];
                            listUsers.Add(name.ToString());
                        }
                    }
                }
            }
            return listUsers;
        }

        public static List GetGroupUsersArr(string groupName)
        {
            var list = new List();
            var group = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
            ManagementObject instance = group.CreateInstance();
            if (instance != null)
            {
                instance.SetPropertyValue("Name", groupName.Trim());
                ManagementBaseObject outParams = instance.InvokeMethod("GetMembers", null, null); //通过实例来调用方法
                if (outParams != null)
                {
                    var members = outParams["Members"] as ManagementBaseObject[];
                    if (members != null)
                    {
                        foreach (ManagementBaseObject member in members)
                        {
                            list.Add(member);
                        }
                    }
                }
            }
            return list;
        }

        #endregion
    }
}



你可能感兴趣的:(c#访问visualsvn server, 按照其 mof文件, 控制其服务端的功能,如建用户 设访问权限)