Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Saturday, March 31, 2012

Storing/Retrieving Objects in the Session

I have a form set up currently so that when someone is added, an object is created with that persons information, and that object is then added to the Session. When the user is done with the form, I have the code setup to mirror the information back on a webpage (when I know it's spewing back the same information I put in, then I'll have it be stored in a database). The problem I am having is that I don't know how to call my toString method of my object from the session.
The class is called Person, and the object is called objPerson, I store it this way:

Session.Add("objPerson", objPerson)

and echo it back to the screen this way:

Response.Write(Session.Item("objPerson"))

The only thing that comes out is the name of the object though, with the namespaces ( COCO.objects.Person ). I tried using

Response.Write( Session.Item( "objPerson.toString()") )

But I had a feeling that wouldn't work, and it didn't. Have I approached this wrong, or am I on the right track here?
Thanks,
DSimmonHi there...

The problem is that you have to sat your item from the session to the Object type of that item, and then you can use it.

Assuming that the class of objPerson is "Person", you would have to do something like this to retreive it:

Person sessionPerson = (Person)Session("Person");

And then use 'sessionPerson' as you want to.

You can use it directly also like this:

((Person)Session("Person")).Name;

Again, assuming you have a "Name" for your "Person" class.

I hope this helps, let me know if you need more info.

Covo
Ahh, so I have to make a storage when I retrieve the object from the session, then recast it to that object type before I use it.
That makes sense, I'll try it now.
Thanks for you help.

David
you're welcome!

Notice that you don't have to make a storage object... If you see the second method I listed, you'll see that you can just cast the session to the object and use it directly.

Strange "Object reference not set to an instance of an object" error in webform

I suddenly received an unexpected error in my project. I have been working
on this project for some time without this issue. Nothing has changed in the
form that caused the exception. A little experimentation shows that I cannot
run ANY .NET web project without getting this error:

-----------------------
--

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

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

Source Error:

Line 1: <%@dotnet.itags.org. Page Language="vb" AutoEventWireup="false"
Codebehind="Login.aspx.vb" Inherits="DataBayWeb.Login" %>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Line 3: <HTML
Source File: c:\inetpub\wwwroot\DataBayWeb\login.aspx Line: 1

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an
object.]
System.Web.UI.Control.get_Controls()
System.Web.UI.Control.AddParsedSubObject(Object obj)

System.Web.UI.Control.System.Web.UI.IParserAccesso r.AddParsedSubObject(Objec
t obj)
ASP.Login_aspx.__BuildControlTree(Control __ctrl) in
c:\inetpub\wwwroot\DataBayWeb\login.aspx:1
ASP.Login_aspx.FrameworkInitialize()
System.Web.UI.Page.ProcessRequest()
System.Web.UI.Page.ProcessRequest(HttpContext context)

System.Web.CallHandlerExecutionStep.System.Web.Htt pApplication+IExecutionSte
p.Execute()
System.Web.HttpApplication.ExecuteStep(IExecutionS tep step, Boolean&
completedSynchronously)

Other developers on my team can run the latest version of the project
without an issue. What has happened?

ChrisVery strange indeed. It might sound obscure, but try removing the
space in <%@. Page...

Otherwise, I would be tempted to do the inevitable and reinstall the
framework.

Simon.

Strange "Object reference not set to an instance of an object" error in web

I suddenly received an unexpected error in my project. I have been working
on this project for some time without this issue. Nothing has changed in the
form that caused the exception. A little experimentation shows that I cannot
run ANY .NET web project without getting this error:
----
--
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.
Source Error:
Line 1: <%@dotnet.itags.org. Page Language="vb" AutoEventWireup="false"
Codebehind="Login.aspx.vb" Inherits="DataBayWeb.Login" %>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Line 3: <HTML>
Source File: c:\inetpub\wwwroot\DataBayWeb\login.aspx Line: 1
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an
object.]
System.Web.UI.Control.get_Controls()
System.Web.UI.Control.AddParsedSubObject(Object obj)
System.Web.UI.Control.System.Web.UI.IParserAccessor.AddParsedSubObject(Objec
t obj)
ASP.Login_aspx.__BuildControlTree(Control __ctrl) in
c:\inetpub\wwwroot\DataBayWeb\login.aspx:1
ASP.Login_aspx.FrameworkInitialize()
System.Web.UI.Page.ProcessRequest()
System.Web.UI.Page.ProcessRequest(HttpContext context)
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication+IExecutionSte
p.Execute()
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)
Other developers on my team can run the latest version of the project
without an issue. What has happened?
ChrisVery strange indeed. It might sound obscure, but try removing the
space in <%@. Page...
Otherwise, I would be tempted to do the inevitable and reinstall the
framework.
Simon.

