AspNetUsers cannot update custom column - asp.net

So I have the problem with .net identity model. I created boolean variable IsEnabled in my ApplicationUserManager, trying to make a "block account" method. So it's working fine, anybody with IsEnabled=false cannot login in to my site. The problem is while Im trying to implement administartion method for this variable (Block_Account() for example) I cannot persist my changes in a user. Here is a code;
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var user = Context.GetOwinContext().Get<ApplicationDbContext>().Users.Where(a => a.Email == itemID).FirstOrDefault();
//Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
And another try
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindByEmail(itemID);
Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
manager.Update(user);
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
Both not working actually.
So I got the right value from GridView and find a User with a right email, but after making changes, they wont appear in my database.

Related

How I can search a field in sql

I have a login page with username and password fields. I want to search an inputted username in my table called 'mytable' and, if this table have such a username, display his data in grid view.
take me linq answer
protected void Button1_Click(object sender, EventArgs e)
{
CostumerDataContext costum = new CostumerDataContext();
LOGIN2 item = new LOGIN2();
var islogin = (from u in costum.LOGIN2s
where u.Username == txtUser.Text
&& u.Passwrod == txtPass.Text select u).ToList();
if (islogin.Count>0)
{
Dgw.Visible = true;
Dgw.DataSource = from u in costum.LOGIN2s select u;
}
else
{
Label3.Visible=true;
}
}
You are selecting data from database on basis of username and password but you are assigning the gridview data of whole table.
You need to bind gridview with filtered data.
var islogin = (from u in costum.LOGIN2s
where u.Username == txtUser.Text.Trim()
&& u.Passwrod == txtPass.Text.Trim() select u).ToList();
if (islogin.Count>0)
{
Dgw.Visible = true;
Dgw.DataSource = islogin;
Dgw.DataBind();
}
else
{
Label3.Visible=true;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (CostumerDataContext costum = new CostumerDataContext ())
{
LOGIN2 item;
item = (from u in costum.LOGIN2s
where u.Username == txtUser.Text
&& u.Passwrod == txtPass.Text select u).FirstOrDefault();
if (item != null)
{
Dgw.Visible = true;
Dgw.DataSource = item;
}
else
{
Label3.Visible=true;
}
}
}

NullReference when user is not logged in

I can't access a page when is no one logged in. I want to show some buttons when userID match and just show the page with FillPage() if no one is logged.
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
if (!String.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
int id = Convert.ToInt32(Request.QueryString["id"]);
JobReqModel model = new JobReqModel();
JobDescriptions job = model.GetJob(id);
if (job.PostedBy == Membership.GetUser().ProviderUserKey.ToString())
{
Button2.Visible = true;
Button3.Visible = true;
Button4.Visible = true;
Lineseparator.Visible = true;
}
else
{
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Lineseparator.Visible = false;
}
}
I get NullReference on this line
if (job.PostedBy == Membership.GetUser().ProviderUserKey.ToString())
I understand why is NULL but how I avoid this expcetion? I tried to test if ProviderUserKey is null and just use Fillpage after that.
Just add a null check.
Caus if GetUser() returns null, you have an NRE when trying to access its ProviderUserKey property.
if (MemberShip.GetUser() != null && Membership.GetUser().ProviderUSerKey.ToString() == josb.PostedBy)

UserAccounts_RowEditing/Updating is not working properly

