Solved

HttpContext.Current.Session - Object reference not set to an instance of an object

Posted on 2012-04-12
19
4,883 Views
Last Modified: 2012-06-27
I have a minimal working test application that uses globalisation and the contents of the URL to load specific resc files. This is all working fine and the code is below.

WEB.CONFIG
------------------------------------
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
      <customErrors mode="Off"/>
  </system.web>
</configuration>


GLOBAL.ASAX
-------------------------------------
<%@ Application Language="VB" %>

<script runat="server">

	Protected Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As System.EventArgs)
        If HttpContext.Current.Session("MRMCStore_Brand") Is Nothing Then
            'set default values
            HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
            HttpContext.Current.Session("CultureChoice") = "en-GB"
            
            If InStr(Request.Url.AbsoluteUri, "somevalue") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "de-DE"
            ElseIf InStr(Request.Url.AbsoluteUri, "somevalue2") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "es-ES"
            ElseIf InStr(Request.Url.AbsoluteUri, "somevalue3") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "en-GB"
            Else
                HttpContext.Current.Session("MRMCStore_Brand") = "mrmc"
                HttpContext.Current.Session("CultureChoice") = "en-GB"
            End If
        End If
        
        If HttpContext.Current.Session("CultureChoice") Is Nothing OrElse HttpContext.Current.Session("CultureChoice").ToString.Trim = String.Empty Then
            HttpContext.Current.Session("CultureChoice") = "en-GB"
        End If
        Dim cc As String = HttpContext.Current.Session("CultureChoice").ToString
        If cc <> String.Empty Then
            System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(cc)
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(cc)
        End If
    End Sub
	   
</script>



MASTER PAGE
----------------------------------
Partial Class MasterPage
	Inherits System.Web.UI.MasterPage

	Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim sURL As String = Request.Url.AbsoluteUri.ToLower
            Session("sURL") = sURL
        End If
	End Sub

	Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
		If DropDownList1.SelectedItem.Value <> String.Empty Then
			Session("CultureChoice") = DropDownList1.SelectedItem.Value
			Response.Redirect(Request.Url.AbsoluteUri, True) ' reload to re-initialize new culture (re-fire Pre_Init/Page_Load)
		End If
	End Sub

End Class



Default.aspx
-----------------------------------------
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            lblURL.Text = Session("sURL")
            Literal1.Text = Me.GetGlobalResourceObject(Session("MRMCStore_Brand"), "CompanyName").ToString
            'Literal1.Text = Me.GetGlobalResourceObject("mrmc", "CompanyName").ToString
        End If
    End Sub

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
	<h1>
		<asp:Literal ID="Literal1" runat="server" />'s Web Page.<br />
        <asp:Label ID="lblURL" runat="server" Text=""></asp:Label>
	</h1>
</asp:Content>

Open in new window


I duplicated this code to the actual website I need to use the globalisation on for a reason unknown to me I keep receiving this error on global.asax.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Line 5:          If HttpContext.Current.Session("MRMCStore_Brand") Is Nothing Or HttpContext.Current.Session("MRMCStore_Brand").ToString.Trim = String.Empty Then

[NullReferenceException: Object reference not set to an instance of an object.]
   ASP.global_asax.Application_PreRequestHandlerExecute(Object sender, EventArgs e) in D:\Websites\Test sites\MTMC-Store\global.asax:5
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +79
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +170

Open in new window


Anyone have any ideas why it works on my test app but not on the proper app?
0
Comment
Question by:swgdesign
  • 10
  • 6
  • 3
19 Comments
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 150 total points
ID: 37838213
Change
 If HttpContext.Current.Session("MRMCStore_Brand") Is Nothing Or HttpContext.Current.Session("MRMCStore_Brand").ToString.Trim = String.Empty Then

to
 If HttpContext.Current.Session("MRMCStore_Brand") Is Nothing OrELSE HttpContext.Current.Session("MRMCStore_Brand").ToString.Trim = String.Empty Then

