session value lost in page load - c#

i have converted a web application project from 2003 to 2005.everything works fine in 2003,but the converted web application project in 2005 has some problem, problem is in session values,initially the session value works fine(for the first time),but if the page is loaded for the second time the session value becomes empty.
in first page session value is set and in second page the session value is received then i click the button the page will reloaded now the session value is empty..
please get me some answers or links to refer.

Check if your application doesn't alter anything in the folder structure, like creating new files or folders. That often causes the application to be reset, which causes the loss of the Session information. Especially some special folders and files, like the App_Code folder and the Web.Config, cause an immediate application reset when modified.
If this is not the case, then it might be a code logic problem. Try to refactor the session variable's read/writes into using a property:
private string MySessionVar {
get { return (string)Session["MySessionVar"]; }
set { Session["MySessionVar"] = value; }
}
Then add breakpoints to the getter and setter and run your code to check what's causing the session variable to be overwritten. Be sure to check usercontrols if you use them.
Also, if the variable is only used on the current page, you might consider using a Viewstate variable instead.

Related

Viewing Properties.Settings.Default variables

I am trying to use Settings.settings to define/persist some vars. For brevity, I've set up a test file to demonstrate the behavior I'm seeing:
First, I define a setting in Settings.settings:
I then have the following code to test changing variableName:
public Form1()
{
InitializeComponent();
string newString = Properties.Settings.Default.variableName;
Properties.Settings.Default.variableName = "This is a new string";
Properties.Settings.Default.Save();
}
Running the above in the debugger for the first time, I grab the current value (the value I set in the Settings.settings window initially) of variableName from Properties.Settings. As expected, newString is set to "This is a string". Good.....
After executing the next two lines, the debugger shows variableName changed to "This is a new string". Good....
I then run the app through the debugger again. I hit the string newString line and, prior to execution, newString is undefined (of course). Good....
As soon as I execute...
string newString = Properties.Settings.Default.variableName;
... and on subsequent executions of the code, the actual value of variableName is defined as "This is a new string" (Good...as expected).
I then go back to the Settings.settings window. variableName has not changed - it's still "This is a string". I've even closed VSE 2012 and re-opened the project. Settings.settings never changes.
Where is the new value being stored? I've checked all of the .config files ([appname].exe.config, [appname].vshost.exe.config, app.config, and the Settings.settings file) and the new value, "This is a new string" isn't anywhere to be found.
In summary, I'm getting the result I desire from the code, but I can't seem to view the result at design time other than to check the value of the var in the debugger. This seems not only peculiar to me, but impossible.
What am I missing/where am I not looking? I would fully expect the value of variableName to change in the Settings.settings window, but it never does. I've looked everywhere on StackOverflow/Google and can't seem to find the answer.
Thanks in advance....
The original value that you configured via Settings.settings is stored in a .config file alongside your executable's assembly. This will never change unless you modify the Settings file directly via Visual Studio; it's essentially a read-only file.
The user's customized setting is stored in a separate config file within the user's profile. The location of this file depends on your assembly's metadata. For example, on Windows 7/Vista the location might look like:
C:\Users\<user name>\AppData\Local\<company name>\<assembly name>\
AssemblyName\<version>\user.config
If you haven't customized the company name in your assembly's metadata then it may default to Microsoft. Also note that AppData is a hidden folder that may not be visible in Windows Explorer depending on your view settings.
I am not sure if I understand your question. That variable content stay persistent. Thats it. Why you would set a persistent variable to change it later?

Flajaxian Custom Folder Save Location