Strange Behavior

Hi All,
I have a webapp page that gathers a bunch of parameters and then saves the parameters into a session variable (as an object). The code then redirects via Response.Redirect() to a new page. The new page then renders a chart based on the values stored in the session variable. On the resulting page I have a button that redirects back to the original page with the form. I'm doing this as follows: Response.Redirect("Frm_KPI.aspx?redo=1");
In the Page_Load() method in "Frm_KPI.aspx.cs" I have the following code:

protectedvoid Page_Load(object sender, System.EventArgs e)

{

//

// Initialize the database connection

//

InitDB();

// Check the query string to see if user wants to reload the form.

if (Quartz_QueryString("redo") =="1")

{

//

// User wants to reload the form from the Session parameter object

//

m_Params = (CKPIParameters)Session["KPI_PARAMS"];

InitJobTypeList(true);

InitJobOwnerList(true);

InitTimingParameters(true);

InitInterval(true);

InitTimeBase(true);

InitNormalizeBy(true);

InitJobPriorityList(m_Params.JobType,true);

InitJobAnalysisMode(m_Params.JobType,true);

InitJobAnalysisHistory(m_Params.JobType,true);

}

else

{

if (!IsPostBack)

{

m_Params.JobType ="SEM";

InitJobTypeList(false);

InitJobOwnerList(false);

InitTimingParameters(false);

InitInterval(false);

InitTimeBase(false);

InitNormalizeBy(false);

InitJobPriorityList(m_Params.JobType,false);

InitJobAnalysisMode(m_Params.JobType,false);

InitJobAnalysisHistory(m_Params.JobType,false);

m_hplStartDate.NavigateUrl ="javascript:;";

m_hplEndDate.NavigateUrl ="javascript:;";

this.m_editStartDate.Text ="01/01/2005";

this.m_editEndDate.Text ="12/31/2005";

//

// Now disable all of the controls except for the job type selector

//

EnableControls(false);

ShowControls(false);

}

}

}

privatestring Quartz_QueryString(string strName)

{

string strReturn ="";

if (Request.QueryString[strName] !=null && Request.QueryString[strName].Length > 0)

{

strReturn = Request.QueryString[strName].ToString();

}

return (strReturn);

}



The problem is that when the new page is redisplayed, all the values are set correctly, but when I attempt to resubmit the page, the line
if (Quartz_QueryString("redo") =="1")

resolves to true even though I'm doing a post via my submit button. Consequently any changes I make to the variables don't stick when the form is ultimately submitted. Any thoughts??
Regards,
Greg.

Possible solution:
I changed the QueryString check to the following:

if (Context.Items["RedoQuery"] !=null && Context.Items["RedoQuery"].ToString().Length > 0)
{
// Reload form from session values
}

This has the desired effect. After the initial Page_Load() the context disappears and the above code block is not called repeatedly.

Strange behavior with HttpCookieCollection

Hi,

I created a simple webform, put a test button on it and implemented a
click handler that looks like so:

