Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, June 25, 2019

Two location within radius

Some time we need to identify one location latitude and longitude with the radius of other  location. How to check is the location in the radius of other location?



I will show you how we can do with help of Google map Api.
    class Coordinate
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
    class Program
    {
        public static void Main()
        {
            //Get center location lat and lng
            Coordinate centerLatLong = GetLatLongForAddress("Delhi");
            //Get any location lat and lng
            Coordinate locationLatLong = GetLatLongForAddress("Noida");
            //Radius: Radius in meter
            int radius = 50000;
            //Check wheater  locations lat and long within  radius of a given  point.
            bool check = isInArea(centerLatLong, locationLatLong, radius);
            Console.Write(check);
         
            Console.ReadLine();
        }
        public static Coordinate GetLatLongForAddress(string location)
        {
            string result = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=true", location);
            Coordinate coordinate = new Coordinate();
            byte[] data;
            using (WebClient webClient = new WebClient())
                data = webClient.DownloadData(result);
            string str = Encoding.GetEncoding("Windows-1252").GetString(data);
            XDocument doc = XDocument.Parse(str);
            string status = doc.Element("GeocodeResponse").Element("status").Value;
            //no errors occurred; the address was successfully parsed and at least one geocode was returned.
            if (status.Equals("OK"))
            {
                var point = doc.Element("GeocodeResponse").Element("result").Element("geometry").Element("location");
                string lat = point.Element("lat").Value;
                string lng = point.Element("lng").Value;
                coordinate.Latitude = Convert.ToDouble(lat);
                coordinate.Longitude = Convert.ToDouble(lng);
            }
            else if (status.Equals("ZERO_RESULTS"))
            {
                //Geocode was successful but returned no results
                throw new ApplicationException("No maps found for this address");
            }
            else if (status.Equals("REQUEST_DENIED"))
            {
                //Request was denied
                throw new ApplicationException("Request Denied");
            }
            else if (status.Equals("INVALID_REQUEST"))
            {
                //Address is missing
                throw new ApplicationException("Address not found");
            }
            else if (status.Equals("UNKNOWN_ERROR"))
            {
                //The request could not be processed due to a server error
                throw new ApplicationException("Unknown Error. Try agian.");
            }
            return coordinate;
        }
        public static bool isInArea(Coordinate centerLatLong, Coordinate locationLatLong, int radius)
        {
            var R = 6371;
            var dLat = (centerLatLong.Latitude - locationLatLong.Latitude) * Math.PI / 180;
            var dLon = (centerLatLong.Longitude - locationLatLong.Longitude) * Math.PI / 180;
            var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(locationLatLong.Latitude * Math.PI / 180) * Math.Cos(centerLatLong.Latitude * Math.PI / 180) *
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            var d = R * c;
            return (d * 1000 <= radius);
        }
    }

Thursday, June 6, 2019

Convert XML to C# Object

How to deserialize simple as well as complex (nested) XML into C# objects. We need to create C# classes as xml tags inside XML. 

XML Document

This is the whole XML document which we need to deserialize into c# class.
<?xml version="1.0" encoding="UTF-8"?>
    <library>
        <name>Level 2</name>
        <levelLabel>A</levelLabel>
        <levelLabel>B</levelLabel>
        <levelLabel>C</levelLabel>
        <levelLabel>D</levelLabel>
        <folder>
            <name>Grade 4 </name>
            <sortOrder>0</sortOrder>
            <comment>
                <name>Canadian Provinces</name>
                <code></code>
                <sortOrder>0</sortOrder>
                <dateCreated>2019-01-28 09:35:34</dateCreated>
                <dateModified>2019-01-28 09:35:34</dateModified>

                <commentLevel>
                    <comment>Explanations.</comment>
                    <level>2</level>
                </commentLevel>
                <commentLevel>
                    <comment>characteristics.</comment>
                    <level>3</level>
                </commentLevel>
            </comment>
            <comment>
                <name>Medieval</name>
                <code></code>
                <sortOrder>0</sortOrder>
                <dateCreated>2019-06-06 09:43:43</dateCreated>
                <dateModified>2019-06-06 09:43:43</dateModified>
                <commentLevel>
                    <comment></comment>
                    <level>0</level>
                </commentLevel>
                <commentLevel>
                    <comment></comment>
                    <level>1</level>
                </commentLevel>
                <commentLevel>
                    <comment>Royalty.</comment>
                    <level>2</level>
                </commentLevel>
                <commentLevel>
                    <comment>With thorough understanding</comment>
                    <level>3</level>
                </commentLevel>
            </comment>
        </folder>
        <folder>
            <name>Term 3</name>
            <sortOrder>0</sortOrder>
            <folder>
                <name>English</name>
                <sortOrder>0</sortOrder>
                <folder>
                    <name>Writing</name>
                    <sortOrder>0</sortOrder>
                    <comment>
                        <name>Writing</name>
                        <code>T3</code>
                        <sortOrder>0</sortOrder>
                        <dateCreated>2007-11-12 14:35:02</dateCreated>
                        <dateModified>2007-11-12 14:35:02</dateModified>
                        <commentLevel>
                            <comment>With assistance.</comment>
                            <level>0</level>
                        </commentLevel>
                        <commentLevel>
                            <comment>With some understanding.</comment>
                            <level>1</level>
                        </commentLevel>
                    </comment>
                </folder>
                <folder>
                    <name>Reading</name>
                    <sortOrder>0</sortOrder>
                    <comment>
                        <name>Reading</name>
                        <code>T3</code>
                        <sortOrder>0</sortOrder>
                        <dateCreated>2007-11-12 14:42:21</dateCreated>
                        <dateModified>2007-11-12 14:42:21</dateModified>
                        <commentLevel>
                            <comment>With prompting</comment>
                            <level>0</level>
                        </commentLevel>
                        <commentLevel>
                            <comment>Beginning to read independently</comment>
                            <level>1</level>
                        </commentLevel>
                        <commentLevel>
                            <comment>Reads independently.</comment>
                            <level>2</level>
                        </commentLevel>
                    </comment>
                </folder>
            </folder>
            <folder>
                <name>French</name>
                <sortOrder>0</sortOrder>
                <comment>
                    <name>French </name>
                    <code>T3</code>
                    <sortOrder>0</sortOrder>
                    <dateCreated>2007-11-12 15:22:24</dateCreated>
                    <dateModified>2007-11-12 15:22:24</dateModified>
                    <commentLevel>
                        <comment>Core French</comment>
                        <level>0</level>
                    </commentLevel>
                    <commentLevel>
                        <comment>Core French.</comment>
                        <level>1</level>
                    </commentLevel>
                </comment>
            </folder>
        </folder>
    </library>

