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)
Related
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.
I have an aspxgridview, I change displayed text via "CustomColumnDisplayText" event, My problem is when I want to use ASPxGridViewExporter for excel output, one of columns shows wrong data. I don't know how to use ASPxGridViewExporter RenderBrick event.
protected void ASPxGridView1_CustomColumnDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDisplayTextEventArgs e)
{
if (e.Column.PropertiesEdit.DisplayFormatString.Equals("Status"))
{
if (Convert.ToInt64(e.Value) == 2)
e.Value = "Successful";
else if (e.GetFieldValue("SaleReferenceId") == null || e.GetFieldValue("SaleReferenceId").ToString() == string.Empty || e.GetFieldValue("SaleReferenceId").ToString().Trim().Equals(""))
e.Value = "Invalid";
else if (e.GetFieldValue("saleOrderId") == null || e.GetFieldValue("saleOrderId").ToString() == string.Empty || e.GetFieldValue("saleOrderId").ToString().Trim().Equals(""))
e.Value = "Invalid";
else
e.Value = "Unsuccessful";
e.DisplayText = e.Value.ToString();
}
}
protected void ASPxGridViewExporter1_RenderBrick(object sender, DevExpress.Web.ASPxGridView.Export.ASPxGridViewExportRenderingEventArgs e)
{
// I don't know how to use it
}
I don't know how but this snippet works fine for me and the result is exactly what I wanted!
protected void ASPxGridViewExporter1_RenderBrick(object sender, DevExpress.Web.ASPxGridView.Export.ASPxGridViewExportRenderingEventArgs e)
{
try
{
GridViewDataColumn dataColumn = e.Column as GridViewDataColumn;
if (dataColumn.FieldName == "Status")
{
e.TextValue = "123";
}
}
catch (Exception ex)
{
}
}
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"
I would like to add very simple, temporary security to my site.
I made a page at Home/UnderConstruction where people testing the site can enter a hard-coded password which will then set the "underconstruction" session variable to "false".
This is what I have so far, but it results in too many redirects:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
string oc = underconstruction.ToString();
if (oc != "false") Response.Redirect("~/Home/UnderConstruction");
}
}
}
Is this close to what I would need to do?
Here is the code we got to work:
Controller Code for UnderConstruction View
public ViewResult UnderConstruction()
{
return View();
}
[HttpPost]
public ActionResult UnderConstruction(string ocp)
{
if (ocp == "mypassword")
{
Session["underconstruction"] = "false";
return RedirectToAction("Index", "Home");
}
else
{
Session["beingredirected"] = "false";
return View();
}
}
Global.Asax
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction.ToString());
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected.ToString());
}
if (uc && !redirected)
{
if (Request.HttpMethod == "GET")
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
else if (Request.HttpMethod == "POST")
{
}
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Is ~/Home/UnderConstruction in a different website? If not, wont it always redirect because oc will always be true? ie - do you also need to add a check for the page you're requesting so you can bypass the redirect if already going to the UnderConstruction page?
UPDATE
Not sure if checking the page name is a great idea, but something like this might work:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction);
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected);
}
if (uc && !redirected)
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Note that I would clean that up, that example was to just give the general idea.
UPDATE
If you want to use roles as mentioned in the comments, then this article from ScottGu's Blog may help. Its a little more complicated, but has the added benefit of not introducing temporary code as the above solution will
The custom event for a DateTimeControl is not firing. Instead the CreateChildControls() is firing, every-time I change the date on Calendar.
namespace myn
{
class StopTimeFieldControl : BaseFieldControl
{
protected DateTimeControl dateTime;
public override object Value
{
get
{
EnsureChildControls();
if (dateTime == null)
{
return string.Empty;
}
return dateTime.SelectedDate;
}
set
{
EnsureChildControls();
dateTime.SelectedDate = Convert.ToDateTime(this.ItemFieldValue);
}
}
protected override string DefaultTemplateName
{
get
{
return "StopTimeFieldControl";
}
}
public override void Validate()
{
if (ControlMode == SPControlMode.Display || !IsValid)
{
//this.ViewState["StopTimeFieldControl"] = Value.ToString();
return;
}
base.Validate();
if (dateTime.IsDateEmpty)
{
this.ErrorMessage = " Du måste ange ett värde för det här obligatoriska fältet.";
IsValid = false;
return;
}
try
{
StartTimeFieldControl child = (StartTimeFieldControl)FindControlRecursive(this.Page, "startDateTime").Parent;
if (dateTime.SelectedDate < Convert.ToDateTime(child.Value))
{
this.ErrorMessage = " Du måste ange ett värde som är senare än startdatum.";
IsValid = false;
return;
}
}
catch (Exception e)
{
PortalLog.LogString("## Exception Occurred: Fail when trying to catch startDateTime ** {0} || {1}", e.Message, e.StackTrace);
}
this.Page.Session["startDateTime"] = Value;
}
protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)
return;
if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
{
dateTime = new DateTimeControl();
dateTime.CssClassTextBox = "ms-long";
dateTime.TimeZoneID = 1053;
dateTime.LocaleId = 1053;
dateTime.ID = "stopDateTime";
dateTime.AutoPostBack = true;
this.dateTime.DateChanged += new EventHandler(dateTime_DateChanged);
Controls.Add(dateTime);
}
//ChildControlsCreated = true;
}
void dateTime_DateChanged(object sender, EventArgs e)
{
string hi = "hej";
}
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
}
}
Try to create your DateTimeControl control in PreInit or Init phase and not in CreateChildControls. Possible reason of such behaviour - your control is created too late, when page life cycle passed through postback event handling.
CreateChildControls() is firing,
every-time I change the date on
Calendar
But is the event handler being bound every time?
In most cases i dont create controls in if statements, things tend to not get wired up correctly.
Try just making the control invisible instead.
dateTime = new DateTimeControl();
if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
{
datetime.Visible = false;