Session FROM ASP.NET to classic asp - asp.net

I have an old system that was developed, not by me, in classic ASP.
I have a new system, developed by me in ASP.NET
How can I pass a session variable (not complex types, just a simple string or int) TO that classic ASP page? I don't need anything back from it.
To add a spanner to the works - how can I do the "hand off" or transfer if the classic ASP site is on a different domain?
Update:
Cannot use the option of passing items via querystring OR storing it in a DB and letting the classic ASP read it from the DB.
Thank you

you could use a classic asp page that sets session variables out of e.g. post parameters.
then call that classic asp page from your asp.net page.
example (not complete) session.asp:
if session("userIsloggedIn") = true and request.form("act") = "setSessionVar" then
session(request.form("name")) = request.form("value")
end if
of course this is some kind of hack but we are talking about classic asp...

I had a different direction. I exchanged the session states via a cookie. Adding these methods. So now instead of calling Session directly, I use these methods instead.
ASP.NET
public static void AddSessionCookie(string key, string value)
{
var cookie = HttpContext.Current.Request.Cookies["SessionCookie"];
if (cookie == null)
{
cookie = new HttpCookie("SessionCookie");
cookie.Expires = DateTime.Now.AddHours(12);
HttpContext.Current.Response.Cookies.Add(cookie);
HttpContext.Current.Request.Cookies.Add(cookie);
}
HttpContext.Current.Session[key] = value;
cookie[key] = value;
}
public static string GetSessionCookie(string key)
{
if (HttpContext.Current.Session[key] == null)
return string.Empty;
string cook = HttpContext.Current.Session[key].ToString();
if (!String.IsNullOrEmpty(cook))
{
var cookie = HttpContext.Current.Request.Cookies["SessionCookie"];
if (cookie == null)
{
cookie = new HttpCookie("SessionCookie");
cookie.Expires = DateTime.Now.AddHours(12);
HttpContext.Current.Response.Cookies.Add(cookie);
HttpContext.Current.Request.Cookies.Add(cookie);
}
if (cookie != null)
cookie[key] = cook;
return cook;
}
return cook;
}
Then for Classic
Function AddSessionCookie(key, value)
Response.Cookies("SessionCookie")(key)= value
Response.Cookies("SessionCookie").Expires = DATE + 1
Session(key) = value
End Function
Function GetSessionCookie(key)
If Session(key) <> "" Then
Response.Write(Session(key))
ELSEIF Response.Cookies("SessionCookie")(key) <> "" THEN
Session(key)=Response.Cookies("SessionCookie")(key)
Set GetSessionCookie = Session(key)
End If
End Function

Related

Asp.Net - How to expire Cookie

