C# 开发dynamics crm修改密码功能

asp.net站点实现,话不多说,先上核心代码,

简单界面如下如所示:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="UpdatePassWord.aspx.cs" Inherits="WebApplication1.UpdatePassWord" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<%--<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="cp.aspx.cs" Inherits="AdService.cp" %>--%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head >   <%--runat="server"--%>
    <title>Update AD Password</title>
    <style>
        .metaphor-grid-header {
            position: relative;
            background-color: #FFFFFF;
            font-stretch:normal;
            color: #1160B7;
        }

        .ms-crm-FormSection {
            margin-left: 0px;
            padding-right: 2px;
            border-collapse: separate;
            background-color: #FFFFFF;
            border: 1px solid #BFC5C6;
            width: 600px;
        }

        .List-SelectedRow {
            height: 36px;
            border-bottom: 1px solid #E0E0E0;
        }

        .ms-crm-Inline-Label {
            font-size: 16px;
            font-family: 'Segoe UI', Tahoma, sans-serif;
            font-style: normal;
            color: #505050;
        }

        .ms-crm-Inline-Value {
            font-size: 16px;
            font-family: 'Segoe UI', Tahoma, sans-serif;
            font-style: normal;
            border: 1px solid #505050;
        }
        
        .postButton {
            clear: both;
            float: left;
            margin-right: 0px;
            vertical-align: top;
            height: 30px;
            border: 1px solid #D4D4D4;
            cursor: pointer;
            margin-right: 1px;
            margin-bottom: 0px;
            padding: 0 15px 0 19px;
            font-size: 16px;
            width:auto;
            white-space: nowrap;
            background: #0078D7 none;
            color: #ffffff;
        }

        .field-validation-error {
            font-size: 16px;
            font-family: 'Segoe UI', Tahoma, sans-serif;
            font-style: normal;
            color: #505050;
        }
    </style>
</head>
<body>
    <%--<form id="form1" runat="server">--%>

        <div class=" navbar-fixed-top">
            <hgroup class="metaphor-grid-header">   <%--AssociatedControlID="LoginTitle"--%>
                <h2 style="color: #1160B7;">
                    <asp:Label runat="server" ID="labLogin" Text="<%$ Resources:Resource,LoginTitle %>" CssClass="metaphor-grid-header"></asp:Label>
                    </h2>
            </hgroup>
            <p class="metaphor-grid-header">
                <asp:Literal runat="server" ID="ErrorMessage" />
            </p>
            <table class="ms-crm-FormSection">
                <tr class="List-SelectedRow">
                    <td style="width:150px; color: #505050;"><asp:Label runat="server" AssociatedControlID="txt_UserName" Text="<%$ Resources:Resource,UserName %>" CssClass="ms-crm-Inline-Label"></asp:Label></td>    <%--User Name--%>                
                    <%--<asp:Label runat="server" ID=Label1 Text="<%$ Resources:Resource,LoginTitle %>" ></asp:Label>--%>                    
                    <td style="width:200px"><asp:TextBox runat="server" ID="txt_UserName" CssClass="ms-crm-Inline-Value" /></td>
                    <td><asp:RequiredFieldValidator runat="server" ControlToValidate="txt_UserName"
                        CssClass="field-validation-error" ErrorMessage="Required Field." /></td>
                </tr>
                <tr class="List-SelectedRow">
                    <td style="width:150px; color: #505050;"><asp:Label runat="server" AssociatedControlID="txt_Old_PassWord" Text="<%$ Resources:Resource,OldPassword %>" CssClass="ms-crm-Inline-Label"></asp:Label></td><%--Old Password--%>
                    <td style="width:200px"><asp:TextBox runat="server" ID="txt_Old_PassWord" TextMode="Password" CssClass="ms-crm-Inline-Value" /></td>
                    <td><asp:RequiredFieldValidator runat="server" ControlToValidate="txt_Old_PassWord"
                            CssClass="field-validation-error" ErrorMessage="Required Field." /></td>
                </tr>
                <tr class="List-SelectedRow">
                    <td style="width:150px; color: #505050;"><asp:Label runat="server" AssociatedControlID="txt_New_Password" Text="<%$ Resources:Resource,NewPassword %>" CssClass="ms-crm-Inline-Label"></asp:Label></td> <%--New Password--%>
                    <td style="width:200px"><asp:TextBox runat="server" ID="txt_New_Password" TextMode="Password" CssClass="ms-crm-Inline-Value" /></td>
                    <td><asp:RequiredFieldValidator runat="server" ControlToValidate="txt_New_Password"
                            CssClass="field-validation-error" ErrorMessage="Required Field." /></td>
                </tr>
                <tr class="List-SelectedRow">
                    <td style="width:150px; color: #505050;"><asp:Label runat="server" AssociatedControlID="txt_New_ConfirmPassword"  Text="<%$ Resources:Resource,ConfirmPassword %>" CssClass="ms-crm-Inline-Label"></asp:Label></td>   <%--Confirm Password--%>
                    <td style="width:200px"><asp:TextBox runat="server" ID="txt_New_ConfirmPassword" TextMode="Password" CssClass="ms-crm-Inline-Value" /></td>
                    <td><asp:RequiredFieldValidator runat="server" ControlToValidate="txt_New_ConfirmPassword"
                            CssClass="field-validation-error" Display="Dynamic" ErrorMessage="Required Field." />
                        <asp:CompareValidator runat="server" ControlToCompare="txt_New_Password" ControlToValidate="txt_New_ConfirmPassword"
                            CssClass="field-validation-error" Display="Dynamic" ErrorMessage="New Password not match" /></td>
                </tr>
                <tr class="List-SelectedRow">
                    <td style="width:150px; color: #505050;">&nbsp;</td>
                    <td style="width:200px"><asp:Button runat="server" ID="btn_Action_Update" CommandName="MoveNext" Text="<%$ Resources:Resource,Update %>" OnClick="btn_Action_Update_Click" CssClass="postButton" /></td>  <%--Text="Update"--%>
                    <td>&nbsp;</td> 
                </tr>
            </table>
        </div>
    <%--</form>--%>
