Can one use sql query in default.aspx web application - c#

Can I use sql query and alter server url based on the sql query result?
If sql query gives value of 1, point the server to home.aspx and if the sql query gives value of 0, point to home2.aspx?
I am trying to show different person different homepage based on a specific associated value in sql database.
Thank you
p.s. I honestly dont know how the log in works. I am not a .net guy and didn't create the system. I know about URL direct for the server in default.aspx because I have been through that. there is singlesignon settings applied on the website so when a user logs into the lets say web A, he/she can click on a hyperlink, it will pass the encrypted user login info and the user will automatically be on the home page of website b (log in page for website B is skipped). I will update my acceptance rate.
Thank you
p.s. 2: I am just trying to pull the INCOMING user's active flag from a column in a table in a sql db. If the flag for that particular user is set to 1, point them to URL A, if flag is set to 0, point them to URL B.
Thank you

You can redirect doing that but you should not! Why? Well, calling the DB every time a visitor comes will make your response time way long to wait. What you can do is cache the result on memory or at least disk (using a B+ tree for example) or better to provide a common homepage and then redirect.
Now, once you identify a user set say a cookie for the redirection and for so on use the cookie (don't forget it to authorize if needed), that'll speed up things.
Go ahead and take a look to personalization and user profiles on ASP.NET which is what you want to do.

Randolf's comments are true. But in order to do what you want, if you for some reason still want to do this, you'll want to look at Server.Transfer() (more efficient, and preferable if you are redirecting to another page that's on the same server, within the same app), or Response.Redirect().

Related

change loginpath for specific user, ASP.Net, webforms

I recently started working on a site that another developer built (who is not within the company anymore, so can't ask him)
On the site there is several separate accounttypes for users, so when a user logs in, the user comes to one of two specified login-start pages.
Some users have two accounttypes. When that's the case I want to make a dropdownlist that holds both startpage-options (let's call them a, and b)
If they choose option a) from the ddl, the a-startpage will be that users permanent startpage until the user changes it to b, then b will be that specific users permanent startpage.
the project is made with C#, ASP.NET, with Webforms, MS SQL.
any suggestions that might lead me in the right direction is much appreciated
/S
there are at least 2 possible solutions that require little effort:
a cookie on the user's system: when accessing the system for the
first time (or after a system change or a browser's cookies clearing)
the application takes the user to the dropdown page and let the user choose the
preferred login-start page. on subsequent accesses the choice is read from the cookie and then the user is forwarded to the expected page. the biggest advantage IMHO is that no changes to the backend structure are required and the changes on the fronted are minimal.BEWARE: do not trust what you get
reading the cookie and always double check that the page suggested
by the cookie is actually allowed for the user.
an attribute of the user: the user choice is saved in the user's profile and read on subsequent accesses.this approach requires some change in the backend because a new attribute must be added to the user entity and maybe also the tools (stored procedure, method, whatever) needed to interact with that new attribute have to be created.this solution requires less or no checks/validation because the information is stored server side so you can redirect 'blindly' to the login-start page.
there is not a 'right' solution because it mainly depends on what you are allowed to do and your skills.are you allwed to alter the backend's structure? what you know better, backend or frontend development?which one is easier for you to change? is there any policy/guideline to follow while developing that favor one of these approaches?
So in the end i solved it like this.
Firstly i created an int(allows null) column called "changesite" in the db (member/user)table so i could use the members id.
Then i connected it to the dropdownlist where the members/users can choose their startpage (in my case i made the ddl only visible to the members if they are the type of user that has the both user accounts).
if the user chooses the first option a 1 got saved in the db, and for the second option a 2. (This method could be used with any number of startpages you might have).
Then in .cs file were users got redirected to their designated startpage it was as simple as creating an if, else-statement, with the value from changesite as identifier.
Basically if the value from column changesite == null, do nothing. If changesite == 1 redirect to the first startpage and else redirect to the second startpage.
A big thx to Paolo for his inputs.

Add session variable to inbound and outbound URLs

I'm designing a site using ASPx and IIS, where clients can sign up and then offer services to their clients. For example:
if you go to http://www.mywebsite.com you can sign up for your mywebsite.com account as a business owner. When you sign up, you are given a Site ID (Example: AA1234).
http://www.mywebsite.com/AA1234
What I want to do is always include the Site ID in every url (Inbound and Outbound). The Site ID is stored in a session variable based on the initial incoming request.
Does anyone know of a good way to do this - or a different design that works better than this?
Thanks
Your question is nebulous at best. However...
Wouldn't this be what cookies are used for?
In particular, if your user is authenticated (this is generally achieved in asp.net with an auth cookie), then at the server, you would have tools at your disposal that allow you to recognize the user and provide a different experience according to whatever criteria you choose. Most likely, these details might be stored in a database.
Found the answer in this topic: http://www.tek-tips.com/viewthread.cfm?qid=1149673
The last response from BoulderBum is exactly what I needed.
Using the HTTP module I will take the /AA1234/ URL and point it to /Company/.
On the way out, I replace all instances of /Company/ with the site id again

Prevent expiration of individual sessions based on custom conditions?

A website I am working on is very data centric. Some reports take more than an hour to complete. Whenever a user submits a request for a report, a new thread is created which generates the report. The user is then redirected to a page which says that the report in progress, and to please refresh to download the report. If the user again refreshes the page and the report is still in progress, the same message is shown; otherwise a download link is provided.
All report/user relations are saved in the application variable. That works fine, except when the user is inactive for more than 20 min (while the report is being processed), and then the user is logged out; if the user logs in again, the report can still be downloaded.
I do not want to increase the session expiration time, but I need to stop the expiration if the user has something going in background, like a report being processed.
In Session_End I am able to retrieve the the userid and match it in Application["work"] to see the user has pending work or not.
However, I am clueless as to how I can defer the session end in the above case?
Edit: Every one has suggested as a workaround from 'maintaining a contact' to 'using query string'. 'Maintaining the contact' looked the most promising to me but it fails in the following scenarios: a. When browser is closed/computed goes in standby mode during lunch, etc. b. When user goes to another non-asp.net section (it's a legacy site).
Isn't It possible to cancel the Session_End event itself?
The short answer
There is currently (that I know of) no simple way to extend the life of a single ASP.NET session. There is one possible solution: use a custom Session-State Store Provider!
The long answer
First things first: Start with something that is already built! Use the sample Session-State Store Provider (and its tutorial) provided by Microsoft. This sample Session-State Store Provider uses Microsoft Access as its back end; although, because it uses ODBC connections, you can have virtually any database back end supported through your installed ODBC drivers.
This sample Session-State Store Provider is simply a custom version of what ASP.NET uses internally (with the exception that ASP.NET's runs in-memory).
Secondly: Let's prepare the Access Database requirements, and the configuration.
Create the table as specified in the tutorial and in the comments of the file:
CREATE TABLE Sessions
(
SessionId Text(80) NOT NULL,
ApplicationName Text(255) NOT NULL,
Created DateTime NOT NULL,
Expires DateTime NOT NULL,
LockDate DateTime NOT NULL,
LockId Integer NOT NULL,
Timeout Integer NOT NULL,
Locked YesNo NOT NULL,
SessionItems Memo,
Flags Integer NOT NULL,
CONSTRAINT PKSessions PRIMARY KEY (SessionId, ApplicationName)
)
NOTE: If you want to use SQL Server, simply replace Text(...) with varchar(...), YesNo with bit, and Memo with varchar(MAX).
Add/update your web.config with the following (you can use connectionstrings.com to help you generate a connection string):
<configuration>
<connectionStrings>
<add name="OdbcSessionServices" connectionString="DSN=SessionState;" />
</connectionStrings>
<system.web>
<sessionState
cookieless="true"
regenerateExpiredSessionId="true"
mode="Custom"
customProvider="OdbcSessionProvider">
<providers>
<add name="OdbcSessionProvider"
type="Samples.AspNet.Session.OdbcSessionStateStore"
connectionStringName="OdbcSessionServices"
writeExceptionsToEventLog="false" />
</providers>
</sessionState>
</system.web>
</configuration>
Third: Adding a function that will extend for more than the specified Timeout.
Make a copy of the ResetItemTimeout function, and name it ResetItemTimeout2:
var ExtendedTotalMinutes = 2 * 60; // hours * minutes
public override void ResetItemTimeout2(HttpContext context, string id)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd =
new OdbcCommand("UPDATE Sessions SET Expires = ? " +
"WHERE SessionId = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value
= DateTime.Now.AddMinutes(ExtendedTotalMinutes); // IMPORTANT!! Set your total expiration time.
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "ResetItemTimeout");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
Fourth: Supporting the extension of a single ASP.NET Session!
Whenever you need to extend a session, call the ResetItemTimeout function as follows:
using Samples.AspNet.Session;
// from inside a User Control or Page
OdbcSessionStateStore.ResetItemTimeout2(this.Context, this.Session.SessionID);
// --or--
// from anywhere else
OdbcSessionStateStore.ResetItemTimeout2(System.Web.HttpContext.Current, System.Web.HttpContext.Current.Session.SessionID);
Footnotes
Read the comments on the page with the sample Session-State Store Provider;
There is one potential good entry about a Mistake in GetSessionStoreItem when using GetItem.
Another good one is that Timestamps should be UTC.
There are obvious performance/maintainability improvements that could be done (especially with having duplicate code in ResetItemTimeout and ResetItemTimeout2).
I have not tested this code!
Edits
I realized I missed the part where you want to extend more than the Timeout - answer has been fully updated.
Added footnotes section.
Maintain a contact with the server will avoid Session Timeout.
Create a empty Web service and run that in your server then call the web service by your site by JQuery by the interval of some seconds is enough to keep the session alive
May be this solution will help you..
Try this link for full details : Prevent Session Timeout in ASP.NET
While desperately looking for defering the session_end event I think it seems impossible?
The easiest work around that I was able to come with was 'Using Cookies' and modifying my authentication logic.
I implemented a method for writing a guid key to the cookie named admin when ever user requested for the report with expiration of 9 hour(Max time office will be open for work).
I save this guid with user id in a seperate table.
In the master page where i was checking for session userid I implemented another method to check for any cookie named admin. If it is found i set session to the user id saved in table else i redirect them to login page as before it was happening.
It seems to work like magic. But I need to know is this a right thing?
What you can do is set the Session timeout to a higher value when you detect that a report has been requested that will take a long time. This of course supposes that you can calculate whether a report will take a long time to run. If so, you can do this before you kick off the thread:
Session.Timeout = 120 // set timeout to two hours for this session only
Apart from pinging a page or service through Ajax, there really is no other way. (unless not relying on sessions at all is an option).
This is because of the way sessions are maintained: the ASP.NET runtime detects a session when the request contains a cookie. This cookie is set at every request / response and will contain an expiration date.
If in your initial request you set an expiration of 20 minutes and the user closes the browser or is inactive for more than 20 minutes there is no way on the server side you can detect which session the request belongs to.
So, to answer your question whether you can cancel the session_end, no you cannot do that as that code runs server side and it cannot access the client cookie. It's a simple event that is fired twenty minutes after you last set the cookie. This is completely asynchronous from the client-side.
The solution I proposed is a workaround that could work if you know how to calculate the duration (at least approximately).
Another solution, but way more complicated, would be to save the reports and make a separate section for the user where he can see all his reports. That way, even if the session times out, he can log back in and go to his history and retrieve the report.
It's best not to rely on Session_end as it doesn't always fire, such as when the worker process recycles or an uncaught exception occurs, i.e. it is basically killed / bounced.
If you want to revive a session then it seems that the best way is to store the user data somehow and totally manage the cache yourself.
It seems from your reply to previous posts that the additional network activity and subsequent page time load increase when using sql state management are unacceptable, and the difference between using sql server state provider to using a session server such as Microsoft AppFabric would be negligible, however it seems a distinct possibility that if you were to use the session server of AppFabric coupled with it's caching, things could be sped up a lot.
P.S. In general doing away with sessions would seem like the most efficient solution, see John Han's answer in this post just about sums it up sessions are bad mmkay.
In order for a session to stay alive, something (not necessarily the user's browser) has to make a request to your app with that user's ASP.NET_SessionId cookie every so often.
What if you had some code that saves the ASP.NET_SessionIds of the users you are interested in, and then have a windows service that requests a page on your app with the required ASP.NET_SessionId(s) every 20 minutes or so.
see http://erlend.oftedal.no/blog/?blogid=41 for some info about this cookie
Are you using FormsAuthentication? If so, you could increase the timeout for the authentication ticket, which will prevent the login screen even after the session has expired.
At the beginning of the request you could check the user through the ticket
After get the user if the session is null it means the user has been offline for while, you the can check the work in progress for that user.
If the user has a work in progress, load session values that you might need it and redirect them to the work in progress or report to download.
If the user has nothing, expire the ticket and redirect them to login page or just keep them logged in and reload session values.
The timeout for the authentication ticket is pretty big
http://msdn.microsoft.com/en-us/library/system.web.configuration.formsauthenticationconfiguration.timeout.aspx
Cheers
I'd suggest increasing the session timeout instead of trying to find a way around it. There's an interesting thread about session and form timeouts here
I suggest that you don't depend on sessions at all .. you can depend on the query string by adding a new GUID variable and use that variable value with the application object to map the user requested file(s) with the GUID value .. this way .. the user will always be able to download the file since he have the link to the file that is mapped to the application object and no need to handle any session timeout.
Why do not you try to show the loading file progress bar and inside that one you can use the logic of checking status of file downloaded so far. It will have two advantage , as you are hitting your website , Session will not expire at the same time you are giving the useful information back to end user.

Redirecting Issues

Let's say I have a website www.mysite.com and I want it to be a multilingual site. Following are the things I wanna achieve :-
1. When a user visits my website, I want to fetch the user's country's ISO code. Let's say the ISO is "FR".
Now I want the user to be redirected to www.mysite.fr
In case the ISO address can't be fetched, the user will be redirected to www.mysite.com
Now I have used the dll from this site http://ipaddressextensions.codeplex.com/ and used their method which is something like
iso3066code(). BUT I am not able to fetch ISO code based on a user's IP address. What is the best method to fetch the ISO code anyway??
2. I have a differenet master page for different countries. Like for France there is France.master, for Germany there is Germany.master, etc.
What I want is that firstly the ISO Code of the user should be fetched, then the user should be redirected to the site corresponding to the ISO
AND want the corresponding master to load.
Here's a scenario:-
A user from France opens my website by typing "www.mysite.com". Now I want to show the user my site's contents in French so I want him to be redirected to
"www.mysite.fr" AND want the France.master to load for all the pages. What I am doing is check the "Top level domain name" entered by user which is "com" in this case, then I fetch the ISO code
then if ISO exists, user is redirected to "www.mysite.fr"
IN CASE, ISO cant be fetched , "www.mysite.com" will only be opened for the user.
3. How do I redirect the user?? Response.Redirect("http://www.mysite.fr") is failing and giving errors like :-
"Page is not redirecting properly" I tried changing it to Response.Redirect("http://www.mysite.fr", false)
and Response.Redirect("http://www.mysite.fr", true). This didn't work.
4. www.mysite.com and www.mysite.fr aren't two different websites.Just that when is it www.mysite.com, English content will be shown on the website.
When it is "www.mysite.fr", French content can be seen inside the website.
What I did was :-
In the Global.asax file :-
I tried fetching ISO code using that dll above from the site ipaddressextensions. Then I created this Application("UserISO") variable in Global.asax file.((Is this a good approach?))
I needed to make it because I wanted to use this global variable within my Global file itself..In some user defined method.
Then I am setting master page name in a cookie and using this cookie to change master page dynamically for every content page in the Page_PreInit() event.
and lastly I am redirecting the user with " Response.Redirect("http://www.mysite.fr", false)". This response.redirect doesnt work!
Now, AM I on the right path?? I am super confused over how to actually make it work! :(
How do multilingual site redirect their users? Where can I learn about all this ? I have tried and tried and tried but this just won't work!
Lastly, there are not really any domain names set for the site as of now. Running it using the IP address set in the IIS.
So how do I test my site. How do I really go about it. Am I following the correct approach at all??
Please direct me to the right path. ANY help will be greatly appreciated. Thanks!
Belgium has 3 official languages, you can't find my language by just looking at the ip address or the domain.
The best way to find the language of a visitor is to check the language of his browser. You can find it in Request.Userlanguages.
Don't do this. It's really frustrating when you try to assume what language the user speaks. You're bound to get it wrong for someone eventually. Put some small flag icons or the language name choices on your main page in a highly visible place, and let your visitors chose what site/language they want to browse in.
Facebook's main sign in page is a great example of this.
Edit: The best you could probably do is to use the HTTP1.1 Header Accept-Language as a hint, but even then I think you should push back on this requirement of your project.
You get redirect error because the .fr site is probably the same site as .com, but session cookies are only valid for a certain domain which means that Session_OnStart() is invoked on the redirect as well. One way to circumvent this is to override the redirect/ip-lookup somehow, maybe send in a querystring or a specific landing page that you can identify:
www.site.fr/?overrideredirect=true
www.site.fr/redirected.aspx -> which then redirects back to / after Session_OnStart
In order to choose the right master page, you could probably identify which host that was requested and from that override master page in your global.asax, perhaps in the BeginRequest event.

Request.UrlReferrer null?

In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page A (the page the user wants to view) redirect to page B (the login page), the Request.UrlReferrer object is null.
Background: If a user isn't logged in, I redirect to the Login page (B in this scenario). After login, I would like to return them to the page they were requesting before they were forced to log in.
UPDATE:
A nice quick solution seems to be:
//if user not logged in
Response.Redirect("..MyLoginPage.aspx?returnUrl=" + Request.ServerVariables["SCRIPT_NAME"]);
Then, just look at QueryString on login page you forced them to and put the user where they were after successful login.
UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
UPDATE: As mentioned in the comments, it is probably a good idea to restrict the redirect from the GET parameter to only work for domain-less relative links, refuse directory patterns (../), etc. So still sanity check the redirect; if you follow the standard "don't use any user-supplied input blindly" rule you should be safe.
If you use the standard Membership provider, and set the Authorization for the directory/page, the code will automatically set a query parameter of ReturnUrl and redirect after a successfull login.If you don't want to use the Membership provider pattern, I would suggest manually doing the query string parameter thing as well. HTTP referrers are not very reliable.
The problem could be related on how you redirect the user to some other page. Anyways, the referer url is nothing you should take as absolute rule - a client can fake it easily.
What you're looking for is best done with a query string variable (e.g. returnURL or originURL). Referrer is best used for data mining operations as it's very unreliable.
See the way ASP.Net does redirection with logins for an example.

Categories

Resources