Using Global.asax to set/check session variable and redirect (for user testing) - asp.net

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

Related

AspNetUsers cannot update custom column

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.

SelectedIndexChanged not firing

My problem is that SelectedIndexChanged of ddlObra control is not firing, but when I erase the Page.ClientScript.RegisterOnSubmitStatement of Page_Load, everything works fine. I can't understand this behavior.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CarregarDropDownLists();
}
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "OnSubmitScript", "return handleSubmit()");
}
protected void ddlObra_SelectedIndexChanged(object sender, EventArgs e)
{
List<Entidades.Empreendimento.Unidade> unidades = Entidades.Empreendimento.Unidade.ListaUnidades(txtLogin.Text);
ddlBloco.Items.Clear();
ddlUnidade.Items.Clear();
ddlBloco.Items.Insert(0, new ListItem("----- Bloco -----", ""));
ddlUnidade.Items.Insert(0, new ListItem("----- Unidade -----", ""));
//if (unidades.Count == 1) return;
foreach (Entidades.Empreendimento.Unidade Un in unidades)
{
if (Un.ObraVinculo.idObraCrm.ToString() == ddlObra.SelectedValue)
{
if (!ddlBloco.Items.Contains(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM)))
{
ddlBloco.Items.Add(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM));
}
Bandeira = Un.Bandeira;
Estado = Un.Estado;
}
}
ddlBloco.SelectedIndex = 0;
ddlUnidade.SelectedIndex = 0;
LoadAreas();
}
This code is in the .aspx file
<script type="text/javascript">
function handleSubmit() {
if (typeof (ValidatorOnSubmit) == 'function' && ValidatorOnSubmit() == false) {
return false;
} else {
$("#btnEnviar").click(function () { return false }).fadeTo(200, 0.5);
return true;
}
}
</script>
Thank you guys for your help!
The client script executed by the submission of the form must return true in
order to allow the form to submit. This enables the client-side script to
prevent the submission of the form conditionally.

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

DateTimeControl Custom OnDateChange event not firing in SharePoint

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;

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