an ASP.NET Open Source CMS & eCommerce platform
Search:
Skip Navigation LinksHome > DotShoppingCart Forums > Development > General Programming > Create user programatically
Last Post 1/7/2010 10:27:19 AM By Bahram. 9 replies.
11/8/2009 9:46:44 PM
paulp
Posts: 9
Joined: 11/3/2009
Location:Melb Aus
Create user programatically
Hi All
 
I have 300 users in another database, and it occurs to me that I can use
the sqlmembership provider code to simply create these users from a csv file, that contains the appropriate fields.
 
 
I added a page placed a create user control on it and then simply ran the page,
 
it created the user and the user could login however it would crash if I clicked on My account, and the user isn't visible under Admin either
 
Obviously doing more than just creating the user.
 
THe program flow is simply,
 
read user info fields from file,
 
attempt to create user in dotshoppiung cart, using create_user and what ever else I missed
 
on success/failure record in log.
 
Any suggestion....
 
Kind regards
 
Paul
 
 
 
11/9/2009 11:06:18 AM
lukezy
Posts: 2109
Joined: 6/12/2007
Location:WA, US
Re: Create user programatically
There is additional step that you need to do. Call method DotShoppingCart.Commercial.Core.User.AddUser. Please take a look at method CreateUserWizard1_CreatedUser in  Web\Controls\Blocks\register.ascx.cs.
 
DotShoppingCart Staff
11/9/2009 7:31:12 PM
paulp
Posts: 9
Joined: 11/3/2009
Location:Melb Aus
Re: Create user programatically
Looks promising
 
In Visual studio it complains
 The type or namespace name 'Controls_AddressInput' could not be found (are you missing a using directive or an assembly reference?)
 
 what's the missing using here?
 
Kind Regards
Paul
 
11/10/2009 1:34:55 PM
lukezy
Posts: 2109
Joined: 6/12/2007
Location:WA, US
Re: Create user programatically
That's UI element. I thought you are writing code to bulk create users. You just need to call AddUser method with propriate parameters.
DotShoppingCart Staff
11/10/2009 10:03:43 PM
paulp
Posts: 9
Joined: 11/3/2009
Location:Melb Aus
Re: Create user programatically
Success.
I created an aspx page with a button and a multiline text box.
Using Sql query designer created a query to retreive the required details.
Using an sqltable adapter I read thru the rows and added the users.
 
The Only strange thing is that if I set the subscribe to newsletter to false, the users would not appear in admin user manager, so had to set it to true.
 
Kind Regards
Paul
____________________
 
 
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using DSC = DotShoppingCart.Commercial.Core;
using DotShoppingCart.Commercial.Core;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

public partial class Admin_Create_User : System.Web.UI.Page
{
   
        string userName;
        string password;
        string email;
        bool newsLetter;
        int? referralId;
        string firstName;
        string lastName;
        string companyName;
        string address;
        string address2;
        string city;
        string state;
        string zipcode;
        int countryId;
        string phone;
        string phoneExt;
        DateTime created;
        bool copyToShippingAddress;
       
   
    protected void Page_Load(object sender, EventArgs e)
    {
      
      
    }
    //  public static void AddUser(string userName, bool newsLetter, int? referralId, string firstName, string lastName, string companyName, string address, string address2, string city, string state, string zipcode, int countryId, string phone, string phoneExt, DateTime created, bool copyToShippingAddress);
     
