Trying to set RadTreeView node checked status programatically from persistence - asp.net

There must be something I'm missing here. I have two instances of RadTreeView, for which I store node check data in a cookie. Upon page load, I then want to read this cookie, and set checked status accordingly.
So I have this OnDataBound event:
protected void RadTreeView1_OnDataBound(object sender, EventArgs e)
{
HttpCookie checkedCookie = Request.Cookies[DataType + "Checked"];
if (checkedCookie != null)
{
var cookieValue = checkedCookie.Values["Checked"];
if (cookieValue != null)
{
var checkedNodeValues = cookieValue.Split('*');
foreach (string nodeValue in checkedNodeValues)
{
RadTreeNode checkedNode = RadTreeView1.FindNodeByValue(HttpUtility.UrlDecode(nodeValue));
if (checkedNode != null)
checkedNode.Checked = true;
}
}
}
}
And in the foreach loop, I find a corresponding node for every cookie value. What's more is, their initial Checked status is false.
So why are all other nodes also getting checked?

Try using the RadPersistenceFramework. Adding a single entry for your treeview to the PersistenceManager (or PersistenceManagerProxy) control should let you store the checked state. You can see this here http://demos.telerik.com/aspnet-ajax/treeview/examples/applicationscenarios/persisting-treeview-settings/defaultcs.aspx?product=persistenceframework
Of course, storing the data depends a bit on your case (you can have a custom provider and still keep the data in a cookie, or you can keep things in a database, whatever works for you: http://demos.telerik.com/aspnet-ajax/persistence-framework/examples/custom-storage-provider/defaultcs.aspx).

Related

User.IsInRole() inconsistent behaviour

I have an MVC4 site and have recently noticed some unexpected behaviour regarding Roles which Im sure is something I have either misunderstood or overlooked but I cant see the problem yet so here goes;
On Login I create an authticket including the roles information in Userdata.
In Application_AuthenticateRequest I retrieve the Role data and assign it to the CurrentUser.
Notwithstanding I suspect I should be using an Authorize mechanism, can anyone see why when I later check User.IsInRole() it times out trying to hit SqlServer presumably because it thinks it is acting as the RoleProvider (its not set in config), why is it not just getting it from the Current User as assigned in the Global.asax?
TIA,
dan
[snipped from my Application_AuthenticateRequest]
try
{
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
var currentUser = HttpContext.Current.User;
var formsId = currentUser.Identity as FormsIdentity;
var ticket = formsId.Ticket;
string userData = ticket.UserData;
var rolesString = userData.GetValueFromKeyValuePairs<string>("roles", "|");
var rolesList = rolesString.SplitAndType<string>("|").Select(s => s.ToLower().Replace(" ", ""));
if (rolesList.Count() > 0)
{
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(ticket.Name), rolesList.ToArray());
}
}
}
catch (Exception ex)
{
if (Debugger.IsAttached)
{
throw ex;
}
}
Ok, so I was setting the User roles at the wrong point in the lifecycle and they were being overwritten, moving the code verbatim to this event ensures it is not overwritten.
Application_PostAuthenticateRequest(Object sender, EventArgs e)

Problem with Session unpack

I have some problems with this code:
private void BoxVisibility(bool email, bool link, Control linkButton)
{
mainEmail.Visible = email;
foreach (Control c in PlaceHolder1.Controls)
{
c.Visible = false;
}
if (linkButton != null)
{
PlaceHolder1.Visible = true;
linkButton.Visible = link;
}
}
when I send to method Control all is ok, but when at first I put Control in Session['temp'] = Control, and then invoke the method like BoxVisibility(false, true, (Control) this.Session['temp']) in this case Control linkButton.Visible = link; doesn't take true, He's still remain false.
The "control" is a reference to a particular instance for this particular page.
The Page is recreated on every request, so a reference to an old instance of your control is no longer valid. So don't store controls in anything (Session, ViewState, static fields) that lives longer than the single request. Local (instance) fields of your page are safe.

ASP.NET - Get SessionID while in from the Global.ASAX

I'm recording the session start times from when people log into my .NET 2.0 web application, but I'd also like to record the Session ID. Can someone give me some example code on how to accomplish this (how to access the Session ID from within the Global.ASAX).
If you need any additional info just let me know.
HttpContext.Current.Session.SessionID
Edit to show null test:
if ((HttpContext.Current != null) && (HttpContext.Current.Session != null) {
id = HttpContext.Current.Session.SessionID
}
You can get at it quite simply with HttpContext.Current.Session.SessionId as you probably already know. You need to be on or after Application_AcquireRequestState before the session state has been loaded, and session state is also only loaded when the requested resource implements IRequiresSessionState. You can see a list of all the events in global.asax here: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html and read more about IRequiresSessionState here: http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx
Write to the session the datetime and sessionid at the moment of the first request following ASP.NET's identifying the user's session.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs eventArgs) {
var session = HttpContext.Current.Session;
if (session != null) {
if (session["foo"] == null) {
session["foo"] = DateTime.Now.Ticks + "|" + session.SessionID;
}
}
}

ASP.NET 2.0: Problem in Httpcontext.current.session.add()