Tried
if (Request.Cookies["IsGuest"] != null)
{
Response.Cookies["IsGuest"].Expires = DateTime.Now.AddDays(-1);
//HttpCookie myCookie = new HttpCookie("IsGuest");
//myCookie.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies.Add(myCookie);
}
string a = Request.Cookies["IsGuest"].Value;
and also tried by commenting uncommented code and uncommenting commented code but
string a = Request.Cookies["IsGuest"].Value;
Always running and Request.Cookies["IsGuest"] is never null
You got the right concept for deleting a cookie programmatically:
HttpCookie myCookie = new HttpCookie("IsGuest");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
However, you missed one point. The above change won't be effective until the postback completes and subsequently user initiates a new request.
MSDN says:
The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
So, the below code illustrates more here::
protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
HttpCookie myCookie = new HttpCookie("IsGuest");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
// this will always be true here as the Request i.e HttpRequest isn't
// modified actually as the postback isn't complete and we are accessing
// the Cookies collection of same request (not a new request)
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie Collection can't be modified without
making a new request";
}
}
// suppose after postback completes,
// user clicks a button to check the cookie,
// which in turn is a new request/postback/....
protected void CheckCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie is present!";
}
else
{
Label1.Text = "No Cookie is present!";
}
}
One last Note::
Calling the Remove method of the Cookies collection removes the cookie on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.
How to Expire a Cookie (on the Client)
I would not reply on ASP.NET Core to remove or expire cookies, as the server-side has very little to do with what happens on the browser. The ASP.NET application & server also has no knowledge of the names of every outdated-cookie, which paths were assigned, if some have already expired, which cookie names are no longer used from an older website, which ones were renamed, which ones are session cookies that need to remain, etc etc.
Cookies are best controlled on the client, which means running JavaScript (unfortunately).
To do that, I recommend you roll your own cookie expiration routine. Below is one I use that removes the top root-path cookies and a sub-path of cookies under the root, starting at the folder from which the script is called from. This generally means most of your cookies are removed. There are some exotic rules as to how browsers remove expired cookies under subpaths that I wont get into. In some cases some subpaths may be missed. But in general, root cookies would all be expired, and any cookies with the same scipts web path and all subpath under it, also expired.
The script below only sets expiration dates on cookies with paths matching the above rules. But the browsers are design to expire cookies under the subpath above as well. Please test in various browser, however, and customize the script as you like. This will NOT delete sessions stored as cookies!
// Get all cookies for this domain but by name-value pairs:
alert('What cookies do I have (name-value)?\r\n ' + document.cookie);
// Get all cookies
var allcookies = document.cookie;
// Splits into multiple cookies
var cookiesArray = allcookies.split(";");
// Loop through each found cookie...
if (cookiesArray && cookiesArray.length >= 0){
for (var i = 0; i < cookiesArray.length; i++) {
var nameString = "";
var pathString = "";
var expiresString = "";
// Strip out all whitespace or formatting from the name-value pair...
var cookieCleaned = cookiesArray[i].replace(/^\s+|\s+$/gm, '').replace(/[\t\n\r]/gm, '')
namePair = cookiesArray[i].split("=");
nameString = namePair[0] + "=; ";// empty the name's value
const earlydate = new Date(0).toUTCString();
expiresString = "expires=" + earlydate;
// DELETE COOKIES using ROOT PATH and SUBPATH
if (namePair[0] !== ""){
// Reset the cookie subpath with new expiration date
// to force the browser cache to delete it.
var pathname = location.pathname.replace(/\/$/,'');
if (pathname !== '') {
pathname = "path=" + pathname + "; ";
document.cookie = nameString + pathname + expiresString;
alert('Final Cookie1:\r\n ' + nameString + pathname + expiresString);
}
// Reset the cookie rootpath, same as above.
document.cookie = nameString + "path=/; " + expiresString;
alert('Final Cookie2:\r\n ' + nameString + "path=/; " + expiresString);
}
}
}
Better you can remove cookie from your list

Pass Authenticated Session In Another Request in ASP.NET

I am using ABCPDF.net to render my HTML to PDF pages, but I want to protect these using the current authenticated session. However, the request to get the HTML to render the PDF doesnt carry over the session, but creates a new one. I am using ASP.NET Membership, and passwigin the session ID and creating a cookie on the ASP.NET request.
var sessionId = HttpUtility.ParseQueryString(Url)["sid"];
if(sessionId != null)
{
doc.HtmlOptions.HttpAdditionalHeaders = string.Format("Cookie:
ASP.NET_SessionId={0}", sessionId);
}
I read this in ABCPDF.net documentation and am doing just that, but the request always uses a different session.
httpadditionalheaders
Do I need to pass something else, or can I do something else?
Fixed it by sending the auth cookie in the URL, and updating the cookie.
Url To Call
Url.ActionAbsolute(MVC.Events.Pools(eventId).AddRouteValue(FormsAuthentication.FormsCookieName, Request.Cookies[FormsAuthentication.FormsCookieName].Value)
Global.asax
protected void Application_BeginRequest()
{
try
{
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[FormsAuthentication.FormsCookieName] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[FormsAuthentication.FormsCookieName]);
}
else if (HttpContext.Current.Request.QueryString[FormsAuthentication.FormsCookieName] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[FormsAuthentication.FormsCookieName]);
}
}
catch
{
}
}
void UpdateCookie(string cookieName, string cookieValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);
if (cookie == null)
{
cookie = new HttpCookie(cookieName);
HttpContext.Current.Request.Cookies.Add(cookie);
}
cookie.Value = cookieValue;
HttpContext.Current.Request.Cookies.Set(cookie);
}

