Efficient way to create large number of Membership via Membership.CreateUser? - asp.net

I just create Membership management program, this program can create user one by one and it can import data from text file as well. When I import data from text file, it can create around 30 user before timeout, after I debug it take nearly 1 sec for each CreateUser call.
I want to know, how can I improve performance when I create large number of aspnet user.

Solution1:
Get all data from user table into dataset ds in table "User"
Get all data from member table into table "Member" in the same dataset ds
Create a relationship between the two tables on field userid
Run a loop on each row of table User
For each user call Membership.CreateUser with UserName and Password as parameters
Get all child rows for the current user DataRow.GetChildRows
For each childrow returned, call Roles.AddUserToRole with username and rolename as parameters (add only if the role is active)
Taken from here.
Solution 2:
Download Peter Keller's Membership Editor
Create a SpreadSheet with these columns: UserName,password, and email.
Import this excel file to this database as table: yourUsers$
Create a Winforms application, Add a button to form and paste this code in its click event:
protected void batchInsertButton_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["1ConnectionString"].ConnectionString;
string strSQL = "SELECT * FROM yourUsers$";
SqlConnection myConnection = new SqlConnection(strConn);
myConnection.Open();
SqlCommand myCommand = new SqlCommand(strSQL,myConnection);
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
ObjectDataSourceMembershipUser.InsertParameters["UserName"].DefaultValue = myReader["UserName"].ToString();//TextBoxUserName.Text; ;
ObjectDataSourceMembershipUser.InsertParameters["password"].DefaultValue = myReader["password"].ToString();//TextBoxPassword.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordQuestion"].DefaultValue ="your qestion";//TextBoxPasswordQuestion.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordAnswer"].DefaultValue = "your answer";//TextBoxPasswordAnswer.Text;
ObjectDataSourceMembershipUser.InsertParameters["email"].DefaultValue = myReader["email"].ToString();//TextBoxEmail.Text;
ObjectDataSourceMembershipUser.InsertParameters["isApproved"].DefaultValue = "true";//CheckboxApproval.Checked == true ? "true" : "false";
ObjectDataSourceMembershipUser.Insert();
//hard code this user role
Roles.AddUserToRole(myReader["UserName"].ToString(), "NormalUser");
}
myConnection.Close();
GridViewMemberUser.DataBind();
GridViewRole.DataBind();
}
Taken from here.

Related

Query SQL Server using session variable

I'm trying to query a SQL Server database table based on a user variable (using ASP.NET and C#). I want to be able to pull just the user's unique records from the Waste Application Information table where the Farm Owner name is equal to the variable name (which is a string).
Here's part of my code:
conn.Open();
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = (user variable) ";
SqlCommand com = new SqlCommand(WasteAppData, conn);
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
If I replace the "(user variable)" with the actual value in the table column it does work correctly. Like this: 'Joe Smith' I've tried referencing the variable which is pulled from another webform with no luck... I think my syntax is incorrect? Any help would be great!
You need to do it this way:
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = #FarmOwn";
using (SqlCommand cmdSQL = new SqlCommand(WasteAppData , conn)
{
cmdSQL.Parameters.Add("#FarmOwn", SqlDbType.NVarChar).Value = strFarmOwnwer;
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader;
GridView1.DataBind();
}
In this case "strFarmOwner" would be replaced with your actual variable that holds the value you want.

Problem in insert (UniqueIdentifier) in Table

Greeting,
I created my own database and used this method by Ankush Agnihotri (Create And Install ASP.NET Membership Database)to create users asnd membership and roles in my web application projects. See link below which method I used:
https://www.c-sharpcorner.com/blogs/create-install-asp-net-membership-database
I designed form to admin site to create an employee account in three steps :
First step :create employee account by (Registration tool) to create user account which will store employee account in Users Table.
Second Step: redirect admin to next page to complete an employee form information.
Until this moment a last two steps working correctly.
Third step: an confirmation appears to admin to catch a ROLE ID and USER ID which represented as (UniqueIdentifier) value to store its in USERSINROLE table as figures below:
A last two steps (one and two) working correctly, but a confirmation catch this problem:
My C# code behind to insert a two parameters in table, I tried in many ways from 1 to 5 but no ways to store a UniqueIdentifier value.
protected void Button1_Command(object sender, CommandEventArgs e)
{
using (SqlConnection sqlcon = new SqlConnection(connString))
{
sqlcon.Open();
string query = "INSERT INTO UsersInRoles(UserId,RoleId) VALUES (#UserId,#RoleId)";
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
//Try NO.1
//sqlcmd.Parameters.AddWithValue("#UserId",(FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.AddWithValue("#RoleId", (FormView1.FindControl("L2") as Label).Text);
//Try NO.2
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("l1") as Label).Text;
// sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("L2") as Label).Text;
//Try NO.3
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("L2") as Label).Text);
//Try NO.4
//sqlcmd.Parameters.AddWithValue("#UserId",new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text)));
//sqlcmd.Parameters.AddWithValue("#RoleId", new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text)));
//Try NO.5
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text));
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text));
//Try NO.6
sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier,32).Value =(FormView1.FindControl("l1") as Label).Text;
sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier, 32).Value = ((FormView1.FindControl("L2") as Label).Text);
sqlcmd.ExecuteNonQuery();
FormView1.DataBind();
sqlcmd.Connection.Close();
}
So anyone able to help me. Thanks

