Can't get the Sessions to work in webmatrix - asp.net

I am trying to pass variables from one page to another using Sessions , but they don't seem to have effect. In the source page inside the razor syntax
Session["variable"] = "value";
And in the target page:
<p>#Session["variable"].ToString()</p>
but I get a server error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Any suggestions would be most welcome........Thanks

I was only ever able to get this to work with casting:
<p>#(string)Session["variable"]</p>
Although it has been a long time since I have tried it with ToString() instead, I do explicitly remember my attempt to call a Session variable only successful with the casting option, although I have heard that ToString() should work. Either way, I always get it to work with casting.
That having been said, I feel it only right of me to warn you that if you are simply trying to pass data between pages, you shouldn't be using Session variables at all. Use hidden form fields, query strings, Url Data, or even cookies and/or databases before you do that.
I like to look at Session variables as something to quickly solve very special cases and only to be used very CAREFULLY. ALWAYS expect the value to be null and test its value before using it.
For help with the options for transferring data between web pages using WebMatrix, check out Mike Brind's very helpful site: http://www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages <-- You'll want to bookmark this for now. It is right up the alley of what you are getting yourself into with WebMatrix.
If you still want to use the Session variable and casting doesn't work, the only other thing I can think that would cause the error is that the value you expect in Session["variable"] isn't what you think it is.
For the Record:
I was only trying to make a point when saying, "or even cookies and/or databases before you do that" Please do not use those options, as they are likely terrible in your case (also, cookies would just give you the same problems as Session variables, actually). In any case, it really all depends on how you are using the data and if you are always checking to make sure the value hasn't been cleared in the case of Session variables and/or cookies.

Related

Is Session in Meteor a misnomer?

Although I started using Meteor extensively only recently, the name "Session" for a Session object in Meteor feels like a misnomer to me. It is very different from how it's conventionally used across the web and I don't understand why it's named that way. Is there a specific reason to this or is it possible to rename it to something more suitable?
A Session variable is a reactive data source which:
can be globally accessed anywhere in your client code
will survive a hot code push
will not survive a hard reload
I agree that the name is confusing because of the last point. To answer your question, yes you could name it something else if you really wanted to. For example:
client/lib/session.js
NotReallySession = Session;
Then elsewhere in your client code, you could do:
NotReallySession.set('answer', 42);
NotReallySession.get('answer');
However, I'm not sure what you really gain by doing this.
A more attractive solution would be to use a package like persistent-session which modifies the Session api to give you persistence across page refreshes by keeping values in localstorage.
Of particular interest may be the Session.setAuth function, which stores a persistent reactive value which is cleared on logout. In my view, this most closely aligns with the notion of "session" from other contexts.

How to handle conflicting HTTP GET param

