Session Variables Not Remaining

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?
LVL 1
davismAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jens FiedererTest Developer/ValidatorCommented:
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
davismAuthor Commented:
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
davismAuthor Commented:
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
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Jens FiedererTest Developer/ValidatorCommented:
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
davismAuthor Commented:
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
Jens FiedererTest Developer/ValidatorCommented:
I am using a newer version of VS, that might be the difference....newly created projects get that in web.config by default.
0
davismAuthor Commented:
That had no effect. Still got the same thing. :-(
0
Jens FiedererTest Developer/ValidatorCommented:
I still have VS2010 on my machine....can you post simple code?
0
davismAuthor Commented:
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
Jens FiedererTest Developer/ValidatorCommented:
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
davismAuthor Commented:
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
Jens FiedererTest Developer/ValidatorCommented:
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
Jens FiedererTest Developer/ValidatorCommented:
(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
davismAuthor Commented:
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
davismAuthor Commented:
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
Jens FiedererTest Developer/ValidatorCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Gary DavisDir Internet SvcsCommented:
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
davismAuthor Commented:
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
Gary DavisDir Internet SvcsCommented:
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
davismAuthor Commented:
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
davismAuthor Commented:
The ViewState is working out and providing all the necessary workings. I appreciate the info and support!

Thanks
0
Jens FiedererTest Developer/ValidatorCommented:
Congratulations!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.