PageRenderTime 82ms CodeModel.GetById 60ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 1ms

/SiteManagement/SiteManagement.Tools/Form1.cs

https://bitbucket.org/KhalidMohammad/site-management-repo
C# | 454 lines | 286 code | 75 blank | 93 comment | 66 complexity | a95665d52de29ee6a23a62c33b21e545 MD5 | raw file
  1using Newtonsoft.Json;
  2using Newtonsoft.Json.Linq;
  3using SiteManagement.Data;
  4using System;
  5using System.Collections.Generic;
  6using System.ComponentModel;
  7using System.Data;
  8using System.Drawing;
  9using System.Linq;
 10using System.Net;
 11using System.Net.Http;
 12using System.Text;
 13using System.Threading;
 14using System.Threading.Tasks;
 15using System.Windows.Forms;
 16using System.Xml.Linq;
 17
 18namespace SiteManagement.Tools
 19{
 20    public partial class Form1 : Form
 21    {
 22        public Form1()
 23        {
 24            InitializeComponent();
 25        }
 26
 27
 28
 29        private void btnFillInfo_Click(object sender, EventArgs e)
 30        {
 31            SiteDataManager.CallDBContext(db =>
 32            {
 33                foreach (var site in db.Sites)
 34                {
 35                    LocationHelper.FillSiteInfo(site, false);
 36                    Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds));
 37
 38                    //var info = new Lazy<locationInfo>(() => RetrieveFormatedAddress(site.Latitude, site.Longitude));
 39                    //if (IsEmptyOrRabish(site.SiteCity) && info.Value != null)
 40                    //{
 41                    //    site.SiteCity = info.Value.CityName;
 42                    //}
 43                    //if (IsEmptyOrRabish(site.SiteAddress) && info.Value != null)
 44                    //{
 45                    //    site.SiteAddress = info.Value.Address;
 46                    //}
 47                    //if (IsEmptyOrRabish(site.StreetName) && info.Value != null)
 48                    //{
 49                    //    site.StreetName = info.Value.StreetName;
 50                    //}
 51                    //if (IsEmptyOrRabish(site.SiteGovernorates) && info.Value != null)
 52                    //{
 53                    //    site.SiteGovernorates = info.Value.Governorate;
 54                    //}
 55                    db.SaveChanges();
 56                }
 57
 58            });
 59
 60        }
 61
 62        private void btnGetMosquInfo_Click(object sender, EventArgs e)
 63        {
 64            if (!String.IsNullOrWhiteSpace(txtLat.Text) && !String.IsNullOrWhiteSpace(txtLong.Text))
 65                RetrieveAddressByType(txtLat.Text, txtLong.Text, "mosque", true);
 66        }
 67
 68        private static readonly string AppKey = "AIzaSyCF9nJ2u-0V7xhDHc4A2PILDJRxpt9cIIA"; //"AIzaSyCFktrzmtVWdWISxiRx2xo5QDEErwBuStE";
 69
 70        public static string baseUri = @"https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location={0},{1}&radius=50000&type={2}&key=" + AppKey;
 71        public static string searchbaseUri = @"https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location={0},{1}&radius=50000&name={2}&key=" + AppKey;
 72
 73        private static List<PlaceInfo> FillAddressByName(string lat, string lng, string namesearch, bool callRecursive, int id = 0)
 74        {
 75            List<PlaceInfo> places = new List<PlaceInfo>();
 76            string requestUri = string.Format(searchbaseUri, lat, lng, namesearch);
 77            string statusCode = String.Empty;
 78            using (WebClient wc = new WebClient())
 79            {
 80                wc.Encoding = Encoding.UTF8;
 81                string result = wc.DownloadString(requestUri);
 82                var xmlElm = XElement.Parse(result);
 83                var status = (from elm in xmlElm.Descendants()
 84                              where
 85                                        elm.Name == "status"
 86                              select elm).FirstOrDefault(); 
 87
 88                statusCode = status.Value.ToLower();
 89                Console.WriteLine(statusCode);
 90                if (statusCode == "ok")
 91                {
 92                    var results = (from elm in xmlElm.Descendants()
 93                                   where elm.Name == "result"
 94                                   select elm);
 95
 96                    bool cont = true;
 97                    if (id > 0)
 98                    {
 99                        using (TempLocationDB db = new TempLocationDB())
100                        {
101                            cont = db.PlaceInfo.Count(p => p.externalId.HasValue && p.externalId.Value == id) < results.Count();
102                        }
103
104                    }
105                    if (cont)
106                        foreach (var locationResult in results)
107                        {
108
109                            var address = (from elm in locationResult.Descendants()
110                                           where elm.Name == "vicinity"
111                                           select elm).FirstOrDefault();
112
113                            var name = (from elm in locationResult.Descendants()
114                                        where elm.Name == "name"
115                                        select elm).FirstOrDefault();
116
117
118                            var loc = (from elm in locationResult.Descendants()
119                                       where elm.Name == "location"
120                                       select elm).FirstOrDefault();
121
122                            var locationLat = (from elm in loc.Descendants()
123                                               where elm.Name == "lat"
124                                               select elm).FirstOrDefault();
125
126                            var locationLong = (from elm in loc.Descendants()
127                                                where elm.Name == "lng"
128                                                select elm).FirstOrDefault();
129
130
131                            PlaceInfo info = new PlaceInfo();
132                            info.Address = address == null ? null : address.Value;
133                            info.Name = name == null ? null : name.Value;
134                            info.Lat = lat == null ? null : locationLat.Value;
135                            info.Long = locationLong == null ? null : locationLong.Value;
136                            if (id > 0)
137                            {
138                                info.externalId = id;
139                            }
140
141                            using (var db = new TempLocationDB())
142                            {
143                                if (!db.PlaceInfo.Any(p => p.Name == info.Name && p.Lat == info.Lat && p.Long == info.Long))
144                                {
145                                    db.PlaceInfo.Add(info);
146                                }
147                                else if (id > 0)
148                                {
149                                    db.PlaceInfo.Add(new PlaceInfo { externalId = id });
150                                }
151                                db.SaveChanges();
152                            }
153                            places.Add(info);
154                        }
155                }
156            }
157            if (callRecursive &&
158                statusCode.ToUpperInvariant() == "OVER_QUERY_LIMIT")
159            {
160                Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds));
161                return RetrieveAddressByType(lat, lng, namesearch, callRecursive, id);
162            }
163            if (statusCode.ToUpperInvariant().Contains("ZERO") && id > 0)
164            {
165                using (var db = new TempLocationDB())
166                {
167
168                    db.PlaceInfo.Add(new PlaceInfo { externalId = id });
169                    db.SaveChanges();
170
171                }
172            }
173
174
175            return places;
176        }
177
178        private static List<PlaceInfo> RetrieveAddressByType(string lat, string lng, string type, bool callRecursive, int id = 0)
179        {
180            List<PlaceInfo> places = new List<PlaceInfo>();
181            string requestUri = string.Format(baseUri, lat, lng, type);
182            string statusCode = String.Empty;
183            using (WebClient wc = new WebClient())
184            {
185                wc.Encoding = Encoding.UTF8;
186                string result = wc.DownloadString(requestUri);
187                var xmlElm = XElement.Parse(result);
188                var status = (from elm in xmlElm.Descendants()
189                              where
190                                        elm.Name == "status"
191                              select elm).FirstOrDefault();
192
193                statusCode = status.Value.ToLower();
194                Console.WriteLine(statusCode);
195                if (statusCode == "ok")
196                {
197                    var results = (from elm in xmlElm.Descendants()
198                                   where elm.Name == "result"
199                                   select elm);
200
201                    bool cont = true;
202                    if (id > 0)
203                    {
204                        using (TempLocationDB db = new TempLocationDB())
205                        {
206                            cont = db.PlaceInfo.Count(p => p.externalId.HasValue && p.externalId.Value == id) < results.Count();
207                        }
208
209                    }
210                    if (cont)
211                        foreach (var locationResult in results)
212                        {
213
214                            var address = (from elm in locationResult.Descendants()
215                                           where elm.Name == "vicinity"
216                                           select elm).FirstOrDefault();
217
218                            var name = (from elm in locationResult.Descendants()
219                                        where elm.Name == "name"
220                                        select elm).FirstOrDefault();
221
222
223                            var loc = (from elm in locationResult.Descendants()
224                                       where elm.Name == "location"
225                                       select elm).FirstOrDefault();
226
227                            var locationLat = (from elm in loc.Descendants()
228                                               where elm.Name == "lat"
229                                               select elm).FirstOrDefault();
230
231                            var locationLong = (from elm in loc.Descendants()
232                                                where elm.Name == "lng"
233                                                select elm).FirstOrDefault();
234
235
236                            PlaceInfo info = new PlaceInfo();
237                            info.Address = address == null ? null : address.Value;
238                            info.Name = name == null ? null : name.Value;
239                            info.Lat = lat == null ? null : locationLat.Value;
240                            info.Long = locationLong == null ? null : locationLong.Value;
241                            if (id > 0)
242                            {
243                                info.externalId = id;
244                            }
245
246                            using (var db = new TempLocationDB())
247                            {
248                                if (!db.PlaceInfo.Any(p => p.Name == info.Name && p.Lat == info.Lat && p.Long == info.Long))
249                                {
250                                    db.PlaceInfo.Add(info);
251                                }
252                                else
253                                {
254                                    db.PlaceInfo.Add(new PlaceInfo { externalId = id });
255                                }
256                                db.SaveChanges();
257                            }
258                            places.Add(info);
259                        }
260                }
261            }
262            if (callRecursive &&
263                statusCode.ToUpperInvariant() == "OVER_QUERY_LIMIT")
264            {
265                Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds));
266                return RetrieveAddressByType(lat, lng, type, callRecursive, id);
267            }
268            if (statusCode.ToUpperInvariant().Contains("ZERO") && id > 0)
269            {
270                using (var db = new TempLocationDB())
271                {
272
273                    db.PlaceInfo.Add(new PlaceInfo { externalId = id });
274                    db.SaveChanges();
275
276                }
277            }
278
279
280            return places;
281        }
282
283        private void btnAllMosquInfo_Click(object sender, EventArgs e)
284        {
285            List<Site> allSites = new List<Data.Site>();
286
287            SiteDataManager.CallDBContext(db =>
288            {
289                allSites = db.Sites.ToList();
290            });
291
292            List<int> ids = new List<int>();
293
294            using (TempLocationDB db = new TempLocationDB())
295            {
296                ids = db.PlaceInfo.Where(p => p.externalId.HasValue && p.externalId.Value > 0).Select(p => p.externalId.Value).Distinct().ToList();
297
298            }
299            allSites = allSites.Where(s => !ids.Contains(s.SiteId)).ToList();
300
301            foreach (var site in allSites.OrderByDescending(a => a.SiteCity))
302            {
303                RetrieveAddressByType(site.Latitude, site.Longitude, "mosque", true, site.SiteId);
304            }
305        }
306
307        public static void AllMosquInfo()
308        {
309            List<Site> allSites = new List<Data.Site>();
310
311            SiteDataManager.CallDBContext(db =>
312            {
313                allSites = db.Sites.ToList();
314            });
315
316            List<int> ids = new List<int>();
317
318            List<MosqueInfo> allMosque = new List<MosqueInfo>();
319
320            using (TempLocationDB db = new TempLocationDB())
321            {
322                ids = db.PlaceInfo.Where(p => p.externalId.HasValue && p.externalId.Value > 0).Select(p => p.externalId.Value).Distinct().ToList();
323                allMosque = db.Mosques.ToList();
324            }
325            allSites = allSites.Where(s => !ids.Contains(s.SiteId)).ToList();
326
327            foreach (var site in allSites.OrderByDescending(a => a.SiteCity))
328            {
329                RetrieveAddressByType(site.Latitude, site.Longitude, "mosque", true, site.SiteId);
330            }
331        }
332
333        public static void FillAllMosquInfo()
334        {
335            List<Site> allSites = new List<Data.Site>();
336
337            SiteDataManager.CallDBContext(db =>
338            {
339                allSites = db.Sites.ToList();
340            });
341
342            List<int> ids = new List<int>();
343
344            List<MosqueInfo> allMosque = new List<MosqueInfo>();
345
346            using (TempLocationDB db = new TempLocationDB())
347            {
348                ids = db.PlaceInfo.Where(p => p.externalId.HasValue && p.externalId.Value > 0).Select(p => p.externalId.Value).Distinct().ToList();
349                allMosque = db.Mosques.ToList();
350            }
351            //allSites = allSites.Where(s => !ids.Contains(s.SiteId)).ToList();
352
353            foreach (MosqueInfo mosque in allMosque)
354            {
355                foreach (var site in allSites)
356                {
357                    var cc = FillAddressByName(site.Latitude, site.Longitude, mosque.Name, true, site.SiteId);
358                    if (cc != null && cc.Count > 0)
359                    {
360                        break;
361                    }
362                }
363            }
364        }
365
366        //static string baseUri = @"http://maps.google.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false&creditntial=AIzaSyAyyPZ_62snfVRtTCgBTrUt7JJiPUzEK2U";
367        //string location = string.Empty;
368
369        //public static locationInfo RetrieveFormatedAddress(string lat, string lng)
370        //{
371        //    locationInfo info = new locationInfo();
372        //    string requestUri = string.Format(baseUri, lat, lng);
373        //    string statusCode = String.Empty;
374        //    using (WebClient wc = new WebClient())
375        //    {
376        //        string result = wc.DownloadString(requestUri);
377        //        var xmlElm = XElement.Parse(result);
378        //        var status = (from elm in xmlElm.Descendants()
379        //                      where
380        //                                elm.Name == "status"
381        //                      select elm).FirstOrDefault();
382
383        //        statusCode = status.Value.ToLower();
384        //        if (statusCode == "ok")
385        //        {
386        //            var address = (from elm in xmlElm.Descendants()
387        //                           where elm.Name == "formatted_address"
388        //                           select elm).FirstOrDefault();
389
390        //            var city = (from elm in xmlElm.Descendants()
391        //                        where elm.Name == "type" &&
392        //                              elm.Value.Equals("locality", StringComparison.InvariantCultureIgnoreCase)
393        //                        select elm).FirstOrDefault();
394
395        //            if (city != null) city = city.Parent.Descendants().FirstOrDefault(p => p.Name == "long_name");
396
397        //            var route = (from elm in xmlElm.Descendants()
398        //                         where
399        //                            elm.Name == "type" &&
400        //                            elm.Value.Equals("route", StringComparison.InvariantCultureIgnoreCase)
401        //                         select elm).FirstOrDefault();
402        //            if (route != null) route = route.Parent.Descendants().FirstOrDefault(p => p.Name == "long_name");
403
404
405        //            var governorate = (from elm in xmlElm.Descendants()
406        //                               where
407        //                                  elm.Name == "type" &&
408        //                                  elm.Value.Equals("administrative_area_level_1", StringComparison.InvariantCultureIgnoreCase)
409        //                               select elm).FirstOrDefault();
410
411        //            if (governorate != null) governorate = governorate.Parent.Descendants().FirstOrDefault(p => p.Name == "long_name");
412
413        //            info.Address = address == null ? null : address.Value;
414        //            info.CityName = city == null ? null : city.Value;
415        //            info.StreetName = route == null ? null : route.Value;
416        //            info.Governorate = governorate == null ? null : governorate.Value;
417        //        }
418        //    }
419        //    Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds));
420        //    if (statusCode.ToUpperInvariant() == "OVER_QUERY_LIMIT")
421        //    {
422        //        return RetrieveFormatedAddress(lat, lng);
423        //    }
424        //    return info;
425        //}
426
427        //private static bool IsEmptyOrRabish(string val)
428        //{
429        //    return String.IsNullOrWhiteSpace(val) || val.Equals("-") || val.Equals("_");
430        //}
431        //public static void FillSiteInfo(Site site)
432        //{
433        //    var info = new Lazy<locationInfo>(() => RetrieveFormatedAddress(site.Latitude, site.Longitude));
434        //    if (IsEmptyOrRabish(site.SiteCity) && info.Value != null)
435        //    {
436        //        site.SiteCity = info.Value.CityName;
437        //    }
438        //    if (IsEmptyOrRabish(site.SiteAddress) && info.Value != null)
439        //    {
440        //        site.SiteAddress = info.Value.Address;
441        //    }
442        //    if (IsEmptyOrRabish(site.StreetName) && info.Value != null)
443        //    {
444        //        site.StreetName = info.Value.StreetName;
445        //    }
446        //    if (IsEmptyOrRabish(site.SiteGovernorates) && info.Value != null)
447        //    {
448        //        site.SiteGovernorates = info.Value.Governorate;
449        //    }
450        //}
451
452    }
453
454}