Change Login and Passwords using iBO.NET and CContactUser

Trying to get this script to change logins and passwords on existing users.  Any idea how I get access to the CContactUser object to assign the new login and password?  

 

The program compiles and runs, with no reported errors, but it does not change the login and password.

Code:

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Asi.iBO;
using Asi.iBO.ContactManagement;

public partial class custom_CreateUsers_Default : System.Web.UI.Page
{
    //Set debug to true in order to conduct a dry run
    private Boolean debug = false;

    //Log file path and name. Ensure the path is properly escaped, \\ not \
    private String log_path = "C:\\Program Files (X86)\\ASI\\iMIS15\\Net\\Customlogs\\";
    private String log_name = "Modify_process_log_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".txt";

    //Modify this SQL query, MUST return ID, LOGIN and PASSWORD
    //You can restrict this by adding top to the query
    private String strSQL = @"SELECT Name.ID AS ID,
                                   Name.Email AS LOGIN,
                                   '2033-03-05' AS EXPIRY_DATE,
                                    LOWER(LEFT(Name.First_Name,1)) + LOWER(LEFT(REPLACE(Last_Name,' ',''),5)) AS PASSWORD
                                  FROM Name
                            WHERE Name.ID = '100397' and LAST_NAME <> ''
                            ORDER BY Name.LAST_NAME ";

    private CStaffUser iBOUser;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Check_Query();
        }
    }

    protected void Create_Users(object sender, EventArgs e)
    {
        //Process_Users();
        //Start a new thread to handle the processing
        ThreadStart ts = delegate { Process_Users(); };
        Thread workerThread = new Thread(ts);
        workerThread.Start();
        lblMessage.Text = String.Format("The task is now running. Check the log file ({0}) for finished message.", this.log_name);
        lblSQLQuery.Visible = false;
        btnCreateUsers.Visible = false;
    }

    protected void Process_Users()
    {
        CContact contact;
        String processing_result;
        String error_msg;
        OpeniMISiBOConnection();
        DateTime started = DateTime.Now;
        Int32 errors = 0;
        Int32 complete = 0;
        using (DataServer server = new DataServer(iboAdmin.ConnectionString))
        {
            DataSet results = server.ExecuteQuery(CommandType.Text, this.strSQL);
            foreach (DataRow row in results.Tables[0].Rows)
            {
                processing_result = "COMPLETE";
                error_msg = "";
                try
                {
                    contact = new CContact(this.iBOUser, row["ID"].ToString());
                    contact.UserSecurity.ChangePassword(row["PASSWORD"].ToString(),"MANAGER","manager") ;
                    contact.UserSecurity.ChangeWebLogin(row["LOGIN"].ToString(),row["PASSWORD"].ToString());
                    if (row.Table.Columns.Contains("EXPIRY_DATE"))
                        contact.UserSecurity.ExpiresOn = DateTime.Parse(row["EXPIRY_DATE"].ToString());
                    if (row.Table.Columns.Contains("SECURITY_GROUP"))
                        contact.UserSecurity.SecurityGroup = row["SECURITY_GROUP"].ToString();
                    contact.Validate();
                    if (!this.debug)
                        contact.Save();
                    complete++;
                }
                catch (Exception ex)
                {
                    processing_result = "ERROR";
                    error_msg = ex.Message;
                    errors++;
                }
                finally
                {
                    WriteLog(processing_result + "\t" + row["ID"].ToString() + "\t" + error_msg);
                }
            }
        }
        DateTime finished = DateTime.Now;
        WriteLog(String.Format("Started: {0}\tFinished: {1}\t", started.ToString(), finished.ToString()));
        WriteLog(String.Format("Complete: {0}\tErrors: {1}\t", complete.ToString(), errors.ToString()));
    }

    protected void Check_Query()
    {
        Boolean error = false;
        lblSQLQuery.Text = this.strSQL;
        lblMessage.Text = "Query check results:";
        //Run the query and test it
        using (DataServer server = new DataServer(iboAdmin.ConnectionString))
        {
            DataSet results = server.ExecuteQuery(CommandType.Text, this.strSQL);
            if (!results.Tables[0].Columns.Contains("ID"))
            {
                error = true;
                lblMessage.Text += "<br /> ERROR: ID is not in the result set";
            }
            if (!results.Tables[0].Columns.Contains("LOGIN"))
            {
                error = true;
                lblMessage.Text += "<br /> ERROR: LOGIN is not in the result set";
            }
            if (!results.Tables[0].Columns.Contains("PASSWORD"))
            {
                error = true;
                lblMessage.Text += "<br /> ERROR: PASSWORD is not in the result set";
            }
            if (!results.Tables[0].Columns.Contains("EXPIRY_DATE"))
            {
                lblMessage.Text += "<br /> WARNING: EXPIRY_DATE is not in the result set, NO expiration date will be set!";
            }
            if (!results.Tables[0].Columns.Contains("SECURITY_GROUP"))
            {
                lblMessage.Text += "<br /> WARNING: SECURITY_GROUP is not in the result set, NO security group will be set!";
            }
            if (error)
            {
                btnCreateUsers.Enabled = false;
                lblMessage.Text += "<br /> Please resolve errors and try again!";
            }
            else
            {
                lblMessage.Text += "<br /> No errors found, ready to run.";
            }
            Application["CU_TOTAL_RECORDS"] = results.Tables[0].Rows.Count;
            lblMessage.Text += String.Format("<br /> Query returned {0} results.", Application["CU_TOTAL_RECORDS"].ToString());
        }
    }

    private void OpeniMISiBOConnection()
    {
        // we need to open connection to IMIS
        this.iBOUser = null;
        Asi.iBO.iboAdmin.InitializeSystem();
        Asi.iBO.iboAdmin.Refresh();
        //this.iBOUser = CStaffUser.Login(ConfigurationSettings.AppSettings["StaffLoginID"].ToString(), ConfigurationSettings.AppSettings["StaffLoginPassword"].ToString());
        this.iBOUser = CStaffUser.GetDefaultStaffUser();
        this.iBOUser.ThrowExceptionOnError = true;
        this.iBOUser.ThrowExceptionOnWarning = true;
    }

 

    private void WriteLog(string message)
    {
        try
        {
            string logfile = this.log_path + this.log_name;
            if (!File.Exists(logfile))
            {
                File.Create(logfile).Close();
            }
            using (StreamWriter w = File.AppendText(logfile))
            {
                w.WriteLine(message.Replace("||", "\t"));
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
        }
    }
}
 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Sample Code

Here is our code for changing the password. It works for us and we have used it a number of times on production sites:

protected void submitPasswordBTN_Click(object sender, EventArgs e)
{
MessageLB2.Text="";
if(PasswordResetTB.Text==PasswordReset2TB.Text)
{
CContactUser userp = null;

userp = CContactUser.LoginByWebLogin(UsernameTB.Text, PasswordTB.Text);

userp.ChangePassword(PasswordTB.Text, PasswordResetTB.Text);
userp.Save();

MessageLB2.Text="your password has been updated

";

}
else
{
MessageLB2.Text="Your passwords must match, please re-enter

";
}
}

For changing the password, you must submit the old password and it must be correct. The iBO will not work without the old password passed to it. Sorry we don't have any for change your login. Hope this helps

James Harrison
www.visualantidote.com