Edit Update Delete in membership - asp.net

I am creating page for admin to view all user in the system database. I’m using gird view to retrieve all the users in membership table. The problem now is how can Admin edit, delete and update the changes made by the admin? When we want to configure the select statement, there's advance button which we can put some additional statements. The membership table in my SQL doesn’t have a primary key. How do I solve this? Much thanks.

Have a look at this tutorial, it does exactly what you ask http://www.codeproject.com/Articles/24085/Insert-Update-Delete-with-Gridview-simple-way

That tutorial that Ashwin suggested looks way too involved for me. The direction I would take...
Store the username field in the datakey property of the gridview. And use the RowDeleting and RowUpdating events of the grid view...
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
e.Cancel = true; // cancel default action.
// delete user myself.
string user = e.Keys["username"].ToString(); // think that's the name of the field in database.
Membership.DeleteUser(user);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true; // cancel default action.
// update user myself.
var userToUpdate = new MembershipUser();
// get new values with e.NewValues[] and fill out all properties of userToUpdate.
Membership.UpdateUser(userToUpdate);
}
Calling methods from the membership object seems much easier in my opinion, and then you don't have to mess with the tables that asp.net generates which could mess something up if done incorrectly.

Related

Linq data not updating form after postback

In my application, I have a form that users fill out, then gets approved by a manager. I have various types of forms that all use the same process, so the approval buttons are all done via a user control (which includes the functionality to update the data in the database and call the postback).
However, once I click on the "Approve" button (which is in the user control), the form information doesn't update (it still says "unapproved"). A postback is definitely happening, but not sure why the page isn't updating properly.
I can confirm that the change are being made - when I manually reload the page, it gets updated - but not on the post back.
What am I missing here?
My page:
protected void Page_Load(object sender, EventArgs e)
{
int ID;
// ensure that there's an ID set in the query string
if (Int32.TryParse(Request.QueryString["ID"], out ID))
PopulatePage(ID);
else
Response.Redirect("~/Default.aspx");
}
}
protected void PopulatePage(int ID)
{
using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
{
lblStatus.Text = wo.Workorder.status;
....
}
}
I think that the Page_Load happens before the code in the submit button. To check this just use a couple of breakpoints. So the page loads the old data since the new data are not saved yet.
You should call a method to load the data inside the OnClick method of the Approve button.
After you've submitted the changes to the database, try running db.Refresh(RefreshMode.OverwriteCurrentValues) to force the changes to be reloaded into the data context.

ASP.NET - Can you make a DetailsView where only users with specific roles see some fields as editable?

For example lets say I want only admins to be able to see and edit CustomerID in details view, moderators can see this value but it is not editable, and regular users cannot even see it. Is this possible?
Here you go. I tried many google searches and no one could clearly explain it. You have to perform this on the PreRender Event. Please not that this code snippet uses the Membership Provider in .net to check if a user is in a role. If you have your own custom tables you will have to write a custom function that checks if a user is in one of your custom roles. Also please not that this solution is using ItemTemplates not BoundFields.
protected void detailsView_OnPreRender(object sender, EventArgs e)
{
if (dvPackage.CurrentMode == DetailsViewMode.Edit)
{
//disables/enables a the dropdown for Process Status if the user has the RLIST role
TextBox txtCustomID = (TextBox)Utilities.FindControlRecursive(dvPackage, "txtCustomID ");
txtCustomID.Visible = false;
if (User.IsInRole("Admin"))
{
txtCustomID.Visible = true;
}
}
Here's the find control recursive funciton. Free of charge.
public static Control FindControlRecursive(Control ctlRoot, string sControlId)
{
// if this control is the one we are looking for, break from the recursion
// and return the control.
if (ctlRoot.ID == sControlId)
{
return ctlRoot;
}
// loop the child controls of this parent control and call recursively.
foreach (Control ctl in ctlRoot.Controls)
{
Control ctlFound = FindControlRecursive(ctl, sControlId);
// if we found the control, return it.
if (ctlFound != null)
{
return ctlFound;
}
}// we never found the control so just return null.
return null;
}
I would recommend either web user controls or the multi-view to handle switching views based on the user's role.

Checking for rights

I am building an application in asp.net using C# where people have their own profiles, and if they want to see others profile they can, but they only have read permission; how to set all these read write permissions in Ms Sql?
here is one way you can hide/show the controls based the user id on asp.net side.
Then there is no need to actually do the work on DB level since user does not have any ability to do that via UI.
pseudo code:
public void Page_Load(object sender,Eventargs e)
if(!Page.IsPostBack){
string userid= //get the id of the user whose profile you want to see
string loggeduserid=//get the id of the logged in user
bool visible = userid==loggeduserid
ShowHideControls(visible)
}
}
private void(bool visible){
btnEdit.Visible=visible;
btnDelete.Visible = visible;
//set other controls' visibility.
}
This is one way. You can refine the code above as per the need.
I will suggest you do it on your code level itself instead of DB because essentially you will be doing the same check if it were in a storedproc.

