Load User control with Query string - asp.net

My requirement is like i need to load a n number of user controls using asp Repeater.
List<string> userControlList = new List<string>();
userControlList.Add("~/WebUserControl2.ascx");
userControlList.Add("~/WebUserControl.ascx");
Repeater1.DataSource = userControlList;
Repeater1.DataBind();
And in the ItemDataBound, I am loading the user control using Page.LoadControl.
string userControlLink = e.Item.DataItem.ToString();
e.Item.FindControl("ItemPanel").Controls.Add(Page.LoadControl(userControlLink));
Here, I need to send parameters to some user control by which the control will be loaded.
I am not able to use properties because i can't type cast it at run time.
Is there any other way by which i can send some parameters to user control?
I tried with query string, but it resulted in run time exception.

Related

How to pass the asp.Identity object to a second register page

I am building a much more advanced registration process which consists of 3 pages, the first page is a form that grabs a username(email form) and a password with confirmation. The button click on this page creates the user in an unverified state in the db and redirects to the page where the profile is created. Once the create profile button is clicked and the profile is created in the db the redirect takes you to the Credit Card info page where the form is filled out, the credit card is verified and then that info is written to a table in the database.
I have disabled the loggedin user display in the header so that I can use the registrants First and Last name which arent entered until the Credit Card page. Since the identityUser is required for the sign on and thus to populate the loggedin user control, how can I pass this object from page to page?
Code where original template was logging in the user: (Note:I commented out the sign in code)
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim manager = New UserManager()
Dim newuser = New IdentityUser() With {.UserName = userName}
manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False}
Dim result = manager.Create(newuser, Password.Text)
If result.Succeeded Then
Session("email") = newuser.UserName
Session("userid") = newuser.Id.ToString()
'uncomment the code below if you want the auto sign in to occur
'IdentityHelper.SignIn(manager, newuser, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Page.ResolveUrl("~/Account/CreateProfile.aspx?Guid=" & newuser.Id.ToString()), Response)
Else
ErrorMessage.Text = Encoder.HtmlEncode(result.Errors.FirstOrDefault())
End If
End Sub
I now call this routine to sign in the user once the third page of the registration process is completed. (Session("userid") is the new registrants generated userid)
Private Sub SignInUserOnFormCompletion()
Dim manager = New UserManager()
manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False}
Dim newuser = New IdentityUser() With {.Id = Session("userid").ToString()}
IdentityHelper.SignIn(manager, newuser, isPersistent:=False)
End Sub
The problem is the above doesnt work as the newuser somehow has different credentials. How can I pass the original newuser from the first page to the third page where I can use it in the SignInUserOnFormCompletion subroutine? Do I create a cookie and pass it around that way?
This is a new topic for me so I'm not familiar with the proper methods to accomplish this.
If you use multiple pages arranged as a wizard, then you will need to pass data between the pages.
However, if you use a single page with a MultiView or Wizard control, then you won't need to do that. Just arrange your current pages as separate views within the MultiView, and use Session state to retain data across the post backs.

autofill textbox based on user input

I'm extremely new to ASP.NET and came across a problem I have yet to figure out. On my Default.aspx page, I have a place where users can signup. This just takes to fields - Email and Password. When the submit button is clicked, they are taking to Signup.aspx, which shows a bigger signup form with fields for username, email, password, confirm password, etc. I would like to auto fill my email and password textboxes with those of the Default.aspx page that the user has entered. Is this possible? I'm using Microsoft Visual Web Developer 2010 Express.
There are multiple ways to do that.
One way is to use querystring to navigate to like :
http://example.com/Signup.aspx?email=value1&password=value2
and get value on Signup.aspx Page_Load event like :
String email = Request.QueryString["email"];
String password = Request.QueryString["password"];
and assign to your text box controls like:
txtEmail.text =email;
txtPassword=password;
But posting password as clear text in query string is not good practice.
Other way is to get HTTP POST information from the source page:
In the source page, include a form element that contains HTML elements (such as input or textarea) or ASP.NET server controls (such as TextBox or DropDownList controls) that post values when the form is submitted.
In the target page, read the Form collection, which returns a dictionary of name/value pairs, one pair for each posted value. e.g.
//
void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder displayValues =
new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection
postedValues = Request.Form;
String nextKey;
for(int i = 0; i < postedValues.AllKeys.Length; i++)
{
nextKey = postedValues.AllKeys[i];
if(nextKey.Substring(0, 2) != "__")
{
displayValues.Append("<br>");
displayValues.Append(nextKey);
displayValues.Append(" = ");
displayValues.Append(postedValues[i]);
}
}
Label1.Text = displayValues.ToString();
}
Best & easiest I think is to use Session:
on Submitbutton_click event of Default.aspx, save values to Session like:
Session["Email"] = txtEmail.text;
Session["Password"]=txtPassword.text;
and retrieve values on Signup.aspx Page_load event like:
string email = (string)(Session["Email"]);
string password = (string)(Session["Password"]);
& assign to your control/textbox like:
txtEmail.text =email;
txtPassword=password;
There are more ways too to retrieve value from previous page like PreviousPage.FindControl("txtEmail") but I never like them.

