PageRenderTime 76ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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