GeocoderLocation IGeoCoder.Geocode(PropertyLocation address)
        {
            string queryAdress = string.Format(((IGeoCoder)this).UrlPattern, HttpUtility.UrlEncode(address.Street + " " + address.StreetNumber), HttpUtility.UrlEncode(address.City));

            WebRequest request = WebRequest.Create(queryAdress);
            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    XDocument document = XDocument.Load(stream);

                    XElement placeElement = document.Descendants("place").FirstOrDefault();

                    if (placeElement != null)
                    {
                        XAttribute longitudeElement = placeElement.Attribute("lon");
                        XAttribute latitudeElement = placeElement.Attribute("lat");

                        if (longitudeElement != null && latitudeElement != null)
                        {
                            return new GeocoderLocation()
                            {
                                Longitude = double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
                                Latitude = double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
                            };
                        }
                    }
                }
            }
            return null;
        }
        internal static string GetRouteAsStoredFile(PropertyLocation source, PropertyLocation destination)
        {
            if (!source.IsMeaningful)
            {
                Logger.Instance.LogFormat(LogType.Warning, typeof(RoutePlanHelper), Properties.Resources.NoSourceLocationDefined);
                return null;
            }
            if (!destination.IsMeaningful)
            {
                Logger.Instance.LogFormat(LogType.Warning, typeof(RoutePlanHelper), Properties.Resources.NoDestinationLocationAvailable);
                return null;
            }

            try
            {
                return GetRouteAsStoredFileCore(source, destination);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogFormat(LogType.Error, typeof(RoutePlanHelper), Properties.Resources.RoutePlanHelperError);
                Logger.Instance.LogException(typeof(RoutePlanHelper), ex);
            }

            return null;
        }
Example #3
0
        GeocoderLocation IGeoCoder.GeoCode(PropertyLocation address)
        {
            string queryAdress = string.Format(((IGeoCoder)this).UrlPattern, HttpUtility.UrlEncode(address.ToString()));

            WebRequest request = WebRequest.Create(queryAdress);

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    XDocument document = XDocument.Load(new StreamReader(stream));

                    XElement longitudeElement = document.Descendants("lng").FirstOrDefault();
                    XElement latitudeElement = document.Descendants("lat").FirstOrDefault();

                    if (longitudeElement != null && latitudeElement != null)
                    {
                        return new GeocoderLocation
                        {
                            Longitude = Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
                            Latitude = Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
                        };
                    }
                }
            }

            return null;
        }
Example #4
0
        GeocoderLocation IGeoCoder.Geocode(PropertyLocation address)
        {
            string queryAddress = string.Format(((IGeoCoder)this).UrlPattern, HttpUtility.UrlEncode(address.ToString()));
            if (!string.IsNullOrWhiteSpace(address.ZipCode))
            {
                queryAddress = string.Format("{0}&components=postal_code:{1}|country:DE", queryAddress, address.ZipCode);
            }
            WebRequest request = WebRequest.Create(queryAddress);

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    XDocument document = XDocument.Load(stream);

                    XElement longitudeElement = document.Descendants("lng").FirstOrDefault();
                    XElement latitudeElement = document.Descendants("lat").FirstOrDefault();

                    if (longitudeElement != null && latitudeElement != null)
                    {
                        return new GeocoderLocation()
                        {
                            Longitude = double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
                            Latitude = double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
                        };
                    }
                }
            }

            return null;
        }
