.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Easy Web
Imran Ghani
Post New Web Links

How to check if session is null or not in C#

Posted By:      Posted Date: October 25, 2010    Points: 0   Category :ASP.Net
 

Hello

 Like to know the syntax to check Session is null or not in C#

Could be something like this....

if(Session["mysession"] == null)

{

Do something

}

else

{

Something

}

Regards,

 




View Complete Post


More Related Resource Links

How to check for null/empty strings on dynamic objects?

  

What is the proper way to check for null or empty strings on dynamic objects? This is the only solution I've found so far:

if (admin.PasswordHash.GetType() == typeof(DBNull) || admin.PasswordHash == string.Empty)

If the field is null, the object returned is DBNull.Value, but if the field is empty string, it's return as a System.String object. This makes it impossible to do regular "admin.PasswordHash == DBNull.Value" check, as that will fail whenever the field has been set to empty string. Is my example the right (and only) way to go?


how to check one time java script file download not every session

  
how to check one time java script file download not every session

how to redirect user to login page if session is null

  
i have 2 page,1.login.aspx ---  2.welcome.aspxin my login.aspx im storing username into sesssion as below:Session["usernm"] = txtUsername.Text;in my welcome.aspx  pagein page_load event if (Session["usernm"]==null)        {            Response.Redirect("Login.aspx");        }----- here if i manulally paste the url ( http://localhost:4125/Loginado/welcome.aspx) it should go to  login.aspx for user credentialsbut its going directly to welcome.aspx  page.

SSRS 2005 + Null check box + change Label 'NULL'

  
Hi, My management asked me if I can change the label of NULL check box for report parameters. They said that users may not understand 'NULL' label means. Is it possible to do. When I searched, some said it can be done by creating custom control and registering it in GAC etc. I appreciate your response. Thanks, Spunny

Check session timeout and warn user before timeout

  

I know there are several articles explaining how to warn the user before their session times out, but so far none of them have worked for our scenario, so I'm hoping someone here will be able to help me figure this one out...  Here's what we've got:

Our application uses SQLServer to store session state.  We've got it set to timeout in 60 minutes.  Unfortunately (I fought hard against this, but lost the battle) our application uses popups for several major screens.  So tracking the session timeout on the client side doesn't really work, because I have no idea what window the user is in at any given point.  I've tried the solution where you inject Javascript into the page using the current session timeout on each request, but again, because the user could be actively using the application in a different window, it doesn't work for us.  So I guess I have a couple key questions:

  1. Is there any way to get the timeout for a session without triggering a request to the server, which would just renew the session?
  2. Is there a way to track the session timeout value across multiple windows? 
    I believe there is a limit to the number of "branches" the main window can have in our app.  In other words, the user can only be 2 levels deep from the main/root window, s

HTTPContext.Current.Session is NULL in SharePoint 2007 (MOSS)

  

For some strange reason HTTPContext.Current.Session is null in SharePoint 2007 web application.

Session is enabled everywhere and used to work so its not a setup issue. Something got corrupted at some point either via patches or something...

Doing "Reset To Definition" fixes the issue, but I can't do that in production environment and what is reset to definition has to do with session being null?

Searching on the web found a post from someone having same exact issue:

http://spbartnet.wordpress.com/2010/05/26/session-state-behaving-strange/

I need to know how to FIX this w/o doing complete "Reset To Definition".


Check for session in master page before child page

  

I have a site which has restricted access.  Access is controlled via session variables.
 
There are a lot of pages to the site so I was going to check for the session variable via the page load event in my mater page.  However, on certain pages I use the session variable in that pages page load event.  This throws an error when the session doesn't exist, but what I want is the master page's page load to fire first.

Does anyone know how I could achieve this?


Session returns null

  

on page load im Assigning a table to session["Tb"]

on changing dropdown i hv to change gridview but thr session["Tb"] returns null...

Could anyone help me to solve tis 

 


SQL CE 3.5 Null Parameter Check

  

Hello,

I cannot find a definitive answer for a very simple question. In SQL CE 3.5, I am attempting to execute the following:

            using (var connection = new SqlConnection(""))
            {
                connection.Open();

                using (var command = connection.CreateCommand())
                {

                    command.CommandType = CommandType.Text;
                    command.CommandText = "Select * From County Where CountyId = Coalesce(@Id,3)";
                    var dbParameter = command.CreateParameter();
                    dbParameter.ParameterName = "@

C# How to check prammatically if null value exists in database table (using stored procedure)?

  
Folks!

How to programattically check if null value exists in database table (using stored procedure)?

I know it's possble in the Query Analyzer (see last SQL query batch statements)?

But how can I pass null value as parameter to the database stored procedure programattically using C#?

Although I can check for empty column (the following code passes string.Empty as parameter but how to pass null value?), I cannot check for null value in the following code snippet:

SQL Queries:

USE [master]
GO

IF EXISTS (SELECT name FROM sys.databases WHERE name = 'ExampleDatabase')
DROP DATABASE [ExampleDatabase];
GO

CREATE DATABASE [ExampleDatabase];
GO

USE [ExampleDatabase];
GO

IF EXISTS (SELECT NAME FROM SYS.TABLES WHERE NAME = 'ExampleTable')
DROP TABLE dbo.ExampleTable;
GO

CREATE TABLE
dbo.ExampleTable
(
ID INT IDENTITY(1,1) NOT NULL,
UserID INT NULL,
Name NVARCHAR(50) NULL,
DateOfBirth DATETIME,
IsActive BIT,
Phone NVARCHAR(50) NULL,
Fax NVARCHAR(50) NULL,
CONSTRAINT PK_ID PRIMARY KEY(ID),
CONSTRAINT UNIQUE_Phone UNIQUE(Phone),
CONSTRAINT FK_UserID FOREIGN KEY(UserID) REFERENCES ExampleTable(ID),
CONSTRAINT FK_Fax FOREIGN KEY(Fax) REFERENCES ExampleTable(Phone)
);
GO

INSERT INT

Where to check the "Session Timeout"

  

Hi all,

this is my situation: I have a master page and in the contentPlaceHolder I have a MultiView in wich I load all my pages (I have a left-side menu, and when I click on it the system load the relative view of the MultiView).

The problem now is how (and where!) to check the session timeout. I would like to comunicate to the user when the session is finished (the timeout is set in my web.config file). Where can I check the session time out?

In the MasterPage I can't, because the master page is loaded only one time, and not when I show the views.

When I click on the menu? It's very strange... I have to insert the check in every menu, and in every page where there is a call to load a page... impossible I think!

So, how can I do?

Thanks.

Igor

 


How do I check if my ExecuteScalar() is null?

  

Hi all,

I know for a fact that the SQL statement below returns NULL but my code statement "if (obj != null)" is not working.
When I debug it I see a value of {} ... not sure what that is. Here is my code:

protected string GetLatestTimeStamp()
{
	DateTime latestTimeStamp1 = DateTime.UtcNow;
	string latestTimeStamp2 = String.Empty;

	string select = "select max(timeStamp) from dbo.JobHistory";

	SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
	SqlCommand cmd = new SqlCommand(select, conn);

	try
	{
		cmd.Connection.Open();
		object obj = cmd.ExecuteScalar();

		if (obj != null)
		{
		latestTimeStamp1 = (DateTime)obj;
		latestTimeStamp2 = latestTimeStamp1.ToString("yyyy-MM-dd HH:mm:ss.fff");
                 	}
	return latestTimeStamp2;
	}
...etc

So, even if SQL returns NULL, it still validates obj as NOT NULL !!! :(

Any ideas? Thank you!


Check For Null Values

  

When using an Access database I had to check text fields for null (which is accepable in my program) withcode like this:

 

If IsDBNull(oData.dr.Item("Media")) = False Then cboMedia.Text = oData.dr.Item("Media")

I am converting my program to SQL Server and this 'Seems" no longer necessary and this line of code seems to work:

cboMedia.Text = oData.dr.Item("Media"<

Session["ret_url"] == null

  

Hi

if (Session["ret_url"] == null)
            {
                Response.Redirect("mypage.aspx");
            }
            else
            {
                Response.Redirect(Session["ret_url"].ToString());
            }

What is the real meaning of these lines

Regards

enquiry


Check for Null Value or Spaces

  

I would like to check field FirstName if it's a null field or if the field has spaces in it.

My FirstName field sometime is NULL or it has spaces in it.

I would like to check for those two scenario.

Thanks!


Check for Session Expiration

  

I have 4 session variables. I just need to check for one variable and see if it is timeout and make a database call to reload the variable. I am storing the user preferences in this session variable. this session variable will be null if that user has no preferences. so I cant use if(Session["userpref"] == null) to see if session expired.

 if (Session.IsNewSession) { }         - What does this do ? I have 4 session variables

Is there a way to find if this particular session variable is expired (timeout) ?


Using a CompareValidator to check input is a valid date

  
The CompareValidator can do more than just compare two controls. You can also compare it against several of the main .net data types such as Date, Integer, Double and Currency.

To do this you would set Operator="DataTypeCheck" and instead of setting the ControlToCompare or ValueToCompare attributes as you normally would you use the Type="Date" (or any of the data types I have listed above).
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend