Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all, i have written a webservice that returns an xmlelement. The relevant part of the code is as follows...
C#
[WebMethod(Description = "Get Current Weather Condition for a particular city")]
        public XmlElement GetWeatherCondition(string strLocation)
        {

            strLocation += ".xml";
            DataSet ds = new DataSet("Weather_Condition");

            XmlDocument xmlConditions = new XmlDocument();


            try
            {
              xmlConditions.Load(string.Format("http://api.wunderground.com/api/xxxxxxx/geolookup/conditions/q/np/{0}", strLocation));

                if (xmlConditions.SelectSingleNode("/response/error") != null)
                {
                    //condition = null;
                    condition.Error = xmlConditions.SelectSingleNode("/response/error/description").InnerText;

                }
                else
                {
                    condition.City = xmlConditions.SelectSingleNode("/response/location/city").InnerText;
                    condition.Condition = xmlConditions.SelectSingleNode("/response/current_observation/weather").InnerText;

.........
dtCurrent.Rows.Add(condition.City, DateTime.Now.DayOfWeek.ToString(), condition.Condition, condition.TempF, condition.TempC, condition.Humidity, condition.Wind, condition.Error, condition.IconUrl);
                    ds.Tables.Add(dtCurrent);
                }
                
                XmlDataDocument xDataDoc = new XmlDataDocument(ds);
            XmlElement xDataElement = xDataDoc.DocumentElement;

            return xDataElement;
}                            

The Code works gr8, but when there is no internet connection, then the xmlconditions.Load( url that returns the xml data) fails. Now what i want is if there is no internet connection then i want to return default values that's inside a different class(condition). How can i do that?? i wrote it in catch as follows
C#
catch 
            {
                dtCurrent.Rows.Add(condition.City, DateTime.Now.DayOfWeek.ToString(), condition.Condition, condition.TempF, condition.TempC, condition.Humidity, condition.Wind, condition.Error, condition.IconUrl);
                ds.Tables.Add(dtCurrent);
                
            }
but this breaks the execution of the entire application and webform does not load beacause of this single weather control.

Further improving the Question...i have called this function in a classlibrary...in the library i have a function as follows...
C#
public Dictionary<string,string> LoadCurrentCondition(string strCity)
        {
            
            XmlElement xData = Weather.GetWeatherCondition(strCity);
// this function call fails when there is no internet connection...some //webservice.soapexception...


i want to make changes in the GetWeatherCondtion() function so that it can return default values when there is no internet connection.

FYI, Condtion class is as follows,
C#
public class Conditions
    {
        private string strCity = "No Data";
        private string strConditions = "No Data";
        private string strDayOfWeek = DateTime.Now.DayOfWeek.ToString();
        private string strTempF = "No Data";
        private string strMinTempF = "No Data";
        private string strTempC = "No Data";

 public string City
        {
            get
            {
                return this.strCity;
            }
            set
            {
                this.strCity = value;
            }

        }
        public string Condition
        {
            get
            {
                return this.strConditions;
            }
            set
            {
                this.strConditions = value;
            }
        }
}

as you can see from the conditions class, i just need to get the properties values and return them...which is by default "No DATA" when there is no internet connection...but i'm not being able to do so.
Please help
Minghang
Posted
Updated 21-Nov-12 8:03am
v3
Comments
Sergey Alexandrovich Kryukov 21-Nov-12 13:29pm    
Class or structure (or an object graph)? There are subtleties, not very considerable though...
--SA

Why dont you put your XmlDocument.Load in separate try catch

C#
try
{
xmlConditions.Load(string.Format("http://api.wunderground.com/api/xxxxxxx/geolookup/conditions/q/np/{0}", strLocation));
}
catch()
{
 // prepare dummy XML
}
//Also check if document loaded correctly
if(xmlConditions == null || xmlConditions.DocumentElement == null)
{
 // prepare dummy xml
}


Hope that helps.
Updated after OP comment:
Minghang. I believe you are trying to put whole code in the try and in the catch you are preparing the xml. In this case, probably it is throwing exception at some place and in your catch you are just preparing the table and datase but not XML out of it.

What I am suggesting is little different i.e. just put XmlConditions.Load in the separate (inner) try and in that try's catch you prepare dummy XML and return from there itself.
Or other way is to put return XML preparation in the finally block.

Sorry if misunderstood your requirement.
Milind
 
Share this answer
 
v2
Comments
Minghang 21-Nov-12 13:50pm    
Thankyou milind for your reply, but that's not what i was looking for, i did the "prepare dummy xml" in the catch...but it didn't work...it still fails to return the default values.
MT_ 22-Nov-12 0:52am    
Check the updated lines please.
Minghang 23-Nov-12 1:26am    
thankyou milind...i'll try what you suggested...i'm a bit occupied by some work right now...i'll let you know if it works. Thanks again
Minghang 4-Dec-12 1:03am    
thankyou millind...i finally get what you were saying...and that's the exact solution i wanted...i just rethrew the exception and handled the exception higher up and returned something else when there is no available internet connection...seems like i really didn't understand exception handling in the first place.
thanks again
minghang
MT_ 4-Dec-12 1:05am    
Welcome. Glad I could help. :-)
You can have a default constructor, let's say, parameterless. You don't have to write one, because if can be your only and default (implicit) constructor, and the actual defaults are initialized by each member by default of by initializers, which are allowed in C# classes but not structures. An initialization through serialization (Data Contract or whatever) could be done in a factory method of your type, call it Load. Failed Load can fallback to default. For a class, it would look like this:

C#
[DataContract(/* ... */] // maybe, it's not a point here
public class MyClass {

    public static class MyClass Load(System.IO.Stream stream) { // a factory method
        try {
            return GetInstanceFromSerialization(stream); // whatever it is
        } catch {
            return new MyClass(); // falls back to default
        } //exception
    } //Load

    public static MyClass Load(string filename) { // another factory method
        try {
            return GetInstanceFromSerialization(filename); // whatever it is
        } catch {
            return new MyClass(); // falls back to default
        } //exception
    } //Load

    public MyClass() { /* ... */ } //this constructor may or may not be needed,
    //depending on available per-member initializers and other constructors

    //...

} //class MyClass


As simple as that. Just the idea. If your case is somewhat more complex, the idea is the same. If you are still confused about doing it for more complex cases, don't hesitate to ask your follow-up questions.

—SA
 
Share this answer
 
v7
Comments
Minghang 21-Nov-12 13:52pm    
hey thanks sergey for the reply, i'll look into your solution. i'm not an expert so it'll take me a while to get it in my head...if there;s nything then i'll let you know
Sergey Alexandrovich Kryukov 21-Nov-12 14:02pm    
You are welcome. Not a problem, but your feed back would be nice to have...
Things are simple enough, but you might need to know a piece of information of default constructor, how static vs instance (non-static) works and serialization, whatever it is...
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900