protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Habilitando o zoom no mapa GoogleMaps.enableHookMouseWheelToZoom = true; GoogleMaps.enableGoogleBar = false; GoogleMaps.enableDragging = false; GoogleMaps.enableDoubleClickZoom = false; GoogleMaps.Version = "3"; // Definir o tipo do mapa // Satellite, Hybrid, Physical, Normal GoogleMaps.mapType = GMapType.GTypes.Normal; //GLatLng latitudeLongitude = new GLatLng("Recife Brasil"); GoogleMaps.setCenter(GoogleMaps.getGeoCodeRequest("Recife Pernambuco").Placemark.coordinates, 10); //mudando o tamanho do mapa //GoogleMaps.Height = 200; //GoogleMaps.Width = 800; // Ver imagem para entender quais sao os controles adicionados GControl mapType = new GControl(GControl.preBuilt.MapTypeControl); GControl overview = new GControl(GControl.preBuilt.GOverviewMapControl); GControl small = new GControl(GControl.preBuilt.SmallMapControl); //GoogleMaps.addControl(mapType); // Ver imagem //GoogleMaps.addControl(overview); // Ver imagem GoogleMaps.addControl(small); // Ver imagem } }
public static void EducationFacilitiesSeed(HackathonContext context) { var url = "https://api.um.warszawa.pl/api/action/datastore_search/?resource_id=1cae4865-bb17-4944-a222-0d0cdc377951"; var response = Requestor.CreateRequest(url).Result; var jsonObj = JsonConvert.DeserializeObject <ResultDto>(response); int total = jsonObj.InnerResult.Total; for (int i = 500; i < total; i += 100) { var requestUrl = url + "&offset=" + i; response = Requestor.CreateRequest(requestUrl).Result; jsonObj = JsonConvert.DeserializeObject <ResultDto>(response); Trace.WriteLine($"{i}: {requestUrl}"); foreach (var item in jsonObj.InnerResult.EducationFacilityDtos) { GMapsLocationDto location = GoogleMaps.RetrieveDataFromGoogleMaps(item); if (location != null) { item.Longitude = location.Longitude; item.Latitude = location.Latitude; } context.EducationFacilities.AddOrUpdate(item); } context.SaveChanges(); } }
private void submitBtn_Click(object sender, EventArgs e) { GoogleMaps client = new GoogleMaps("AIzaSyAScSP2zdmi7mzAqW9Ow3Fi434Y45YqriI"); string targetName = nameTxt.Text; string targetBranch = branchTxt.Text; string targetRank = rankTxt.Text; string targetCountry = countryTxt.Text; string targetCity = cityLbl.Text; //here is the connection string for our DB //Database={your_database}; Data Source=socpacxasu.mysql.database.azure.com; User Id=capstoneAdmin@socpacxasu; Password={your_password} Address addr = client.QueryAddress($"{targetCity} {targetCountry}"); //Geolocation.Coordinate coordinate = new Geolocation.Coordinate(); //string targetLat = coordinate.Latitude.ToString(); //string targetLong = coordinate.Longitude.ToString(); latLbl.Text = addr.State.ToString(); longLbl.Text = addr.Longitude.ToString(); //need to find an API that returns coordinates to search with in DB }
public ShowMapWindow(Journey journey) { InitializeComponent(); Settings.Theme.Apply(this); Text = $"{ Settings.Localization.Map } - { Settings.Localization.Journey } - { DataFeedDesktop.Basic.Stops.FindByIndex(journey.JourneySegments[0].SourceStopID).Name } - { DataFeedDesktop.Basic.Stops.FindByIndex(journey.JourneySegments[journey.JourneySegments.Count - 1].TargetStopID).Name } - { journey.DepartureDateTime.ToShortTimeString() } { journey.DepartureDateTime.ToShortDateString() }"; resultsWebBrowser.ObjectForScripting = new GoogleMapsScripting.Journey(journey); resultsWebBrowser.DocumentText = GoogleMaps.GetMapWithMarkersAndPolylines(journey); }
public ShowMapWindow() { InitializeComponent(); Settings.Theme.Apply(this); Text = Settings.Localization.Map; resultsWebBrowser.ObjectForScripting = new GoogleMapsScripting.General(); resultsWebBrowser.DocumentText = GoogleMaps.GetMapWithMarkers(DataFeedDesktop.Basic.Stops); }
public ShowMapWindow(Departure departure) { InitializeComponent(); Settings.Theme.Apply(this); Text = $"{ Settings.Localization.Map } - { Settings.Localization.Departure } - { DataFeedDesktop.Basic.Stops.FindByIndex(departure.StopID).Name } - { departure.DepartureDateTime.ToShortTimeString() } { departure.DepartureDateTime.ToShortDateString() }"; resultsWebBrowser.ObjectForScripting = new GoogleMapsScripting.Departure(departure); resultsWebBrowser.DocumentText = GoogleMaps.GetMapWithMarkersAndPolylines(departure); }
public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .AddUserSecrets <Program>() .Build(); if (args.Length == 0) { args = new[] { "montreal", "quebec, qc", "halifax", "calgary", "edmonton", "yellowknife", "moncton, nb", "toronto", "ottawa", "winnipeg", "saskatoon, sk", "regina, sk", "vancouver", }; } Console.WriteLine($"INPUT"); foreach (var arg in args) { Console.WriteLine($"{Array.IndexOf(args, arg)}: {arg}"); } Console.WriteLine(); Console.WriteLine($"Using Google Directions solver"); var apiKey = configuration["ApiKey"]; var solver = new GoogleDirectionsTsp(apiKey); var result = solver.Solve(args); for (int i = 0; i < result.Length; i++) { Console.WriteLine($"{i}: {result[i]}"); } Console.WriteLine(); Console.WriteLine($"Using OR Tools solver"); var maps = new GoogleMaps(new LoggerFactory(), new MemoryCache(Microsoft.Extensions.Options.Options.Create(new MemoryCacheOptions())), apiKey); result = new OrToolsTsp(maps).Solve(args); for (int i = 0; i < result.Length; i++) { Console.WriteLine($"{i}: {result[i]}"); } }
public static void Init(string apiKey) { if (!string.IsNullOrEmpty(apiKey)) { GoogleMaps.Init(apiKey); } else { Debug.Assert(!string.IsNullOrEmpty(apiKey), "apiKey is null or empty!"); } Init(); }
private Event AddTransfer(Event startEvent, Event endEvent) { if (transfers == null) { transfers = new ObservableCollection <Transfer>(); } if (transfers.Where(x => x.startEvent == startEvent && x.endEvent == endEvent).FirstOrDefault() == null) { Transfer transfer = new Transfer(startEvent, endEvent); GoogleMaps.GetTransferMap(transfer); GoogleMaps.GetTimeAndDistance(transfer); transfers.Add(transfer); } return(endEvent); }
/// <summary> /// Retrieves the Geocode for an address to fill in the Latitude and Longitude fields. /// </summary> /// <param name="address"></param> /// <returns></returns> public JsonResult Geocode(string address) { Dictionary <string, string> response = new Dictionary <string, string>(); decimal[] geocode = GoogleMaps.GetGeocode(address); if (geocode != null) { response.Add("status", "success"); response.Add("lat", geocode[0].ToString(CultureInfo.InvariantCulture)); response.Add("lng", geocode[1].ToString(CultureInfo.InvariantCulture)); } else { response.Add("status", "failed"); } return(Json(response, JsonRequestBehavior.AllowGet)); }
void CalulateMileage() { if (!doCalculate || string.IsNullOrWhiteSpace(txtFromAdd.Text) || string.IsNullOrWhiteSpace(txtToAdd.Text) || txtFromAdd.Text == EMPTYADDRESS || txtToAdd.Text == EMPTYADDRESS) { return; } double distance = 0d; distance = GoogleMaps.GetDistance(txtFromAdd.Text, txtToAdd.Text, (bool)chkAvdFerr.IsChecked); double dist = distance; if (!txtMonHrs.IsReadOnly && journalline.Day1 > 0) { txtMonHrs.EditValue = dist; } if (!txtTueHrs.IsReadOnly && journalline.Day2 > 0) { txtTueHrs.EditValue = dist; } if (!txtWedHrs.IsReadOnly && journalline.Day3 > 0) { txtWedHrs.EditValue = dist; } if (!txtThuHrs.IsReadOnly && journalline.Day4 > 0) { txtThuHrs.EditValue = dist; } if (!txtFriHrs.IsReadOnly && journalline.Day5 > 0) { txtFriHrs.EditValue = dist; } if (!txtSatHrs.IsReadOnly && journalline.Day6 > 0) { txtSatHrs.EditValue = dist; } if (!txtSunHrs.IsReadOnly && journalline.Day7 > 0) { txtSunHrs.EditValue = dist; } CalculateTotal(); }
protected void Page_Load(object sender, EventArgs e) { // Habilitando o zoom no mapa GoogleMaps.enableHookMouseWheelToZoom = true; // Definir o tipo do mapa // Satellite, Hybrid, Physical, Normal GoogleMaps.mapType = GMapType.GTypes.Normal; // Define a Latitude e Logitude inicial do Mapa // Como moro em Brasília, coloquei o Congresso Nacional GLatLng latitudeLongitude = new GLatLng(-25.366085, -49.220698); // Definimos onde será o ponto inicial do nosso mapa // e o numero é o ZOOM inicial GoogleMaps.setCenter(latitudeLongitude, 17); GIcon icon = new GIcon(); icon.image = "/img/3gsaticon.png"; icon.iconSize = new GSize(32, 32); icon.shadowSize = new GSize(22, 20); icon.iconAnchor = new GPoint(6, 20); icon.infoWindowAnchor = new GPoint(5, 1); GMarkerOptions mOpts = new GMarkerOptions(); mOpts.icon = icon; // Acionando os controles GControl overview = new GControl(GControl.preBuilt.GOverviewMapControl); GControl MapControl = new GControl(GControl.preBuilt.LargeMapControl3D); GoogleMaps.addControl(overview); GoogleMaps.addControl(MapControl); GMarker marker = new GMarker(latitudeLongitude, mOpts); GInfoWindow window = new GInfoWindow(marker, "<center><b>Teste 3GSat<BR>Teste linha<BR>" + latitudeLongitude + "</b></center>"); GoogleMaps.addGMarker(marker); GoogleMaps.addInfoWindow(window); }
public ActionResult Maps(int?id) { var vacancy = from vac in db.Vacancies where (vac.Id == id) select vac; Vacancies viewData = new Vacancies(); foreach (Vacancies result in vacancy) { viewData = result; } GoogleMaps newMap = new GoogleMaps(); var latLng = newMap.GetVacantFormattedUrl(viewData.StreetNumber, viewData.StreetName, viewData.City, viewData.State, viewData.ZipCode); ViewBag.Lat = latLng[0]; ViewBag.Long = latLng[1]; return(View(viewData)); }
public HaversineDistanceEvaluator(string[] nodes, GoogleMaps maps) { _nodes = nodes; _maps = maps; }
/// <summary> /// Creates a new service provider. /// </summary> /// <param name="name">Name of the service provider that should be crreated.</param> /// <param name="url">Url for the service provider.</param> /// <returns>The created service provider.</returns> public static ServiceProvider Create(string name, string url = null) { var servEq = (Func <string, bool>)(s => name?.Equals(s, StringComparison.InvariantCultureIgnoreCase) == true); ITileCache <byte[]> fileCache() => new FileCache(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TileCache", name), "jpg", new TimeSpan(30, 0, 0, 0)); if (servEq(Resources.EsriHydroBaseMap)) { return(new BrutileServiceProvider(name, new ArcGisTileSource("http://bmproto.esri.com/ArcGIS/rest/services/Hydro/HydroBase2009/MapServer/", new GlobalSphericalMercator()), fileCache())); } if (servEq(Resources.EsriWorldStreetMap)) { return(new BrutileServiceProvider(name, new ArcGisTileSource("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/", new GlobalSphericalMercator()), fileCache())); } if (servEq(Resources.EsriWorldImagery)) { return(new BrutileServiceProvider(name, new ArcGisTileSource("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/", new GlobalSphericalMercator()), fileCache())); } if (servEq(Resources.EsriWorldTopo)) { return(new BrutileServiceProvider(name, KnownTileSources.Create(KnownTileSource.EsriWorldTopo), fileCache())); } if (servEq(Resources.BingHybrid)) { return(new BrutileServiceProvider(name, KnownTileSources.Create(KnownTileSource.BingHybrid), fileCache())); } if (servEq(Resources.BingAerial)) { return(new BrutileServiceProvider(name, KnownTileSources.Create(KnownTileSource.BingAerial), fileCache())); } if (servEq(Resources.BingRoads)) { return(new BrutileServiceProvider(name, KnownTileSources.Create(KnownTileSource.BingRoads), fileCache())); } if (GoogleMaps.Contains(name)) { if (string.IsNullOrEmpty(url)) { return(null); } else { return(new BrutileServiceProvider(name, CreateGoogleTileSource(url), fileCache()) { Projection = WebMercProj.Value }); } } if (name.Contains("TianDiTu")) { if (string.IsNullOrEmpty(url)) { return(null); } else { return(new BrutileServiceProvider(name, CreateTianDiTuTileSource(url), fileCache()) { Projection = WebMercProj.Value }); } } if (servEq(Resources.OpenStreetMap)) { return(new BrutileServiceProvider(name, KnownTileSources.Create(), fileCache())); } if (servEq(Resources.WMSMap)) { return(new WmsServiceProvider(name)); } if (url?.ToLower().Contains("wmts") == true) { return(new WmtsServiceProvider(name, url, fileCache())); } // No Match return(new OtherServiceProvider(name, url)); }
public OrToolsTsp(GoogleMaps maps) { _maps = maps; }
public ActionResult Edit(int?locationId, int?organizationId, NewLocationModel locationModel) { var location = GetLocation(locationId, organizationId); if (ModelState.IsValid) { // Google limits number of lookups per day. No reason to waste them. bool needGeocode = location.IsNew || locationModel.AddressLine1 != location.AddressLine1 || (locationModel.AddressLine2 ?? "") != location.AddressLine2 || locationModel.City != location.City || locationModel.State != location.State || locationModel.Country != location.Country; // Admin can edit geocode if the lookup fails. if (!needGeocode && RoleUtils.IsUserServiceAdmin()) { // If they aren't set by admin, then lookup, ... or retry. if ((!locationModel.Latitude.HasValue || locationModel.Latitude == 0) && (!locationModel.Longitude.HasValue || locationModel.Longitude == 0)) { needGeocode = true; } else { // Admin set them manually. So use the edited values, ... or // the same unedited values as before. location.Latitude = locationModel.Latitude; location.Longitude = locationModel.Longitude; } } // this is already set at this point by GetLocation() location.OrganizationId = locationModel.OrganizationId; location.Name = locationModel.Name; location.AddressLine1 = locationModel.AddressLine1; location.AddressLine2 = locationModel.AddressLine2; location.City = locationModel.City; location.State = locationModel.State; location.Country = locationModel.Country; location.PostalCode = locationModel.PostalCode; location.PhoneNumber = locationModel.PhoneNumber; if (needGeocode) { if (GoogleMaps.GetGeocode(location) == null && RoleUtils.IsUserServiceAdmin()) { location.Latitude = locationModel.Latitude; location.Longitude = locationModel.Longitude; } } if (RoleUtils.IsUserServiceAdmin()) { location.IsActive = locationModel.IsActive; } if (location.IsNew) { location.UniqueIdentifier = LocationUtils.CreateUid(); } location.Save(); return(new EmptyResult()); } else { Response.StatusCode = 417; Response.TrySkipIisCustomErrors = true; } return(PartialView(locationModel)); }
void HandleAction(GoogleMaps.Polygon arg1, NotifyCollectionChangedEventArgs arg2) { }
public ActionResult GetData() { // create list of markers var markers = new LinqMetaData().Location .Where(x => x.Latitude != null && x.Longitude != null) .ToList().Select(x => { var icon = GetLocationIcon(x); return new Marker { Latitude = x.Latitude.Value, Longitude = x.Longitude.Value, Icon = icon, Content = String.Format(Operation.LocationLabel, x.Name) + "<br /><table>" + string.Join("</tr><tr>", x.Devices.Select( y => "<td>" + y.SerialNumber + "</td><td>" + y.DeviceState + "</td><td>" + y.CurrentStatus + "</td>")) + "<table>", ZIndex = icon.Contains("CCCC00") ? 1 : 3, Title = x.Name, MinZoom = 3, MaxZoom = 17 }; }) .Concat(new LinqMetaData().Organization .Where(o => o.Locations.Any()) .ToList().Select(x => { var locations = x.Locations .Where(l => l.Latitude != null && l.Longitude != null) .Select(l => new LatLng(l.Latitude.Value, l.Longitude.Value)); var point = GoogleMaps.GetAverage(locations); var icon = GetOrganizationIcon(x); return new Marker { Latitude = point.Latitude, Longitude = point.Longitude, Icon = icon, Content = String.Format(Operation.OrganizationLabel, x.Name) + "<br /><table>" + string.Join("</tr><tr>", x.Locations.SelectMany(l => l.Devices.Select( y => (locations.Count() > 1 ? ("<td>" + l.Name + "</td>") : "") + "<td>" + y.SerialNumber + "</td><td>" + y.DeviceState + "</td><td>" + y.CurrentStatus + "</td>"))) + "<table>", ZIndex = icon.Contains("996633") ? 0 : 2, Title = x.Name, MinZoom = 0, MaxZoom = 17, Locations = locations }; })); UserSettingEntity todaySetting = null; try { // get the time the daily count was updated var timeSetting = Membership.GetUser().GetUserEntity().Settings.FirstOrDefault(x => x.Name == "SupportInboxUpdated"); DateTime result; if(timeSetting != null && // try to parse the time caches in the user settings DateTime.TryParse(timeSetting.Value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result) && // make sure the count was updated today result.Date == DateTime.UtcNow.Date) // get the daily count for today caches in user settings todaySetting = Membership.GetUser().GetUserEntity().Settings.FirstOrDefault(x => x.Name == "SupportInboxToday"); } catch { } var daily = new[] { new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|6666CC|000000", Text = Operation.ScansPerformed, Count = new LinqMetaData().DeviceEvent.Count(x => x.ReceivedTime > DateTime.UtcNow.Date && x.EventType == EventType.ScanBegin).ToString() }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00CC00|000000", Text = Operation.PurchasesMade, Count = String.Format("{0:C}", new LinqMetaData().PurchaseHistory.Where(x => x.PurchaseTime > DateTime.UtcNow.Date).Sum(x => x.AmountPaid)) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CCCC00|000000", Text = Operation.DevicesActive, Count = new LinqMetaData().DeviceEvent.Where(x => x.ReceivedTime > DateTime.UtcNow.Date && x.EventType == EventType.Ping).DistinctBy(x => x.DeviceId).Count().ToString() }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC0000|000000", Text = Operation.ExceptionsReceived, Count = new LinqMetaData().ExceptionLog.Count(x => x.ReceivedTime > DateTime.UtcNow.Date).ToString() }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC00CC|000000", Text = Operation.UsersOnline, Count = Membership.GetNumberOfUsersOnline().ToString() }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC9900|000000", Text = Operation.SupportRequests, Count = todaySetting != null ? todaySetting.Value : "0" } }; var system = new[] { new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|6666CC|000000", Text = Operation.TotalScans, Arrow = new LinqMetaData().DeviceEvent.Any(x => x.EventType == EventType.ScanBegin && x.EventTime > DateTime.UtcNow.AddMilliseconds(-UpdateController.UPDATE_INTERVAL * 2)) ? Url.Content("~/Content/GreenUp.gif") : Url.Content("~/Content/spacer.gif"), Count = new LinqMetaData().DeviceEvent.Count(x => x.EventType == EventType.ScanBegin).ToString(CultureInfo.InvariantCulture) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00CC00|000000", Text = Operation.TotalPurchases, Arrow = new LinqMetaData().PurchaseHistory.Any(x => x.PurchaseTime > DateTime.UtcNow.AddMilliseconds(-UpdateController.UPDATE_INTERVAL * 2)) ? Url.Content("~/Content/GreenUp.gif") : Url.Content("~/Content/spacer.gif"), Count = String.Format("{0:C}", new LinqMetaData().PurchaseHistory.Sum(x => x.AmountPaid)) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CCCC00|000000", Text = Operation.TotalDevices, Arrow = new LinqMetaData().Device.Any(x => x.DateIssued > DateTime.UtcNow.AddMilliseconds(-UpdateController.UPDATE_INTERVAL * 2)) ? Url.Content("~/Content/GreenUp.gif") : Url.Content("~/Content/spacer.gif"), Count = new LinqMetaData().Device.Count().ToString(CultureInfo.InvariantCulture) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC0000|000000", Text = Operation.TotalExceptions, Arrow = new LinqMetaData().ExceptionLog.Any(x => x.ReceivedTime > DateTime.UtcNow.AddMilliseconds(-UpdateController.UPDATE_INTERVAL * 2)) ? Url.Content("~/Content/GreenUp.gif") : Url.Content("~/Content/spacer.gif"), Count = new LinqMetaData().ExceptionLog.Count().ToString(CultureInfo.InvariantCulture) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC00CC|000000", Text = Operation.TotalUsers, Arrow = new LinqMetaData().User.Any(x => x.CreateTime > DateTime.UtcNow.AddMilliseconds(-UpdateController.UPDATE_INTERVAL * 2)) ? Url.Content("~/Content/GreenUp.gif") : Url.Content("~/Content/spacer.gif"), Count = new LinqMetaData().User.Count().ToString(CultureInfo.InvariantCulture) }, new { Icon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|996633|000000", Text = Operation.TotalOrganizations, Arrow = Url.Content("~/Content/spacer.gif"), // TODO: something interesting here Count = new LinqMetaData().Organization.Count().ToString(CultureInfo.InvariantCulture) } }; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); return Json(new { markers, daily, system }, JsonRequestBehavior.AllowGet); }
private void TopCallWorkersFrm_Load(object sender, EventArgs e) { if (Call == null) { return; } //show which call this is callLbl.Text = Call.ToString(); //get the service user for this call ServiceUser serviceuser = Call.ServiceUser; ////this is the list of workers to add to the list List <TopWorkersViewModel> workersToAdd = new List <TopWorkersViewModel>(); //Get infor for every active worker foreach (Worker worker in WorkerManager.Instance.ActiveWorkers) { //first lets get distance double miles = -1; if (worker.LongLatCoords != null && worker.LongLatCoords.HasLongLat) { try { miles = GoogleMaps.GetDistance(worker.LongLatCoords, serviceuser.LongLatCoords, "M"); } catch (Exception ex) { } } //now whether they are a keyworker bool isKeyWorker = serviceuser.KeyWorkers.Contains(worker); //no Image img = null; if (isKeyWorker) { img = Cura.Properties.Resources.key; } //now get the time unassigned int minutes_unassinged = worker.Unassigned_Mins_ForWeek(StartDate); //ignore people without any of this information! if (minutes_unassinged == 0 && !isKeyWorker && miles < 0) { continue; } workersToAdd.Add( new TopWorkersViewModel() { worker = worker, distance_miles = miles, isKeyWorker = isKeyWorker, image = img, mins_workingtime_unassigned = minutes_unassinged } ); } IEnumerable <TopWorkersViewModel> res = workersToAdd.OrderByDescending(w => w.isKeyWorker).ThenBy(w => w.distance_miles).ThenByDescending(w => w.mins_workingtime_unassigned).Take(10); int index = 1; foreach (TopWorkersViewModel model in res) { model.index = index++; } ////hours remaining listView1.SetObjects(res); ////distance ////get the closest remaining who aren't key workers //Dictionary<Worker, double> WorkerMiles = new Dictionary<Worker, double>(); //if (serviceuser.LongLatCoords != null && serviceuser.LongLatCoords.HasLongLat) //{ // foreach (Worker worker in WorkerManager.Instance.Workers.Where(w => !serviceuser.KeyWorkers.Contains(w))) // { // if (worker.LongLatCoords == null || !worker.LongLatCoords.HasLongLat) // continue ; // double miles = GoogleMaps.GetDistance(worker.LongLatCoords, serviceuser.LongLatCoords, "M"); // WorkerMiles.Add(worker, miles); // } //} ////FIRST DO THE KEYWORKERS //foreach (Worker worker in serviceuser.KeyWorkers) //{ // if (remaining == 0) // break; // double miles = -1; // if (worker.LongLatCoords != null && worker.LongLatCoords.HasLongLat) // { // try // { // miles = GoogleMaps.GetDistance(worker.LongLatCoords, serviceuser.LongLatCoords, "M"); // }catch(Exception ex){} // } // workersToAdd.Add(new TopWorkersViewModel() { worker = worker, distance_miles = miles, isKeyWorker = true, image = ImageGenerator.Instance.GenerateWorkerImage(ImageGenerator.WorkerImageGen.Key), mins_workingtime_unassigned = worker.Unassigned_Mins_ForWeek(StartDate) }); // remaining -= 1; //} ////NOW DO THE PEOPLE THAT ARE CLOSEST BUT NOT KEY WORKERS // foreach(KeyValuePair<Worker, double> pair in WorkerMiles) //{ // if (remaining == 0) // break; // workersToAdd.Add(new TopWorkersViewModel() { worker = pair.Key, distance_miles = pair.Value, isKeyWorker = false, mins_workingtime_unassigned = pair.Key.Unassigned_Mins_ForWeek(StartDate) }); // remaining -= 1; //} //IEnumerable<Worker> list1 = WorkerManager.Instance.Workers; //list1.OrderByDescending(w => w.Unassigned_Mins_ForWeek(StartDate)); // foreach (Worker worker in list1) // { // if (remaining == 0) // break; // workersToAdd.Add(new TopWorkersViewModel() { worker = worker, isKeyWorker = false, mins_workingtime_unassigned = worker.Unassigned_Mins_ForWeek(StartDate) }); // remaining -= 1; // } // workersToAdd.OrderBy(w => w.isKeyWorker).ThenBy(w => w.distance_miles).ThenBy(w => w.mins_workingtime_unassigned); ////hours remaining //listView1.SetObjects(workersToAdd); }
/// <summary> /// Called during startup by each shared project /// </summary> public static void Initialize(string environment) { //Initialize all static settings classes based on current environment //See "instructions.txt" for details on the configurations to use per environment. //Host application must pass in the current environment name to initialize settings Environment.Current = environment; //--------------------------------------------------------------------- //URLs & Email Addresses are initialized first as they are used in copy within other settings // Endpoint Settings --------------- URLs.Initialize(); Emails.Initialize(); //--------------------------------------------------------------------- // Remaining settings are then initialized... // AZURE Services ----------------- Databases.Initialize(); DocumentDB.Initialize(); Redis.Initialize(); Storage.Initialize(); Search.Initialize(); // EXTERNAL Services --------------- Stripe.Initialize(); SendGrid.Initialize(); MailChimp.Initialize(); GoogleMaps.Initialize(); CloudFlare.Initialize(); Registration.Initialize(); GarbageCollection.Initialize(); Custodian.Initialize(); Worker.Initialize(); Partitioning.Initialize(); Payments.Initialize(); // Platform Settings --------------- Application.Initialize(); Platform.Users.Initialize(); Accounts.Users.Initialize(); Commerce.Credits.Initialize(); //Copy Settings --------------- EmailMessages.Initialize(); NotificationMessages.Initialize(); PlatformMessages.Initialize(); //Image Settings ------------ Imaging.Images.Initialize(); // Flush ALL Redis caches when we initialize CoreServices // This allows new updates to be forced into cached objects var redisEndpoints = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.RedisMultiplexer.GetEndPoints(true); var redisserver = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.RedisMultiplexer.GetServer(redisEndpoints[0]); try { redisserver.FlushAllDatabases(); } catch (Exception e) { string exception = e.Message; } /* * // Flush ALL Redis caches when we initialize CoreServices * // This allows new updates to be forced into cached objects * var accountsRedisEndpoints = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.AccountManager_Multiplexer.GetEndPoints(true); * var accountRedisserver = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.AccountManager_Multiplexer.GetServer(accountsRedisEndpoints[0]); * accountRedisserver.FlushAllDatabases(); * * var platformRedisEndpoints = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.PlatformManager_Multiplexer.GetEndPoints(true); * var platformRedisserver = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.PlatformManager_Multiplexer.GetServer(platformRedisEndpoints[0]); * platformRedisserver.FlushAllDatabases(); */ }
static void Main(string[] args) { while (String.IsNullOrEmpty(_ApiKey)) { Console.Write("API key: "); _ApiKey = Console.ReadLine(); } _GoogleMaps = new GoogleMaps(_ApiKey); _GoogleMaps.Logger = Console.WriteLine; while (_RunForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { continue; } if (userInput.Equals("q")) { _RunForever = false; } else if (userInput.Equals("cls") || userInput.Equals("c")) { Console.Clear(); } else if (userInput.Equals("?")) { Menu(); } else if (userInput.StartsWith("ts ")) { string timestampStr = userInput.Substring(2); DateTime ts = DateTime.Now; string tz = null; if (timestampStr.Contains(",")) { string[] parts = timestampStr.Split(new char[] { ',' }, 2); double latitude = Convert.ToDouble(parts[0]); double longitude = Convert.ToDouble(parts[1]); ts = _GoogleMaps.LocalTimestamp(latitude, longitude, DateTime.Now, out tz); } else { ts = _GoogleMaps.LocalTimestamp(timestampStr, DateTime.Now, out tz); } Console.WriteLine(tz + ": " + ts.ToString("s")); } else { Address addr = null; if (userInput.Contains(",")) { string[] parts = userInput.Split(new char[] { ',' }, 2); double latitude = Convert.ToDouble(parts[0]); double longitude = Convert.ToDouble(parts[1]); addr = _GoogleMaps.QueryCoordinates(latitude, longitude); } else { addr = _GoogleMaps.QueryAddress(userInput); } Console.WriteLine(SerializeJson(addr)); } } }