How do I populate multiple textboxes based on value of another textbox or dropdownlist?

hello again.
We have a webform that employees use to make request for such things as VPN access to the company resources from remote locations.
I am populating a dropdownlist box from Active Directory. This works fine.
Then I have a textbox that is also populated from Active Directory by simply assigning the value of the logged in user as shown:
textbox1.Text = User.Identity.Name
Based on the value of my name assigned to textbox1.Text
The rest of the texboxes are populated with my work information with the following code:
textbox1.Text = User.Identity.Name
textbox1.Text = StrConv(textbox1.Text, vbProperCase)
txtdate.Text = DateTime.Now.ToString("MM/dd/yyyy")
Try
'Creates a Directory Entry Instance with the Username and Password provided
Dim deSystem As New DirectoryEntry("LDAP://OU=Departments,DC=domaname, DC=com", "usrname", "password")
'Authenticacion type Secure
deSystem.AuthenticationType = AuthenticationTypes.Secure
'Creates a Directory Searcher Instance
Dim dsSystem As New DirectorySearcher(deSystem)
'sAMAccountName is equal to our username passed in.
dsSystem.Filter = "sAMAccountName=" & textbox1.Text
'Properties that the Procedures will load from Active Directory
dsSystem.PropertiesToLoad.Add("mail") 'email address
dsSystem.PropertiesToLoad.Add("department") 'dept
dsSystem.PropertiesToLoad.Add("physicalDeliveryOfficeName") 'office
dsSystem.PropertiesToLoad.Add("title") 'title, eg programmer1
dsSystem.PropertiesToLoad.Add("telephoneNumber") 'phone
dsSystem.PropertiesToLoad.Add("streetAddress") 'street address
dsSystem.PropertiesToLoad.Add("l") 'city
dsSystem.PropertiesToLoad.Add("st") 'state
dsSystem.PropertiesToLoad.Add("postalCode") 'zip code
dsSystem.PropertiesToLoad.Add("EmployeeId") 'empid
dsSystem.PropertiesToLoad.Add("givenName") '//first name from active directory
dsSystem.PropertiesToLoad.Add("sn") '//lastname from active directory
'Find the user data
Dim srSystem As SearchResult = dsSystem.FindOne()
'Obtains the properties recently loaded
txtemail.Text = srSystem.Properties("mail").Item(0).ToString
dept.Text = srSystem.Properties("department").Item(0).ToString
office.Text = srSystem.Properties("physicalDeliveryOfficeName").Item(0).ToString
txttitle.Text = srSystem.Properties("title").Item(0).ToString
phone.Text = srSystem.Properties("telephoneNumber").Item(0).ToString
workaddress.Text = srSystem.Properties("streetAddress").Item(0).ToString
city.Text = srSystem.Properties("l").Item(0).ToString
state.Text = srSystem.Properties("st").Item(0).ToString
zipcode.Text = srSystem.Properties("postalCode").Item(0).ToString
hiddenempId.Value = srSystem.Properties("EmployeeId").Item(0).ToString
HiddenFName.Value = srSystem.Properties("givenName").Item(0).ToString
HiddenLName.Value = srSystem.Properties("sn").Item(0).ToString
This works fine as well.
Here is where my problem lies.
Initially, when the user logs in, based on logged user name from Active Directory, the rest of the textboxes get populated with the user's info.Sorry for repeating myself here.
However, sometimes, the user logged in is not necessarily the user needing reguest.
In other words, I can log in to fill a request for another employee.
In this case, I am required to select the name of the user I am completing the request for from the dropdownlist that is populated from Active Directory.
When I select this name from dropdownlist, it replaces my own name on textbox1.Text.
This works fine but the rest of the textboxes retain my own information.
What do I need to do to ensure that the name that replaces my original name on textbox1.Text also replaces the information on the rest of the textboxes?
I will post additional information as requested.
Many thanks in advance
Instead of loading all the text boxes when the form loads, load them from the TextChanged event of the user name text box. That way, any time the user name text box changes, all the other text boxes will automatically be re-loaded to reflect the change.

What is happening when ASP.NET MVC 3 Accounts Scaffolding calls Membership.Createuser?

