Exemple #1
0
 public async Task Update(ErrorOrigin entity)
 {
     using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
     {
         cmd.CommandText = "UPDATE ErrorOrigins SET " +
                           "CountryCode=@CountryCode, " +
                           "CountryName=@CountryName, " +
                           "RegionCode=@RegionCode, " +
                           "RegionName=@RegionName, " +
                           "City=@City, " +
                           "ZipCode=@ZipCode, " +
                           "Latitude=@Latitude, " +
                           "Longitude=@Longitude, " +
                           "IsLookedUp = 1 " +
                           "WHERE Id = @id";
         cmd.AddParameter("CountryCode", entity.CountryCode);
         cmd.AddParameter("CountryName", entity.CountryName);
         cmd.AddParameter("RegionCode", entity.RegionCode);
         cmd.AddParameter("RegionName", entity.RegionName);
         cmd.AddParameter("City", entity.City);
         cmd.AddParameter("ZipCode", entity.ZipCode);
         cmd.AddParameter("Latitude", entity.Latitude);
         cmd.AddParameter("Longitude", entity.Longitude);
         cmd.AddParameter("Id", entity.Id);
         await cmd.ExecuteNonQueryAsync();
     }
 }
Exemple #2
0
        /// <summary>
        /// Appends text and scrolls down the log
        /// </summary>
        public void AppendOutput(string s, ErrorType errorType, ErrorOrigin origin)
        {
            if (errorType != ErrorType.Message)
            {
                s = "> (" + DateTime.Now.ToLongTimeString() + ") " + s;
            }
            TextEditor        editor = null;
            var               selTab = LogTab.System;
            TextMarkerService tms    = null;

            switch (origin)
            {
            default:
                editor = Text_Sys;
                selTab = LogTab.System;
                tms    = tms1;
                break;

            case ErrorOrigin.Build:
                editor = Text_Build;
                selTab = LogTab.Build;
                tms    = tms2;
                break;

            case ErrorOrigin.Debug:
            case ErrorOrigin.Program:
                selTab = LogTab.Output;
                editor = Text_Output;
                tms    = tms3;
                break;
            }

            if (editor == null)
            {
                return;
            }

            //TODO?: Find out why invoking the dispatcher thread blocks the entire application sometimes
            if (!Util.IsDispatcherThread)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    SelectedTab = selTab;
                    int off     = editor.Document.TextLength;
                    editor.AppendText(s + "\r\n");
                    editor.ScrollToEnd();

                    AddMarkerForOffsetUntilEnd(editor, tms, off, errorType);
                }), System.Windows.Threading.DispatcherPriority.Background);
            }
            else
            {
                int off = editor.Document.TextLength;
                SelectedTab = selTab;
                editor.AppendText(s + "\r\n");
                editor.ScrollToEnd();

                AddMarkerForOffsetUntilEnd(editor, tms, off, errorType);
            }
        }
Exemple #3
0
 internal void Set(Exception e, ErrorOrigin origin = ErrorOrigin.None)
 {
     Error      = e.ToMessage();
     Originator = origin;
     Exception  = e;
     _callback?.Invoke(this);
 }