Can anybody help me to find out solution of following problem.
In ASP.NET website: at Application_OnPostAuthenticate() event, whatever code i write is executed for every request. therefore due to this customidentity object, countryid and weatherid is called everytime for each request (call for database for value). It effect response time of page and unneccessary code execute.
void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
// Get a reference to the current User
IPrincipal objIPrincipal = HttpContext.Current.User;
// If we are dealing with an authenticated forms authentication request
if ((objIPrincipal.Identity.IsAuthenticated) && (objIPrincipal.Identity.AuthenticationType == "Forms"))
{
CustomPrincipal objCustomPrincipal = new CustomPrincipal();
objCustomPrincipal = objCustomPrincipal.GetCustomPrincipalObject(objIPrincipal.Identity.Name);
HttpContext.Current.User = objCustomPrincipal;
CustomIdentity ci = (CustomIdentity)objCustomPrincipal.Identity;
HttpContext.Current.Cache["CountryID"] = FatchMasterInfo.GetCountryID(ci.CultureId);
HttpContext.Current.Cache["WeatherLocationID"] = FatchMasterInfo.GetWeatherLocationId(ci.UserId);
Thread.CurrentPrincipal = objCustomPrincipal;
}
}
To solve this problem when i try tochange code as follows
HttpContext.Current.Session.Add("test", FatchMasterInfo.GetWeatherLocationId(ci.UserId);); in place of cache i found foolowing error
"Object refrence not set to the instance of object"
I don't know whether we can store session variable inside Application_OnPostAuthenticate() event or not?
You could try doing this a bit later in the request, such as in the PreRequestHandlerExecute event:
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
IPrincipal objIPrincipal = HttpContext.Current.User;
if ((objIPrincipal.Identity.IsAuthenticated) && (objIPrincipal.Identity.AuthenticationType == "Forms"))
{
HttpSessionState session = HttpContext.Current.Session;
CustomPrincipal objCustomPrincipal = new CustomPrincipal();
if (session[objIPrincipal.Identity.Name] == null)
{
// get data from database or wherever
objCustomPrincipal = objCustomPrincipal.GetCustomPrincipalObject(objIPrincipal.Identity.Name);
CustomIdentity ci = (CustomIdentity)objCustomPrincipal.Identity;
Object countryID = FatchMasterInfo.GetCountryID(ci.CultureId);
Object weatherLocationID = FatchMasterInfo.GetWeatherLocationId(ci.UserId);
// save in session (not cache as cache is application-wide, not per-user):
session.Add(objIPrincipal.Identity.Name, objCustomPrincipal);
session.Add(objIPrincipal.Identity.Name + "_CountryID", countryID);
session.Add(objIPrincipal.Identity.Name + "_WeatherLocationID", weatherLocationID);
}
else
{
// already have custom principal object in session
objCustomPrincipal = (CustomPrincipal)session[objIPrincipal.Identity.Name];
}
// set the custom principal object to context/thread
HttpContext.Current.User = objCustomPrincipal;
Thread.CurrentPrincipal = objCustomPrincipal;
}
}
You probably don't want to access the session in any event that happens in every request. Some requests don't even have session (for instance, a lot of web service calls, or calls to WebResource.axd that load static resources).
Before adding value to cache object, check if it already exists in the cache.
You might not have session state enabled. Does it work anywhere else (like in a web form's display)?
Look for a <sessionState> element under your system.web element in web.config make sure it's turned on (set it to InProc unless you have a web farm).

get session ID in ASP.Net

how can I get IDs of all current sessions?
To get the session id, do this:
// In a user control or page
string sessionId = this.Session.SessionID;
// In a normal class, running in a asp.net app.
string sessionId = System.Web.HttpContext.Current.Session.SessionID;
You should not need to:
Make any data table or loop anything
Use SQL server for session state
Handle Session_Start or Session_End
In a cookieless scenario, the session id is created when you access the Session object for the first time. This shouldn't matter much, because the moment you access the SessionID property, the session object is accessed.
For more info, look into this:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
Note: The msdn examples have been written by monkeys.
You can use Global.asax file and set the Session at Session_Start event. See below
in Global.asax file you can do something like this:
protected void Session_Start(object sender, EventArgs e)
{
Session["sid"] = Session.SessionID;
Session["sid"] = "Test";
}
Then in your WebForm you can get the Session ID and Value like below
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Session ID is:" + Session.SessionID.ToString()+ "<br/>");
Response.Write("Session value is:" + Session["sid"].ToString());
}
For details, see http://www.dotnetcurry.com/ShowArticle.aspx?ID=126
According to Dino Esposito each session is stored in the application's Cache and with some work you can retreive this information:
DataTable dt = new DataTable();
dt.Columns.Add("SessionID", typeof(string));
foreach(DictionaryEntry elem in Cache) {
string s = elem.Key.ToString();
if (s.StartsWith("System.Web.SessionState.SessionStateItem")) {
DataRow row = dt.NewRow();
char[] parms = {':'};
string[] a = s.Split(parms);
row["SessionID"] = a[1];
dt.Rows.Add(row);
}
}
If you want a way to store a list of the current sessions where you control the backing store, so that you may store extra data about the client, you can use a list. (I'm writing the following example from the top of my head)
Hook into Application_SessionStart in the global.asax.cs file:
static List<string> sessions = new List<string>();
static object sessionLock = new object();
void Application_SessionStart()
{
lock (sessionLock) {
sessions.Add(Session.SessionID);
}
}
void Application_SessionEnd()
{
lock (sessionLock) {
sessions.Remove(Session.SessionID);
}
}
Alternatively, you can use a dictionary, storing the session ID as a key, and extra data about that user as the value. Then you can easily create a page that shows all current user sessions, for example, for an admin site to show current user sessions.
SessionEnd will only be called if your sessions are InProc.
The answer depends partially on where you store session state. Assuming you use the default (inproc) then you can maintain a list of current session ids using the Session_Start and Session_End events in global.asax.
If you are storing your session state in SQL Server, you can also easily get it from there.

Resources