I am an asp mvc 3 noob trying to modify the user account scaffolding to hold more information. When users create an account, I want to add additional information like their full name and start date--not just their username/pw. I am going to store this added info in an Employees table in the DB.
I see the line of code in the AccountController that creates the account after the user types in input to the form.
Membership.CreateUser(model.UserName, model.Password, model.Email, Nothing, Nothing, True, Nothing, createStatus)
It seems like this line calls a stored procedure in SQL server. It seems like the most likely stored procedure is aspnet_Membership_CreateUser. But this stored proc has 13 parameters, and the code above passes 8 parameters.
What stored procedure is called by the VB code shown above (membership.createuser...)?
Why don't aspnet_Membership_CreateUser and Membership.CreateUser have the same number of parameters?
How do I modify the create user code/stored procedure to add employee information into the EmployeeTable based on info from the registration form, and then add a link between the user account and the Employee record? In general, the idea would be to add the employee info as additional parameters to the stored proc and then have the stored proc do the inserts/add the ids, but where exactly do I look to do this?
The code will run the aspnet_Membership_CreateUser stored procedure
The Membership.CreateUser is overloaded, and will put default values for parameters that would not have been provided. For example, if you call CreateUser with just the username and password, all the other parameters will be defaulted, e.g. IsApproved will be true. >>When typing in CreateUser, you should see the overload options. You can look at the code in "C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.web.dll" using a tool like Just Decompile
There are different ways of storing additional data. Look at this one. I prefer linking the tables by UserId/Email address, and when creating a user, I call the CreateUser, and if its successful, then save the additional data (which is a slight variation of the method described in that tutorial). You can also modify/extend the whole membership provider, see this link (Implementing a Membership Provider) or this video tutorial
I can't answer your other questions, but here is the code I use the extend the user registration to contain more date (using a profile table, not the profile provider):
'
' POST: /Account/Register
<HttpPost()> _
Public Function Register(ByVal model As RegisterModel) As ActionResult
If ModelState.IsValid Then
' Attempt to register the user
Dim createStatus As MembershipCreateStatus
Dim MembershipUser = Membership.CreateUser(model.UserName, model.Password, model.Email, Nothing, Nothing, True, Nothing, createStatus)
If createStatus = MembershipCreateStatus.Success Then
Dim providerKeyObject = MembershipUser.ProviderUserKey
Dim providerKeyGuid = MembershipUser.ProviderUserKey
' update profile entity
Dim db As UserProfileDbContext = New UserProfileDbContext
Dim profile As New UserProfile
profile.UserId = providerKeyGuid
profile.IsCompanyOwner = True
profile.CompanyId = model.Company
profile.BlogId = model.Blog
profile.IsCompanyOwner = model.IsCompanyOwner
profile.IsBlogOwner = model.IsBlogOwner
db.UserProfiles.Add(profile)
db.SaveChanges()
FormsAuthentication.SetAuthCookie(model.UserName, False)
' send email
' TODO: fix error on send
Call New EmailController().VerificationEmail(model).Deliver()
Return RedirectToAction("Index", "Home")
Else
ModelState.AddModelError("", ErrorCodeToString(createStatus))
End If
End If
' If we got this far, something failed, redisplay form
Return View(model)
End Function

ASP GridView All Rows In Edit Mode

In my ASP.NET page, I'm using a GridView to view data (Items & their prices). Currently users can edit the data (prices) in the grid row by row. (Click --> "Edit" link, change the values then "Update"). This is ROW by ROW. Is it possible to open all rows in Edit mode & use a single button (eg. Submit) to update all data once?
If you don't need to read only mode, in that case you can put input boxes ( textbox, dropdownlist, etc.) in ItemTEmplate section and bind them with existing data.
Next, put a submit button at above/below of the GridView and handle button Click event and loop through the GridView item data and save all database.
I'll post code block if you need. Thanks for your time.
And you will have better control on that you doing by using listview instead of gridview.
My best practise is using listview and custom web user control for this kind of problems.
If you fill your listview with your user control, you will easy to manage your saving method, just have to iterate on the listview items, find control and call your Save() method for each item.
I know that this question has already been answered but here is the code for loop through the GridView getting data and store it in the Data Base:
Using libraries:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Odbc;
Code Behind:
// this is a variable that have the Query or SQL Commands.
string DataBaseQuery = "UPDATE [table] SET [variable2] = #variable2, [variable3] = #variable3) WHERE [variable1] = #variable1";
//Click Event from a LinkButton.
protected void LinkButton1_Click(object sender, EventArgs e)
{
//"ConnectionString" its the string connection for your DataBase (often get from the WebConfig File or a DataSource element.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//this is for open the database using the string connection.
connection.Open();
//this is the algorithm for going through the entire GridView.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//"DataBaseQuery" it's a string variable that have the Query or SQL Commands.
SqlCommand cmd = new SqlCommand(DataBaseQuery, conexion);
//this case it's for obtain the text variable of the first column of the gridview (in my case it was the ID of the register).
cmd.Parameters.AddWithValue("#variable1", ((Label)GridView1.Rows[i].Cells[0].FindControl("Label1")).Text.ToString());
//this case it's for obtain the selected value of a DropDownList that were in the 14 th column)
cmd.Parameters.AddWithValue("#variable2", ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("DropDownlist2")).SelectedValue.ToString());
//this command it's for obtain the text of a textbox that is in the 15 th column of the gridview.
cmd.Parameters.AddWithValue("#variable3", ((TextBox)GridView1.Rows[i].Cells[16].FindControl("TextBox17")).Text.ToString());
cmd.ExecuteNonQuery();
}
//after going through all the gridview you have to close the connection to the DataBase.
connection.Close();
}
}
Of course you have to adjust the code to your particular case but it's very easy. In this code you have the example to obtain values for other object like labes, textbox and dropdownlist in the gridview.
I suffered a lot to make run this code (I'm not good programming) but I'm happy to help.
NOTE: For count the columns of the gridview you have to start at zero.
NOTE2: Sorry for my bad English by the way... It's not my nature language.

Resources