Exemple #4
0
        /// <summary>
        ///     Process an event asynchronously.
        /// </summary>
        /// <param name="e">event to process</param>
        /// <returns>
        ///     Task to wait on.
        /// </returns>
        public async Task HandleAsync(IMessageContext context, ReportAddedToIncident e)
        {
            // Random swedish IP for testing purposes
            if (e.Report.RemoteAddress == "::1" || e.Report.RemoteAddress == "127.0.0.1")
            {
                e.Report.RemoteAddress = "94.254.57.227";
            }

            var numberStyles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;
            var collection   = e.Report.GetCoderrCollection();

            if (collection != null)
            {
                var latitude  = 0d;
                var longitude = 0d;
                var gotLat    = collection.Properties.TryGetValue("Longitude", out var longitudeStr) &&
                                double.TryParse(longitudeStr, numberStyles,
                                                CultureInfo.InvariantCulture, out longitude);

                var gotLong = collection.Properties.TryGetValue("Latitude", out var latitudeStr) &&
                              double.TryParse(latitudeStr, numberStyles,
                                              CultureInfo.InvariantCulture, out latitude);
                if (gotLat && latitude > 0 && gotLong && longitude > 0)
                {
                    var errorOrigin2 = new ErrorOrigin(e.Report.RemoteAddress, longitude, latitude);
                    await _repository.CreateAsync(errorOrigin2, e.Incident.ApplicationId, e.Incident.Id, e.Report.Id);

                    return;
                }
            }


            var latitude1  = e.Report.FindCollectionProperty("ReportLatitude");
            var longitude1 = e.Report.FindCollectionProperty("ReportLongitude");

            if (longitude1 != null &&
                double.TryParse(latitude1, numberStyles, CultureInfo.InvariantCulture,
                                out var latitude2) &&
                latitude1 != null &&
                double.TryParse(longitude1, numberStyles, CultureInfo.InvariantCulture,
                                out var longitude2))
            {
                var errorOrigin2 = new ErrorOrigin(e.Report.RemoteAddress, longitude2, latitude2);
                await _repository.CreateAsync(errorOrigin2, e.Incident.ApplicationId, e.Incident.Id, e.Report.Id);

                return;
            }


            if (string.IsNullOrEmpty(e.Report.RemoteAddress) ||
                string.IsNullOrEmpty(_originConfiguration.Value?.ApiKey))
            {
                return;
            }


            var origin = new ErrorOrigin(e.Report.RemoteAddress);
            await _repository.CreateAsync(origin, e.Incident.ApplicationId, e.Incident.Id, e.Report.Id);
        }
Exemple #5
0
        private async Task LookupIpAddress(ErrorOrigin origin)
        {
            if (string.IsNullOrEmpty(_originConfiguration.Value.ApiKey))
            {
                return;
            }

            var url     = $"http://api.ipstack.com/{origin.IpAddress}?access_key={_originConfiguration.Value.ApiKey}";
            var request = WebRequest.CreateHttp(url);
            var json    = "";

            try
            {
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                /*
                 *  {
                 *     "ip":"94.254.21.175",
                 *     "country_code":"SE",
                 *     "country_name":"Sweden",
                 *     "region_code":"10",
                 *     "region_name":"Dalarnas Lan",
                 *     "city":"Falun",
                 *     "zipcode":"",
                 *     "latitude":60.6,
                 *     "longitude":15.6333,
                 *     "metro_code":"",
                 *     "areacode":""
                 *  }
                 */

                // Key is only included in error messages.
                if (jsonObj.ContainsKey("success"))
                {
                    return;
                }

                var lat = double.Parse(jsonObj["latitude"].Value <string>(), CultureInfo.InvariantCulture);
                var lon = double.Parse(jsonObj["longitude"].Value <string>(), CultureInfo.InvariantCulture);
                origin.Longitude   = lon;
                origin.Latitude    = lat;
                origin.City        = jsonObj["city"].ToString();
                origin.CountryCode = jsonObj["country_code"].ToString();
                origin.CountryName = jsonObj["country_name"].ToString();
                origin.RegionCode  = jsonObj["region_code"].ToString();
                origin.RegionName  = jsonObj["region_name"].ToString();
                origin.ZipCode     = jsonObj["zip"].ToString();
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to call lookupService or parse the JSON: {json}.", exception);
            }
        }
        /// <summary>
        ///     Process an event asynchronously.
        /// </summary>
        /// <param name="e">event to process</param>
        /// <returns>
        ///     Task to wait on.
        /// </returns>
        public async Task HandleAsync(IMessageContext context, ReportAddedToIncident e)
        {
            if (string.IsNullOrEmpty(e.Report.RemoteAddress))
            {
                return;
            }

            if (string.IsNullOrEmpty(_originConfiguration.Value?.ApiKey))
            {
                return;
            }

            if (e.Report.RemoteAddress == "::1")
            {
                return;
            }
            if (e.Report.RemoteAddress == "127.0.0.1")
            {
                e.Report.RemoteAddress = "94.254.57.227";
            }

            var    url     = $"http://api.ipstack.com/{e.Report.RemoteAddress}?access_key={_originConfiguration.Value.ApiKey}";
            var    request = WebRequest.CreateHttp(url);
            string json    = "";

            try
            {
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                /*    /*{"ip":"94.254.21.175","country_code":"SE","country_name":"Sweden","region_code":"10","region_name":"Dalarnas Lan","city":"Falun","zipcode":"",
                 * "latitude":60.6,"longitude":15.6333,
                 * "metro_code":"","areacode":""}*/

                var lat = double.Parse(jsonObj["latitude"].Value <string>(), CultureInfo.InvariantCulture);
                var lon = double.Parse(jsonObj["longitude"].Value <string>(), CultureInfo.InvariantCulture);
                var cmd = new ErrorOrigin(e.Report.RemoteAddress, lon, lat)
                {
                    City        = jsonObj["city"].ToString(),
                    CountryCode = jsonObj["country_code"].ToString(),
                    CountryName = jsonObj["country_name"].ToString(),
                    RegionCode  = jsonObj["region_code"].ToString(),
                    RegionName  = jsonObj["region_name"].ToString(),
                    ZipCode     = jsonObj["zip"].ToString()
                };

                await _repository.CreateAsync(cmd, e.Incident.ApplicationId, e.Incident.Id, e.Report.Id);
            }
            catch (Exception exception)
            {
                _logger.Error($"Failed to store location for incident {e.Incident.Id}/report {e.Report.Id}: {json}", exception);
            }
        }
