?
Solved

Session Variables Not Remaining

Posted on 2014-08-01
22
Medium Priority
?
226 Views
Last Modified: 2014-08-04
Hi,

Would could possibly be the reasons why when setting a Session variable in a button click event, when it hits the Page_Load the session variable is null meaning it does not appear to exist. The IsPortBack in the Page_Load is true. There is nothing in the web.config file regarding sessionstate or anything to do with sessions.

If I just create a new web app project and do a session variable and all it seems to work so the configuration of IIS, machine.config seems ok in the new web app project there is nothing in the web.config either regarding sessionstate.

What could possibly cause this or am I just missing something?
0
Comment
Question by:davism
  • 11
  • 9
  • 2
22 Comments
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40234815
Is this on a SUBSEQUENT event?

If it is on the same event, the Page_Load runs BEFORE the Button's Click event, so the variable would not have been set yet.

One of the most frustrating things about ASP.NET is having to deal with the rather complex life-cycle:

http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx
0
 
LVL 1

Author Comment

by:davism
ID: 40234909
subsequent event? Not sure what you're asking.

But in a nut-shell I am doing this:

> Execute the web page (like in VS 2010)
> Page_Load fires.
> Page is presented and has 2 buttons.
> I click one button and that defines the Session variable like Session["MyTest"] = Test;
> I click the second button
> The Page_Load is fired.
> The Session["MyTest"] variable is null like the session variable does not even exist.
0
 
LVL 1

Author Comment

by:davism
ID: 40234912
By the way, this page have a multiview, a view and a grid that is databound.

The other one does not but I'm not sure how that associates with a Session variable.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40234946
I meant was this

PageLoad
user clicks button
PageLoad (variable not set) <--- "same event"
button even sets variable

and clearly it was not.