</body>

</html>




</asp:Content>

核心功能代码如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.DirectoryServices;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class UpdatePassWord : System.Web.UI.Page
    {
        static string _exception = "";

        string P_flag;
        string  languagenum=null;
        string cultureString = null;
       
        protected void Page_Load(object sender, EventArgs e)
        {
            //languagenum = "1033";   //Request.QueryString["languageid"].ToString().Trim();
            //InitializeCulture1();
            //this.labLogin.Text = Resources.Resource.LoginTitle;//后台代码中使用
            //this.txt_UserName.Text = Resources.Resource.UserName;
            //this.txt_Old_PassWord.Text = Resources.Resource.OldPassword;
            //this.txt_New_Password.Text = Resources.Resource.NewPassword;
            //this.txt_New_ConfirmPassword.Text = Resources.Resource.ConfirmPassword;
            //this.btn_Action_Update.Text = Resources.Resource.Update;
        }     
        protected override void InitializeCulture()
        {

            if (string.IsNullOrEmpty(Request.QueryString["languageid"]))
            {
                cultureString = "en-us";
            }
            else
            {
                languagenum = Request.QueryString["languageid"].ToString().Trim();  // "2052";   /
            }                       
            //"en-us";   //null; //en-us "zh-cn"  可以根据用户选择的语言,保存到session/cookie中 然后去取
            if (languagenum == "1033")
            {
                cultureString = "en-us";
            }
            else if (languagenum == "2052")
            {
                cultureString = "zh-cn";
            }
            else
            {

            }
            if (string.IsNullOrEmpty(cultureString))
            {
                return;
            }
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureString);
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cultureString);
        }

        string _fileDirectory = "log";
        string _filePath = "log_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";//输出日志

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Action_Update_Click(object sender, EventArgs e)
        {
            int _flog = 1;//记录标识,是否存在修改密码的账户 1:代表存在此用户 2:代表不存在此用户 3:代表程序出错 4:代表旧密码不正确 5:新密码和旧密码相同    
            _fileDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + _fileDirectory;
            _filePath = _fileDirectory + "//" + _filePath;

            CheckIsHaveFileDirectory(_fileDirectory);
            CheckIsHaveFile(_filePath);
            string DomainServer = null;
            string ManagerName = null;
            string ManagerPassword = null;
            DirectoryEntry entry = null;
            try
            {
                string Uname = null;
                WriteLogToTxt(_filePath, "----执行开始----");
                if (txt_UserName.Text.ToString().Contains(@"csi\"))
                {
                    Uname = txt_UserName.Text.Replace(@"csi\", "").Trim();
                }
                else
                {
                    Uname=txt_UserName.Text.Trim();
                }                
                //bool Uname=txt_UserName.Text.Contains("csi'\'");  
                string _UserName = Uname;     //txt_UserName.Text.Trim();
                string _Old_PassWord = txt_Old_PassWord.Text.Trim();
                string _New_Password = txt_New_Password.Text.Trim();
                string _New_ConfirmPassword = txt_New_ConfirmPassword.Text.Trim();
                //密码强度限制
                PasswordStrength(_New_Password);
                if (P_flag == "0" || P_flag=="1" )   //|| P_flag=="2"
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "温馨提示:密码必须包含数字,字母,且长度不能小于6位!";
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips: the password must contain Numbers,letters,and the length must not be less than 6 bits!";
                    }
                    
                    return;
                }
                else
                {

                }
                DomainServer = ConfigurationManager.AppSettings["DomainServer_AD"].ToString();
                ManagerName = ConfigurationManager.AppSettings["ManagerName_AD"].ToString();
                ManagerPassword = ConfigurationManager.AppSettings["ManagerPassword_AD"].ToString();

                //string DomainServer = "1";
                //string ManagerName = "1";
                //string ManagerPassword = "1";

                WriteLogToTxt(_filePath, "----域控服务器:----" + DomainServer);
                WriteLogToTxt(_filePath, "----管理员账户:----" + ManagerName);
                WriteLogToTxt(_filePath, "----管理员密码:----" + ManagerPassword);

                WriteLogToTxt(_filePath, "----被修改账户:----" + _UserName);
                WriteLogToTxt(_filePath, "----旧密码:----" + _Old_PassWord);
                WriteLogToTxt(_filePath, "----新密码:----" + _New_Password);
                WriteLogToTxt(_filePath, "----语言:----" + languagenum);
                entry = new DirectoryEntry("LDAP://" + DomainServer, ManagerName, ManagerPassword, AuthenticationTypes.Secure);
                if (_Old_PassWord != _New_Password)
                {
                    if (CheckIs_Old_PassWord_IsCorrect(_UserName, _Old_PassWord, _filePath))
                    {
                        #region 密码修改部分
                        //DirectoryEntry entry = new DirectoryEntry("LDAP://" + DomainServer, ManagerName, ManagerPassword, AuthenticationTypes.Secure);
                        List<string> directorys = new List<string>();
                        //try
                        //{
                        if (entry != null)
                        {
                            DirectorySearcher mySearcher = new DirectorySearcher(entry);
                            mySearcher.Filter = ("(&(objectClass=user)(sAMAccountName=" + _UserName + "))");
                            SearchResult searchResult = mySearcher.FindOne();
                            if (searchResult != null)
                            {
                                _flog = 1;
                                WriteLogToTxt(_filePath, "----是否存在:----域中存在此账户");
                                DirectoryEntry userEntry = searchResult.GetDirectoryEntry();
                                //userEntry.Invoke("ChangePassword", new object[] { _Old_PassWord, _New_ConfirmPassword });//调ChangePassword方法修改密码
                                userEntry.Invoke("SetPassword", new object[] { _New_ConfirmPassword });
                                entry.CommitChanges();//提交修改  
                                WriteLogToTxt(_filePath, "----执行结果:----密码修改成功");
                            }
                            else
                            {
                                _flog = 0;
                                WriteLogToTxt(_filePath, "----是否存在:----域中不存在此账户");
                            }
                        }
                        #region
                        //}
                        //catch (Exception ex)
                        //{
                        //    WriteLogToTxt(_filePath, "错误admin用户:" + ManagerName);
                        //    WriteLogToTxt(_filePath, "错误admin密码:" + ManagerPassword);
                        //    WriteLogToTxt(_filePath, "----程序报错:----" + ex.Message);
                        //    ErrorMessage.Text = "程序报错:" + ex.Message;
                        //    _exception = ex.Message;
                        //    _flog = 3;
                        //}
                        //finally
                        //{
                        //    if (entry != null)
                        //    {
                        //        //释放资源
                        //        entry.Close();
                        //        entry.Dispose();
                        //    }
                        //}
                        #endregion
                        #endregion
                    }
                    else
                        _flog = 4;
                }
                else
                {
                    _flog = 5;
                }

                WriteLogToTxt(_filePath, "----执行结束----");

                if (_flog == 5)
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "温馨提示:旧密码和新密码不能相同!";
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips:The old password and the new password cannot be the same!";
                    }
                    
                }
                else if (_flog == 4)
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "程序报错:" + _exception;
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips:" + _exception;
                    }
                   
                }
                else if (_flog == 0)
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "温馨提示:域中不存在此账户!";
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips:This account does not exist in the domain!";
                    }
                    
                }
                else if (_flog == 1)
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "温馨提示:修改成功!";
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips:Modified successfully!";
                    }
                   
                }
                else if (_flog == 3)
                {
                    if (cultureString == "zh-cn")
                    {
                        ErrorMessage.Text = "程序报错:" + _exception;
                    }
                    else
                    {
                        ErrorMessage.Text = "Tips:" + _exception;
                    }
                    //ErrorMessage.Text = "程序报错:" + _exception;
                }

            }
            catch (Exception ex)
            {
                WriteLogToTxt(_filePath, "错误admin用户:" + ManagerName);
                WriteLogToTxt(_filePath, "错误admin密码:" + ManagerPassword);
                WriteLogToTxt(_filePath, "----程序报错:----" + ex.Message);
                if (cultureString == "zh-cn")
                {
                    ErrorMessage.Text = "程序报错:" + ex.Message;
                }
                else
                {
                    ErrorMessage.Text = "Tips:" + ex.Message;
                }
                //ErrorMessage.Text = "程序报错:" + ex.Message;
                _exception = ex.Message;
                _flog = 3;
            }
            finally
            {
                if (entry != null)
                {
                    //释放资源
                    entry.Close();
                    entry.Dispose();
                }
            }
        }

        /// <summary>
        /// 检查输入的用户和老密码是否正确
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public static bool CheckIs_Old_PassWord_IsCorrect(string userName, string passWord, string _filePath)
        {
            //string _fileDirectory = "log";
            //string _filePath = "log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//输出日志  
            //_fileDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + _fileDirectory;
            //_filePath = _fileDirectory + "//" + _filePath;

            int _temp = 0;
            string DomainServer = ConfigurationManager.AppSettings["DomainServer_AD"].ToString();
            string path = "LDAP://" + DomainServer;

            DirectoryEntry entry = new DirectoryEntry(path, userName, passWord, AuthenticationTypes.Secure);

            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            mySearcher.Filter = ("(SAMAccountName=" + userName + ")");
            WriteLogToTxt(_filePath, "用户1:" + userName);
            WriteLogToTxt(_filePath, "密码1:" + passWord);
            try
            {
                SearchResult searchResult = mySearcher.FindOne();
                //WriteLogToTxt(_filePath, "错误用户:" + userName);
                //WriteLogToTxt(_filePath, "错误密码:" + passWord);

                if (searchResult != null)
                    _temp = 1;
            }
            catch (Exception ex)
            {
                WriteLogToTxt(_filePath, "错误用户:" + userName);
                WriteLogToTxt(_filePath, "错误密码:" + passWord);
                WriteLogToTxt(_filePath, "----程序报错:----" + ex.Message);
                _exception = ex.Message;
                _temp = 0;
            }

            if (_temp == 1)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断文件夹是否存在
        /// </summary>
        /// <param name="_filePath"></param>
        public static void CheckIsHaveFileDirectory(string _fileDirectory)
        {
            if (Directory.Exists(_fileDirectory) == false)
            {
                Directory.CreateDirectory(_fileDirectory);
            }
        }
        /// <summary>
        /// 判断是否存在文件
        /// </summary>
        /// <param name="_filePath"></param>
        public static void CheckIsHaveFile(string _filePath)
        {
            if (!System.IO.File.Exists(_filePath))
            {
                System.IO.File.WriteAllText(_filePath, "");
            }
            else
            {
                System.IO.File.Create(_filePath);
            }
        }

        /// <summary>
        /// 写入txt文件记录信息
        /// </summary>
        /// <param name="_filePath"></param>
        /// <param name="strdata"></param>
        public static void WriteLogToTxt(string _filePath, string strdata)
        {
            StreamWriter sw = System.IO.File.AppendText(@_filePath);
            sw.WriteLine(DateTime.Now.ToLocalTime() + "  " + strdata);
            sw.Flush();
            sw.Close();
        }

        /// <summary>
        /// 密码强度
        /// </summary>
        private enum Strength
        {
            Invalid = 0, //无效密码
            Weak = 1, //低强度密码
            Normal = 2, //中强度密码
            Strong = 3 //高强度密码
        };
        /// <summary>
        /// 计算密码强度
        /// </summary>
        /// <param name="password">密码字符串</param>
        /// <returns></returns>
        //private static Strength PasswordStrength(string password)
        //{
        //    //空字符串强度值为0
        //    string P_flag=null;
        //    if (password == "") return Strength.Invalid.ToString();
        //    //字符统计
        //    int iNum = 0, iLtt = 0, iSym = 0;
        //    foreach (char c in password)
        //    {
        //        if (c >= '0' && c <= '9') iNum++;
        //        else if (c >= 'a' && c <= 'z') iLtt++;
        //        else if (c >= 'A' && c <= 'Z') iLtt++;
        //        else iSym++;
        //    }
        //    if (iLtt == 0 && iSym == 0) return Strength.Weak; //纯数字密码
        //    if (iNum == 0 && iLtt == 0) return Strength.Weak; //纯符号密码
        //    if (iNum == 0 && iSym == 0) return Strength.Weak; //纯字母密码
        //    if (password.Length <= 6) return Strength.Weak; //长度不大于6的密码
        //    if (iLtt == 0) return Strength.Normal; //数字和符号构成的密码
        //    if (iSym == 0) return Strength.Normal; //数字和字母构成的密码
        //    if (iNum == 0) return Strength.Normal; //字母和符号构成的密码
        //    if (password.Length <= 10) return Strength.Normal; //长度不大于10的密码
        //    return Strength.Strong; //由数字、字母、符号构成的密码
        //}
        public string PasswordStrength(string password)
        {
            //空字符串强度值为0           
            if (password == "") return P_flag="0";
            //字符统计
            int iNum = 0, iLtt = 0, iSym = 0;
            foreach (char c in password)
            {
                if (c >= '0' && c <= '9') iNum++;
                else if (c >= 'a' && c <= 'z') iLtt++;
                else if (c >= 'A' && c <= 'Z') iLtt++;
                else iSym++;
            }
            if (iLtt == 0 && iSym == 0) return P_flag = "1"; //纯数字密码
            if (iNum == 0 && iLtt == 0) return P_flag = "1"; //纯符号密码
            if (iNum == 0 && iSym == 0) return P_flag = "1"; //纯字母密码
            if (password.Length < 6) return P_flag = "1"; //长度不大于6的密码
            //if (iLtt == 0) return P_flag = "2"; //数字和符号构成的密码
            //if (iSym == 0) return P_flag = "2"; //数字和字母构成的密码
            //if (iNum == 0) return P_flag = "2"; //字母和符号构成的密码
            //if (password.Length <6) return P_flag = "2"; //长度不大于10的密码
            return P_flag = "3"; //由数字、字母组成    //、符号构成的密码
        }
    }
}

开发换成后,需要在站点地图中添加菜单,然后绑定界面html+js功能调用该站点。

具体实现如下:

<html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
    <script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script type="text/javascript">
        var languageid = Xrm.Page.context.getUserLcid();
        //alert(languageid);
        window.onload = function () {
            var protocol = window.location.protocol;
            var domain = window.location.host;
            var port = window.location.port;
            var newurl = protocol + "//" + domain + ":81/cp?languageid="+languageid;
            window.open(newurl,"_blank");
            //window.location.href=newurl;
        }
    </script>                 
<meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta><meta></head>
<body style="overflow-wrap: break-word;"></body></html>

站点地图配置如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值