Exemple #7
0
        protected override void OnLog(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                new CrashDialog(ex).ShowDialog();
            }));

            //base.OnLog(ex, ErrorType, Origin);
        }
Exemple #8
0
        public async Task Can_store_origin()
        {
            var origin = new ErrorOrigin("127.0.0.1", 934.934, 28.282);
            var uow    = ConnectionFactory.Create();

            var handler = new ErrorOriginRepository(uow);
            await handler.CreateAsync(origin, 1, 2, 3);

            uow.Dispose();
        }
        public async Task Can_store_origin()
        {
            var origin = new ErrorOrigin("127.0.0.1", 934.934, 28.282);

            using (var uow = CreateUnitOfWork())
            {
                var handler = new ErrorOriginRepository(uow);
                await handler.CreateAsync(origin, FirstApplicationId, _incidentId, _reportId);

                uow.SaveChanges();
            }
        }
Exemple #10
0
 public static void Throw(ErrorOrigin origin, String message)
 {
     throw new Exception(
               Print.Alert(
                   "Error",
                   Print.SubContent(new string[] {
         Print.Message(origin.ToString(), message)
     }
                                    )
                   )
               );
 }
        public async Task Can_store_origin()
        {
            var origin = new ErrorOrigin("127.0.0.1", 934.934, 28.282);
            var uow    = _testTools.CreateUnitOfWork();

            _testTools.CreateUserAndApp();

            var handler = new ErrorOriginRepository(uow);
            await handler.CreateAsync(origin, 1, 1, 1);

            uow.Dispose();
        }
        public async Task CreateAsync(ErrorOrigin entity, int applicationId, int incidentId, int reportId)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (applicationId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationId));
            }
            if (incidentId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(incidentId));
            }
            if (reportId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(reportId));
            }

            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = "SELECT Id FROM ErrorOrigins WHERE IpAddress = @ip";
                cmd.AddParameter("ip", entity.IpAddress);
                var id = await cmd.ExecuteScalarAsync();

                if (id is int)
                {
                    await CreateReportInfoAsync((int)id, applicationId, incidentId, reportId);

                    return;
                }
            }

            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO ErrorOrigins (IpAddress, CountryCode, CountryName, RegionCode, RegionName, City, ZipCode, Latitude, Longitude, CreatedAtUtc) "
                                  +
                                  "VALUES (@IpAddress, @CountryCode, @CountryName, @RegionCode, @RegionName, @City, @ZipCode, @Latitude, @Longitude, @CreatedAtUtc);select cast(SCOPE_IDENTITY() as int);";
                cmd.AddParameter("IpAddress", entity.IpAddress);
                cmd.AddParameter("CountryCode", entity.CountryCode);
                cmd.AddParameter("CountryName", entity.CountryName);
                cmd.AddParameter("RegionCode", entity.RegionCode);
                cmd.AddParameter("RegionName", entity.RegionName);
                cmd.AddParameter("City", entity.City);
                cmd.AddParameter("ZipCode", entity.ZipCode);
                //cmd.AddParameter("Point", SqlGeography.Point(command.Latitude, command.Longitude, 4326));
                cmd.AddParameter("Latitude", entity.Latitude);
                cmd.AddParameter("Longitude", entity.Longitude);
                cmd.AddParameter("CreatedAtUtc", DateTime.UtcNow);
                var id = (int)await cmd.ExecuteScalarAsync();
                await CreateReportInfoAsync(id, applicationId, incidentId, reportId);
            }
        }
