public void PopulateDriveTimes() { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var sources = context.Places.ToList(); var conns = context.Connections.Select(p => p); var destinations = sources; foreach (var source in sources) { foreach (var destination in destinations) { if (source.Name == destination.Name) { continue; } var _conxn = conns.Where(x => x.SourceId == source.Id && x.DestinationId == destination.Id).FirstOrDefault(); if (_conxn != null && !_conxn.DrivingTime.HasValue) { double driveTime = _CalculateDrivingTime(source.Name, destination.Name); if (driveTime > 0) { _conxn.DrivingTime = (decimal)driveTime; context.SaveChanges(); } } } } context.SaveChanges(); } }
/// <summary> /// /// </summary> /// <param name="tm"></param> /// <param name="title"></param> /// <param name="tripId"></param> /// <returns></returns> public static DomingoBlError CreateThreadforTrip(ThreadMessage tm, string title, int tripId) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { // create the Thread var _thread = new Thread() { AuthorUserId = tm.TravellerId, CreatedDate = DateTime.Now, MostRecentPostDate = DateTime.Now, Title = title, Tags = "message", AspnetUserId = tm.AspnetUserId }; // save it to the DB context.Threads.Add(_thread); context.SaveChanges(); // add the message with the ID context.ThreadMessages.Add(tm); tm.ThreadId = _thread.Id; var trip = context.Trips.FirstOrDefault(p => p.Id == tripId); if (trip != null) { trip.ThreadId = _thread.Id; } // commit context.SaveChanges(); } } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); }
/// <summary> /// /// </summary> /// <param name="tm"></param> /// <returns></returns> public static DomingoBlError AddToThread(ThreadMessage tm) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { // update the MostRecentPostDate of the parent thread var thread = context.Threads.Find(tm.ThreadId); thread.MostRecentPostDate = DateTime.Now; // add the message context.ThreadMessages.Add(tm); // commit context.SaveChanges(); } } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); }
public void PopulateAirportAddress() { double latitude, longitude; using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var airports = context.Airports.Where(p => p.Id >= 100050); foreach (var airport in airports) { if (airport.Lattitude.HasValue) { continue; } _GeocodePlace(airport.Name, out latitude, out longitude); if (latitude != 0.0 && longitude != 0.0) { airport.Lattitude = (decimal)latitude; airport.Longitude = (decimal)longitude; latitude = 0; longitude = 0; } } context.SaveChanges(); } }
private void _SaveTransitDetails(int originId, int destinationId, DateTime depTime) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var origin = context.Places.Find(originId); var destination = context.Places.Find(destinationId); if (origin == null || destination == null) { return; } var transitDirectionRequest = new DirectionsRequest { Origin = origin.Name, Destination = destination.Name, TravelMode = TravelMode.Transit, DepartureTime = depTime, ApiKey = GoogleKey }; DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest); if (transitDirections.Status == DirectionsStatusCodes.OK) { string jsonStr = JsonConvert.SerializeObject(transitDirections); string transitStart = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().DepartureTime.Text; var _dbVal = context.Transits.Where(p => p.SourceId == originId && p.DestinationId == destinationId && p.departure_time == transitStart); if (_dbVal.Count() == 0) { var _transitDetail = new Transit(); _transitDetail.SourceId = originId; _transitDetail.DestinationId = destinationId; _transitDetail.Distance = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value / 1000; _transitDetail.departure_time = transitStart; _transitDetail.arrival_time = transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().ArrivalTime.Text; _transitDetail.Transit_Time = (decimal)transitDirections.Routes.FirstOrDefault().Legs.FirstOrDefault().Duration.Value.TotalHours; context.Transits.Add(_transitDetail); context.SaveChanges(); } } } } catch (Exception ex) { string _debug = ex.Message; } }
public void PopulateAirConnectivityTimes() { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var sources = context.Places.ToList(); var conns = context.Connections.Select(p => p); var airportconns = context.AirportConnections.Select(p => p); var destinations = sources; foreach (var source in sources) { foreach (var destination in destinations) { // if the source is destination - skip if (source.Name == destination.Name) { continue; } // if the places do not have airports - skip if (String.IsNullOrEmpty(source.NearestAirport) || String.IsNullOrEmpty(destination.NearestAirport)) { continue; } // if the places are near the same airport - skip if (source.NearestAirport == destination.NearestAirport) { continue; } // ok now that we have two airports - calculate flight time int fromAirport = context.Airports.Where(p => p.Code == source.NearestAirport).FirstOrDefault().Id; int toAirport = context.Airports.Where(p => p.Code == destination.NearestAirport).FirstOrDefault().Id; var flights = airportconns.Where(p => p.SourceId == fromAirport && p.DestinationId == toAirport); if (flights == null || flights.Count() == 0) // there are no connecting flightts { continue; } var averageFlightTime = flights.Average(p => p.FlightTime1); var minFLightTime = flights.Min(p => p.FlightTime1); var maxFlightTime = flights.Max(p => p.FlightTime1); var conn = conns.Where(p => p.SourceId == source.Id && p.DestinationId == destination.Id).FirstOrDefault(); if (conn != null) { conn.MaxFlightTime = maxFlightTime + source.NearestAirportDriveTime + destination.NearestAirportDriveTime; conn.MinFlightTime = minFLightTime + source.NearestAirportDriveTime + destination.NearestAirportDriveTime; conn.AvgFlightTime = averageFlightTime + source.NearestAirportDriveTime + destination.NearestAirportDriveTime; context.SaveChanges(); } } } } }
public void PopulateDistances() { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var sources = context.Places.ToList(); var distances = context.Connections.Select(p => p); var destinations = sources; foreach (var source in sources) { foreach (var destination in destinations) { if (source.Name == destination.Name) { continue; } var _dbDistance = distances.Where(x => x.SourceId == source.Id && x.DestinationId == destination.Id).FirstOrDefault(); if (_dbDistance != null) { continue; } double distanceKm = _CalculateDistance(source.Name, destination.Name); if (distanceKm > 0) { context.Connections.Add(new Connection() { SourceId = source.Id, DestinationId = destination.Id, Distance = (decimal)distanceKm }); context.SaveChanges(); } } //System.Threading.Thread.Sleep(10000); } context.SaveChanges(); } }
/// <summary> /// /// </summary> /// <param name="_travellerObj"></param> /// <returns></returns> public static DomingoBlError UpdateUserTravellerProfile(Traveller _travellerObj) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { // look for the profile var _xtravellerObj = context.Travellers.FirstOrDefault(p => p.AspnetUserid == _travellerObj.AspnetUserid); // if it exists, update it if (_xtravellerObj != null) { _xtravellerObj.FirstName = _travellerObj.FirstName; _xtravellerObj.LastName = _travellerObj.LastName; _xtravellerObj.Telephone = _travellerObj.Telephone; _xtravellerObj.Mobile = _travellerObj.Mobile; _xtravellerObj.AddressLine1 = _travellerObj.AddressLine1; _xtravellerObj.AddressLine2 = _travellerObj.AddressLine2; _xtravellerObj.City = _travellerObj.City; _xtravellerObj.Country = _travellerObj.Country; _xtravellerObj.PostCode = _travellerObj.PostCode; _xtravellerObj.TravelGroupSize = _travellerObj.TravelGroupSize; _xtravellerObj.TravelStyle = _travellerObj.TravelStyle; _xtravellerObj.TravelInterests = _travellerObj.TravelInterests; } else // create it { context.Travellers.Add(_travellerObj); } // save everything context.SaveChanges(); } } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> public static async Task <DomingoBlError> SaveTripProvider(TripProvider model) { try { if (model != null) { using (var context = new TravelogyDevEntities1()) { if (model.Id == 0) { context.TripProviders.Add(model); context.SaveChanges(); } else { var _tripProvider = context.TripProviders.Find(model.Id); _tripProvider.Address = model.Address; _tripProvider.Description = model.Description; _tripProvider.EmailAddressCustSupport = model.EmailAddressCustSupport; _tripProvider.EmailAddressMarketingSales = model.EmailAddressMarketingSales; _tripProvider.EmailAddressPrimary = model.EmailAddressPrimary; _tripProvider.Name = model.Name; _tripProvider.Telephone01 = model.Telephone01; _tripProvider.Telephone02 = model.Telephone02; _tripProvider.Telephone03 = model.Telephone03; _tripProvider.Type = model.Type; _tripProvider.Website = model.Website; await context.SaveChangesAsync(); } } } } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); }
public void PopulateMinimumTransitTimes() { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var conns = context.Connections.Select(p => p); foreach (var conn in conns) { if (conn.MinFlightTime != 0 && conn.MinFlightTime < conn.DrivingTime) { conn.MinimumTransitTime = (int)(conn.MinFlightTime * 60); } else { conn.MinimumTransitTime = (int)(conn.DrivingTime * 60); } } context.SaveChanges(); } }
public void PopulateAirportDistances() { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var placesWithAirports = context.Places.Where(p => p.NearestAirport.Length > 0); foreach (var city in placesWithAirports) { var airport = context.Airports.Where(p => p.Code == city.NearestAirport).FirstOrDefault(); if (airport == null) { continue; } if (city.NearestAirportDistance.HasValue) { continue; } var origin = new LatLong { Latitude = (double)airport.Lattitude, Longitude = (double)airport.Longitude }; var destinaiton = new LatLong() { Latitude = (double)city.Lattitude, Longitude = (double)city.Longitude }; System.Threading.Thread.Sleep(1000); var distance = _CalculateDistance(origin, destinaiton); city.NearestAirportDistance = (decimal)distance; } context.SaveChanges(); } } catch (Exception) { } }
internal static readonly string _FixerApiurl = "http://api.fixer.io/latest"; //"http://api.fixer.io/latest?callback=?"; /// <summary> /// Get the currency exchange rate /// </summary> /// <param name="fromCurrency"></param> /// <param name="toCurrency"></param> /// <param name="convertRate"></param> /// <returns></returns> public static DomingoBlError GetCurrencyExchangeRate(string fromCurrency, string toCurrency, out double convertRate) { convertRate = 0D; if (String.IsNullOrEmpty(fromCurrency) || String.IsNullOrEmpty(toCurrency)) { return(new DomingoBlError() { ErrorCode = 200, ErrorMessage = "Invalid or NULL parameters" });; } // return a 1 when we do not have to compare if (String.Compare(fromCurrency, toCurrency, false) == 0) { convertRate = 1D; return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); } // try to look if we have already cached it convertRate = _GetCachedCurrencyXchangeRate(fromCurrency, toCurrency); if (convertRate > 0D) { return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" });; } // if not, then call the Fixer API to get it try { var strJsonRequest = _SendJsonRequestToFixer(); var _fixerCurrencyExchange = JsonConvert.DeserializeObject <FixerCurrencyExchange>(strJsonRequest); var fromRate = _fixerCurrencyExchange.rates[fromCurrency]; var toRate = String.Compare(toCurrency.ToUpper(), "EUR") == 0 ? 1.0D : _fixerCurrencyExchange.rates[toCurrency]; if (fromRate > 0D) { convertRate = toRate / fromRate; } // once we get it, save it - so we dont look again using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { // find the record if exists var cx = context.CurrencyExchanges.Where(p => p.CurrencyFrom.ToUpper() == fromCurrency.ToUpper() && p.CurrencyTo.ToUpper() == toCurrency.ToUpper()).FirstOrDefault(); // or else create one if (cx == null) { cx = new CurrencyExchange(); cx.CurrencyFrom = fromCurrency; cx.CurrencyTo = toCurrency; cx.DateOfUpdate = DateTime.Now; cx.XchangeRate = (decimal)convertRate; context.CurrencyExchanges.Add(cx); } else { cx.XchangeRate = (decimal)convertRate; } // copy the values context.SaveChanges(); } } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); }
public DomingoBlError SendEmailWithAttachments(string emailAlias, List<MailAddress> deliveryAddresses, Dictionary<String, String> parameters, string attachmentPath) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { // get the xml template from DB HtmlEmailTemplate emailTemplate = context.HtmlEmailTemplates.Where(p => p.Alias == emailAlias).FirstOrDefault(); if (emailTemplate == null) { return new DomingoBlError() { ErrorCode = 200, ErrorMessage = "Invalid template alias" }; } // replace the parameters into the template HtmlEmail processedTemplate = ProcessTemplate(emailTemplate, parameters); MailMessage objMessage = new MailMessage(); objMessage.From = new MailAddress(processedTemplate.FromAddress, processedTemplate.FromName); foreach (MailAddress address in deliveryAddresses) { processedTemplate.ToAddress = address.Address; // construct the SMTP mail and send objMessage.From = new MailAddress(processedTemplate.FromAddress, processedTemplate.FromName); objMessage.Subject = processedTemplate.EmailSubject; objMessage.IsBodyHtml = true; objMessage.Body = processedTemplate.EmailText; objMessage.To.Clear(); objMessage.To.Add(address); var sendinBlue = new API("ICdw29ZamvD0WXcJ"); // sendinblue access key from the portal Dictionary<string, Object> data = new Dictionary<string, Object>(); Dictionary<string, string> to = new Dictionary<string, string>(); to.Add(address.Address, address.DisplayName); List<string> from_name = new List<string>(); from_name.Add(processedTemplate.FromAddress); from_name.Add(processedTemplate.FromName); List<string> attachment = new List<string>(); attachment.Add(attachmentPath); data.Add("to", to); data.Add("from", from_name); data.Add("subject", processedTemplate.EmailSubject); data.Add("html", processedTemplate.EmailText); data.Add("attachment", attachment); Object sendEmail = sendinBlue.send_email(data); Console.WriteLine(sendEmail); // save the mail to DB // to save the mail on DB context.HtmlEmails.Add(processedTemplate); context.SaveChanges(); } } return new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }; } // exception part catch (FormatException ex) { return new DomingoBlError() { ErrorCode = 100, ErrorMessage = string.Format("Error : {0}", ex) }; } }
public static void FindAndSaveFlights(int fromId, int toId, int year, int month, int day) { try { using (TravelogyDevEntities1 context = new TravelogyDevEntities1()) { var fromAirport = context.Airports.Find(fromId); var toAirport = context.Airports.Find(toId); if (fromAirport == null || toAirport == null) { throw new ApplicationException("Invalid Airport ID"); } var _dbVal = context.AirportConnections.Where(p => p.SourceId == fromId && p.DestinationId == toId).FirstOrDefault(); if (_dbVal != null) { return; } string payload = string.Format("https://api.flightstats.com/flex/schedules/rest/v1/json/from/{0}/to/{1}/departing/{2}/{3}/{4}?appId={5}&appKey={6}&extendedOptions=includeDirects", fromAirport.Code, toAirport.Code, year, month, day, applicationId, applicationKey); var response = _SendRequest(payload); foreach (var schedule in response.scheduledFlights) { DateTime depTime, arrTime; if (!DateTime.TryParse(schedule.departureTime, out depTime) || (!DateTime.TryParse(schedule.arrivalTime, out arrTime))) { throw new ApplicationException("Invalid Flight time"); } string flightNumber = string.Format("{0}-{1}", schedule.carrierFsCode, schedule.flightNumber); _dbVal = context.AirportConnections.Where(p => p.SourceId == fromId && p.DestinationId == toId && p.FlightNumber == flightNumber).FirstOrDefault(); // duplicate flight if (_dbVal != null) { return; } var flight = new AirportConnection(); flight.SourceId = fromId; flight.DestinationId = toId; flight.Stops = schedule.stops; flight.FlightNumber = flightNumber; flight.DepartureTime = depTime.TimeOfDay.ToString(); flight.ArrivalTime = arrTime.TimeOfDay.ToString(); var flightDuration = arrTime - depTime; flight.FlightTime1 = (decimal)flightDuration.TotalMinutes / (decimal)60.0; context.AirportConnections.Add(flight); context.SaveChanges(); } } } catch (Exception ex) { } }