I see a lot of people coming up with some excessive ways to change the folder location on the fly with flajaxian multiple file upload control.
Was just wondering if the more experienced could take a look at the way I've come up with and let me know if there are any major issues I should be concerned about. (Assuming I have the proper error checking in place.)
I planned on initializing the control as seen below. :
<cc1:FileUploader ID="FileUploader1" runat="server" OnFileReceived="fileUploader_FileReceived" RequestAsPostBack="true">
</cc1:FileUploader>
(I RequestAsPostBack="true" as there are some other controls I need to check in my event handler)
I simply change the HttpFileCollection.SaveAs property in the fileUploader_FileReceived event. Since flajaxian does this one file upload at a time, we can expect that there is only 1 file in the collection (or else we could use a loop).
protected void fileUploader_FileReceived(object sender,
com.flajaxian.FileReceivedEventArgs e)
{
HttpFileCollection files = Request.Files;
// Change path to whichever folder I need
String TempFileName = "C:\\NEW\\PATH\\TO\\Folder\\" + files[0].FileName;
// Save the file.
files[0].SaveAs(TempFileName);
}
This implementation seems to work great as long as the folder is existing! I was just wondering if there is anything technically wrong with an implementation like this, again , assuming all error checking was in place.
Thanks!
A better way to do this would be to use an adapter, and over write the folder location in the
OnFileNameDetermining event. This way, we also get all the goodies with the adapter.
<cc1:FileUploader ID="FileUploader1" runat="server"` OnFileReceived="fileUploader_FileReceived" RequestAsPostBack="true">
<Adapters>
<cc1:FileSaverAdapter runat="server" FolderName="Ups" OnFileNameDetermining="fileUploader_FileDetermined" />
</Adapters>
</cc1:FileUploader>
In the file determined event, we can change the folder location programatically
protected void fileUploader_FileDetermined(object sender, com.flajaxian.FileNameDeterminingEventArgs e)
{
e.FileName = "C:\\NewFolder\\" + e.File.FileName;
}
We can use the FileReceived event to check if the folder exists, and if not, create it.
protected void fileUploader_FileReceived(object sender, com.flajaxian.FileReceivedEventArgs e)
{
int fileIndex = e.Index;
if (fileIndex == 0)
{
// We are on our first file, check if the new folder exists, if not, create it
}
}
What you are doing is fine, although, if you are saving files within the web site, consider using the MapPath method to create a physical folder from a virtual path within the web site
MapPath("/Images/User1")
This my mininal APSX implementation
<fjx:FileUploader ID="FileUploader1" runat="server" OnFileReceived="FileUploader2_FileReceived">
</fjx:FileUploader>
No adapters or folder is specified. When the FileRecevied event fires, I save files to a folder based on the Forms Authentication user name (names do not use characters not allowed in folder names).
Also note that the FileReceivedEventArgs has a reference to the (HTTP) file
e.File
The FileUploader control will show all files processed - you can even set the status code (e.g. 550) if there is an error, which is returned to the client.
Note that, the server call to the FileReceived event does not occur inside a nornal page postback, even if you specify
RequestAsPostBack="true"
So, a PagePreRender does not take place.
The only issue is, how do you perform any other processing at the client after the uploads complete (e.g. showing images uploaded).
Work I have in progress to this end is to use the client side event
FileStateChanged
When the last file is processed
if (file.state > Flajaxian.File_Uploading && isLast) {
I use JQuery to click a hidden submit button. The postback looks through session values stored when the files were saved, and renders back the images into a DIV.
However, an immediate submit causes issues with empty session inside the FileReceived event for some reason (I assume because the internal asynchronous call back has not completed). A pause of a few seconds before initiating the postback works OK.

How to correctly iterate application settings in C# using reflection

I am trying to iterate through application properties in C# using reflection (.NET 3.5 using VS 2010). The code "works" in that it successfully gets properties. However, it always gets the property values that were defined at design time and does not see the current values in myapp.exe.config. Properties that I access directly by name do reflect what is in the .config file. Here is the reflection-based code which only sees design-time properties:
List<StringDictionary> dictList = new List<StringDictionary>();
StringCollection bogus = new StringCollection();
foreach (PropertyInfo info in Properties.Settings.Default.GetType().GetProperties())
{
if (!("logLevel".Equals(info.Name) || "eventURL".Equals(info.Name)))
{
if (bogus.GetType().IsAssignableFrom(info.PropertyType))
{
StringCollection rawConfig = (StringCollection)info.GetValue(Properties.Settings.Default, null);
// do something
}
}
}
This code does pick up the current values in myapp.exe.config.
String logLevelStr = Properties.Settings.Default.logLevel
What am I doing wrong in my reflection code that causes me to pull only the properties defined at design time and not what is currently in myapp.exe.config?
To get the current value you need to use something like this which looks at Default.PropertyValues instead of Default.Properties
foreach (SettingsPropertyValue property in Properties.Settings.Default.PropertyValues)
{
Debug.WriteLine(string.Format("Property {0}'s value is {1}",property.Name,property.PropertyValue));
}
// note: the above may not work in some multi-form app, even if the applicaton prefix is prepended in front of Properties esp for visual studio 2010 compiled app with .net frame work 4
I think that there is a fundamental misunderstanding here. Settings can be one of two types- Application settings and User settings.
Application settings are intended to be written only at design time. As Henk points out it is possible to edit them after deployment if you are admin, but that isn't really the intent. Also, it should be noted that while Application settings are stored in the .config file, they are only read once and then cached in memory. That's why you don't see the new values when you edit the file.
User settings can be overwritten at run time by application code and saved, but they are saved at a user scope, so a different user running the same application can have different values. The intention there was things like user preferences. There is a drop down in the settings designer grid to switch between Application and User scope for each Setting.
Either way, you shouldn't be accessing them via reflection.
There must be some kind of misunderstanding here.
If you want to read the configurations from myapp.exe.config you should use ConfigurationManager. This class allows you to access AppSettings and ConnectionString directly through static properties or read custom sections by the GetSection method.
Beside, application configurations are meant to be design-time only. You shouldn't alter myapp.exe.config at runtime. Never. This file must be the same for each execution of your application.
Beside, what is Properties.Settings.Default.logLevel ???
Consider:
foreach (SettingsProperty sp in Settings.Default.Properties)
{
Console.WriteLine(sp.Name + "=" + Settings.Default.Properties.Default[sp.Name].ToString());
}

C# MultiView SetActiveView by ID not working properly

I'm currently trying to figure out what's wrong with my code:
Doesn't work
if(...){
...
}else{
someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
Works
if(...){
...
}else{
//someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
.. why and any solutions for this?
Because you are attempting to act on the INIT rather than the load, the data has not yet been attached at the server.
You should find this review of the life cycle of a web request in ASP.NET useful: MSDN ASP.NET Page Life Cycle
Here is the relevant extract:
Initialization
During page initialization, controls on the page are available and
each control's UniqueID property is
set. A master page and themes are also
applied to the page if applicable. If
the current request is a postback, the
postback data has not yet been loaded
and control property values have not
been restored to the values from view
state.
Load
During load, if the current request is a postback, control
properties are loaded with information
recovered from view state and control
state.
Move the code you are trying to execute into (or after) the page load handler (remember to test for IsPostBack) and see if that doesn't get what you want.
Something New to try:
try changing your doesn't work to:
if(...){
...
}else{
string someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
It sounds like someVariableAsString is possibly throwing an exception to cause the code not to reach the next line. Check your variable type.
I was able to get a solution to my case:
I changed someVariableAsString to a Property as View.
Created a session variable to Gobal.asax and now I get correct result (one page load later). :-)
but in my case this will do.
Problem solved.
onInit{
m_myVariable;
myFunction();
...
}
void myFunction(){
// if clause described up
}
public View myVariable
{
get { return m_myVariable = Session["myVariableAtSession"] as View; }
set { m_myVariable = value;
Session["myVariableAtSession"] = m_myVariable;
}
}

session value lost in asp.net in c#

hai..
Am doing wepsite for show images from local drive using asp.net.am using session object for Transfer image path from first page to second page
its running nice in vs 2003 .but i converted this website to vs 2005.but session value does't pass to next page.i got null value in session object.
am using inproc session mode
kindly help me
thanks
Your application will probably encounter an error and therefore the session will end. Afterwards a new Session is started. Accessing that value in the new value will return null.
Steps to find your error:
Create the global.asax in your Rootdirectory. Set Breakpoints for Session_OnStart, Session_OnEnd and Application_OnError and try to find where the error lies.
How you are storing the path of images.
See i am doing like this and everything goes file for me.
Session["Path"] = #"D:\Images\PNEUMATIX_MR_CardiovascularHeart Cardiac Function_6\img.jpeg";
on another page i am taking like this.
Label1.Text = Session["Path"].ToString();
And i am using sessionState mode="inProc".
My be you have some problem with path.
http://markmail.org/message/emd3swpsembfplis#query:+page:1+mid:dfdchaihfj7c46j7+state:results
Thanks god this post save my life! IE bugs with _ in the domain name .. they flush all session variable

Categories