Exemple #13
0
        /// <summary>
        ///     Process an event asynchronously.
        /// </summary>
        /// <param name="e">event to process</param>
        /// <returns>
        ///     Task to wait on.
        /// </returns>
        public async Task HandleAsync(ReportAddedToIncident e)
        {
            if (string.IsNullOrEmpty(e.Report.RemoteAddress))
            {
                return;
            }

            if (e.Report.RemoteAddress == "::1")
            {
                return;
            }
            if (e.Report.RemoteAddress == "127.0.0.1")
            {
                return;
            }

            var    request = WebRequest.CreateHttp("http://freegeoip.net/json/" + e.Report.RemoteAddress);
            string json    = "";

            try
            {
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                /*    /*{"ip":"94.254.21.175","country_code":"SE","country_name":"Sweden","region_code":"10","region_name":"Dalarnas Lan","city":"Falun","zipcode":"",
                 * "latitude":60.6,"longitude":15.6333,
                 * "metro_code":"","areacode":""}*/

                var lat = double.Parse(jsonObj["latitude"].Value <string>(), CultureInfo.InvariantCulture);
                var lon = double.Parse(jsonObj["longitude"].Value <string>(), CultureInfo.InvariantCulture);
                var cmd = new ErrorOrigin(e.Report.RemoteAddress, lon, lat)
                {
                    City        = jsonObj["city"].ToString(),
                    CountryCode = jsonObj["country_code"].ToString(),
                    CountryName = jsonObj["country_name"].ToString(),
                    RegionCode  = jsonObj["region_code"].ToString(),
                    RegionName  = jsonObj["region_name"].ToString(),
                    ZipCode     = jsonObj["zip_code"].ToString()
                };

                await _repository.CreateAsync(cmd, e.Incident.ApplicationId, e.Incident.Id, e.Report.Id);
            }
            catch (Exception exception)
            {
                _logger.Error("Failed to store location: " + json, exception);
            }
        }
Exemple #14
0
		/// <summary>
		/// Appends text and scrolls down the log
		/// </summary>
		public void AppendOutput(string s,ErrorType errorType,ErrorOrigin origin)
		{
			if(errorType!=ErrorType.Message)
				s = "> ("+DateTime.Now.ToLongTimeString()+") "+s;
			TextEditor editor=null;
			var selTab = LogTab.System;
			TextMarkerService tms = null ;
			switch (origin)
			{
				default:
					editor = Text_Sys;
					selTab = LogTab.System;
					tms = tms1;
					break;
				case ErrorOrigin.Build:
					editor = Text_Build;
					selTab = LogTab.Build;
					tms = tms2;
					break;
				case ErrorOrigin.Debug:
				case ErrorOrigin.Program:
					selTab = LogTab.Output;
					editor = Text_Output;
					tms = tms3;
					break;
			}

			if (editor == null)
				return;			

			//TODO?: Find out why invoking the dispatcher thread blocks the entire application sometimes
			if (!Util.IsDispatcherThread)
				Dispatcher.BeginInvoke(new Action(() =>
				{
					SelectedTab = selTab;
					int off=editor.Document.TextLength;
					editor.AppendText(s + "\r\n");
					editor.ScrollToEnd();

					AddMarkerForOffsetUntilEnd(editor, tms, off,errorType);
				}),System.Windows.Threading.DispatcherPriority.Background);
			else
			{
				int off = editor.Document.TextLength;
				SelectedTab = selTab;
				editor.AppendText(s + "\r\n");
				editor.ScrollToEnd();

				AddMarkerForOffsetUntilEnd(editor, tms, off,errorType);
			}
		}
