Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Index was out of range in Blazor [duplicate]

$
0
0

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

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

System.ArgumentOutOfRangeExceptionHResult=0x80131502Message=Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')Source=System.Private.CoreLibStackTrace: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.UpdateAndExecute2T0,T1,TRetat ElevationFinder.Pages.Index.<Submit>d__20.MoveNext() in C:\Users\allam\source\repos\ElevationFinder\ElevationFinder\Pages\Index.razor:line 222This exception was originally thrown at this call stack:CopySystem.ThrowHelper.ThrowArgumentOutOfRange_IndexMustBeLessException()System.Collections.Generic.List<T>.this[int].get(int)Newtonsoft.Json.Linq.JContainer.GetItem(int)System.Dynamic.UpdateDelegates.UpdateAndExecute2<T0, T1, TRet>(System.Runtime.CompilerServices.CallSite, T0, T1)ElevationFinder.Pages.Index.Submit() in Index.razor
@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 />    @loc<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 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 = "Au7sMtQzyQZRzuQ2krOIbZg8j2MGoHzzOJAmVym6vQjHq_BJ8a1YQGX3iCosFh8u";        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                {                    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 = "";                    errmsg = "Invalid Location";                }                time1 = timez.Substring(0, 2);                time2 = timez.Substring(3, 2);                time3 = timez.Substring(5, 14);                timef = timez.Substring(11, 8);        }          }}

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>