Example #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OperationData"/> class.
        /// </summary>
        public OperationData()
        {
            Resources = new HashSet<OperationResourceData>();
            DispositionedResources = new HashSet<DispositionedResourceData>();

            Einsatzort = new PropertyLocation();
            Zielort = new PropertyLocation();
            Keywords = new OperationKeywords();
        }
        private static string GetRouteAsStoredFileCore(PropertyLocation source, PropertyLocation destination)
        {
            int width = 800;
            int height = 800;

            // https://developers.google.com/maps/documentation/directions/?hl=de

            string originText = source.ToString();
            string destinationText = destination.ToString();

            StringBuilder sbInitialRequest = new StringBuilder();
            sbInitialRequest.Append("http://maps.google.com/maps/api/directions/xml?");
            sbInitialRequest.AppendFormat("origin={0}", HttpUtility.UrlEncode(originText));
            sbInitialRequest.AppendFormat("&destination={0}", HttpUtility.UrlEncode(destinationText));
            sbInitialRequest.Append("&sensor=false");

            WebRequest wreqInitial = WebRequest.Create(sbInitialRequest.ToString());
            XDocument docResponse = null;
            using (WebResponse wresInitial = wreqInitial.GetResponse())
            {
                using (Stream stream = wresInitial.GetResponseStream())
                {
                    docResponse = XDocument.Load(stream);
                }

                string status = docResponse.Root.Element("status").Value;
                if (status != "OK")
                {
                    Logger.Instance.LogFormat(LogType.Error, typeof(RoutePlanHelper), Properties.Resources.MapsRequestFailed, status);
                    return null;
                }
            }

            XElement overviewE = docResponse.Root.Element("route").Element("overview_polyline").Element("points");

            StringBuilder sbContinuationRequest = new StringBuilder();
            sbContinuationRequest.Append("http://maps.google.com/maps/api/staticmap?");
            sbContinuationRequest.AppendFormat("size={0}x{1}", width, height);
            sbContinuationRequest.AppendFormat("&sensor=false&path=weight:3|color:red|enc:{0}", overviewE.Value);

            WebRequest wr1 = WebRequest.Create(sbContinuationRequest.ToString());
            using (WebResponse res1 = wr1.GetResponse())
            {
                using (Image image = Image.FromStream(res1.GetResponseStream()))
                {
                    using (FileStream tempFile = File.OpenWrite(Path.GetTempFileName()))
                    {
                        image.Save(tempFile, ImageFormat.Png);
                        return tempFile.Name;
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Operation"/> class and sets the value of the <see cref="P:TimestampIncome"/>-property to <see cref="P:DateTime.Now"/>.
        /// </summary>
        public Operation()
        {
            CustomData    = new Dictionary <string, object>();
            Resources     = new OperationResourceCollection();
            OperationGuid = Guid.NewGuid();
            Loops         = new OperationLoopCollection();

            Einsatzort = new PropertyLocation();
            Zielort    = new PropertyLocation();
            Keywords   = new OperationKeywords();

            TimestampIncome = DateTime.Now;
        }
Example #8
0
 internal static string GetRouteAsStoredFile(PropertyLocation source, PropertyLocation destination)
 {
     try
     {
         return GetRouteAsStoredFileCore(source, destination);
     }
     catch (Exception ex)
     {
         Logger.Instance.LogFormat(LogType.Error, typeof(RoutePlanHelper), Resources.RoutePlanHelperError);
         Logger.Instance.LogException(typeof(RoutePlanHelper), ex);
     }
     return null;
 }
Example #9
0
        /// <summary>
        /// Renders the given operation using the provided template file and restricts the output to the given size.
        /// </summary>
        /// <param name="source">The source location to start. This is usually the fire department site.</param>
        /// <param name="operation">The operation to render.</param>
        /// <param name="templateFile">The HTML template file to use for layouting.</param>
        /// <param name="size">The maximum size of the created image.</param>
        /// <returns></returns>
        internal static Image RenderOperation(PropertyLocation source, Operation operation, string templateFile, Size size)
        {
            TemplateObject to = new TemplateObject();
            to.Operation = operation;
            to.RouteImageFilePath = RoutePlanHelper.GetRouteAsStoredFile(source, operation.Einsatzort);

            // Create HTML to render
            StringBuilder sb = new StringBuilder();
            foreach (string line in File.ReadAllLines(templateFile))
            {
                sb.AppendLine(ObjectFormatter.ToString(to, line));
            }

            Image image = RenderOperationWithBrowser(to, sb.ToString(), size);

            TryDeleteRouteImageFile(to);

            return image;
        }
        /// <summary>
        /// Renders the given operation using the provided template file and restricts the output to the given size.
        /// </summary>
        /// <param name="source">The source location to start. This is usually the fire department site.</param>
        /// <param name="operation">The operation to render.</param>
        /// <param name="templateFile">The HTML template file to use for layouting.</param>
        /// <param name="size">The maximum size of the created image.</param>
        /// <returns></returns>
        internal static Image RenderOperation(PropertyLocation source, Operation operation, string templateFile, Size size)
        {
            TemplateObject to = new TemplateObject();
            to.Operation = operation;
            to.RouteImageFilePath = RoutePlanHelper.GetRouteAsStoredFile(source, operation.Einsatzort);

            Image image = null;
            try
            {
                string html = CreateHtml(templateFile, to);

                image = RenderOperationWithBrowser(to, html, size);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogException(typeof(TemplateRenderer), ex);
            }
            finally
            {
                TryDeleteRouteImageFile(to);
            }

            return image;
        }
        private PropertyLocation GetZielort(OperationData entity)
        {
            PropertyLocation pl = new PropertyLocation();
            pl.Street = entity.ZielortStreet;
            pl.StreetNumber = entity.ZielortStreetNumber;
            pl.ZipCode = entity.ZielortZipCode;
            pl.City = entity.ZielortCity;
            pl.Intersection = entity.ZielortIntersection;
            pl.Location = entity.ZielortLocation;
            pl.Property = entity.ZielortProperty;

            string[] latlng = entity.ZielortLatLng.Split(';');
            pl.GeoLatitude = latlng[0];
            pl.GeoLongitude = latlng[1];

            return pl;
        }
        /// <summary>
        /// Connects to Google Maps and queries an image displaying the route from the given start to finish position.
        /// See documentation for further information.
        /// </summary>
        /// <remarks>When using this method, make sure that the <paramref name="source"/> and <paramref name="destination"/>-parameters contain meaningful data!
        /// You can check this by calling <see cref="PropertyLocation.IsMeaningful"/> to see if the data is meaningful enough to return a good result.</remarks>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <returns>The resulting PNG-image as a buffer. -or- null, if an error occurred during download of the image.</returns>
        public Image GetRouteImage(PropertyLocation source, PropertyLocation destination)
        {
            int width = 800;
            int height = 800;

            // https://developers.google.com/maps/documentation/directions/?hl=de

            // Create initial request
            StringBuilder sbInitialRequest = new StringBuilder();
            sbInitialRequest.Append("http://maps.google.com/maps/api/directions/xml?origin=");
            sbInitialRequest.AppendFormat("{0} {1},{2},{3}", source.Street, source.StreetNumber, source.ZipCode, source.City);
            sbInitialRequest.Append("&destination=");
            sbInitialRequest.AppendFormat("{0} {1},{2},{3}", destination.Street, destination.StreetNumber, destination.ZipCode, destination.City);
            sbInitialRequest.Append("&sensor=false");

            WebRequest wreqInitial = WebRequest.Create(sbInitialRequest.ToString());
            XDocument docResponse = null;
            using (WebResponse wresInitial = wreqInitial.GetResponse())
            {
                docResponse = XDocument.Load(wresInitial.GetResponseStream());

                // Load the response XML
                string status = docResponse.Root.Element("status").Value;
                switch (status)
                {
                    // TODO: Handle the errors!
                    case "NOT_FOUND":
                    case "ZERO_RESULTS":
                        Logger.Instance.LogFormat(LogType.Warning, null, "The maps-request failed with status '{0}'. This is an indication that the location could not be retrieved. Sorry, but there's no workaround.", status);
                        return null;
                    case "OVER_QUERY_LIMIT":
                        Logger.Instance.LogFormat(LogType.Error, null, "The maps-request failed with status 'OVER_QUERY_LIMIT'. This indicates too many queries within a short timeframe.");
                        return null;

                    case "MAX_WAYPOINTS_EXCEEDED":
                    case "INVALID_REQUEST":
                    case "REQUEST_DENIED":
                    case "UNKNOWN_ERROR":
                    default:
                        Logger.Instance.LogFormat(LogType.Error, null, "The maps-request failed with status '{0}'. Please contact the developers!", status);
                        return null;

                    case "OK":
                        // Everything ok.
                        break;
                }
            }

            // Get the path data
            XElement overviewE = docResponse.Root.Element("route").Element("overview_polyline").Element("points");

            StringBuilder sbContinuationRequest = new StringBuilder();
            sbContinuationRequest.Append("http://maps.google.com/maps/api/staticmap?");
            sbContinuationRequest.AppendFormat("size={0}x{1}", width, height);
            sbContinuationRequest.Append("&sensor=false&path=weight:3|color:red|");
            sbContinuationRequest.AppendFormat("enc:{0}", overviewE.Value);

            WebRequest wr1 = WebRequest.Create(sbContinuationRequest.ToString());
            WebResponse res1 = wr1.GetResponse();

            // Save the image as PNG
            using (MemoryStream ms = new MemoryStream())
            {
                return Image.FromStream(res1.GetResponseStream());
            }
        }
Example #13
0
        private static string GetRouteAsStoredFileCore(PropertyLocation source, PropertyLocation destination)
        {
            int width = 800;
            int height = 800;

            // https://developers.google.com/maps/documentation/directions/?hl=de

            string originText = source.ToString();
            string destinationText = destination.ToString();

            // Create initial request
            StringBuilder sbInitialRequest = new StringBuilder();
            sbInitialRequest.Append("http://maps.google.com/maps/api/directions/xml?");
            sbInitialRequest.AppendFormat("origin={0}", originText);
            sbInitialRequest.AppendFormat("&destination={0}", destinationText);
            sbInitialRequest.Append("&sensor=false");

            WebRequest wreqInitial = WebRequest.Create(sbInitialRequest.ToString());
            XDocument docResponse = null;
            using (WebResponse wresInitial = wreqInitial.GetResponse())
            {
                docResponse = XDocument.Load(wresInitial.GetResponseStream());

                // Load the response XML
                string status = docResponse.Root.Element("status").Value;
                switch (status)
                {
                    // TODO: Handle the errors!
                    case "NOT_FOUND":
                    case "ZERO_RESULTS":
                        Logger.Instance.LogFormat(LogType.Warning, typeof(RoutePlanHelper), "The maps-request failed with status '{0}'. This is an indication that the location could not be retrieved. Sorry, but there's no workaround.", status);
                        return null;
                    case "OVER_QUERY_LIMIT":
                        Logger.Instance.LogFormat(LogType.Error, typeof(RoutePlanHelper), "The maps-request failed with status 'OVER_QUERY_LIMIT'. This indicates too many queries within a short timeframe.");
                        return null;

                    case "MAX_WAYPOINTS_EXCEEDED":
                    case "INVALID_REQUEST":
                    case "REQUEST_DENIED":
                    case "UNKNOWN_ERROR":
                    default:
                        Logger.Instance.LogFormat(LogType.Error, typeof(RoutePlanHelper), "The maps-request failed with status '{0}'. Please contact the developers!", status);
                        return null;

                    case "OK":
                        // Everything ok.
                        break;
                }
            }

            // Get the path data
            XElement overviewE = docResponse.Root.Element("route").Element("overview_polyline").Element("points");

            StringBuilder sbContinuationRequest = new StringBuilder();
            sbContinuationRequest.Append("http://maps.google.com/maps/api/staticmap?");
            sbContinuationRequest.AppendFormat("size={0}x{1}", width, height);
            // TODO: Maybe allow configuring the thickness and color, especially for b/w-printers?
            sbContinuationRequest.AppendFormat("&sensor=false&path=weight:3|color:red|enc:{0}", overviewE.Value);

            WebRequest wr1 = WebRequest.Create(sbContinuationRequest.ToString());
            using (WebResponse res1 = wr1.GetResponse())
            {
                using (Image image = Image.FromStream(res1.GetResponseStream()))
                {
                    using (FileStream tempFile = File.OpenWrite(Path.GetTempFileName()))
                    {
                        image.Save(tempFile, ImageFormat.Png);
                        return tempFile.Name;
                    }
                }
            }
        }
        private static PropertyLocation GetFDLocation()
        {
            if (FDLocation == null)
            {
                FDLocation = new PropertyLocation();

                try
                {
                    using (var service = ServiceFactory.GetCallbackServiceWrapper<ISettingsService>(new SettingsServiceCallback()))
                    {
                        FDLocation.Street = service.Instance.GetSetting(SettingKeys.FDStreet).GetValue<string>();
                        FDLocation.StreetNumber = service.Instance.GetSetting(SettingKeys.FDStreetNumber).GetValue<string>();
                        FDLocation.ZipCode = service.Instance.GetSetting(SettingKeys.FDZipCode).GetValue<string>();
                        FDLocation.City = service.Instance.GetSetting(SettingKeys.FDCity).GetValue<string>();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogException(typeof(OperationToRouteImageConverter), ex);
                }
            }

            return FDLocation;
        }