I'm designing a REST API that supports HTTP GET parameters. In most cases I only accept one value for a parameter. But how should I handle duplicate parameters?
For example, Stack Overflow accepts a GET param tab:
http://stackoverflow.com/?tab=hot
http://stackoverflow.com/?tab=featured
Duplicate parameters are allowed, passing both values is correct:
http://stackoverflow.com/?tab=hot&tab=featured
What should I do? Just go with the first value, thus silently ignoring other values (what SO does) or return an error stating only one value is allowed? In the latter case, what error should I return with what status code (409 Conflict, perhaps)?
I agree with VKSingla that this is a design decision, therefore there is no correct answer only opinions in this matter.
If you ask me I would make a 'strict' API and just throw an error (I would make sure that it is a clear error and not just a random code which doesn't help the user). I prefer this strict approach because if usercode is adding the same param twice it will likely be a bug somewhere in the users code. Revealing this bug as early as possible helps the user finding the bug asap.
If you choose to go with ignoring the other parameters then make sure that the user knows this behavior. For example document 'all duplicate parameters after the first will be ignored'. Undocumented 'magic behavior' like this can make code pretty damn hard to debug.
This is a design decision. Its your API design on how you want it to function.
If you choose to ignore any one , then the question is which one ?
So, it is simply a conflict. or else
your API can respond with combined data, but the request for that should be like this
https://stackoverflow.com/?tab=hot,featured
Also refer this question Extra Query parameters in the REST API Url

Common module dynamic backlink

It's C# + .net 2.0, but this can be pretty much any environment
I have a list in my website where you can get coming from several different locations (modules). It is a normal list screen, with add/edit (an other) links in it.
You sometimes get here from one module, sometimes from an other module. The only thing that I would like to fix is the Back link. It should always take you back to the module where you came from.
What is the best way to do this?
Session variable (this is so far my best choice, but I am not really happy to use this)
URL. I could transmit a parameter all over, "carry it with me" (i don't like this a lot because of the number of the pages that are related to this list, I would have to carry that variable with me in add, edit and other screens, too many places to change)
cookies ?(limited number of cookies, and things like that, don't really like this one either.)
4-5-6 ?
How are all you guys handling this issue?
Save the referer in Session and redirect them to this from the back link eventhandler.
This assumes you are doing nothing funky with the querystring.
I have concerns myself about using Session to store information but for this scenario, it is perfectly acceptable.
Cookies are another option, but overkill, unless you factor in the possibility of losing session information on website/app-pool recycle

Asp.net error object not set to a reference

Because I rush in development (a lot of whip cracking here) and declare my objects at the top of the function and instantiate inside my try-catch block, I get a lot of the good old "object not set to an instance of an object" errors while doing TDD, and later if I do miss a branch that object was used in (doing VB now, would prefer C#) or just in every day coding, object not set to an instance of an object is a bit vague. Sure the stack trace sends me to the line the error occured at, but it would be nice if I could modify my logging to either name the object or its type because sometimes I have multiple objects on the same line. It's not the end of the world, but in the end it would save me a few minutes each day. Any ideas on how I can pass the info on which object wasn't set? Thanks
It is non trivial to "modify your logging" to output variable name or type - I am sure that if the framework could easily get this information from the executing IL, MS would have included it the null reference exception.
Prevention is always better than cure. Here are a couple of tips I would do
Fix your compiler warnings
C# would generate a compile error if it detects that there are code paths that could use an unassigned local variable. [For some odd reason] VB.Net will still compile but the compiler will generate a warning - take heed of these and go and fix the code and you should never run into the problem of unassigned variables again!
Adopt a different coding pattern for variable declaration
I appreciate that method variable scope in ye olde VB was that the variable was visible throughout the entire method regardless of where it was defined. As a result, it was a reasonable practice to put all your var declarations at the top of the method. VB.Net of course is different - you can only use variables after they are declared and so it is OK (and I would say preferable*) to put the declaration (and assignment) closer to where the variable is actually used. This should help you see "by eye" if your program logic means it is possible to use an unassigned variable.
Some people think this is a think that it is always good practice to put variable declarations in a block at the top of the method. I will not argue against them but I would say that that approach works best with small methods that do not use lots of variables.

Looking for a hack to prevent rewriting an app without using session variables

Our company uses an app that was originally ColdFusion + Access later converted to classic ASP + MS Sql for task/time tracking called the request system. It's broken down by department, so there's one for MIS, marketing, logistics, etc. The problem comes in when (mainly managers) are using more than one at a time, with 2 browser windows open. The request system uses session variables, a lot of session variables, "session" is referenced 2300 times in the application. When 2 are open at once as you can imagine this causes all sorts of anomalies from the variables getting mixed up.
There's a 3 year old MIS request in the system to "fix" this and it's been worked on by 3 developers, and now it's my turn to take a shot at it. I was wondering if anyone else has had to work on a project like this, and if there was some sort of hack to try and mitigate some of the problems. I was thinking of maybe calling something in global.asa to load misc. session variables from the querystring. The problem is, there's all sorts of this going on:
If (Session("Application") <> Request("App")) and Request("App") <> "" THEN
Session("Application") = Request("App")
End If
Looking at the functions in include files, you'll have a function with 4 parameters, that makes references to 6 different session variables. So you get the idea, this is going to be painful.
Has anyone had to do anything like this in the past? Any hacks you found useful?
refactor the code away from the direct Session("whatever") interface:
create an API for session access and replace all existing use of Session with it (it can be a session 'class/object' or just an include-file)
mangle the passed-in names for session variables with something that will make them unique per domain according to your needs (department or whatever)
test carefully
then rewrite the whole thing later in a modern web language, and/or find another job before they ask you to perform another miracle ;-)
My manager (who's a business guy, not a code guy), is infatuated with this system. He's in no rush to rewrite it. If I did rewrite this the only session variables used would be login-related. I'm more concerned with fast than right unfortunately :(
How many times "Session" is referenced doesn't mean as much as you seem to think it does. Also, unless there's a coding error, having two browsers open should start two separate sessions, and there shouldn't be any "mixing up" of the values for those sessions.
I suspect it may have to do with something else like both sessions reading from the same cookie or some issues with the App variables. Without seeing the whole source, its hard to say. It may be worth finding out if there's someone more familiar with the code to help you out.
And yes, its going to be painful to dig around in the code, but at least you'll know more the next time you have to fix something. ;)
Besides, rewriting isn't always the best option. You never know what sorts of fun business logic/bug fixes get lost in the rewrites.
I agree with AnonJr
Blockquote
having two browsers open should start two separate sessions
Blockquote
maybe the use of static global variables is causing your dataloss
In your sessions class (if you will use one), when you reference each variable, use a prefix or something common so that you can identify all your variables...then you can loop through ALL session variables and perhaps find others that are being referenced/created...
Private Const PREFIX As String = "MyPrefix_"
Public Shared Property MyVariable() As String
Get
Return HttpContext.Current.Session(String.Concat(PREFIX, "MyVariable"))
End Get
Set(ByVal value As String)
HttpContext.Current.Session(String.Concat(PREFIX, "MyVariable")) = value
End Set
End Property
loop to find session variables that aren't in your class
For Each Item As Object In HttpContext.Current.Session.Contents
If Not Item.ToString.StartsWith(PREFIX) Then
End If
Next

Resources