Index was out of range in Blazor

Anonymous
2024-04-11T09:28:22.69+00:00

When searched for Location that doesn't exist timeZoneAtLocation[0] is [] and is throwing the below error .

Please suggest on how to check nulls.

Note : Replace

"My Bing Key"

with Bing Key.

timez = data3.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.localTime;

System.ArgumentOutOfRangeException

HResult=0x80131502

Message=Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')

Source=System.Private.CoreLib

StackTrace:

at System.ThrowHelper.ThrowArgumentOutOfRange_IndexMustBeLessException()

at System.Collections.Generic.List`1.get_Item(Int32 index)

at Newtonsoft.Json.Linq.JContainer.GetItem(Int32 index)

at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet]

at ElevationFinder.Pages.Index.

Developer technologies | .NET | Blazor
Azure Maps
Azure Maps
An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
831 questions
Azure | Azure Startups
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2024-04-12T13:05:49.62+00:00

    I added another line and I able to trap exception

    placename =data3.resourceSets[0].resources[0].timeZoneAtLocation[0].placename;

     
    @page "/"
    @using Newtonsoft.Json;
    @using Microsoft.AspNetCore.Components.Forms
    @using System.Text;
    @using System.Net.Http.Headers;
    <h1>Elevation </h1>
    <EditForm Model="@submitActivity" OnSubmit="@Submit">
    <div class="row">
        <div class="col-md-3">
            <p>Location</p>
        </div>
        <div class="col-md-4">
            <input placeholder="Location" @bind="@loc" />
        </div>
    </div>
    <br />
    <div>
        <button type="submit">Submit</button>
    </div>
    <div>
        @errmsg
    </div>
    <br />
        @placename
    <br />
        <p>Altitude</p>
     <br/>
        @elevation
        <p>Meters</p>
        <br/>
        <p>Time</p>
        <br />
        @timez
        <br />
        @timezone
        <p>Weather</p>
        <br/>
        @temparature 
        <p>C</p>
        <br />
        @tempformat
        <p>F</p>
        @weather
    </EditForm>
    @code {
        private string loc; string errmsg = ""; double latitude = 0.0; double tempf; double tempformat; double temparature;
        double longitude = 0.0; double elevation = 0.0; string placename;
        string time1 = "";
        string time2 = "";
        string time3 = "";
        dynamic timezone = ""; dynamic timez = ""; string weather = "";
        string timef = "";
        private ACTIVITY submitActivity { get; set; } = new();
        public class ACTIVITY
        {        public string Dummy { get; set; }
        }
        private  async Task Submit()
        {
            string key = "MY Bing Key";
            string query = loc; 
            using (HttpClient client = new HttpClient())
            {
                string timez = "";
                string final = "";
                string timezone = "";
                string checknull = "";
                string time3 = "";
                string timef = ""; 
                Uri geocodeRequest = new Uri(string.Format("https://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key));
                client.BaseAddress = new Uri(geocodeRequest.ToString());
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response1 = null;
                try
                {
                    response1 = await client.GetAsync(geocodeRequest);
                    string     jsonstring = await response1.Content.ReadAsStringAsync();
                    // Parse the JSON response to extract the address
                    dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);
                    var result1 = data1.resourceSets[0].resources[0];
                    latitude = result1.point.coordinates[0];
                    longitude = result1.point.coordinates[1];
                }
                catch (Exception e)
                {
                    loc = "";
                    timez = "";
                    errmsg = "Invalid Location";
                }
            }
            using (HttpClient client1 = new HttpClient())
            {
                Uri elevationReq = new Uri($"https://api.open-meteo.com/v1/elevation?latitude={latitude}&longitude={longitude}");
                client1.BaseAddress = new Uri(elevationReq.ToString());
                client1.DefaultRequestHeaders.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response2 = null;
                try
                {
                    response2 = await client1.GetAsync(elevationReq);
                    string jsonstring2 = await response2.Content.ReadAsStringAsync();
                    // Parse the JSON response to extract the address
                    dynamic datael = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring2);
                    elevation = datael.elevation[0];
                }
                catch (Exception e)
                {
                    loc = "";
                    elevation = 0;
                    errmsg = "Invalid Location";
                }
            }
            using (HttpClient client3 = new HttpClient())
            {
                string urlw = $"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current_weather=true";
                client3.BaseAddress = new Uri(urlw.ToString());
                client3.DefaultRequestHeaders.Clear();
                client3.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage responsew = null;
                try
                {
                    responsew = await client3.GetAsync(urlw);
                    string jsonw = await responsew.Content.ReadAsStringAsync();
                    dynamic dataw = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonw);
                    tempf = (dataw.current_weather.temperature * 1.8) + 32;
                    tempformat = Math.Round(tempf, 1);
                    temparature = dataw.current_weather.temperature;
                    int weathercode = dataw.current_weather.weathercode;
                    switch (weathercode)
                    {
                        case 0:
                            weather = "Clear Sky";
                            break;
                        case 1:
                            weather = "Mainly Clear";
                            break;
                        case 2:
                            weather = " partly cloudy";
                            break;
                        case 3:
                            weather = "overcast";
                            break;
                        case 51:
                            weather = "Rain  Slight";
                            break;
                        case 53:
                            weather = "Rain moderate";
                            break;
                        case 55:
                            weather = "Rain heaving intensity";
                            break;
                        case 71:
                            weather = "Snowfall  Slight";
                            break;
                        case 73:
                            weather = "Snowfall moderate";
                            break;
                        case 75:
                            weather = "Snowfall heaving intensity";
                            break;
                        case 80:
                            weather = "Rain showers slight";
                            break;
                        case 81:
                            weather = "Rain showers moderate";
                            break;
                        case 82:
                            weather = " Rain showers violent";
                            break;
                        case 85:
                            weather = "Snow showers slight";
                            break;
                        case 86:
                            weather = " Snow showers heavy";
                            break;
                        case 95:
                            weather = " Thunderstorm: Slight or moderate";
                            break;
                        default:
                            weather = " ";
                            break;
                    }
                }
                catch (Exception e)
                {
                    loc = "";
                    temparature = 0.0; tempformat = 0.0;
                    errmsg = "Invalid Location";
                }
            }
            using (HttpClient client2 = new HttpClient())
            {
                Uri geocodetime = new Uri(string.Format("https://dev.virtualearth.net/REST/v1/timezone/?q={0}&key={1}", query, key));
                client2.BaseAddress = new Uri(geocodetime.ToString());
                client2.DefaultRequestHeaders.Clear();
                client2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response3 = null;
                string final = "";
                int len;
                string checknull = "";
                string checkflag = "N";
                response3 = await client2.GetAsync(geocodetime);
                string jsonstring3 = await response3.Content.ReadAsStringAsync();
                // Parse the JSON response to extract the address
                dynamic data3 = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring3);
                try
                {
                    placename =data3.resourceSets[0].resources[0].timeZoneAtLocation[0].placeName;
                    timez = data3.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.localTime;
                    timezone = data3.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.timeZoneDisplayName;
                }
                catch (Exception e)
                {
                    loc = "";
                    timez = "";
                    timezone = "";
                    errmsg = "Invalid Location";
                    weather = "";
                    elevation = 0.0;
                    placename = ""; tempformat = 0.0; temparature = 0.0;
                }
                 
                
            }
              }
    }
    
    0 comments No comments

  2. rbrundritt 20,836 Reputation points Microsoft Employee Moderator
    2024-07-03T15:00:04.5033333+00:00

    Check the length of the timeZoneAtLocation property before trying to use it.

    if (data3.resourceSets[0].resources[0].timeZoneAtLocation.Length > 0) 
    {
    	placename =data3.resourceSets[0].resources[0].timeZoneAtLocation[0].placeName;
    	timez = data3.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.localTime;
    	timezone = data3.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.timeZoneDisplayName;       
    } 
    else 
    {
    	loc = "";
    	timez = "";
    	timezone = "";
    	errmsg = "Invalid Location";
    	weather = "";
    	elevation = 0.0;
    	placename = ""; tempformat = 0.0; temparature = 0.0;
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.