User details stored in separate table ASP.NET Identity

I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...

How to insert data in multiple tables at a time?

I have following tables in my MS Access database.
Personal, Partner, ContactDetails, NativeAddress bla bla bal. I created a Wizard in Visual Studio 2012 for above tables. A screenshot is given below. Now I want to submit all data at once in all tables when user presses the submit button. So what syntax should I use now. Please guide.
My code is something like this. Its incomplete and just beginning of my script. So please don't get me wrong.
protected void dataWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\micronets\jobwork-2013\arunthathiyar-sangham\arunthathiyar-web-application\App_Data\arunthathiyar-db.accdb";
string personalDetails = "INSERT INTO PersonalDetails(FirstName, MiddleName, LastName, Sex, Age, DateOfBirth, PlaceOfBirth, EducationalQualification, EmploymentStatus, Profession, PhysicalStatus, BloodGroup) VALUES (#fnPD, #mmPD, #lnPD, #sexPD, #agePD, #dobPD, #pobPD, #eqPD, #esPD, #profPD, #phyicPD, #bgPD)";
string familyDetails = "INSERT INTO FamilyDetails(Relationship, FullName, Status, BloodGroup, EducationalQualification, Profession, EmploymentStatus) VALUES(#relFD, #fnFD, #statusFD, #bgFD, #eqFD, #profFD, #esFD)";
string contactDetails = "INSERT INTO ContactDetails(FlatBuildingStreet, Landmark, Area, City, Pincode, State, Country, Mobile, Telephone, Email) VALUES(#fbsCD, #landCD, #areaCD, #cityCD, #pinCD, #stateCD, #countryCD, #mobCD, #telCD, #emailCD)";
try
{
con.Open();
txtMemAmountReceived.Text = txtPDFirstName.Text;
}
catch
{
txtMemAmountReceived.Text = "Sorry";
}
You're heading in the right direction. Here's what you need to do next:
Create an OleDbCommand object
You have a connection, now you need to create and Command object that can store the SQL text and execute commands against the database. Something like this:
OleDbCommand cmd = new OleDbCommand(personalDetails, con);
Open, execute, close
Then, inside your try block, you want to open the connection, execute the query, and close the connection:
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Rinse and repeat
You can take it from there as far as executing all three queries. You just need to update the cmd.CommandText property with the text for the other queries you want to execute, and call ExecuteNonQuery again.
you could possibly concatenate all of your query strings into one separated by semicolons(;) So the one large string would be sent to the server and each query would be processed and you would then only have to make one connection to the database.
string myQuery = personalDetails+ "; " + familyDetails + "; " + contactDetails
However i would just make 3 separate connections just so it will be easier to manage all of your parameters. If you ever have to go back and change the query or a parameter it will be a mess.

SQLite DataAdapter no update or insert

I use Sqlite v1.0.79 and vs2010 to create a simple winform application.
I have a customer table, and want to use the SQLiteDataAdapter to easily insert, update and delete records. So i do not need to type the whole insert, update and delete statements.
So i have a Customer class with a static load function that returns a dataset.
private static SQLiteDataAdapter _Adapter;
internal static DataSet Load(long id)
{
var q = "SELECT * FROM Customer WHERE id = {0}".FormatInvariant(id);
var cmd = new SQLiteCommand();
cmd.Connection = [_Connection];
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 10;
cmd.CommandText = commandText;
return cmd; _Adapter = new SQLiteDataAdapter();
_Adapter.SelectCommand = cmd;
var ds = new DataSet();
_Adapter.Fill(ds, "Customer");
if (id == 0)
{
ds.AddRow(ds.NewRow());
}
var b = new SQLiteCommandBuilder(_Adapter);
_Adapter.AcceptChangesDuringUpdate = true;
_Adapter.InsertCommand = b.GetInsertCommand();
_Adapter.UpdateCommand = b.GetUpdateCommand();
_Adapter.DeleteCommand = b.GetDeleteCommand();
// Commented out code for note A:
////ds.SetRowValue("lastname", "blaat44");
////_Adapter.Update(ds, "Customer");
return ds;
}
After calling the Load method, the DataSet is used in bindings on a windows form. And after some changes, the Save method is called, where the changes supposed to be saved.
internal static void Save(DataSet data)
{
//// data.AcceptChanges();
_Adapter.Update(data, "Customer");
}
But after the update, the database is not updating anything. What am i missing? I already tried the data.AcceptChanges before the update, but nothing works.
btw. the dataset in the save methods does have the 'right' values, but the update or insert is not working....
The strange thing is if i change a field in the dataset in the Load method (the commented out code at Note A in the example above), the data is saved correctly.
Im not an expert and have a basic understanding of sqlite etc but could the problem be that you are passing the dataset to the save function so the adapter is using a copy maybe of the original dataset. Which is why it works in the load method as the adapter is acessing tje original dataset?
Again this maybe complete babble and i may not understand but ive found sometimes the uneducated answer is a very good push in the right direction

Resources