Persisting Session to DB

My architect is wondering why we need to persist each user's session to the DB instead of just using cookies. I have never seen anyone use just cookies.
Usually I hold the Session Id in a cookie then use it to perform CRUDS on the session record keyed off the ID.
I mean I don't see how you can do session state without in proc. I've always done session state via a custom table holding routine fields like IsLoggedIn, IsClosed, IsNew, IPAddress, Browser, and so on.
Has anyone done session state on an e-commerce site without persisting it in a DB?
UPDATED
So here is kinda how we did things at another place I worked for an e-commerce site that got 500+ page hits a month:
public USession CreateNewSession(int userID)
{
string ipAddress = GetCurrentRequestIPAddress(context.Request);
USession newSession = USession.NewSession();
newSession.IpAddress = ipAddress;
newSession.UserID = customerID;
newSession.Browser = context.Request.UserAgent ?? string.Empty;
if (context.Request.UrlReferrer != null)
newSession.Referer = context.Request.UrlReferrer.ToString();
else
newSession.Referer = string.Empty;
InsertSession(newSession);
return newSession;
}
public USession CreateNewSession(int userID)
{
string ipAddress = GetCurrentRequestIPAddress(context.Request);
USession newSession = USession.NewSession();
newSession.IpAddress = ipAddress;
newSession.UserID = customerID;
newSession.Browser = context.Request.UserAgent ?? string.Empty;
if (context.Request.UrlReferrer != null)
newSession.Referer = context.Request.UrlReferrer.ToString();
else
newSession.Referer = string.Empty;
InsertSession(newSession);
return newSession;
}
public USession GetSession()
{
// existing sessionId this session?
HttpCookie cookie = context.Request.Cookies["usessionId"];
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
session = CreateNewSession(0);
else
{
string sessionID = cookie.Value;
session = GetSession(sessionID);
if (session == null)
session = CreateNewSession(0);
else if (session.IsClosed > 0)
session = CreateNewSession(session.UserID);
}
if (session.LastAccessed < DateTime.Now.AddHours(-1)) session.LoggedIn = false;
if (session.LastDestination.Equals("lesson"))
session.LastDestPageDestinationID = ContextValue(context, "lessonid");
else
session.LastDestPageDestinationID = 0;
if (session.IsNew) session.FirstDestination = session.LastDestination;
SaveSession();
return session;
}
private void SaveSession()
{
session.LastAccess = DateTime.Now;
session.LastDest = string.Empty;
db.UpdateSession(session);
if (!cookieIsSet)
{
// add a session cookie for this current session
HttpCookie cookie = CreateSessionCookie("usessionId", session.SessionID, 365);
if (session.LastDest.Equals("logout", StringComparison.OrdinalIgnoreCase))
cookie.Value = string.Empty;
if (session.LastDest.Equals("lessonOrder")) return;
context.Response.SetCookie(cookie);
}
}
internal void UpdateSession(USession s)
{
using (ourConnection conn = CreateConnection("UpdateSession"))
{
conn.CommandText = #"update csession set
closed = #closed,
userID = #customerID,
lastAccess = #lastAccess,
lastDestination = #lastDest,
orderId = #OrderId,
IsloggedIn = #isLoggedIn;
conn.AddParam("#id", s.Id);
conn.AddParam("#closed", s.Closed);
conn.AddParam("#userID", s.UserID);
conn.AddParam("#lastAccess", s.LastAccess);
conn.AddParam("#firstDestination", s.FirstDestination);
conn.AddParam("#lastDestination", s.LastDestination);
conn.AddParam("#isLoggedIn", s.IsLoggedIn);
conn.AddParam("#orderID", s.OrderID);
try
{
conn.ExecuteNonQuery();
}
catch (Exception ex)
{
LogException(ex);
}
}
}
public HttpCookie CreateSessionCookie(string cookieValue, string uSessionID, double daysTillExpiration)
{
HttpCookie cookie = new HttpCookie("usessionid", uSessionID);
cookie.Expires = DateTime.Now.AddDays(daysTillExpiration);
cookie.Path = "/";
return cookie;
}
So we'd work with the USession custom object in memory throughout our code for checking for loggedIn, to force close their session, and all sorts of stuff based on their current session.
Also in our Application_Error in global.asax we would log the current sessionId for tracking purposes on error.
HttpCookie cookie = Request.Cookies["usessionid"];
if (cookie != null)
{
logger.Variables = "<b>uSessionID:</b> " + cookie.Value;
if (cookie.Value.Length > 0)
logger.USessionID = GetUSessionID(cookie.Value);
}
The ASP.NET session has 3 possible states:
Off (my preferred) - don't use any session at all
InProc - the session is stored in the memory of the web server. Fast, but not convinient if you are running in a web farm because each node of the web farm will have a different copy of the session and you might get conflicts.
Out-of-Proc - the session is stored in memory of a specially dedicated server running the ASP.NET Session state Windows service. Good for webfarms scenarios but not reliable enough as the session is still persisted in the memory of some server which might not survive crashes.
SQL Server - the session is persisted in SQL server. Very reliable and suitable for web farms. Problem is with performance. It will be slower than the previous modes as the session is now persisted in the database.
The 3 modes are covered in depth in the following article.
The mode you choose is configured in web.config and it is completely transparent to your code in which you simply use the Session["someKey"] to work with the session, it's just the underlying storage mechanism that differs.