C# Program

This is the main method of console application which will pick the XML document from folder path "C:\temp\document.xml". This XML file is same as above shown
 static void Main(string[] args) {
     const string path = @ "C:\temp\document.xml";
     XmlSerializer ser = new XmlSerializer(typeof(library));
     library request;
     using(XmlReader reader = XmlReader.Create(path)) {
         request = (library) ser.Deserialize(reader);
     }
     foreach(folder folder in request.folder) {
         getFolders(folder);
     }
     Console.ReadLine();
 }
static void getFolders(folder folder) {
    //Get Folder
    Console.WriteLine("foler name: {0}", folder.name);
    if (folder.Folder != null) {
        foreach(folder child in folder.Folder) {
            Console.WriteLine("child foler name: {0}", child.name);

            //Get Comments
            if (folder.comment != null) {
                foreach(comment comment in child.comment) {
                    Console.WriteLine("comment name: {0}", comment.name);
                    foreach(commentLevel commentLevel in comment.commentLevel) {
                        if (!string.IsNullOrWhiteSpace(commentLevel.comment)) {
                            Console.WriteLine("commentLevel comments comes here"); //, commentLevel.comment);
                        }
                    }
                }
            }
            getFolders(child);
        }
    } else {

        //Get Comments
        if (folder.comment != null) {
            foreach(comment comment in folder.comment) {
                Console.WriteLine("comment name: {0}", comment.name);
                foreach(commentLevel commentLevel in comment.commentLevel) {
                    if (!string.IsNullOrWhiteSpace(commentLevel.comment)) {
                        Console.WriteLine("commentLevel comments comes here"); //, commentLevel.comment);
                    }
                }
            }
        }
    }
}
We have to write C# class which map the XML document tags and attributes as below

library XML to library C#

<library>
        <name>Level 2</name>
        <levelLabel>A</levelLabel>
        <levelLabel>B</levelLabel>
        <levelLabel>C</levelLabel>
        <levelLabel>D</levelLabel>
        <folder>
           <folder>
 		...
	   </folder>
	   <folder>
 		...
	   </folder>
        </folder>
        <folder>
           <folder>
 		...
	   </folder>
	   <folder>
 		...
	   </folder>
        </folder>
</library>
public class library {
     [XmlElement("name")]
     public string name {
         get;
         set;
     }
     [XmlElement("levelLabel")]
     public string[] levelLabel {
             get;
             set;
         }
         [XmlElement("folder")]
     public folder[] folder {
         get;
         set;
     }
 }

folder XML to folder C#

<folder>
        <name>Grade 4 </name>
        <sortOrder>0</sortOrder>
        <comment>
              ....
        </comment>
        <comment>
              ....
        </comment>
</folder>
 public class folder {
     [XmlElement("name")]
     public string name {
         get;
         set;
     }
     [XmlElement("sortOrder")]
     public int sortOrder {
         get;
         set;
     }
     [XmlElement("comment")]
     public comment[] comment {
             get;
             set;
         }
         [XmlElement("folder")]
     public folder[] Folder {
         get;
         set;
     }
 }

comment XML to comment C#

 <comment>
         <name>Canadian Provinces</name>
         <code></code>
         <sortOrder>0</sortOrder>
         <dateCreated>2019-01-28 09:35:34</dateCreated>
         <dateModified>2019-01-28 09:35:34</dateModified>
	 <commentLevel>
		...
         </commentLevel>
         <commentLevel>
		...
         </commentLevel>
</comment>
 public class comment {
     public string name {
         get;
         set;
     }
     public string code {
         get;
         set;
     }
     public int sortOrder {
         get;
         set;
     }
     [XmlElement("commentLevel")]
     public commentLevel[] commentLevel {
         get;
         set;
     }
 }

commentLevel XML to commentLevel C#

<commentLevel>
         <comment>Explanations.</comment>
         <level>2</level>
</commentLevel>
public class commentLevel {
     public string comment {
         get;
         set;
     }
     public string level {
         get;
         set;
     }
 }