What you are describing should work fine (and works for me) unless there is some interference with the session (browser does not accept cookies or such, web.config set in such a way as to interfere with sessions (custom session provider that does weird things, which you say is not the case)....

Your web.config is set to the normal?

    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>

Open in new window

0
 
LVL 1

Author Comment

by:davism
ID: 40235120
Actually, I didn't have that in the web.config.

In fact, even when I tried the new app it still worked and it did not have that in it either. But let me try that just in case.

I do not expect it to work being that it's not even in anything else but will not hurt to give it a go.
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40235193
I am using a newer version of VS, that might be the difference....newly created projects get that in web.config by default.
0
 
LVL 1

Author Comment

by:davism
ID: 40235297
That had no effect. Still got the same thing. :-(
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40235332
I still have VS2010 on my machine....can you post simple code?
0
 
LVL 1

Author Comment

by:davism
ID: 40235724
It appears from what I have gathered thus far it is due to the fact that I am modifying the connection string in the web.config. More so, I think the modification to the web.config is causing the issue. I think that might be dropping the Session or timing it out.

if (dbConnStr != null)
            {
                var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

                connectionStringsSection.ConnectionStrings["DBTest"].ConnectionString = dbConnStr;

                config.Save();

            }

Open in new window


If that is truly causing the session to timeout or end, what other options do I have or can I do?

Do I have to put the connectionstrings in a separate configuration file and update that?

If so, any idea on how that is done and how I can end up using the connection string then in the asp.net web site app?
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40236162
Can you post your web.config?   If it has sensitive material in it like usernames and passwords, just replace those with "username" and  "password"
0
 
LVL 1

Author Comment

by:davism
ID: 40236386
Sure. Here is it with renamed aspects:

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.webServer>
    <httpRedirect enabled="false" />
  </system.webServer>
  <connectionStrings>
    <add name="xxxEntities" connectionString="metadata=res://*/xxxEntities.csdl|res://*/xxxxEntities.ssdl|res://*/xxxEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(local);initial catalog=xxx;integrated security=True;;multipleactiveresultsets=True;App=EntityFramework;Connect Timeout=30&quot;"
      providerName="System.Data.EntityClient" />
    <add name="xxxEntities-Local" connectionString="metadata=res://*/xxxEntities.csdl|res://*/xxxEntities.ssdl|res://*/xxxEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(local);initial catalog=xxx;integrated security=True;;multipleactiveresultsets=True;App=EntityFramework;Connect Timeout=30&quot;"
      providerName="System.Data.EntityClient" />
    <add name="xxxEntities-xx" connectionString="metadata=res://*/xxxEntities.csdl|res://*/xxxEntities.ssdl|res://*/xxxEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=xx.xx.xxx.xx;initial catalog=xxx;User ID=xx;Password=xxxx;multipleactiveresultsets=True;App=EntityFramework;Connect Timeout=30&quot;"
      providerName="System.Data.EntityClient" />
    <add name="xxxEntities-xxx" connectionString="metadata=res://*/xxxEntities.csdl|res://*/xxxEntities.ssdl|res://*/xxxEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=xx.xx.xx.xx;initial catalog=xxx;User ID=xx;Password=xxxxx;multipleactiveresultsets=True;App=EntityFramework;Connect Timeout=30&quot;"
      providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientCertificateAuth">
          <clientCredentials>
            <clientCertificate findValue="xxxxx" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySerialNumber"/>
            <serviceCertificate>
              <authentication  certificateValidationMode="PeerOrChainTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="AtEndPointxxxxx" closeTimeout="00:01:00" openTimeout="00:05:00"
          receiveTimeout="00:10:00" sendTimeout="00:05:00" bypassProxyOnLocal="false"
          transactionFlow="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
          textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
            enabled="false" />
          <security mode="Transport">
            <transport clientCredentialType="Certificate" proxyCredentialType="None"
              realm="" />
          </security>
        </binding>
        <binding name="AtEndPointxxxxx" closeTimeout="00:10:00" openTimeout="00:10:00"
          receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" />
          <security mode="None" />
        </binding>
        <binding name="AtEndPointLocal" closeTimeout="00:10:00" openTimeout="00:10:00"
          receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" />
          <security mode="None" />
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://xxxxx.xxxxx.xxxxx/xxxxx/xxxxx.svc"
        behaviorConfiguration="ClientCertificateAuth" binding="wsHttpBinding"
        bindingConfiguration="AtEndPointXXX" contract="xxxxx.xxxxx"
        name="AtEndPointXXX" />
      <endpoint address="http://xxxxx.xxx.xxx.com/xxxx/xxxx.svc"
        binding="wsHttpBinding" bindingConfiguration="AtEndPointxxxxx"
        contract="xxxxx.xxxxx" name="AtEndPointxxxxx" />
      <endpoint address="http://localhost/xxxxxx/xxxxx.svc"
        binding="wsHttpBinding" bindingConfiguration="AtEndPointLocal"
        contract="xxxxx.xxxxx" name="AtEndPointLocal" />
    </client>
  </system.serviceModel>
</configuration>

Open in new window


Now, what is happening is the I need to have the xxxEntities above changed to the use one of the xxxEntities-xx depending upon what option is selected.

That is in the web.config.

So, I changed it to use the a connection.config file where the connectionstring config was the connection.config thinking that changing it in web.config is causing the session to end which it does. However, with the connection.config file for the DB connection strings it was still doing the same thing.

You will see that I have a web service in the web.config as well.  I need to maintain that web service well. This is where the main reason is. I was thinking I can take that web service all instantiation and store it in a session variable.

That is all fine and great until I need to change the connectionstring which involved changing the web.config. When that happened the Session variable is then lost because the session ended.


So, the other think I am thinking... Using a ViewState type variable instead. Well the ViewState is client-side and that means has to be serialized. I would need to serialize the web service object and then on the Page_Load deserialize and create an instance.  *Maybe*, as I am typing this I just thought of something...maybe I can just put the endpoint reference text (AtEndPointXX, AtEndPointLocal) to a viewstate variable then on the Postback, have the Page_Load instantiate the web service.

If I cannot do that then I will have to serialize the web service object and then put it in the ViewState variable and deserialize it.

If I used a hidden field in ASP.NET, I found that it still needs to serialize it even though a hidden field is server side.

The ideal resolution is to have it stored in the Session. But when I have to change the web.config then I lose the session. The SessionState is InProc and I cannot change it to StateServer or SQLServer. :-(

Any thoughts on how I could achieve the ideal solution or any other thoughts?
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40236574
Actually, a true hidden field is client side, and can store serialized data for you.

That is NOT a field with Visible=false, that really IS a server side construct,  but an

<input type="hidden" value="serialized stuff"> field that can be sent to the browser and will be sent back to the server on postback.
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40236575
(you can DEAL with such a field directly on the server by making it runat="server", otherwise you'd need to consult form data directly on postback)
0
 
LVL 1

Author Comment

by:davism
ID: 40236590
I'm not sure what your saying. I know on can do a hiddenfield with a runat="server" (that is the only option for a runat. :-) )

But I'm starting to think I can use the view state and just use the AtEndPointXXX variable instead of this serialization/deserialization of an object. What I'm not sure is serialized or not...is it going to have an affect on channels? Because I would be creating a new instance.

Now sure but I am going to have to try. However, in the event is doesn't work out do you have an idea on how to deserialize an object? Or is there any way to modify a web.config (or connection.config if I have to go that route again) and keep the session variables?
0
 
LVL 1

Author Comment

by:davism
ID: 40236792
I *think* I maybe have it with the ViewState and only using the AtEndPoint stuff, like I mentioned. I'm still going to go through more tests. I will let you know on the results of that but so far so good. :-)
0
 
LVL 23

Accepted Solution

by:
Jens Fiederer earned 450 total points
ID: 40236882
With <input type=hidden ....> you have the option of runat="server" or you have the option of no runat attribute at all.  The latter would give you a pure client-side form field that would not show up in your Controls collection.  

Objects serialize fairly well into JSON:  http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx

However, this is often more data than is strictly required, and it is often a good idea to save just a minimum bit of info (a key that lets you retrieve the object from a database...or just enough information to pass to a constructor for a new instance).

Good luck with the ViewState, that should work, too....but since ViewState is encrypted it is a bit harder to see what is going on when it hits the browser....you can't just use F12 developer tools and see anything that makes sense the way you can with a hidden field.
0
 
LVL 18

Expert Comment

by:Gary Davis
ID: 40238008
If you are losing your session variable due to a modify of the connection string in the Web.config which restarts the application, you could change to using the state service instead of inproc (make sure the state service is running in the control panel->services.

Another possibility is to put the connection strings in a separate file and in Web.config for the connection string, point to the file with a file="" parameter.

Modify the connection string in the new file and it will not restart the application. However, the change may not be notified by the application.

Also, review this article for another idea.

http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
0
 
LVL 1

Author Comment

by:davism
ID: 40238012
Hi Gary,

It seems like putting in the connection string into a new file actually did restart.

From a previous post:

So, I changed it to use the a connection.config file where the connectionstring config was the connection.config thinking that changing it in web.config is causing the session to end which it does. However, with the connection.config file for the DB connection strings it was still doing the same thing.

With respect to changing the session state mode:

The ideal resolution is to have it stored in the Session. But when I have to change the web.config then I lose the session. The SessionState is InProc and I cannot change it to StateServer or SQLServer. :-(
0
 
LVL 18

Expert Comment

by:Gary Davis
ID: 40238019
You want to avoid having your application restart just because you changed connection strings so you have to look at a different technique for maintaining your current connections to the DB.

My site puts the connection strings in a completely different place - in Database.xml which is easily changed if we need to switch out the DB. connection(s).

Then we have a library routine that returns a connection string from the xml file. The contents of the file are cached so the filesystem does not have to be hit every time and a cache dependency is set on that file so if it is changed, the cache is purged and then reloaded on next request.

Gary
0
 
LVL 1

Author Comment

by:davism
ID: 40238084
Actually, as mentioned, I am using VideOtape variables instead of Session variables and that it working out so far. I just need to test more.
0
 
LVL 1

Author Closing Comment

by:davism
ID: 40240153
The ViewState is working out and providing all the necessary workings. I appreciate the info and support!

Thanks
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 40240287
Congratulations!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses
Course of the Month16 days, 1 hour left to enroll

850 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