Example #1
0
        /// <summary>
        /// Get a TimeZoneData object for given latitude and longitude corrdinates. With that, you can calculate the current time for the given timezone
        /// </summary>
        /// <param name="Address"></param>
        /// <returns></returns>
        public TimeZoneData GetTimeZoneData(string latLng)
        {
            string cacheKey = FormatCacheKey("TimeZoneData", latLng);

            TimeZoneData timeZone = Cache.Get <TimeZoneData>(cacheKey);

            if (timeZone == null)
            {
                // make sure the lat and long corrdinates are not empty befor continuing on
                if (!string.IsNullOrEmpty(latLng))
                {
                    // Goolge api requires the number of seconds from midnight on January 1, 1970 to get a timezone
                    int seconds = (int)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;

                    // Google api requires a developer key for this api
                    string googleKey = ConfigurationManager.AppSettings.Get("GoogleKey");

                    string url = string.Format("https://maps.googleapis.com/maps/api/timezone/json?location={0}&timestamp={1}&key={2}", latLng, seconds, googleKey);
                    timeZone = GetAsyncResult <TimeZoneData>(url);

                    if (timeZone != null)
                    {
                        Cache.Set(cacheKey, timeZone, 43200);
                    }
                }
            }

            return(timeZone);
        }
Example #2
0
        /// <summary>
        /// Set device Time Zone and Synchronization Server via device twin.
        /// </summary>
        private async void SetTimeInfoButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            TimeZoneData selectedTimeZoneData = (TimeZoneData)TimeZoneCombobox.SelectedItem;

            if (selectedTimeZoneData == null)
            {
                _mainPage.ShowDialogAsync("Invaid Input", "Time Zone value is not selected");
                return;
            }

            TimeSettingsDataContract.DesiredProperties desiredProperties = new TimeSettingsDataContract.DesiredProperties();
            desiredProperties.ntpServer    = NtpServerCombobox.SelectedValue.ToString();
            desiredProperties.timeZoneBias = selectedTimeZoneData.Bias;

            desiredProperties.timeZoneStandardBias      = selectedTimeZoneData.StandardBias;
            desiredProperties.timeZoneStandardDate      = selectedTimeZoneData.StandardDate;
            desiredProperties.timeZoneStandardName      = selectedTimeZoneData.StandardName;
            desiredProperties.timeZoneStandardDayOfWeek = selectedTimeZoneData.StandardDayOfWeek;

            desiredProperties.timeZoneDaylightBias      = selectedTimeZoneData.DaylightBias;
            desiredProperties.timeZoneDaylightDate      = selectedTimeZoneData.DaylightDate;
            desiredProperties.timeZoneDaylightName      = selectedTimeZoneData.DaylightName;
            desiredProperties.timeZoneDaylightDayOfWeek = selectedTimeZoneData.DaylightDayOfWeek;

            desiredProperties.timeZoneKeyName             = selectedTimeZoneData.Id;
            desiredProperties.dynamicDaylightTimeDisabled = selectedTimeZoneData.DisableDynamicDaylightTime;

            string refreshingValue = "\"refreshing\"";
            string finalValue      = "{" + desiredProperties.ToJsonString() + "}";
            await _mainPage.UpdateTwinData(refreshingValue, finalValue);
        }
        public string ToJson()
        {
            TimeZoneData timeZoneData = (TimeZoneData)DisplayNames.SelectedItem;

            TimeSettingsDataContract.DesiredProperties desiredProperties = new TimeSettingsDataContract.DesiredProperties();

            desiredProperties.ntpServer = ((ComboBoxItem)DesiredNtpServer.SelectedItem).Content.ToString();

            desiredProperties.timeZoneBias = timeZoneData.Bias;

            desiredProperties.timeZoneStandardBias      = timeZoneData.StandardBias;
            desiredProperties.timeZoneStandardDate      = timeZoneData.StandardDate;
            desiredProperties.timeZoneStandardName      = timeZoneData.StandardName;
            desiredProperties.timeZoneStandardDayOfWeek = timeZoneData.StandardDayOfWeek;

            desiredProperties.timeZoneDaylightBias      = timeZoneData.DaylightBias;
            desiredProperties.timeZoneDaylightDate      = timeZoneData.DaylightDate;
            desiredProperties.timeZoneDaylightName      = timeZoneData.DaylightName;
            desiredProperties.timeZoneDaylightDayOfWeek = timeZoneData.DaylightDayOfWeek;

            desiredProperties.timeZoneKeyName             = timeZoneData.Id;
            desiredProperties.dynamicDaylightTimeDisabled = false;

            return(desiredProperties.ToJsonString());
        }
        private string GetSpecialTokenValue(DateTimeOffset value, string token, CultureInfo culture)
        {
            switch (token)
            {
            case "Mo":   return(AddOrdinal(value.Month));

            case "Q":    return(GetQuarter(value.Month).ToString());

            case "Qo":   return(AddOrdinal(GetQuarter(value.Month)));

            case "Do":   return(AddOrdinal(value.Day));

            case "DDD":  return(value.DayOfYear.ToString());

            case "DDDo": return(AddOrdinal(value.DayOfYear));

            case "DDDD": return(value.DayOfYear.ToString("000"));

            case "d":    return(((int)value.DayOfWeek).ToString());

            case "do":   return(AddOrdinal((int)value.DayOfWeek));

            case "e":    return(((int)value.DayOfWeek).ToString());

            case "E":    return(((int)value.DayOfWeek + 1).ToString());

            case "w":
            case "wo":
            case "ww":
            case "W":
            case "Wo":
            case "WW":
                return(GetWeekTokenValue(value, token, culture));

            case "a":         return(value.ToString("tt", culture).ToLower());

            case "k":         return((value.Hour + 1).ToString());

            case "kk":        return((value.Hour + 1).ToString("00"));

            case "SSSSSSSS":  return(value.ToString("fffffff00", culture));

            case "SSSSSSSSS": return(value.ToString("fffffff000", culture));

            case "z":
            case "zz":
                return(TimeZoneData.GetFirstForOffset(value.Offset).Abbreviation);

            case "ZZ": return(value.ToString("zzz", culture).Replace(":", ""));

            case "X":  return(value.ToUnixTimeSeconds().ToString());

            case "x":  return(value.ToUnixTimeMilliseconds().ToString());
            }

            return(token);
        }
