Solved

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

Posted on 2012-04-12
19
5,382 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

705 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