enable mini profiler only to specific user and roles - c#

In asp.net mvc the scott hanselman example shows how to show the mini profiler for a local environmnet
protected void Application_BeginRequest()
{
if (Request.IsLocal) { MiniProfiler.Start(); } //or any number of other checks, up to you
}
But, I would like to go a step further and be able to see it remotely, only for specific logged in users, or ips.
Any idea how?
Update: I used the following code:
protected void Application_EndRequest()
{
MiniProfiler.Stop(); //stop as early as you can, even earlier with MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
protected void Application_PostAuthorizeRequest(object sender, EventArgs e)
{
if (!IsAuthorizedUserForMiniProfiler(this.Context))
{
MiniProfiler.Stop(discardResults: true);
}
}
private bool IsAuthorizedUserForMiniProfiler(HttpContext context)
{
if (context.User.Identity.Name.Equals("levalencia"))
return true;
else
return context.User.IsInRole("Admin");
}

You could subscribe to the PostAuthorizeRequest event and discard the results if the current user is not in a given role or the request is coming from a specific IP or whatever check you want:
protected void Application_BeginRequest()
{
MiniProfiler.Start();
}
protected void Application_PostAuthorizeRequest(object sender, EventArgs e)
{
if (!DoTheCheckHere(this.Context))
{
MiniProfiler.Stop(discardResults: true);
}
}
private bool DoTheCheckHere(HttpContext context)
{
// do your checks here
return context.User.IsInRole("Admin");
}

Related

Ensure page is accessed from a specific link

Say if I have link1.aspx and link2.aspx. Within link1.aspx, I redirect the user to link2.aspx.
What is the most efficient way of checking that link2.aspx is only accessed via link1.aspx?
For example, something like:
link2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if page is not accessed via link1.aspx
{
Response.Redirect("~/portal.aspx");
}
}
}
I could use a query string but are there any other ways?
You can use UrlReferrer. However, it is not a secure way of detecting where the user comes from.
For example,
if (string.Equals(Request.UrlReferrer.AbsoluteUri,
"YOUR_REFERRER_URL",
StringComparison.InvariantCultureIgnoreCase))
{
}
If it is redirecting between pages inside your application, I would like to suggest to use SessionState which is more secure and robust than UrlReferrer.
link1.aspx.cs
private bool IsValidUrl
{
set { Session["IsValidUrl"] = true; }
}
protected void Button1_Click(object sender, EventArgs e)
{
IsValidUrl = true;
Response.Redirect("link2.aspx");
}
link2.aspx.cs
private bool IsValidUrl
{
get
{
if (Session["IsValidUrl"] != null)
return Convert.ToBoolean(Session["IsValidUrl"]);
return false;
}
set { Session["IsValidUrl"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsValidUrl)
{
// user comes from valid url.
// .... Do somthing
// Reset session state value
IsValidUrl = false;
}
}
You could use the Request.UrlReferrer property to check what page the user is coming from.

ASP.NET prevent accessing the homepage before and after logout

I have a login page and a homepage. It's not possible to access homepage without login but after i login and click logout at the homepage. Users are able to access homepage from browser's address row. How can prevent this ? Here is my implementation
Login Click Method at AdminPanelLogin.aspx.cs:
protected void adminLoginButton_Click(object sender, EventArgs e)
{
String adminName = adminNameText.Text;
String password = adminPwdText.Text;
AdminPanelLoginProcess aplp = new AdminPanelLoginProcess();
if (aplp.adminLogin(adminName, password))
{
Session["AdminAuthentication"] = aplp.Admn.AdminID;
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Write("<script>alert('Login failed !');</script>");
}
}
Logout Click Method at AdminPanel.aspx.cs
protected void adminPanelLogoutLink_Click(object sender, EventArgs e)
{
Session["AdminAuthentication"] = null;
Session.Abandon();
Response.Redirect("AdminPanelLogin.aspx");
}
AdminPanel.aspx.cs Page Load Method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
else
{
if (!IsPostBack)
{
showProducts();
showModels();
showShoes();
}
else
{
if (Session["AdminAuthentication"] == null)
{
Response.Redirect("AdminPanelLogin.aspx");
}
}
}
}
By default, the back button does not reload the page but get it from cache. Try to disable cache in AdminPanel.aspx as
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
or use any other method from http://www.codeproject.com/Tips/135121/Browser-back-button-issue-after-logout.aspx

Event Handler is Always null