GridView_RowCommand event fired again on page refresh

I have implement GridView Row Editing feature in my .net application using <asp:CommandField.
I clicked on Update button to save the record after editing the row.Now if i refresh the page or press F5 GridView_RowCommand fired again.
How can we avoid this.Is there any mechanism to identify when user press F5 OR refresh the page.Is there any method in client side or in server side.
Not exactly the best "technical" solution to your problem but you could always just do a Response.Redirect(Request.RawUrl) once you have finished doing anything you need to do in your RowCommand
Like I said, it's not the best "technical" solution but it is a solution
Dave
One method of capturing this is to maintain a session variable that is related to the page in question. In the session variable you would keep some kind of state enumeration, key or string that would determine the last action taken. You could even use a simple incremented counter, and if you ever received a postedback counter that was equal to the session variable it would indicate a page refresh rather than a new action.
Session["LastInsertedItem"] = null;
MyCustomObjType myCustomObject;
protected void Page_Load(object sender, EventArgs e)
{
myCustomObject = Session["LastInsertedItem"] as MyCustomObjType;
}
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
If(myCustomObject == null || //!(compare your value with myCustomObject.field) )
{
// do your operations and save the values to myCustomObject and save that object back to Session.
}
else
{
// It is refreshed or same data is being insterted - don't know if second option is possible in your case.
}
}

Asp.Net GridView EditIndex race condition?

This is a bit of a hypothetical question that has sent me off down the garden path... Say I have a gridview that I'd like to edit... given a method that binds the data..
private void BindGridFirst() {
var data = new List<string>() {
"A","B","C","D","E","F"
};
gridView.DataSource = data;
gridView.DataBind();
}
Now presume that I'm looking at this page, and another user has come along and made some changes to the underlying data, and I now go and click the edit button to edit D...
The edit method is pretty straight forward:
protected void RowEdit(object sender, GridViewEditEventArgs e) {
gridView.EditIndex = e.NewEditIndex;
BindGridSecond();
}
Edit: I feel compelled to point out, that this method is used in pretty much all the online examples, including ones from Microsoft.
This BindGridSecond() method looks like so:
private void BindGridSecond() {
var data = new List<string>() {
"A", "AA", "B","C","D","E","F"
};
gridView.DataSource = data;
gridView.DataBind();
}
It's exactly the same, but the data is now changed. Once the UI updates, the user is now in edit mode against row C.
Not what the user expected or wanted. How should this scenario be handled to avoid such an issue?
Personally, I use the DataKeyNames property and the SelectedDataKey on the GridView, so that I can easily obtain the primary key of the row the user wants, rather than relying on the index of the grid.
By using the primary key, you don't have any issues with new items being added to the collection, such as in your example. Plus, using the primary key makes it easier to deal with paging on the grid, as you don't have to take the page number and index into account.
Imho there are two options:
You could cache the Data you want to bind to the Grid in a Session for example. So you are able to check for changes before you call the BindGridSecond-Method and alert the user if any changes have been made while he was browsing the Page.
In option 2 you would again cache the Data you were binding in the BindGridFirst-Method and just work with this data for the next PostBack actions. So you don't have to worry about changes that may occur while browsing the Grid.

Resources