Exemple #15
0
 protected override void OnLog(string Message, ErrorType etype, ErrorOrigin Origin)
 {
     if (Origin == ErrorOrigin.System)
     {
         base.OnLog(Message, etype, Origin);
     }
     try
     {
         if (Owner != null && Owner.Panel_Log != null)
         {
             Owner.Panel_Log.AppendOutput(Message, etype, Origin);
         }
     }
     catch { }
 }
        private async Task <ErrorOrigin> LookupIpAddress(ReportAddedToIncident e)
        {
            var         url     = $"http://api.ipstack.com/{e.Report.RemoteAddress}?access_key={_originConfiguration.Value.ApiKey}";
            var         request = WebRequest.CreateHttp(url);
            var         json    = "";
            ErrorOrigin errorOrigin;

            try
            {
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                /*    /*{"ip":"94.254.21.175","country_code":"SE","country_name":"Sweden","region_code":"10","region_name":"Dalarnas Lan","city":"Falun","zipcode":"",
                 * "latitude":60.6,"longitude":15.6333,
                 * "metro_code":"","areacode":""}*/

                var lat = double.Parse(jsonObj["latitude"].Value <string>(), CultureInfo.InvariantCulture);
                var lon = double.Parse(jsonObj["longitude"].Value <string>(), CultureInfo.InvariantCulture);
                errorOrigin = new ErrorOrigin(e.Report.RemoteAddress, lon, lat)
                {
                    City        = jsonObj["city"].ToString(),
                    CountryCode = jsonObj["country_code"].ToString(),
                    CountryName = jsonObj["country_name"].ToString(),
                    RegionCode  = jsonObj["region_code"].ToString(),
                    RegionName  = jsonObj["region_name"].ToString(),
                    ZipCode     = jsonObj["zip"].ToString()
                };
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to call lookupService or parse the JSON: {json}.", exception);
            }

            return(errorOrigin);
        }
Exemple #17
0
        protected virtual void OnLog(string Message, ErrorType ErrorType, ErrorOrigin origin)
        {
            var icon = MessageBoxIcon.Error;

            if (ErrorType == ErrorType.Warning)
            {
                icon = MessageBoxIcon.Warning;
            }
            else if (ErrorType == ErrorType.Information || ErrorType == ErrorType.Message)
            {
                icon = MessageBoxIcon.Information;
            }

            MessageBox.Show(Message, origin.ToString() + " " + ErrorType.ToString(), MessageBoxButtons.OK, icon);

            try
            {
                if (origin == ErrorOrigin.System)
                {
                    File.AppendAllText(IDEInterface.ConfigDirectory + "\\sys.log", Message + "\r\n", System.Text.Encoding.Unicode);
                }
            }
            catch { }
        }