Alright, so I have a Gridview and added RowEditing and RowUpdating to it, but it won't really edit something.. This is my code for both:
protected void UserAccounts_RowEditing(object sender, GridViewEditEventArgs e)
{
UserAccounts.EditIndex = e.NewEditIndex;
BindUserAccounts();
}
protected void UserAccounts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = UserAccounts.EditIndex;
GridViewRow row = UserAccounts.Rows[e.RowIndex];
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
email = ((TextBox)row.Cells[2].Controls[0]).Text;
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
user.Email = email;
Membership.UpdateUser(user);
ActionStatus.Text = string.Format("User {0} details have been successfully updated!", username);
}
UserAccounts.EditIndex = -1;
BindUserAccounts();
}
What am I doing wrong in here?
EDIT: This is my BindUserAccounts:
private void BindUserAccounts()
{
int totalRecords;
UserAccounts.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
UserAccounts.DataBind();
bool visitingFirstPage = (this.PageIndex == 0);
lnkFirst.Enabled = !visitingFirstPage;
lnkPrev.Enabled = !visitingFirstPage;
int lastPageIndex = (totalRecords - 1) / this.PageSize;
bool visitingLastPage = (this.PageIndex >= lastPageIndex);
lnkNext.Enabled = !visitingLastPage;
lnkLast.Enabled = !visitingLastPage;
}
i think the should be like this
protected void update_click_foredu(object sender, GridViewUpdateEventArgs e)
{
Label edui = (Label)edugrid.Rows[e.RowIndex].FindControl("label");
TextBox unitxt = (TextBox)edugrid.Rows[e.RowIndex].FindControl("txtuni");
if (unitxt != null && costxt != null && startdatetxt != null && enddatetxt != null)
{
using (Entities1 context = new Entities1())
{
string eduID = edui.Text;
model obj = context.entitytabel.First(x => x.ID == eduID);
obj.Univ_Name = unitxt.Text;
context.SaveChanges();
lblMessage.Text = "Saved successfully.";
edugrid.EditIndex = -1;
bindgrid();
}
}
}
here im using EF like this you can find the control of the text box and save it in gridview
hope this helps you
Somehow it works now after editing the GridView and set "UserName", "IsApproved", "IsLockedOut" and "IsOnline" to ReadOnly="true"

Is this the best/correct way to use the DevExpress ASPxGridView to edit a List<T>?