Example #5
0
        /// <summary>
        /// Populate the timezone info and update on UI.
        /// </summary>
        private void PopulateTimeZones()
        {
            ReadOnlyCollection <TimeZoneInfo> tzCollection = TimeZoneInfo.GetSystemTimeZones();

            List <TimeZoneData> displayNames = new List <TimeZoneData>();

            foreach (TimeZoneInfo timeZone in tzCollection)
            {
                TimeZoneData timeZoneData = new TimeZoneData();
                timeZoneData.Id           = timeZone.Id;
                timeZoneData.DaylightName = timeZone.DaylightName;
                timeZoneData.StandardName = timeZone.StandardName;
                timeZoneData.DisplayName  = timeZone.DisplayName;
                timeZoneData.Bias         = -1 * (int)timeZone.BaseUtcOffset.TotalMinutes;

                TimeZoneInfo.AdjustmentRule[] rules = timeZone.GetAdjustmentRules();
                if (rules.Length != 0)
                {
                    TimeZoneInfo.AdjustmentRule currentRule = rules[rules.Length - 1];

                    int daylightYear = 0;
                    if (currentRule.DaylightTransitionStart.TimeOfDay.Year != 1)    // .net uses 1 so that DateTime accepts it.
                    {
                        daylightYear = currentRule.DaylightTransitionStart.TimeOfDay.Year;
                    }

                    timeZoneData.DaylightDate = daylightYear +
                                                "-" + currentRule.DaylightTransitionStart.Month.ToString() +
                                                "-" + currentRule.DaylightTransitionStart.Week +
                                                "T" + currentRule.DaylightTransitionStart.TimeOfDay.ToString("HH:mm:ss");

                    timeZoneData.DaylightBias      = -1 * (int)currentRule.DaylightDelta.TotalMinutes;
                    timeZoneData.DaylightDayOfWeek = (int)currentRule.DaylightTransitionStart.DayOfWeek;

                    int standardYear = 0;
                    if (currentRule.DaylightTransitionEnd.TimeOfDay.Year != 1)    // .net uses 1 so that DateTime accepts it.
                    {
                        standardYear = currentRule.DaylightTransitionEnd.TimeOfDay.Year;
                    }

                    timeZoneData.StandardDate = standardYear +
                                                "-" + currentRule.DaylightTransitionEnd.Month.ToString() +
                                                "-" + currentRule.DaylightTransitionEnd.Week +
                                                "T" + currentRule.DaylightTransitionEnd.TimeOfDay.ToString("HH:mm:ss");
                    timeZoneData.StandardBias      = 0;
                    timeZoneData.StandardDayOfWeek = (int)currentRule.DaylightTransitionEnd.DayOfWeek;
                }

                displayNames.Add(timeZoneData);
            }

            TimeZoneCombobox.ItemsSource   = displayNames;
            TimeZoneCombobox.SelectedIndex = 0;
        }
        public TimeZoneData GetTimeZoneByIdOrDefault(int id)
        {
            if (_timezones == null || _gmt == null)
            {
                throw new InvalidOperationException("Time zones provider not initialized");
            }

            TimeZoneData timeZoneData = _timezones.Where(t => t.Id == id).FirstOrDefault();

            return(timeZoneData ?? _gmt);
        }