I have searched extensively on this, but cannot find the solution to my problem. I am trying to call a function in the code behind of a page from a user control on that page.
I have a web application that uses a master page. I am adding a user control that I wrote to one of the content pages. I added the user control to the aspx page by dragging and dropping it from the toolbox. I am able to see the user control from the code behind, but I cannot access the public functions. To fix that problem, I created an object of the user control in the code behind and used the LoadControl function. All of that seems to work fine.
The problem I am having is when I am trying to hook the into the EventHandler from the aspx page to the user control. Everything compiles and runs just fine, but I am not seeing anything happen on the page. I think the issue is that the EventHandler is always null.
User Control Code
public partial class ucBuyerList : System.Web.UI.UserControl
{
public delegate void BuyerSelectedEventHandler(object sender, EventArgs e);
public event BuyerSelectedEventHandler BuyerSelected;
private string name = "";
public string Name
{
get { return name; }
set { name = value; }
}
private string auid = "";
public string AUID
{
get { return auid; }
set { auid = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void OnBuyerSelected(EventArgs e)
{
if (BuyerSelected != null)
{
BuyerSelected(this, new EventArgs());
}
}
protected void lbBuyerList_SelectedIndexChanged(object sender, EventArgs e)
{
SetNameAndAUID();
OnBuyerSelected(e);
}
private void SetNameAndAUID()
{
name = lbBuyerList.SelectedItem.Text;
auid = lbBuyerList.SelectedItem.Value;
}
}
Parent Page Code
public partial class frmBuyerInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Master.changePageTitle("Buyer Information");
buyerList.BuyerSelected += new ucBuyerList.BuyerSelectedEventHandler(buyerListControl_BuyerSelected);
}
void buyerListControl_BuyerSelected(object sender, EventArgs e)
{
DisplayBuyerInformation();
}
public void DisplayBuyerInformation()
{
tbName.Text = buyerList.Name;
tbAUID.Text = buyerList.AUID;
}
}
Can anyone see what I am doing wrong?
EDIT: This issue has been resolved. The code snippits above are now functional. If anyone runs into the issue I had, you can model the code above. Make sure that AutoEventWireup="true" in both the aspx and ascx pages. Thank you June Paik for your solution. Thank you Diego De Vita for your input as well.
I've been struggling with events for quite a while as well. Nowadays I always create them this way 'cause it's the only way I know it works. Haven't tested it with your code but here it goes anyway:
public partial class ucBuyerList : System.Web.UI.UserControl
{
public delegate void BuyerSelectedEventHandler(object sender, EventArgs e);
public event BuyerSelectedEventHandler BuyerSelected;
public string Name;
public string AUID;
protected void Page_Load(object sender, EventArgs e)
{
//Select the first buyer in the list when the user control loads
if (!IsPostBack)
{
lbBuyerList.SelectedIndex = 0;
}
}
private void OnBuyerSelected(EventArgs e)
{
BuyerSelectedEventHandler handler = BuyerSelected;
if (handler != null)
{
handler(this, new EventArgs());
}
}
protected void lbBuyerList_SelectedIndexChanged(object sender, EventArgs e)
{
Name = lbBuyerList.SelectedItem.Text;
AUID = lbBuyerList.SelectedItem.Value;
OnBuyerSelected(e);
}
}
In the parent page you can just call your function the same way you're doing it already.
It could be that Page_Load is too late in the page lifecycle to be using LoadControl and subscribing to the event. What happens if you move that code to the Page_Init method?

page.Isvalid always return false?

I have two buttons and two separate validation groups for each button. I kept EnableClientScript=false on each requiredfield validator of the textboxes. I have c# code like below
void submitButton_Click(object sender, EventArgs e)
{
this.Page.Validate("LoginAccountGroup");
if (this.Page.IsValid)
{
}
}
void saveButton_Click(object sender, EventArgs e)
{
this.Page.Validate("CreateAccountGroup");
if (Page.IsValid)
{
}
}
My question is this Page.Isvalid is always returning false in the c# code. How to make it work
Try This
protected bool IsGroupValid(string sValidationGroup)
{
Page.Validate(sValidationGroup);
foreach (BaseValidator validator in Page.GetValidators(sValidationGroup))
{
if (!validator.IsValid)
{
return false;
}
}
return true;
}

c#, listbox, stackOverflow exception

I inherited KryptonToolkit ListBox control to get SelectedItemChanging event.
public class CPListBox : KryptonListBox
{
public event CancelEventHandler SelectedIndexChanging;
protected virtual void OnSelectedIndexChanging(CancelEventArgs e)
{
SelectedIndexChanging(this, e);
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
CancelEventArgs cArgs = new CancelEventArgs();
OnSelectedIndexChanged(cArgs);
if(!cArgs.Cancel)
{
base.OnSelectedIndexChanged(e);
}
}
}
In form I handle event with code:
void UsersListBoxSelectedIndexChanging(object sender, CancelEventArgs e)
{
if(_presenter.CurrentUser.IsModified)
{
MessageBox.Show("Nie zapisales zmian!");
e.Cancel = true;
}
}
And I got stackOverflow ;) Exception. Maybe someone now what is wron with this code?
You're recursively calling the method in itself forever. There's no terminating condition for these recursive calls. It'll result in Stack Overflow.
protected override void OnSelectedIndexChanged(EventArgs e)
{
CancelEventArgs cArgs = new CancelEventArgs();
OnSelectedIndexChanged(cArgs); // Clearly calling yourself indefinitely.
//...
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
CancelEventArgs cArgs = new CancelEventArgs();
//Next line!!
OnSelectedIndexChanged(cArgs);
if(!cArgs.Cancel)
{
base.OnSelectedIndexChanged(e);
}
}
You're calling yourself. Hence the StackOVerflow exception.
You have OnSelectedIndexChanged call within OnSelectedIndexChanged, it's an endless recursive call.

Categories