Would someone who knows DeveExpess ASPxGridView take a look at this.
Is this the best/correct way to use the grid to edit a List?
I have an object of Type ItemModel and the code below is used to allow an ASP.NET Web Site user to do CRUD operations on list of ItemModels.
My problem is that it seems too complex and I suspect I am not taking good advantage of the Grid.
For simplicity, I have left the Database Access Code that will load and save the list of ItemModels.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
BindGrid();
}
protected void OnRowInserting(object sender, ASPxDataInsertingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = 0;
if (itemModels .Count > 0)
{
lineID = itemModels[itemModels.Count - 1].LineID + 1;
}
ItemModel itemModel = new ItemModel()
{
, Code = e.NewValues["Code"] == null ? string.Empty : e.NewValues["Code"].ToString()
, Name = e.NewValues["Name"] == null ? string.Empty : e.NewValues["Name"].ToString()
, DateCreated = DateTime.Now
, DateUpdated = DateTime.Now
};
itemModels.Add(itemModel);
CachedModels = itemModels;
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
protected void OnRowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = Convert.ToInt32(e.Keys[0].ToString());
ItemModel itemModel = null;
foreach (ItemModel model in itemModels)
{
if (model.LineID == lineID)
{
itemModel = model;
break;
}
}
if (itemModel != null)
{
itemModel.Code = e.NewValues["Code"] == null ? string.Empty : e.NewValues["Code"].ToString();
itemModel.Name = e.NewValues["Name"] == null ? string.Empty : e.NewValues["Name"].ToString();
containerItemModel.DateUpdated = DateTime.Now;
itemModels[lineID] = itemModel;
CachedModels = itemModels;
}
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
protected void OnRowDeleting(object sender, ASPxDataDeletingEventArgs e)
{
IList<ItemModel> itemModels = CachedModels;
int lineID = Convert.ToInt32(e.Keys[0].ToString());
ItemModel itemModel = null;
foreach (ItemModel model in itemModels)
{
if (model.LineID == lineID)
{
itemModel = model;
break;
}
}
if (itemModel != null)
{
itemModels.Remove(itemModel);
CachedModels = itemModels;
}
ASPxGridView aspxGridView = (ASPxGridView)sender;
aspxGridView.CancelEdit();
e.Cancel = true;
BindGrid();
}
private void BindGrid()
{
grdItems.DataSource = CachedModels;
grdItems.DataBind();
}
private IList<ItemModel> CachedModels
{
get
{
List<ItemModel> models= (List<ItemModel>)Session["ItemModels"];
if (models == null)
{
models= new List<ItemModel>();
Session["ItemModels"] = models;
}
return models;
}
set
{
Session["ItemModels"] = value;
}
}
I believe your current code is quite correct.
Here is the suggested way from DX:
ASPxGridView - How to implement CRUD operations with a custom data source

Saving State Dynamic UserControls...Help!

I have page with a LinkButton on it that when clicked, I'd like to add a Usercontrol to the page. I need to be able to add/remove as many controls as the user would like. The Usercontrol consists of three dropdownlists. The first dropdownlist has it's auotpostback property set to true and hooks up the OnSelectedIndexChanged event that when fired will load the remaining two dropdownlists with the appropriate values.
My problem is that no matter where I put the code in the host page, the usercontrol is not being loaded properly. I know I have to recreate the usercontrols on every postback and I've created a method that is being executed in the hosting pages OnPreInit method. I'm still getting the following error:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
Here is my code:
Thank you!!!!
bool createAgain = false;
IList<FilterOptionsCollectionView> OptionControls
{
get
{
if (SessionManager.Current["controls"] != null)
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
else
SessionManager.Current["controls"] = new List<FilterOptionsCollectionView>();
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
}
set
{
SessionManager.Current["controls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Master.Page.Title = Title;
LoadViewControls(Master.MainContent, Master.SideBar, Master.ToolBarContainer);
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if ((control != null && control.ClientID ==
(lbAddAndCondtion.ClientID) || createAgain))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
protected void AddAndConditionClicked(object o, EventArgs e)
{
var control = LoadControl("~/Views/FilterOptionsCollectionView.ascx");
OptionControls.Add((FilterOptionsCollectionView)control);
control.ID = "options" + OptionControls.Count.ToString();
phConditions.Controls.Add(control);
}
public event EventHandler<Insight.Presenters.PageViewArg> OnLoadData;
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
phConditions.Controls.Add(c);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Here is the usercontrol's code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FilterOptionsCollectionView.ascx.cs" Inherits="Insight.Website.Views.FilterOptionsCollectionView" %>
namespace Insight.Website.Views
{
[ViewStateModeById]
public partial class FilterOptionsCollectionView : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
LoadColumns();
ddlColumns.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ColumnsSelectedIndexChanged);
base.OnInit(e);
}
protected void ColumnsSelectedIndexChanged(object o, EventArgs e)
{
LoadCriteria();
}
public void LoadColumns()
{
ddlColumns.DataSource = User.GetItemSearchProperties();
ddlColumns.DataTextField = "SearchColumn";
ddlColumns.DataValueField = "CriteriaSearchControlType";
ddlColumns.DataBind();
LoadCriteria();
}
private void LoadCriteria()
{
var controlType = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].CriteriaSearchControlType;
var ops = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].ValidOperators;
ddlOperators.DataSource = ops;
ddlOperators.DataTextField = "key";
ddlOperators.DataValueField = "value";
ddlOperators.DataBind();
switch (controlType)
{
case ResourceStrings.ViewFilter_ControlTypes_DDL:
criteriaDDL.Visible = true;
criteriaText.Visible = false;
var crit = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].SearchCriteria;
ddlCriteria.DataSource = crit;
ddlCriteria.DataBind();
break;
case ResourceStrings.ViewFilter_ControlTypes_Text:
criteriaDDL.Visible = false;
criteriaText.Visible = true;
break;
}
}
public event EventHandler OnColumnChanged;
public ISearchCriterion FilterOptionsValues { get; set; }
}
}
I figured it out. Here is my solution:
I modified the GetPostBackControl to look for not only the linkbutton that inserts the user control, but for controls that contain the id of child controls of the inserted user control(as to capture the OnSelectedIndexChanged that gets fired from inside my user control).
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
//if it contains options then it's a control inside my usercontrol
if (ctrlname.Split('$')[2].Contains("options"))
{
var c = new Control();
c.ID = ctrlname;
return c;
}
else
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
Then I modify the OnPreInit event to look for controls with an id of the linkbutton or an id that contains "options" :
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if (control != null)
{
if ((control.ClientID == (lbAddAndCondtion.ClientID) || createAgain) || control.ID.Contains("options"))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
}
The critical fix was in the CreateUserControl method. In my original code I was trying to directly load the user control from my generic list that was stored in Session. I changed that to actually create a new instance of the user control, assign that new instance an id that matches the one stored in Session, and then add it to the placeholder:
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
FilterOptionsCollectionView foc = new FilterOptionsCollectionView();
foc = Page.LoadControl("~/Views/FilterOptionsCollectionView.ascx") as FilterOptionsCollectionView;
foc.ID = c.ID;
phConditions.Controls.Add(foc);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The only thing I changed in the user control was moving the method that loads my drop down lists's and wiring up the OnSelectedIndexChanged event into the OnInit event. Now I can dynamically load as many instances of the user control I want and all of the event's inside the user control fire correctly and state is persisted across postbacks!!
Hope this helps someone else!!

Resources