private void btnTest_Click(object sender, System.EventArgs e)
{
HttpCookieCollection oCookReq =
HttpContext.Current.Request.Cookies;
HttpCookieCollection oCookResp =
HttpContext.Current.Response.Cookies;

int n1 = oCookReq.Count;
int n2 = oCookResp.Count;
bool bIsNull = (oCookResp["someCookieName"] == null);
int n3 = oCookReq.Count;
int n4 = oCookResp.Count;

Response.Write(string.Format("Before: Request = {0}, Response
= {1}<br>", n1, n2));
Response.Write(string.Format("After: Request = {0}, Response
= {1}<br>", n3, n4));
}

When I click the button the test output on the page is:

Before: Request = 1, Response = 0
After: Request = 2, Response = 1

Can anyone explain why the mere act of looking for a cookie in the
response collection would cause one to get added to both the response
and request collections? I tried the test again using a new
HttpCookieCollection (i.e. not one from the current context) and do
not get this behavior. Clues?

Thanks much...

- Aadlaird@.earthlink.net wrote in
news:3f18afd7.184287250@.news.earthlink.net:

> Hi,
> I created a simple webform, put a test button on it and
> implemented a click handler that looks like so:
> private void btnTest_Click(object sender, System.EventArgs e)
> {
> HttpCookieCollection oCookReq =
> HttpContext.Current.Request.Cookies;
> HttpCookieCollection oCookResp =
> HttpContext.Current.Response.Cookies;
> int n1 = oCookReq.Count;
> int n2 = oCookResp.Count;
> bool bIsNull = (oCookResp["someCookieName"] == null);
> int n3 = oCookReq.Count;
> int n4 = oCookResp.Count;
> Response.Write(string.Format("Before: Request = {0},
> Response
>= {1}<br>", n1, n2));
> Response.Write(string.Format("After: Request = {0},
> Response
>= {1}<br>", n3, n4));
> }
>
> When I click the button the test output on the page is:
> Before: Request = 1, Response = 0
> After: Request = 2, Response = 1
> Can anyone explain why the mere act of looking for a cookie in
> the response collection would cause one to get added to both the
> response and request collections? I tried the test again using
> a new HttpCookieCollection (i.e. not one from the current
> context) and do not get this behavior. Clues?

You've stumbled upon a frustrating (and, AFAIK, undocumented) aspect
of the ASP.NET cookies response collection. Simply querying the
collection will create the cookie if it doesn't exist.

Here's an article that explains this in more depth:

http://www.codeproject.com/aspnet/AspNetCookies.asp

Hope this helps.

Chris.
----
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/

Wednesday, March 28, 2012

Strange behaviour in Production environnement

Hello experts,

I have the following peice of code in my Global.asax

void Application_Error(object sender, EventArgs e)

{

//get reference to the source of the exception chain

Log log = new Log();

Exception ex = Server.GetLastError();

log.AddLogEntry(Request, ex);

log.SaveData();

Response.Redirect("~/Error.aspx");

}

This code works well on my test server Win2k3 , IIS 6. It write to my
erro.log text file and displays Error.aspx as expected.

In Production( Win2k3 , IIS 6) , it open the file error.log(Can be seen on
last modified date) but the expection is not written to the file. Neither is
Error.aspx displayed. Can someone tell were i should be looking?

Many thanks in advance .

SHi,

Does asp.net process has write /modify permission on the folder/file that
you are attemting to write? I would also use:
Server.ClearError(); before redirecting.

Regards

Med

"Smith" <Smith@.pricateemail.comwrote in message
news:%23yjQVIQMIHA.5224@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

>
Hello experts,
>
I have the following peice of code in my Global.asax
>
void Application_Error(object sender, EventArgs e)
>
{
>
//get reference to the source of the exception chain
>
Log log = new Log();
>
Exception ex = Server.GetLastError();
>
log.AddLogEntry(Request, ex);
>
log.SaveData();
>
Response.Redirect("~/Error.aspx");
>
>
>
>
>
>
}
>
>
>
This code works well on my test server Win2k3 , IIS 6. It write to my
erro.log text file and displays Error.aspx as expected.
>
>
>
In Production( Win2k3 , IIS 6) , it open the file error.log(Can be seen on
last modified date) but the expection is not written to the file. Neither
is Error.aspx displayed. Can someone tell were i should be looking?
>
>
>
>
>
Many thanks in advance .
>
S
>
>


"Med" <nospam@.nowhere.nowherewrote in message
news:%236KXucQMIHA.4228@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

Hi,
>
Does asp.net process has write /modify permission on the folder/file that
you are attemting to write? I would also use:
Server.ClearError(); before redirecting.
>


The user asp.net process is running under har full permission in the folder
where the code lives.Also note that the modified date of the error file
actually change according to the time error occured. It this was permission
problem, would it be allowed to actually open the file?
How does ServerClear() helps here?

Thanks
S
Hi,

Quote:

Originally Posted by

The user asp.net process is running under har full permission in the
folder where the code lives.


Does the log folder/file resides in this folder?

Actually Server.ClearError(); was irrelavant to your problem here, it was
just a suggestion as it prevents the error from continuing to the
Application_Error event handler.

Could you send the code for AddLogEntry(Request, ex)?

This is how I do it:

<%@. Import Namespace = "System.IO" %>
<%@. Import Namespace = "System.Diagnostics" %>

void Application_Error(object sender, EventArgs e)
{
//Only redirect to error page if in Release mode.
#if DEBUG
{
//Show error details
}
#else
{
try
{
LogError(Server.GetLastError().GetBaseException()) ;
Server.ClearError();
}
catch
{
//Do something....
}

//Redirect to error.aspx page
Response.Redirect("error.aspx");
}
#endif
}

private void LogError(Exception objError)
{

try
{
string sLogFilePathAndName = String.Format(@."{0}{1} {2}.log",
Server.MapPath("~/Logs/"), DateTime.Now.ToLongDateString(),
DateTime.Now.DayOfWeek);
using (StreamWriter sw = File.AppendText(sLogFilePathAndName))
{
sw.WriteLine(Environment.NewLine);
sw.WriteLine(String.Format("Error Caught in Application on
{0} {1} @. {2}", DateTime.Now.DayOfWeek, DateTime.Now.ToLongDateString(),
DateTime.Now.ToLongTimeString()));
sw.WriteLine(String.Format("IP Address: {0}",
Request.ServerVariables["REMOTE_ADDR"].ToString()));
sw.WriteLine(String.Format("Platform: {0}",
Request.Browser.Platform));
sw.WriteLine(String.Format("Browser: {0}",
Request.Browser.Type));
sw.WriteLine(String.Format("Error in: {0}",
Request.Url.ToString()));
sw.WriteLine(String.Format("Error Message: {0}",
objError.Message.ToString()));
sw.WriteLine("Stack Trace:");
sw.WriteLine(objError.StackTrace.ToString());
sw.WriteLine(Environment.NewLine);
sw.WriteLine("--------------------------");
sw.Close();
}
}
catch
{
//Do something....
}
}

You may also want to look at:
http://support.microsoft.com/defaul...kb;en-us;306355
Hope it helps

Med

"Smith" <Smith@.pricateemail.comwrote in message
news:e5iA$HRMIHA.1208@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>
"Med" <nospam@.nowhere.nowherewrote in message
news:%236KXucQMIHA.4228@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

>Hi,
>>
>Does asp.net process has write /modify permission on the folder/file that
>you are attemting to write? I would also use:
>Server.ClearError(); before redirecting.
>>


>
The user asp.net process is running under har full permission in the
folder where the code lives.Also note that the modified date of the error
file actually change according to the time error occured. It this was
permission problem, would it be allowed to actually open the file?
How does ServerClear() helps here?
>
Thanks
S
>


http://support.microsoft.com/kb/890960

Strange behaviour in Production environnement

Hello experts,
I have the following peice of code in my Global.asax
void Application_Error(object sender, EventArgs e)
{
//get reference to the source of the exception chain
Log log = new Log();
Exception ex = Server.GetLastError();
log.AddLogEntry(Request, ex);
log.SaveData();
Response.Redirect("~/Error.aspx");
}
This code works well on my test server Win2k3 , IIS 6. It write to my
erro.log text file and displays Error.aspx as expected.
In Production( Win2k3 , IIS 6) , it open the file error.log(Can be seen on
last modified date) but the expection is not written to the file. Neither is
Error.aspx displayed. Can someone tell were i should be looking?
Many thanks in advance .
SHi,
Does asp.net process has write /modify permission on the folder/file that
you are attemting to write? I would also use:
Server.ClearError(); before redirecting.
Regards
Med
"Smith" <Smith@.pricateemail.com> wrote in message
news:%23yjQVIQMIHA.5224@.TK2MSFTNGP02.phx.gbl...
> Hello experts,
> I have the following peice of code in my Global.asax
> void Application_Error(object sender, EventArgs e)
> {
> //get reference to the source of the exception chain
> Log log = new Log();
> Exception ex = Server.GetLastError();
> log.AddLogEntry(Request, ex);
> log.SaveData();
> Response.Redirect("~/Error.aspx");
>
>
>
> }
>
> This code works well on my test server Win2k3 , IIS 6. It write to my
> erro.log text file and displays Error.aspx as expected.
>
> In Production( Win2k3 , IIS 6) , it open the file error.log(Can be seen on
> last modified date) but the expection is not written to the file. Neither
> is Error.aspx displayed. Can someone tell were i should be looking?
>
>
> Many thanks in advance .
> S
>
"Med" <nospam@.nowhere.nowhere> wrote in message
news:%236KXucQMIHA.4228@.TK2MSFTNGP02.phx.gbl...
> Hi,
> Does asp.net process has write /modify permission on the folder/file that
> you are attemting to write? I would also use:
> Server.ClearError(); before redirecting.
>
The user asp.net process is running under har full permission in the folder
where the code lives.Also note that the modified date of the error file
actually change according to the time error occured. It this was permission
problem, would it be allowed to actually open the file?
How does ServerClear() helps here?
Thanks
S
Hi,

> The user asp.net process is running under har full permission in the
> folder where the code lives.
Does the log folder/file resides in this folder?
Actually Server.ClearError(); was irrelavant to your problem here, it was
just a suggestion as it prevents the error from continuing to the
Application_Error event handler.
Could you send the code for AddLogEntry(Request, ex)?
This is how I do it:
<%@. Import Namespace = "System.IO" %>
<%@. Import Namespace = "System.Diagnostics" %>
void Application_Error(object sender, EventArgs e)
{
//Only redirect to error page if in Release mode.
#if DEBUG
{
//Show error details
}
#else
{
try
{
LogError(Server.GetLastError().GetBaseException());
Server.ClearError();
}
catch
{
//Do something....
}
//Redirect to error.aspx page
Response.Redirect("error.aspx");
}
#endif
}
private void LogError(Exception objError)
{
try
{
string sLogFilePathAndName = String.Format(@."{0}{1} {2}.log",
Server.MapPath("~/Logs/"), DateTime.Now.ToLongDateString(),
DateTime.Now.DayOfW);
using (StreamWriter sw = File.AppendText(sLogFilePathAndName))
{
sw.WriteLine(Environment.NewLine);
sw.WriteLine(String.Format("Error Caught in Application on
{0} {1} @. {2}", DateTime.Now.DayOfW, DateTime.Now.ToLongDateString(),
DateTime.Now.ToLongTimeString()));
sw.WriteLine(String.Format("IP Address: {0}",
Request.ServerVariables["REMOTE_ADDR"].ToString()));
sw.WriteLine(String.Format("Platform: {0}",
Request.Browser.Platform));
sw.WriteLine(String.Format("Browser: {0}",
Request.Browser.Type));
sw.WriteLine(String.Format("Error in: {0}",
Request.Url.ToString()));
sw.WriteLine(String.Format("Error Message: {0}",
objError.Message.ToString()));
sw.WriteLine("Stack Trace:");
sw.WriteLine(objError.StackTrace.ToString());
sw.WriteLine(Environment.NewLine);
sw.WriteLine("---
--");
sw.Close();
}
}
catch
{
//Do something....
}
}
You may also want to look at:
http://support.microsoft.com/defaul...kb;en-us;306355
Hope it helps
Med
"Smith" <Smith@.pricateemail.com> wrote in message
news:e5iA$HRMIHA.1208@.TK2MSFTNGP05.phx.gbl...
> "Med" <nospam@.nowhere.nowhere> wrote in message
> news:%236KXucQMIHA.4228@.TK2MSFTNGP02.phx.gbl...
> The user asp.net process is running under har full permission in the
> folder where the code lives.Also note that the modified date of the error
> file actually change according to the time error occured. It this was
> permission problem, would it be allowed to actually open the file?
> How does ServerClear() helps here?
> Thanks
> S
>
I use the same log class as in the project :
http://www.asp.net/downloads/starter-kits/my-web-pages/
// ========================================
==================================
=====================
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See
http://www.microsoft.com/resources/...br />
es.mspx.
// All other rights reserved.
//
// ========================================
==================================
=====================
using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace MyWebPagesStarterKit
{
/// <summary>
/// Utility for writing error messages to a Logfile
/// </summary>
[Serializable]
public class Log : Persistable<Log.LogData>
{
/// <summary>
/// Load Log File from App_Data
/// </summary>
public Log()
{
try
{
LoadData();
}
catch { }
}
/// <summary>
/// List of all Log-Entries in the Logfile
/// </summary>
public List<LogData.LogEntry> Entries
{
get { return _data.LogEntries; }
}
/// <summary>
/// Adding a new Log-Entry to the LogData
/// </summary>
/// <param name="Created"></param>
/// <param name="PageTitle"></param>
public void AddLogEntry(HttpRequest httpRequest, Exception ex)
{
LogData.LogEntry entry = new LogData.LogEntry();
//PageTitle
entry.PageTitle = httpRequest.Url.AbsolutePath;
//Date
entry.Created = DateTime.Now.ToLongDateString() + " " +
DateTime.Now.ToLongTimeString();
//Error
entry.Error = ex.ToString();
//HTTP-Values
foreach (string key in httpRequest.ServerVariables)
{
string value = httpRequest.ServerVariables[key];
if (value != string.Empty)
{
if (key == "ALL_HTTP" || key == "ALL_RAW")
value = value.Replace(System.Environment.NewLine, ", ");
entry.ServerVariables.Add(key + ": " + value);
}
}
/ ========================================
===================================
====================
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See
http://www.microsoft.com/resources/...br />
es.mspx.
// All other rights reserved.
//
// ========================================
==================================
=====================
using System;
using System.Web;
using System.IO;
using System.Xml.Serialization;
using System.Web.Caching;
namespace MyWebPagesStarterKit
{
/// <summary>
/// Generic class for a perssitable object. Encapsulates the logic to
load/save data from/to the filesystem. To speed up the acces, caching is
used.
/// </summary>
/// <typeparam name="T">class or struct with all the data-fields that must
be persisted</typeparam>
public abstract class Persistable<T>
{
private String _path;
protected T _data;
/// <summary>
/// Creates a instance of Persistable. Also creates a instance of T
/// </summary>
public Persistable()
{
_data = (T)Activator.CreateInstance(typeof(T));
}
/// <summary>
/// Loads the data from the filesystem. For deserialization a XmlSeralizer
is used.
/// </summary>
protected void LoadData()
{
_path = HttpContext.Current.Server.MapPath(GetDataFilename());
lock (_path)
{
//first check, if the object is maybe already in the cache
object o = HttpContext.Current.Cache[_path];
if (o != null)
{
_data = (T)o;
}
else
{
//if nothing was found in the cache, the data must be loaded from the disk
//load and deserialize the data from the filesystem
using (FileStream reader = File.Open(_path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
_data = (T)serializer.Deserialize(reader);
}
HttpContext.Current.Cache.Insert(_path, _data);
}
}
}
/// <summary>
/// Persists the data back to the filesystem
/// </summary>
public void SaveData()
{
_path = HttpContext.Current.Server.MapPath(GetDataFilename());
lock (_path)
{
//insert the data into the cache
HttpContext.Current.Cache.Insert(_path, _data, null, DateTime.MaxValue,
TimeSpan.FromHours(1), CacheItemPriority.Normal, null);
//if the given path does not exist yet, create it
if (!Directory.Exists(Path.GetDirectoryName(_path)))
Directory.CreateDirectory(Path.GetDirectoryName(_path));
//serialize and store the data to the filesystem
using (FileStream writer = File.Create(_path))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, _data);
}
}
}
//Deletes the data from the cache and filesystem
public virtual bool Delete()
{
bool success = true;
if (File.Exists(_path))
{
lock (_path)
{
try
{
File.Delete(_path);
HttpContext.Current.Cache.Remove(_path);
}
catch { success = false; }
}
}
return success;
}
protected abstract string GetDataFilename();
}
}
Cheers
S

Saturday, March 24, 2012

Strange Event Behavior


Scenario:

Class A has a method that returns an instantiated object of Class B.

Class A has a Public Event called "DataUpdated".

When the Class A method is called to return an instance of Class B,
Class A hands to Class B a pointer to itself. Therefore, Class B can
reference the instance of Class A that instantiated it.

Thus, Class B can call the DataUpdated event on the instance of Class A
that instantied it. A method of Class A marked "Friend", called
OnDataUpdated, is called when the "Save" method of Class B is called.

Weirdness:
This all works as planned, but strangely. In an ASP.NET application,
I'm storing an instance of Class A in the Cache. When I call the "Save"
method on Class B, the event bubbles up to the instance of Class A as
expected. However, the event fires up to five times. I've stepped
through the code; the event is only raised once.

Any ideas? Thanks.

Dave Swersky

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!Is it a special needs class?
Try giving them a longer recess. It will allow them to expend some energy
before they return to your classroom.