asp.net system variable?

Is it possible to set a variable in the system which is not for each user unique?, who access the page?
Ex.
I access the page and in codebehind something like that:
// create variable over all
if (sysstring != null || "")
SystemString sysstring = DateTime.now;
So if another user already accessed the page, I receive the value of the date when he accessed the page.
Thank you
You're looking for Application scope:
string lastAccess = (DateTime)Application["lastAccess"];
Altho this will reset with every app recycle. I would suggest storing it in a DB, which is where all cross-user variables should be!
You can use the Application object:
HttpApplicationState app = this.Context.Application;
DateTime myValue = null;
app.Lock();
try
{
myValue = (DateTime)app["key"];
if (myValue == null)
{
myValue = DateTime.Now;
app["key"] = myValue;
}
}
finally
{
app.UnLock();
}
Why not just make this static?
static string sysstring;
if (string.IsNullOrEmpty(sysstring))
sysstring = DateTime.Now;
As 'Loren said, just about anything other than storing this in the database will be lost when the app recycles.

How to get SessionID on a request where EnableSessionState="False"

I want to be able to get the SessionID of the currently authenticated session in a WebMethod function where EnableSession = false.
I cannot set EnableSession=true on this request, because another (long running) request on a different page is keeping the SessionState locked (EnableSessionState == "True" not "Readonly").
Is there a consistent way of getting the SessionID from either the ASP.NET Session cookie or the Url for cookieless sessions? I can code it myself but I would rather use a function that is already documented and tested.
Thank you very much,
Florin.
There seems to be no ASP.NET function that can do this, so I made up a hack of my own, which works... for now ;):
private string GetSessionID(HttpContext context)
{
var cookieless = context.Request.Params["HTTP_ASPFILTERSESSIONID"];
if (!string.IsNullOrEmpty(cookieless))
{
int start = cookieless.LastIndexOf("(");
int finish = cookieless.IndexOf(")");
if (start != -1 && finish != -1)
return cookieless.Substring(start + 1, finish - start - 1);
}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
if (cookie != null)
return cookie.Value;
return null;
}
HttpContext.Current.Session.SessionID

Resources