MRMCSTore_Brand is probably initalied in the test app.

The orElse short Circuts the check and says if the first part of the condition is true assume the rest is true.


and becomes AndAlso which means only check the rest if I'm true, otherwise the entire statement is false.
0
 

Author Comment

by:swgdesign
ID: 37838360
Thanks for your suggestion I did try this before I posted, but it throws the same exception...

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

The only thing I can think that could cause this is my main app's web.config file, but I have no idea what would?
0
 

Author Comment

by:swgdesign
ID: 37838385
BTW it is not the line of coe that is the issue it seems, it is infact any session i try and test or create! If I change the erroneous line to

HTTPContent.Current.session("Blah") = "somevalue" it still gives me the same error message! :(

Why are my session not working?


my 'actual' web.config file...

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>        
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
        <section name="resizer" type="ImageResizer.ResizerSection,ImageResizer"  requirePermission="false"  />
	</configSections>
    <resizer>
        <pipeline fakeExtensions=".ashx" />
        <plugins>
            <!-- <add name="DiskCache" /> -->
            <!-- <add name="PrettyGifs" /> -->
        </plugins>
    </resizer>
	<system.web>
		<sessionState cookieless="false" mode="InProc" timeout="120" />
		<globalization uiCulture="en" culture="en-gb" />
        <httpRuntime maxRequestLength="409600" executionTimeout="600" />
        <compilation debug="true">            
            <assemblies>
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
				<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Speech, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
				<add assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
				<add assembly="System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.DirectoryServices.Protocols, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.EnterpriseServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
				<add assembly="System.Web.RegularExpressions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
    	    	    	<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /></assemblies>
		</compilation>
		<membership>
			<providers>
				<clear />
				<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
			</providers>
		</membership>
		<profile>
			<providers>
				<clear />
				<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
			</providers>
		</profile>
		<roleManager enabled="false">
			<providers>
				<clear />
				<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
				<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
			</providers>
		</roleManager>
		<pages enableSessionState="true" enableViewStateMac="false">
			<namespaces>
				<clear />
				<add namespace="Microsoft.VisualBasic" />
				<add namespace="System" />
				<add namespace="System.Data" />
				<add namespace="System.Collections" />
				<add namespace="System.Collections.Specialized" />
				<add namespace="System.Configuration" />
				<add namespace="System.Text" />
				<add namespace="System.Text.RegularExpressions" />
				<add namespace="System.Web" />
				<add namespace="System.Web.Services" />
				<add namespace="System.Web.Services.Protocols" />
				<add namespace="System.Web.Caching" />
				<add namespace="System.Web.SessionState" />
				<add namespace="System.Web.Security" />
				<add namespace="System.Web.Profile" />
				<add namespace="System.Web.UI" />
				<add namespace="System.Web.UI.WebControls" />
				<add namespace="System.Web.UI.WebControls.WebParts" />
				<add namespace="System.Web.UI.HtmlControls" />
				<add namespace="System.IO" />
				<add namespace="System.IO.File" />
				<add namespace="MRMCStore" />
    	    	<add namespace="System.Collections.Generic" />
                <add namespace="System.XML" />
                <add namespace="System.Linq" />
    	    	<add namespace="System.Xml.Linq" />
			</namespaces>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
				<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
    	    	<add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
			</controls>
		</pages>
		<httpHandlers>
			<remove verb="*" path="*.asmx" />
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
			<add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
			<add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
    	    	    	<add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
    	    	    	<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
		</httpHandlers>
		<httpModules>
            <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
		</httpModules>
        <customErrors mode="Off" defaultRedirect="~/404.aspx" />
	</system.web>
    <system.web.extensions>
        <scripting>
            <scriptResourceHandler enableCompression="false" enableCaching="true" />
        </scripting>
    </system.web.extensions>
	<!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
    <system.webServer>
		<modules runAllManagedModulesForAllRequests="true">
			<remove name="ScriptModule" />
            <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
		</modules>
		<validation validateIntegratedModeConfiguration="false" />
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated" />
			<remove name="ScriptHandlerFactory" />
			<remove name="ScriptHandlerFactoryAppServices" />
			<remove name="ScriptResource" />
    	    <remove name="ChartImage_axd" />
    	    <remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
    	    <remove name="Telerik_Web_UI_DialogHandler_aspx" />
    	    <remove name="Telerik_RadUploadProgressHandler_ashx" />
    	    <remove name="Telerik_Web_UI_WebResource_axd" />
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
			<add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
			<add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
			<add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
			<add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
    	    	    	<add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode,runtimeVersionv2.0" />
		</handlers>
        <defaultDocument>
            <files>
                <clear />
                <add value="default.aspx" />
                <add value="Default.htm" />
                <add value="Default.asp" />
                <add value="index.htm" />
                <add value="index.html" />
                <add value="iisstart.htm" />
            </files>
        </defaultDocument>
	</system.webServer>
	<system.codedom>
		<compilers>
			<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
				<providerOption name="CompilerVersion" value="v3.5" />
				<providerOption name="WarnAsError" value="false" />
			</compiler>
			<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
				<providerOption name="CompilerVersion" value="v3.5" />
				<providerOption name="OptionInfer" value="true" />
				<providerOption name="WarnAsError" value="false" />
			</compiler>
		</compilers>
	</system.codedom>
	<runtime>
		<assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" />
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
			</dependentAssembly>
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" />
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
			</dependentAssembly>
		</assemblyBinding>
	</runtime>
    <location path="__smtp_settings.xml">
        <system.web>
            <authorization>
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
</configuration>

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 37838401
It's coming from the global.asax file.  

I wonder if HttpContext is initialized at that point?

Try this:

 If HttpContext isnot nothing andalso HttpContext.Current isnot nothing andalso HttpContext.Current.Session isnot nothing then

   If HttpContext.Current.Session("MRMCStore_Brand") Is Nothing Then
            'set default values
            HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
            HttpContext.Current.Session("CultureChoice") = "en-GB"
           
            If InStr(Request.Url.AbsoluteUri, "somevalue") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "de-DE"
            ElseIf InStr(Request.Url.AbsoluteUri, "somevalue2") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "es-ES"
            ElseIf InStr(Request.Url.AbsoluteUri, "somevalue3") Then
                HttpContext.Current.Session("MRMCStore_Brand") = "mtmc"
                HttpContext.Current.Session("CultureChoice") = "en-GB"
            Else
                HttpContext.Current.Session("MRMCStore_Brand") = "mrmc"
                HttpContext.Current.Session("CultureChoice") = "en-GB"
            End If
        End If
       
        If HttpContext.Current.Session("CultureChoice") Is Nothing OrElse HttpContext.Current.Session("CultureChoice").ToString.Trim = String.Empty Then
            HttpContext.Current.Session("CultureChoice") = "en-GB"
        End If
        Dim cc As String = HttpContext.Current.Session("CultureChoice").ToString
        If cc <> String.Empty Then
            System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(cc)
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(cc)
        End If


end if
0
 

Author Comment

by:swgdesign
ID: 37838475
That fixed the issue but not properly as I now think my session("MRMCStore-Brand") is not getting any values as it is causing this error in one of my pages. This is not the correct fix I feel.

ltBreadcrumbs_Home.Text = GetGlobalResourceObject(Session("MRMCStore_Brand"), "Breadcrumbs_Home").ToString

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 37838600
The issue is that the session doesn't exist in Application_PreRequestHandlerExecute.

At minimum you need to move it to a different event such as Session_Start.     You can, however also put it in your master page load in the not page.IsPostback block.


Will still only fire once and is more easily "findable".


More about global.asax and the order of events:
http://en.wikipedia.org/wiki/Global.asax

Also note that the Session is not loaded by default for every request:  
http://stackoverflow.com/questions/4439737/session-is-null-in-prerequesthandlerexecute

Let me know if you still have issues.
0
 

Author Comment

by:swgdesign
ID: 37838635
I understand all that, But I strongly feel that this is not the issue as why does it work in my test application and not in my real world application. IF it was a syntax/execution order issue it would not work at all!
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 37838813
Check all of your IIS settings . . . make sure you have the default page set and all of that.  It could be the account or type of application pool.

I get what you're saying from the code should work in both places . . . but if it's not the code, it's got to be the settings.  Looking at the code though . . . it doesn't seem like it should work, at least not all of the time.

You using the same IIS version in both places?  Also same authentication schemes and what not?

If you do an IISrest in both places do you still get the same results?
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 350 total points
ID: 37839328
Session is available in PreRequesthandlerExecute, contrary to what others
have posted.

The problem is that your code is being executed for every request into the
server, and some requests (like ones for WebResourxe.axd) don't utlilize
Session (because the handler doesn't implement IRequireSessionState). So
change your code to only access Session if that request has access to it.
Change your code to do this:

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs
e)

{

if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
SetCulture();

}

http://www.velocityreviews.com/forums/t282576-asp-net-2-0-session-availability-in-global-asax.html
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:swgdesign
ID: 37841523
OK, if that fixes it, great. Could the difference be that my test app(works with global.asax sessions) is ASP.Net 4 and my actual app is asp.net 3.5 coded?
0
 

Author Comment

by:swgdesign
ID: 37841606
Unfortunately that just breaks the application even more as the session is never getting set now. :(

I need to understand why it works in my test application but not when the same identical code is copied to my actual web app...
0
 

Author Comment

by:swgdesign
ID: 37841754
CodeCruiser: Your solution similar to Geds first suggestion worked but caused issues when pulling out values from the .resx files as (I think) the sessions aren't being set.

Ged: The applications are on the same server. The only difference is the web.config files in that the test app is like 4 lines and my web app has hundreds of lines relating to assemblies and versions etc.

It is either asp.net version differences between the apps or web.config related.... I feel
0
 

Author Comment

by:swgdesign
ID: 37841766
CodeCruiser: this is the error I now receive after applying your logic;

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

 ltWebsiteTitle.Text = Me.GetGlobalResourceObject(Session("MRMCStore_Brand"), "somestringname").ToString

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   Generic.Page_Load(Object sender, EventArgs e) in D:\Websites\Test sites\MTMC-Store\Generic.master.vb:33
   System.Web.UI.Control.OnLoad(EventArgs e) +131
   System.Web.UI.Control.LoadRecursive() +65
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2427

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 37843776
At Minimum you need a different app pool and a different virtual directory.  

Though the fact you have a blank web.config might also have something to do with it.  Can you import the common items via copy and paste into the new web.config?  The assemblies may have to be updated as you're running the upgraded version.

And CC:

I said "The session is not loaded by default for every request."  I never said that it wasn't accessible in there, but that the precense is conditional based on the type of request, based on the url.  Please let me know if that's not correct.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37853681
@ged325

Note that I just quoted text from the link. I did not say that and I was thinking that people would be confused(into thinking that I am saying that) when I was posting :-)
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37853684
@swgdesign

That logic is just an IF statement. What else damage it could have done? not sure.
0
 

Author Comment

by:swgdesign
ID: 37854861
I don't know hence why I posted my issue here as I couldn't work out how to fix it. haha

The 2 applications use 2 seperate app_pools are totally seperate to one another. They have no relationships in any way.

I guess I'll have to slowly put all my code from my non working app into my blank web.config and see what happens!
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 37861763
Compare your app pool settings or better yet create a new one based on the template of the working one, then repoint to a different app pool (and also modifying the .net Version).  After that you can delete the other app pool if no other virtual directories use it.
0
 

Author Closing Comment

by:swgdesign
ID: 37861805
Thanks for everyone's help I got it all working using a mixture of if/else statements related to CodeCruiser and Ged's comments. Thanks Guys
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now