    protected void Button1_Click(object sender, EventArgs e)
    {
        Membership.RequiresQuestionAndAnswer;
        // Assumes that customerConnection is a valid SqlConnection object.
        // Assumes that orderConnection is a valid OleDbConnection object.
          SqlConnection customerConnection  = new SqlConnection("//whatever you connection string is
          string Selectstring = //whatever your select statement is    
        SqlDataAdapter custAdapter = new SqlDataAdapter(
         Selectstring, customerConnection);
     
        DataSet customerOrders = new DataSet();
        custAdapter.Fill(customerOrders, "Customers");
 

        foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
        {
            // TextBox1.Text +=  + "/n";
            userName = pRow["username"].ToString().Trim();//the names are aliases in sql select statment.
            password = pRow["password"].ToString();
            email = pRow["email"].ToString();
            newsLetter = true;
            referralId = CoreHelper.GetReferralId();
            string[] split = pRow["contactName"].ToString().Split(' ');
            firstName = split[0];
            lastName = split[1];
            companyName = pRow["companyName"].ToString();
            address = pRow["address1"].ToString();
         //   address2 = pRow["address2"].ToString();
            city = pRow["city"].ToString();
            state = pRow["state"].ToString();
            zipcode = pRow["postcode"].ToString();
            countryId = 8;
            phone = pRow["phone1"].ToString();
            phoneExt = "";
            created = DateTime.Now;
            copyToShippingAddress = false;
            //   Console.WriteLine(pRow["CustomerID"]);
            //    foreach (DataRow cRow in pRow.GetChildRows(relation))
            //        Console.WriteLine("\t" + cRow["OrderID"]);
 
            MembershipCreateStatus status;
            try
            {
            
               //   MembershipUser newuser = Membership.CreateUser(userName,password,email,"question","answer",true,out status);
             //   Membership.DeleteUser(userName); // uncomment to delete a user and refresh details, you will lose users sales history I would suspect?
               MembershipUser newuser=  Membership.CreateUser(userName, password, email, "question", "answer", true, out status);
             
                    if (newuser == null)
                    {
                      TextBox1.Text += GetErrorMessage(status) + Environment.NewLine;
                    }
                    else
                    {
                       TextBox1.Text += "added user " + userName+Environment.NewLine;
                        
                                   //       DSC.User.Delete(userName); // uncomment to delete a user and refresh details, you will lose users sales history I would suspect?

                     DSC.User.AddUser(userName, newsLetter, CoreHelper.GetReferralId(), firstName, lastName, companyName, address, address2, city, state, zipcode, countryId, phone, phoneExt, created, false);
                           
                  }
                }
              
                catch
               {
                   TextBox1.Text += "An exception occurred creating the user."+Environment.NewLine;
               }

            }
        }
      
     
       
   
    public string GetErrorMessage(MembershipCreateStatus status)
    {
        switch (status)
        {
            case MembershipCreateStatus.DuplicateUserName:
                return "Username already exists. Please enter a different user name.";
            case MembershipCreateStatus.DuplicateEmail:
                return "A username for that e-mail address already exists. Please enter a different e-mail address.";
            case MembershipCreateStatus.InvalidPassword:
                return "The password provided is invalid. Please enter a valid password value.";
            case MembershipCreateStatus.InvalidEmail:
                return "The e-mail address provided is invalid. Please check the value and try again.";
            case MembershipCreateStatus.InvalidAnswer:
                return "The password retrieval answer provided is invalid. Please check the value and try again.";
            case MembershipCreateStatus.InvalidQuestion:
                return "The password retrieval question provided is invalid. Please check the value and try again.";
            case MembershipCreateStatus.InvalidUserName:
                return "The user name provided is invalid. Please check the value and try again.";
            case MembershipCreateStatus.ProviderError:
                return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            case MembershipCreateStatus.UserRejected:
                return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            default:
                return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        }
    }

}
 
1/6/2010 11:58:52 AM
Bahram
Posts: 878
Joined: 12/8/2008
Location:Vancouver, BC Canada
Re: Create user programatically
Hi Luke,
 
What format a password must be, I got a meesage "Password is invalid format" on this function.  I want to create user in program:
 
 
   MembershipUser newuser = Membership.CreateUser(UserName, Password, Email, "question", "answer", true, out status);
 
 
Thanks,
Bahram
 
1/6/2010 3:14:13 PM
lukezy
Posts: 2109
Joined: 6/12/2007
Location:WA, US
Re: Create user programatically
Check the settings for AspNetSqlMembershipProvider in your web.config.
DotShoppingCart Staff
1/6/2010 4:27:42 PM
Bahram
Posts: 878
Joined: 12/8/2008
Location:Vancouver, BC Canada
Re: Create user programatically
I did it and fixed before see your reply,
 
Now my Question is :
 
My Membership Method is working and  users are created or checked, and the output status is true  but the second DCS.User.AddUser(....) method fails
 
Now the question is Is it OK  If delete the users in dbo.aspnet_users  and dbo.aspnet_Membership  who are are not in DSC.user. Is there aby other tables that logs these users.
 
What is the parameter value  CoreHelper.GetReferalID() ? what is the default ?
Bahram
1/7/2010 9:58:46 AM
lukezy
Posts: 2109
Joined: 6/12/2007
Location:WA, US
Re: Create user programatically
You probably don't want to mess up with the database directly. Instead use Membership.DeleteUser method.
DotShoppingCart Staff
1/7/2010 10:27:19 AM
Bahram
Posts: 878
Joined: 12/8/2008
Location:Vancouver, BC Canada
Re: Create user programatically
Ok I did it correctly,
 
Now What is the parameter value  CoreHelper.GetReferalID() ? what should be  the default in my code.
 
 
DSC.User.AddUser(newCustomer.UserName, newCustomer.NewsLetter,  CoreHelper.GetReferralId(),  newCustomer.FirstName, ....
 
Bahram