Exemple #18
0
 public static void Log(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
 {
     Instance.OnLog(ex, ErrorType, Origin);
 }
Exemple #19
0
 protected virtual void OnLog(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
 {
     OnLog(ex.Message, ErrorType, Origin);
 }
Exemple #20
0
 public ErrorContent(string message, ErrorOrigin errorType)
 {
     Message   = message;
     ErrorType = errorType;
 }
Exemple #21
0
		protected override void OnLog(string Message, ErrorType etype, ErrorOrigin Origin)
		{
			if(Origin==ErrorOrigin.System)
				base.OnLog(Message, etype,Origin);
			try
			{
				if (Owner != null && Owner.Panel_Log != null)
					Owner.Panel_Log.AppendOutput(Message, etype, Origin);
			}
			catch { }
		}
Exemple #22
0
		public static void Log(string Message, ErrorType ErrorType,ErrorOrigin Origin)
		{
			Instance.OnLog(Message,ErrorType,Origin);
		}
Exemple #23
0
 public static void Log(string Message, ErrorType ErrorType, ErrorOrigin Origin)
 {
     Instance.OnLog(Message, ErrorType, Origin);
 }
Exemple #24
0
        private async Task LookupCoordinatesUsingMapQuest(string mapQuestKey, ErrorOrigin origin)
        {
            #region JSON example

            /*
             *  {
             *    "info": {
             *      "statuscode": 0,
             *      "copyright": {
             *        "text": "© 2018 MapQuest, Inc.",
             *        "imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
             *        "imageAltText": "© 2018 MapQuest, Inc."
             *      },
             *      "messages": []
             *    },
             *    "options": {
             *      "maxResults": 1,
             *      "thumbMaps": true,
             *      "ignoreLatLngInput": false
             *    },
             *    "results": [
             *      {
             *        "providedLocation": {
             *          "latLng": {
             *            "lat": 30.333472,
             *            "lng": -81.470448
             *          }
             *        },
             *        "locations": [
             *          {
             *            "street": "12714 Ashley Melisse Blvd",
             *            "adminArea6": "",
             *            "adminArea6Type": "Neighborhood",
             *            "adminArea5": "Jacksonville",
             *            "adminArea5Type": "City",
             *            "adminArea4": "Duval",
             *            "adminArea4Type": "County",
             *            "adminArea3": "FL",
             *            "adminArea3Type": "State",
             *            "adminArea1": "US",
             *            "adminArea1Type": "Country",
             *            "postalCode": "32225",
             *            "geocodeQualityCode": "L1AAA",
             *            "geocodeQuality": "ADDRESS",
             *            "dragPoint": false,
             *            "sideOfStreet": "R",
             *            "linkId": "0",
             *            "unknownInput": "",
             *            "type": "s",
             *            "latLng": {
             *              "lat": 30.33472,
             *              "lng": -81.470448
             *            },
             *            "displayLatLng": {
             *              "lat": 30.333472,
             *              "lng": -81.470448
             *            },
             *            "mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=KEY&type=map&size=225,160&pois=purple-1,30.3334721,-81.4704483,0,0,|&center=30.3334721,-81.4704483&zoom=15&rand=-553163060",
             *            "nearestIntersection": {
             *              "streetDisplayName": "Posey Cir",
             *              "distanceMeters": "851755.1608527573",
             *              "latLng": {
             *                "longitude": -87.523761,
             *                "latitude": 35.013434
             *              },
             *              "label": "Danley Rd & Posey Cir"
             *            },
             *            "roadMetadata": {
             *              "speedLimitUnits": "mph",
             *              "tollRoad": null,
             *              "speedLimit": 40
             *            }
             *          }
             *        ]
             *      }
             *    ]
             *  }
             */
            #endregion

            var url =
                $"http://open.mapquestapi.com/geocoding/v1/reverse?key={mapQuestKey}&location={origin.Latitude.ToString(CultureInfo.InvariantCulture)},{origin.Longitude.ToString(CultureInfo.InvariantCulture)}&includeRoadMetadata=true&includeNearestIntersection=true";
            var request = WebRequest.CreateHttp(url);
            var json    = "";
            try
            {
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                var array = (JArray)jsonObj["results"][0]["locations"];
                if (array.Count == 0)
                {
                    return;
                }

                var firstLocation = jsonObj["results"][0]["locations"][0];
                origin.ZipCode = firstLocation["postalCode"].Value <string>();

                /*  "street": "12714 Ashley Melisse Blvd",
                 *        "adminArea6": "",
                 *        "adminArea6Type": "Neighborhood",
                 *        "adminArea5": "Jacksonville",
                 *        "adminArea5Type": "City",
                 *        "adminArea4": "Duval",
                 *        "adminArea4Type": "County",
                 *        "adminArea3": "FL",
                 *        "adminArea3Type": "State",
                 *        "adminArea1": "US",
                 *        "adminArea1Type": "Country",
                 *        "postalCode": "32225",*/

                for (var i = 1; i <= 6; i++)
                {
                    var token = firstLocation[$"adminArea{i}"];
                    var value = token?.Value <string>();
                    if (value == null)
                    {
                        continue;
                    }

                    switch (firstLocation[$"adminArea{i}Type"].Value <string>())
                    {
                    case "Country":
                        origin.CountryCode = value;
                        break;

                    case "State":
                        origin.RegionName = value;
                        break;

                    case "County":
                        break;

                    case "City":
                        origin.City = value;
                        break;
                    }
                }

                //origin.CountryName = firstLocation["country_name"].ToString();
                //origin.RegionCode = firstLocation["region_code"].ToString();
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to call lookupService or parse the JSON: {json}.", exception);
            }
        }
Exemple #25
0
        private async Task LookupCoordinatesUsingLocationIq(string apiKey, ErrorOrigin origin)
        {
            /*
             *      {
             *          "place_id": "26693344",
             *          "licence": "© LocationIQ.com CC BY 4.0, Data © OpenStreetMap contributors, ODbL 1.0",
             *          "osm_type": "node",
             *          "osm_id": "2525193585",
             *          "lat": "-37.870662",
             *          "lon": "144.9803321",
             *          "display_name": "Imbiss 25, Blessington Street, St Kilda, City of Port Phillip, Greater Melbourne, Victoria, 3182, Australia",
             *          "address": {
             *              "cafe": "Imbiss 25",
             *              "road": "Blessington Street",
             *              "suburb": "St Kilda",
             *              "county": "City of Port Phillip",
             *              "region": "Greater Melbourne",
             *              "state": "Victoria",
             *              "postcode": "3182",
             *              "country": "Australia",
             *              "country_code": "au"
             *          },
             *          "boundingbox": [
             *              "-37.870762",
             *              "-37.870562",
             *              "144.9802321",
             *              "144.9804321"
             *          ]
             *      }
             */
            var url =
                $"https://us1.locationiq.com/v1/reverse.php?key={apiKey}&lat={origin.Latitude.ToString(CultureInfo.InvariantCulture)}&lon={origin.Longitude.ToString(CultureInfo.InvariantCulture)}&format=json";

            var json = "";

            try
            {
                var request  = WebRequest.CreateHttp(url);
                var response = await request.GetResponseAsync();

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                json = await reader.ReadToEndAsync();

                var jsonObj = JObject.Parse(json);

                var address = jsonObj["address"];
                if (address == null)
                {
                    return;
                }

                /*  "address": {
                 *      "cafe": "Imbiss 25",
                 *      "road": "Blessington Street",
                 *      "suburb": "St Kilda",
                 *      "county": "City of Port Phillip",
                 *      "region": "Greater Melbourne",
                 *      "state": "Victoria",
                 *      "postcode": "3182",
                 *      "country": "Australia",
                 *      "country_code": "au"
                 *  }*/
                origin.City        = address["city"]?.Value <string>();
                origin.CountryCode = address["country_code"]?.Value <string>();
                origin.CountryName = address["country"]?.Value <string>();
                origin.RegionCode  = address["region_code"]?.Value <string>();
                origin.RegionName  = address["state"]?.Value <string>();
                origin.ZipCode     = address["postcode"]?.Value <string>();
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Failed to call lookupService or parse the JSON: {json}.", exception);
            }
        }
Exemple #26
0
		protected virtual void OnLog(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
		{
			OnLog(ex.Message, ErrorType, Origin);
		}
Exemple #27
0
		protected override void OnLog(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
		{
				Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
				{
					new CrashDialog(ex).ShowDialog();
				}));
			
			//base.OnLog(ex, ErrorType, Origin);
		}
Exemple #28
0
		public static void Log(Exception ex, ErrorType ErrorType, ErrorOrigin Origin)
		{
			Instance.OnLog(ex,ErrorType,Origin);
		}
Exemple #29
0
		protected virtual void OnLog(string Message, ErrorType ErrorType, ErrorOrigin origin)
		{
			var icon = MessageBoxIcon.Error;
			if (ErrorType==ErrorType.Warning)
				icon = MessageBoxIcon.Warning;
			else if (ErrorType==ErrorType.Information || ErrorType==ErrorType.Message)
				icon = MessageBoxIcon.Information;

			MessageBox.Show(Message,origin.ToString() +" "+ ErrorType.ToString(),MessageBoxButtons.OK,icon);

			try
			{
				if (origin == ErrorOrigin.System)
					File.AppendAllText(IDEInterface.ConfigDirectory + "\\sys.log", Message + "\r\n", System.Text.Encoding.Unicode);
			}
			catch { }
		}