Example #7
0
        public GetTimeZoneDataResponse GetDefaultTimeZone(GetTimeZoneDataRequest request)
        {
            GetTimeZoneDataResponse response = new GetTimeZoneDataResponse();
            ILookUpRepository       repo     = Factory.GetRepository(request, RepositoryType.LookUp);
            TimeZoneData            data     = repo.GetDefaultTimeZone();

            if (data != null)
            {
                response.TimeZone = data;
            }
            return(response);
        }
        public void Init(ResourceManager timeZonesResourceManager)
        {
            if (timeZonesResourceManager == null)
            {
                throw new ArgumentNullException("timeZonesResourceManager");
            }

            _timeZonesResourceManager = timeZonesResourceManager;
            _timezones = new List <TimeZoneData>();

            _timezones.Add(new TimeZoneData(-43200, new TimeSpan(0, -12, 0, 0), "tz_m_12", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-39600, new TimeSpan(0, -11, 0, 0), "tz_m_11", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-36000, new TimeSpan(0, -10, 0, 0), "tz_m_10", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-32400, new TimeSpan(0, -9, 0, 0), "tz_m_9", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-28800, new TimeSpan(0, -8, 0, 0), "tz_m_8", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-25200, new TimeSpan(0, -7, 0, 0), "tz_m_7", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-21600, new TimeSpan(0, -6, 0, 0), "tz_m_6", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-18000, new TimeSpan(0, -5, 0, 0), "tz_m_5", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-14400, new TimeSpan(0, -4, 0, 0), "tz_m_4", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-12600, new TimeSpan(0, -3, -30, 0), "tz_m_3_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-10800, new TimeSpan(0, -3, 0, 0), "tz_m_3", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-7200, new TimeSpan(0, -2, 0, 0), "tz_m_2", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-3600, new TimeSpan(0, -1, 0, 0), "tz_m_1", _timeZonesResourceManager));

            _gmt = new TimeZoneData(0, new TimeSpan(0, 0, 0, 0), "tz_0", _timeZonesResourceManager);
            _timezones.Add(_gmt);

            _timezones.Add(new TimeZoneData(3600, new TimeSpan(0, 1, 0, 0), "tz_p_1", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(7200, new TimeSpan(0, 2, 0, 0), "tz_p_2", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(10800, new TimeSpan(0, 3, 0, 0), "tz_p_3", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(12600, new TimeSpan(0, 3, 30, 0), "tz_p_3_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(14400, new TimeSpan(0, 4, 0, 0), "tz_p_4", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(16200, new TimeSpan(0, 4, 30, 0), "tz_p_4_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(18000, new TimeSpan(0, 5, 0, 0), "tz_p_5", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(19800, new TimeSpan(0, 5, 30, 0), "tz_p_5_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(20700, new TimeSpan(0, 5, 45, 0), "tz_p_5_45", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(21600, new TimeSpan(0, 6, 0, 0), "tz_p_6", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(25200, new TimeSpan(0, 7, 0, 0), "tz_p_7", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(28800, new TimeSpan(0, 8, 0, 0), "tz_p_8", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(32400, new TimeSpan(0, 9, 0, 0), "tz_p_9", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(34200, new TimeSpan(0, 9, 30, 0), "tz_p_9_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(36000, new TimeSpan(0, 10, 0, 0), "tz_p_10", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(39600, new TimeSpan(0, 11, 0, 0), "tz_p_11", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(43200, new TimeSpan(0, 12, 0, 0), "tz_p_12", _timeZonesResourceManager));
        }
        public void Init(ResourceManager timeZonesResourceManager)
        {
            if (timeZonesResourceManager == null)
                throw new ArgumentNullException("timeZonesResourceManager");

            _timeZonesResourceManager = timeZonesResourceManager;
            _timezones = new List<TimeZoneData>();

            _timezones.Add(new TimeZoneData(-43200, new TimeSpan(0, -12, 0, 0), "tz_m_12", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-39600, new TimeSpan(0, -11, 0, 0), "tz_m_11", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-36000, new TimeSpan(0, -10, 0, 0), "tz_m_10", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-32400, new TimeSpan(0, -9, 0, 0), "tz_m_9", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-28800, new TimeSpan(0, -8, 0, 0), "tz_m_8", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-25200, new TimeSpan(0, -7, 0, 0), "tz_m_7", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-21600, new TimeSpan(0, -6, 0, 0), "tz_m_6", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-18000, new TimeSpan(0, -5, 0, 0), "tz_m_5", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-14400, new TimeSpan(0, -4, 0, 0), "tz_m_4", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-12600, new TimeSpan(0, -3, -30, 0), "tz_m_3_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-10800, new TimeSpan(0, -3, 0, 0), "tz_m_3", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-7200, new TimeSpan(0, -2, 0, 0), "tz_m_2", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(-3600, new TimeSpan(0, -1, 0, 0), "tz_m_1", _timeZonesResourceManager));

            _gmt = new TimeZoneData(0, new TimeSpan(0, 0, 0, 0), "tz_0", _timeZonesResourceManager);
            _timezones.Add(_gmt);

            _timezones.Add(new TimeZoneData(3600, new TimeSpan(0, 1, 0, 0), "tz_p_1", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(7200, new TimeSpan(0, 2, 0, 0), "tz_p_2", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(10800, new TimeSpan(0, 3, 0, 0), "tz_p_3", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(12600, new TimeSpan(0, 3, 30, 0), "tz_p_3_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(14400, new TimeSpan(0, 4, 0, 0), "tz_p_4", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(16200, new TimeSpan(0, 4, 30, 0), "tz_p_4_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(18000, new TimeSpan(0, 5, 0, 0), "tz_p_5", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(19800, new TimeSpan(0, 5, 30, 0), "tz_p_5_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(20700, new TimeSpan(0, 5, 45, 0), "tz_p_5_45", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(21600, new TimeSpan(0, 6, 0, 0), "tz_p_6", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(25200, new TimeSpan(0, 7, 0, 0), "tz_p_7", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(28800, new TimeSpan(0, 8, 0, 0), "tz_p_8", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(32400, new TimeSpan(0, 9, 0, 0), "tz_p_9", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(34200, new TimeSpan(0, 9, 30, 0), "tz_p_9_30", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(36000, new TimeSpan(0, 10, 0, 0), "tz_p_10", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(39600, new TimeSpan(0, 11, 0, 0), "tz_p_11", _timeZonesResourceManager));
            _timezones.Add(new TimeZoneData(43200, new TimeSpan(0, 12, 0, 0), "tz_p_12", _timeZonesResourceManager));
        }
        public static void SeedDataBase(ApplicationDbContext context)
        {
            if (!context.Currencies.Any())
            {
                var currencies = CurrencyData.GetCurrencyList();
                foreach (var currency in currencies)
                {
                    context.Currencies.Add(currency);
                }
                context.SaveChanges();
            }
            if (!context.StateTimeZones.Any())
            {
                var timeZones        = TimeZoneData.GetTimeZoneList();
                var timeZonesSplited = timeZones.SplitList(100);
                foreach (var tzSplited in timeZonesSplited)
                {
                    foreach (var timeZone in tzSplited)
                    {
                        context.StateTimeZones.Add(timeZone);
                    }
                    context.SaveChanges();
                }
            }

            if (!context.Users.Any())
            {
                var users = UserData.GetUserList();
                foreach (var user in users)
                {
                    byte[] passwordHash, passwordSalt;
                    CreatePasswordHash("password", out passwordHash, out passwordSalt);

                    user.PasswordHash = passwordHash;
                    user.PasswordSalt = passwordSalt;
                    user.UserName     = user.UserName.ToLower();

                    context.Users.Add(user);
                }
                context.SaveChanges();
            }
        }
Example #11
0
        public void RequestPasswordReset(string email, string siteUrl, Func <string, string> resetUrlGenerator)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentNullException("email");
            }

            if (string.IsNullOrEmpty(siteUrl))
            {
                throw new ArgumentNullException("siteurl");
            }

            if (resetUrlGenerator == null)
            {
                throw new ArgumentNullException("resetUrlGenerator");
            }

            User user = _userService.GetUserByEmail(email);

            if (user == null)
            {
                throw new UserNotExistsException(string.Format(CultureInfo.InvariantCulture, "User with email {0} not found", email));
            }

            DateTime expiration = DateTime.UtcNow.Add(_webConfiguration.ResetPasswordRequestExpiration);

            ResetPasswordRequest request = _userService.CreatePasswordResetRequestForUser(user, expiration);
            string       link            = resetUrlGenerator(request.Token);
            TimeZoneData timeZoneData    = _timeZonesProvider.GetTimeZoneByIdOrDefault(user.TimeZone);
            var          templateData    = new Dictionary <string, object>
            {
                { "link", link },
                { "siteurl", siteUrl },
                { "username", user.Name },
                { "expire", new DateTimeOffset(request.Expiration).ToOffset(timeZoneData.Offset).ToString("dd.MM.yyyy HH:mm zzz") }
            };
            string emailBody    = _templateEngine.TransformTemplate(templateData, MailResources.RestorePasswordMailBody);
            string emailSubject = _templateEngine.TransformTemplate(templateData, MailResources.RestorePasswordMailSubject);

            _mailService.SendMessage(emailSubject, emailBody, _webConfiguration.RestorePasswordMailFrom, user.Email);
        }
Example #12
0
        /// <summary>
        /// Time zone dropdown input changed, update the UI.
        /// </summary>
        private void TimeZoneInput_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = (ComboBox)sender;

            if (comboBox != null)
            {
                TimeZoneData selectedTimeZoneData = (TimeZoneData)comboBox.SelectedItem;

                TimezoneKeyNameInput.Text     = selectedTimeZoneData.DisplayName;
                DynamicDaylightTimeInput.Text = selectedTimeZoneData.DisableDynamicDaylightTime.ToString();

                TimeZoneBiasInput.Text              = selectedTimeZoneData.Bias.ToString();
                TimeZoneStandardNameInput.Text      = selectedTimeZoneData.StandardName ?? string.Empty;
                TimeZoneStandardDateInput.Text      = selectedTimeZoneData.StandardDate ?? string.Empty;
                TimeZoneStandardBiasInput.Text      = selectedTimeZoneData.StandardBias.ToString() ?? string.Empty;
                TimeZoneStandardDayOfWeekInput.Text = selectedTimeZoneData.StandardDayOfWeek.ToString() ?? string.Empty;
                TimeZoneDaylightNameInput.Text      = selectedTimeZoneData.DaylightName ?? string.Empty;
                TimeZoneDaylightDateInput.Text      = selectedTimeZoneData.DaylightDate ?? string.Empty;
                TimeZoneDaylightBiasInput.Text      = selectedTimeZoneData.DaylightBias.ToString() ?? string.Empty;
                TimeZoneDaylightDayOfWeekInput.Text = selectedTimeZoneData.StandardDayOfWeek.ToString() ?? string.Empty;
            }
        }
Example #13
0
        public async Task TimezoneCommand(string Action = "", [Remainder] string Argument = "")
        {
            if (string.IsNullOrEmpty(Action) || Action.ToLower() == "info")
            {
                await BuildEmbed(EmojiEnum.Sign)
                .WithTitle("Time Zone Info")
                .WithDescription("Time Zones are used to coordinate the times you input with those of other members in different parts of the world.\n" +
                                 "Many countries use a mechanism called **Daylight Saving Time** (DST), whereby time gets advanced for 1 hour during the summer half of the year.\n" +
                                 "When inputting your time zone, make sure to check whether your local area uses DST or not, and specify the correct time zone.\n" +
                                 $"Dexter is running in {TimeZoneData.ToTimeZoneExpression(DateTimeOffset.Now.Offset)}.")
                .WithCurrentTimestamp()
                .SendEmbed(Context.Channel);

                return;
            }

            switch (Action.ToLower())
            {
            case "search":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide a Time Zone Abbreviation to search for!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                {
                    string[] Results          = LanguageHelper.SearchTimeZone(Argument, LanguageConfiguration);
                    string[] ResultsHumanized = new string[Math.Min(10, Results.Length)];

                    for (int i = 0; i < ResultsHumanized.Length; i++)
                    {
                        ResultsHumanized[i] = $"{Results[i]}: {LanguageConfiguration.TimeZones[Results[i]]}";
                    }

                    await BuildEmbed(EmojiEnum.Love)
                    .WithTitle("Top 10 Results")
                    .WithDescription(string.Join("\n", ResultsHumanized))
                    .SendEmbed(Context.Channel);
                }
                return;

            case "span":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide a Time Zone Expression to search for!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                {
                    if (!TimeZoneData.TryParse(Argument, LanguageConfiguration, out TimeZoneData TimeZone))
                    {
                        await BuildEmbed(EmojiEnum.Annoyed)
                        .WithTitle("Couldn't find time zone!")
                        .WithDescription($"Time Zone {Argument} doesn't exist. Use `{BotConfiguration.Prefix}timezone search {Argument}` to look for similar ones.")
                        .SendEmbed(Context.Channel);

                        return;
                    }

                    string[] Results          = LanguageHelper.SearchTimeZone(TimeZone.TimeOffset, LanguageConfiguration, out int Exact);
                    string[] ResultsHumanized = new string[Math.Min(Math.Max(Exact, 10), Results.Length)];

                    for (int i = 0; i < ResultsHumanized.Length; i++)
                    {
                        ResultsHumanized[i] = $"{Results[i]}: {LanguageConfiguration.TimeZones[Results[i]]}";
                    }

                    await BuildEmbed(EmojiEnum.Love)
                    .WithTitle($"Top {ResultsHumanized.Length} Results similar to {TimeZoneData.ToTimeZoneExpression(TimeZone.Offset)}")
                    .WithDescription(string.Join("\n", ResultsHumanized))
                    .SendEmbed(Context.Channel);
                }
                return;

            case "now":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide a Time Zone Expression to search for!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                {
                    if (!TimeZoneData.TryParse(Argument, LanguageConfiguration, out TimeZoneData TimeZone))
                    {
                        await BuildEmbed(EmojiEnum.Annoyed)
                        .WithTitle("Couldn't find time zone!")
                        .WithDescription($"Time Zone {Argument} doesn't exist. Use `{BotConfiguration.Prefix}timezone search {Argument}` to look for similar ones.")
                        .SendEmbed(Context.Channel);

                        return;
                    }

                    await Context.Channel.SendMessageAsync($"It is currently **{DateTimeOffset.Now.ToOffset(TimeZone.TimeOffset):dddd',' MMMM d',' hh:mm tt}** in {TimeZoneData.ToTimeZoneExpression(TimeZone.Offset)} ({TimeZone.Name}).");
                }
                return;

            case "get":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide a Time Zone Abbreviation to search for!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                if (!LanguageConfiguration.TimeZones.ContainsKey(Argument))
                {
                    string[] Results          = LanguageHelper.SearchTimeZone(Argument, LanguageConfiguration);
                    string[] ResultsHumanized = new string[Math.Min(3, Results.Length)];

                    for (int i = 0; i < ResultsHumanized.Length; i++)
                    {
                        ResultsHumanized[i] = $"{Results[i]}: {LanguageConfiguration.TimeZones[Results[i]]}";
                    }

                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Unable to find time zone!")
                    .WithDescription($"Did you mean...\n{string.Join("\n", ResultsHumanized)}")
                    .SendEmbed(Context.Channel);

                    return;
                }

                await BuildEmbed(EmojiEnum.Love)
                .WithTitle("Found time zone!")
                .WithDescription($"{Argument}: {LanguageConfiguration.TimeZones[Argument]}")
                .SendEmbed(Context.Channel);

                return;

            case "when":
            case "until":
            case "till":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide a Date and Time to compare to!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                if (!LanguageHelper.TryParseTime(Argument, CultureInfo.CurrentCulture, LanguageConfiguration, out DateTimeOffset Time, out _))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Failed to parse date!")
                    .WithDescription($"I was unable to parse the time: `{Argument}`\n Make sure it follows the correct format! For more info, check out `{BotConfiguration.Prefix}checktime [Your Date]`")
                    .SendEmbed(Context.Channel);

                    return;
                }

                await BuildEmbed(EmojiEnum.Love)
                .WithTitle("Found Time!")
                .WithDescription($"{Time:MMM dd, yyyy hh:mm tt 'UTC'zzz} {(Time.CompareTo(DateTimeOffset.Now) < 0 ? "happened" : "will happen")} {Time.Humanize()}.")
                .SendEmbed(Context.Channel);

                return;

            case "diff":
            case "difference":
            case "comp":
            case "compare":
                if (string.IsNullOrEmpty(Argument))
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Invalid number of arguments!")
                    .WithDescription("You must provide two time zones to compare!")
                    .SendEmbed(Context.Channel);

                    return;
                }

                {
                    string[] Args = Argument.Split(" ");
                    if (Args.Length < 2)
                    {
                        await BuildEmbed(EmojiEnum.Annoyed)
                        .WithTitle("Invalid number of arguments!")
                        .WithDescription("You haven't provided enough time zones to compare! You must provide two.")
                        .SendEmbed(Context.Channel);

                        return;
                    }

                    TimeZoneData[] TimeZones = new TimeZoneData[2];

                    for (int i = 0; i < TimeZones.Length; i++)
                    {
                        if (!TimeZoneData.TryParse(Args[i], LanguageConfiguration, out TimeZones[i]))
                        {
                            await BuildEmbed(EmojiEnum.Annoyed)
                            .WithTitle("Couldn't find time zone!")
                            .WithDescription($"Time Zone {Args[i]} doesn't exist. Use `{BotConfiguration.Prefix}timezone search {Args[i]}` to look for similar ones.")
                            .SendEmbed(Context.Channel);

                            return;
                        }
                    }

                    float Diff = TimeZones[0].Offset - TimeZones[1].Offset;

                    string Message;
                    if (Diff != 0)
                    {
                        Message = $"{Args[0]} ({TimeZones[0].Name}) is " +
                                  $"**{LanguageHelper.HumanizeSexagesimalUnits(Math.Abs(Diff), new string[] { "hour", "hours" }, new string[] { "minute", "minutes" }, out _)} " +
                                  $"{(Diff < 0 ? "behind" : "ahead of")}** {Args[1]} ({TimeZones[1].Name}).";
                    }
                    else
                    {
                        Message = $"{Args[0]} ({TimeZones[0].Name}) is **in sync with** {Args[1]} ({TimeZones[1].Name}).";
                    }

                    await Context.Channel.SendMessageAsync(Message);
                }
                return;

            default:
                await BuildEmbed(EmojiEnum.Annoyed)
                .WithTitle("Unrecognized action!")
                .WithDescription($"Unable to parse action \"`{Action}`\"! \nFor more information on accepted actions, check out the `help timezone` command.")
                .SendEmbed(Context.Channel);

                return;
            }
        }
Example #14
0
        public void ImportFile(string excelFile)
        {
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + @";Extended Properties=""Excel 8.0;HDR=YES;""";

            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

            using (DbConnection connection = factory.CreateConnection())
            {
                connection.ConnectionString = connectionString;

                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT Address, [Birth Date], Gender, [Home Phone],  Name, [Work Phone] FROM [Patient Data$]";

                    connection.Open();

                    using (DbDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            #region Parse all needed data
                            //PatientData
                            string[] fullname = dr["Name"].ToString().Split(", ".ToCharArray());

                            string dob       = dr["Birth Date"].ToString();
                            string firstname = fullname[2].ToString();
                            string lastname  = fullname[0].ToString();
                            string gender    = dr["Gender"].ToString();

                            //Contact Info
                            string   newadd       = dr["Address"].ToString().Replace("<br/>", "-");
                            string[] splitaddress = newadd.Split("-".ToCharArray());
                            string[] cityStateZip = splitaddress[1].Split(",".ToCharArray());
                            string[] stateZip     = cityStateZip[1].Split(" ".ToCharArray());

                            string homePhone = dr["Home Phone"].ToString().Replace("-", string.Empty);
                            string workPhone = dr["Work Phone"].ToString().Replace("-", string.Empty);
                            string line1     = splitaddress[0];
                            string city      = cityStateZip[0].Trim();
                            string state     = stateZip[1];
                            string zip       = stateZip[2];
                            #endregion


                            #region Insert Patient
                            //DOB = Birth Date
                            //FirstName = second part of Name(after , )
                            //Gender = Gender
                            //LastName = first part of Name (before ,)
                            PatientData patient = new PatientData
                            {
                                DOB       = dob,
                                FirstName = firstname,
                                Gender    = gender,
                                LastName  = lastname
                            };
                            PutPatientDataRequest patientRequest = new PutPatientDataRequest
                            {
                                Patient = patient
                            };

                            PutPatientDataResponse responsePatient = import.InsertPatient(patientRequest);
                            #endregion


                            #region Add Contact Info (home phone, work phone, address)
                            if (responsePatient.Id != null)
                            {
                                //timezone defaulting to central
                                TimeZoneData tZone = import.GetDefaultTimeZone();

                                List <IdNamePair>   modesLookUp = import.GetModes();
                                List <CommModeData> modes       = new List <CommModeData>();
                                List <PhoneData>    phones      = new List <PhoneData>();
                                List <AddressData>  addresses   = new List <AddressData>();
                                List <EmailData>    emails      = new List <EmailData>();

                                //modes
                                if (modesLookUp != null && modesLookUp.Count > 0)
                                {
                                    foreach (IdNamePair l in modesLookUp)
                                    {
                                        modes.Add(new CommModeData {
                                            ModeId = l.Id, OptOut = false, Preferred = false
                                        });
                                    }
                                }


                                //phones
                                if (!string.IsNullOrEmpty(homePhone))
                                {
                                    PhoneData home = new PhoneData
                                    {
                                        Number         = Convert.ToInt64(homePhone),
                                        OptOut         = false,
                                        PhonePreferred = true,
                                        TypeId         = import.GetType("Home")
                                    };
                                    phones.Add(home);
                                }

                                if (!string.IsNullOrEmpty(workPhone))
                                {
                                    PhoneData work = new PhoneData
                                    {
                                        Number         = Convert.ToInt64(workPhone),
                                        OptOut         = false,
                                        PhonePreferred = true,
                                        TypeId         = import.GetType("Work")
                                    };
                                    phones.Add(work);
                                }

                                //address
                                if (!string.IsNullOrEmpty(newadd))
                                {
                                    AddressData add1 = new AddressData
                                    {
                                        Line1      = line1,
                                        City       = city,
                                        PostalCode = zip,
                                        OptOut     = false,
                                        Preferred  = true,
                                        StateId    = import.GetState(state),
                                        TypeId     = import.GetFirstTypeLookUp()
                                    };

                                    addresses.Add(add1);
                                }

                                //Contact
                                ContactData data = new ContactData {
                                    PatientId  = responsePatient.Id,
                                    Modes      = modes,
                                    TimeZoneId = tZone.Id,
                                    Phones     = phones,
                                    Emails     = emails,
                                    Addresses  = addresses,
                                };
                                InsertContactDataRequest contactRequest = new InsertContactDataRequest
                                {
                                    ContactData    = data,
                                    Version        = patientRequest.Version,
                                    Context        = patientRequest.Context,
                                    ContractNumber = patientRequest.ContractNumber
                                };

                                InsertContactDataResponse responseContact = import.InsertContactForAPatient(contactRequest, responsePatient.Id.ToString());
                                if (responseContact.Id == null)
                                {
                                    throw new Exception("Contact card import request failed.");
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }