1

I am using Asp.net 3.5 and C#

I have to add an XmlDocument to my application state so that everytime my application doesnt access the XML file on my filesystem, I will add this at the Application_Start() function in Global.asax.cs

I am adding this to system state as :

protected void Application_Start(Object sender, EventArgs e)
{    
    string filePath = Server.MapPath("<path to my XML FILE>");
    XmlDocument xmlDoc = new XmlDocument();
    try
    {
        xmlTickerDoc.Load(filePath);
    }
    finally
    {
        HttpContext.Current.Application["xmlDoc"] = xmlDoc;
    }
}

In this code i try to load the xml file and if the file is not loaded due to any problem then i am wanting a null XmlDocument.

I access this XmlDocument as :

XmlDocument xmlDoc = new XmlDocument();
xmlDoc = HttpContext.Current.Application["xmlDoc"];

the error i get while build is

Cannot implicitly convert type 'object' to 'System.Xml.XmlDocument'. An explicit conversion exists

So How to assign the HttpContext.Current.Application["xmlDoc"] variable as System.Xml.XmlDocument ?

Umair Jabbar
  • 3,596
  • 5
  • 30
  • 42

2 Answers2

2

Your problem is here:

xmlDoc = HttpContext.Current.Application["xmlDoc"];

Try

xmlDoc = HttpContext.Current.Application["xmlDoc"] as System.Xml.XmlDocument; 
  • ahan thanks, how about the answer that i just posted, can you guide me which approach shall I use. I mean is there a difference between the two, both explicitly cast dont they ? – Umair Jabbar Feb 09 '10 at 07:42
  • The explicit cast might throw an exception if the object it cannot be casted. Using 'as' will set the object to null. So direct cast might be slightly more performant and help catch errors faster. Using 'as' looks more readable to me though. –  Feb 09 '10 at 08:03
0

Got the answer after a little googling, a simple one but can be tricky for a PHP developer working on C# (as it was in my case) well i just had to explicitly cast my application state variable to XmlDocument that is at place of :

XmlDocument xmlDoc = new XmlDocument();
xmlDoc = HttpContext.Current.Application["xmlDoc"];

I used :

XmlDocument xmlDoc = new XmlDocument();
xmlDoc = (XmlDocument) HttpContext.Current.Application["xmlDoc"];

and it becomes Robust :)

can any one tell me what will be the lifetime of this ApplicationState Variable ?

Umair Jabbar
  • 3,596
  • 5
  • 30
  • 42
  • Please edit your question/add a separate question if you have another question. Don't have it as part of an answer. –  Feb 09 '10 at 08:14