Esempio n. 1
0
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        public static int ToTimeInt <T>(this DateTime time)
        {
            var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);

            return((int)((time) - startTime).TotalSeconds);
        }
Esempio n. 2
0
 /// <summary>Converts given local time to Pacific time.</summary>
 /// <param name="timestamp">Timestamp in local time to be converted to Pacific time.</param>
 /// <returns>
 /// <para>Timestamp in Pacific time.</para>
 /// </returns>
 public static DateTime LocalTimeToPacificTime(this DateTime timestamp) => TimeZoneInfo.ConvertTime(timestamp, TimeZoneInfo.Local, USTimeZones.Pacific);
Esempio n. 3
0
 public static DateTime GetDate()
 { // server yurt disinda oldugundan tarih ayari yapalim diye
     return(TimeZoneInfo.ConvertTime(DateTime.Now.ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById("GTB Standard Time")));
 }
Esempio n. 4
0
        public void showNextAppTime()
        {
            string county = form1.selecteCounty.Shops[form1.selectedShop];        //big surprise!!! the official entrance is the encoding with s-jis of county's name, BUT, shop's name also works! And now I use shop's name with others' will narely do

            string shop    = form1.selecteCounty.Sids[form1.selectedShop];
            string forTest = Form1.ToUrlEncode(
                county,
                System.Text.Encoding.GetEncoding("shift-jis")
                );

            DateTime dateTime = DateTime.MinValue;
            string   day      = "";
            string   time     = "";

            string html = Form1.weLoveYue(
                form1,
                "http://aksale.advs.jp/cp/akachan_sale_pc/search_event_list.cgi?area2="
                + Form1.ToUrlEncode(
                    county,
                    System.Text.Encoding.GetEncoding("shift-jis")
                    )
                + "&event_type=" + sizeType + "&sid=" + shop + "&kmws=",

                "GET", "", false, "", ref cookieContainer,
                false
                );

            //available
            //   <th>予約受付期間</th>
            //					<td>
            //						10/12<font color="#ff0000">(月)</font>&nbsp;13:30~10/12<font color="#ff0000">(月)</font>&nbsp;22:00<br />

            if (county == form1.selecteCounty.Shops[form1.selectedShop] &&
                shop == form1.selecteCounty.Sids[form1.selectedShop] &&
                sizeType == form1.selectedType)
            {
                rgx     = @"(?<=<th>予約受付期間</th>\n.*\n\s*)\d+\/\d+(?=\D)";
                myMatch = (new Regex(rgx)).Match(html);
                while (myMatch.Success)
                {
                    day = myMatch.Groups[0].Value;// no available appointment
                    rgx = @"(?<=<th>予約受付期間</th>\n.*\n\s*" + day + @"(\s|\S)+?)\d+\:\d+(?=\D)";
                    Match match2 = (new Regex(rgx)).Match(html);
                    if (match2.Success)
                    {
                        time = match2.Groups[0].Value;

                        DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
                        dtFormat.ShortDatePattern = "yyyy-M-d hh:mm:ss";
                        dateTime = Convert.ToDateTime("2015-" + Regex.Match(day, @"\d+(?=\/)") + "-" + Regex.Match(day, @"(?<=\/)\d+") + " " + time + ":00");


                        //how to find the year ?

                        TimeZoneInfo jst            = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
                        TimeZoneInfo cst            = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
                        DateTime     nowInTokyoTime = TimeZoneInfo.ConvertTime(DateTime.Now, jst);
                        if ((dateTime - nowInTokyoTime).TotalMinutes > -15)
                        {
                            delegate2 d111 = new delegate2(
                                delegate() {
                                form1.label14.Text = "the nearest booking on type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county
                                                     + " is on: \n" + dateTime.ToString("MM/dd HH:mm") + " Tokyo Standard Time\n"
                                                     + TimeZoneInfo.ConvertTimeFromUtc(TimeZoneInfo.ConvertTimeToUtc(dateTime, jst), cst).ToString("MM/dd HH:mm")
                                                     + " China Standard Time"
                                ;
                            }
                                );
                            form1.label14.Invoke(d111);
                            return;
                        }
                    }
                    myMatch = myMatch.NextMatch();
                }
                delegate2 d222 = new delegate2(
                    delegate() {
                    if (Regex.Match(html, @"条件に一致する予約販売が存在しません").Success)
                    {
                        form1.label14.Text = "There is no type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county;
                    }
                    else
                    {
                        form1.label14.Text = "No available booking these days on type " + (sizeType == "6" ? "M" : "L") + " in " + form1.selecteCounty.Name + " " + county;
                    }
                }
                    );
                form1.label14.Invoke(d222);
            }//end of if the search option not changed
        }
Esempio n. 5
0
 /// <summary>Converts given local time to Central time.</summary>
 /// <param name="timestamp">Timestamp in local time to be converted to Central time.</param>
 /// <returns>
 /// <para>Timestamp in Central time.</para>
 /// </returns>
 public static DateTime LocalTimeToCentralTime(this DateTime timestamp) => TimeZoneInfo.ConvertTime(timestamp, TimeZoneInfo.Local, USTimeZones.Central);
Esempio n. 6
0
 /**
  * @return a calendar for the user locale and time zone
  */
 public static DateTime GetLocaleCalendar(TimeZoneInfo timeZone)
 {
     return(TimeZoneInfo.ConvertTime(DateTime.Now, timeZone));
     //return Calendar.GetInstance(timeZone, GetUserLocale());
 }
Esempio n. 7
0
 public static DateTime ConvertTimeStampToTime(this double timeStamp)
 {
     return(TimeZoneInfo.ConvertTime(new DateTime(0x7b2, 1, 1), TimeZoneInfo.Local));
 }
Esempio n. 8
0
        /// <summary>
        ///     Converts a DateTimeOffset into a DateTime using the specified time zone.
        /// </summary>
        /// <param name = "dateTimeUtc">The base DateTimeOffset.</param>
        /// <param name = "localTimeZone">The time zone to be used for conversion.</param>
        /// <returns>The converted DateTime</returns>
        public static DateTime ToLocalDateTime(this DateTimeOffset dateTimeUtc, TimeZoneInfo localTimeZone)
        {
            localTimeZone = (localTimeZone ?? TimeZoneInfo.Local);

            return(TimeZoneInfo.ConvertTime(dateTimeUtc, localTimeZone).DateTime);
        }
Esempio n. 9
0
        public static string DateTimeNow()
        {
            DateTime now = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ConstansValuesClass.StandardTimeZone));

            return(now.ToString(ConstansValuesClass.formatDateTime));
        }
Esempio n. 10
0
        public async Task <bool> PostActivatePromoCode(dynamic data)
        {
            if (data == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            using (userappsEntities ctx = new userappsEntities())
            {
                ctx.ChangeTracker.DetectChanges();
                ctx.Configuration.AutoDetectChangesEnabled = true;
                ctx.Configuration.LazyLoadingEnabled       = false;

                try
                {
                    var userId    = (string)data.userId;
                    var promoCode = (string)data.promoCode;

                    var code = ctx.promotioncodes.Where(x => x.promocode.Equals(promoCode) && x.userid == userId).FirstOrDefault();

                    if (code == null)
                    {
                        return(false);
                    }

                    var customerTimeZone = DateHelpers.GetTimeZoneInfoForTzdbId(code.timezone);

                    var validFrom = TimeZoneInfo.ConvertTime(new DateTime(code.validfrom.Value.Year, code.validfrom.Value.Month, code.validfrom.Value.Day,
                                                                          code.validfrom.Value.Hour, code.validfrom.Value.Minute, code.validfrom.Value.Second),
                                                             customerTimeZone,
                                                             customerTimeZone);

                    var validTo = TimeZoneInfo.ConvertTime(new DateTime(code.validuntil.Value.Year, code.validuntil.Value.Month, code.validuntil.Value.Day, code.validuntil.Value.Hour,
                                                                        code.validuntil.Value.Minute, code.validuntil.Value.Second),
                                                           customerTimeZone,
                                                           customerTimeZone);

                    if ((validFrom <= validTo) && (validTo > (DateTime.UtcNow + customerTimeZone.GetUtcOffset(validTo))))
                    {
                        if (code.redeemed.HasValue)
                        {
                            if (code.redeemed.Value)
                            {
                                code.IsActive = false;
                                await ctx.SaveChangesAsync();

                                return(true);
                            }
                        }
                        code.IsActive = true;
                        await ctx.SaveChangesAsync();
                    }
                    else
                    {
                        return(false);
                    }


                    return(true);
                }
                catch (Exception ex)
                {
                    return(false);
                }
            }
        }
Esempio n. 11
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            // TODO verify this code is necessary for TZ data or if builtin exist
            var startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(
                new DateTime(1, 1, 1, 3, 0, 0), 3, 5, DayOfWeek.Sunday);
            var endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(
                new DateTime(1, 1, 1, 4, 0, 0), 10, 5, DayOfWeek.Sunday);
            var delta      = new TimeSpan(1, 0, 0);
            var adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
                new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition,
                endTransition);

            TimeZoneInfo.AdjustmentRule[] adjustments =
            {
                adjustment
            };
            var germanyTz = TimeZoneInfo.CreateCustomTimeZone(
                "W. Europe Standard Time", new TimeSpan(1, 0, 0), "(GMT+01:00) W. Europe Standard Time",
                "W. Europe Standard Time", "W. Europe DST Time", adjustments);
            var releases        = new List <ReleaseInfo>();
            var searchString    = query.GetQueryString();
            var searchUrl       = IndexUrl;
            var queryCollection = new NameValueCollection
            {
                { "strWebValue", "torrent" },
                { "strWebAction", "search" },
                { "sort", "torrent_added" },
                { "by", "d" },
                { "type", "2" }, // 0 active, 1 inactive, 2 all
                { "do_search", "suchen" },
                { "time", "0" }, // 0 any, 1 1day, 2 1week, 3 30days, 4 90days
                { "details", "title" } // title, info, descr, all
            };

            if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("searchstring", searchString);
            }
            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                queryCollection.Add("dirs" + cat, "1");
            }
            searchUrl += "?" + queryCollection.GetQueryString();
            var response = await RequestWithCookiesAsync(searchUrl);

            var titleRegexp = new Regex(@"^return buildTable\('(.*?)',\s+");

            try
            {
                var parser = new HtmlParser();
                var dom    = parser.ParseDocument(response.ContentString);
                var rows   = dom.QuerySelectorAll("table.torrenttable > tbody > tr");
                foreach (var row in rows.Skip(1))
                {
                    var qColumn1     = row.QuerySelectorAll("td.column1");
                    var qColumn2     = row.QuerySelectorAll("td.column2");
                    var qDetailsLink = row.QuerySelector("a[href^=\"index.php?strWebValue=torrent&strWebAction=details\"]");
                    var qCatLink     = row.QuerySelector("a[href^=\"index.php?strWebValue=torrent&strWebAction=search&dir=\"]");
                    var qDlLink      = row.QuerySelector("a[href^=\"index.php?strWebValue=torrent&strWebAction=download&id=\"]");
                    var qDateStr     = row.QuerySelector("font:has(a)");
                    var catStr       = qCatLink.GetAttribute("href").Split('=')[3].Split('#')[0];
                    var link         = new Uri(SiteLink + qDlLink.GetAttribute("href"));
                    var dateStr      = qDateStr.TextContent;
                    var split        = dateStr.IndexOf("Uploader", StringComparison.OrdinalIgnoreCase);
                    dateStr = dateStr.Substring(0, split > 0 ? split : dateStr.Length).Trim().Replace("Heute", "Today")
                              .Replace("Gestern", "Yesterday");
                    var    dateGerman = DateTimeUtil.FromUnknown(dateStr);
                    double downloadFactor;
                    if (row.QuerySelector("img[src=\"themes/images/freeleech.png\"]") != null ||
                        row.QuerySelector("img[src=\"themes/images/onlyup.png\"]") != null)
                    {
                        downloadFactor = 0;
                    }
                    else if (row.QuerySelector("img[src=\"themes/images/DL50.png\"]") != null)
                    {
                        downloadFactor = 0.5;
                    }
                    else
                    {
                        downloadFactor = 1;
                    }
                    var title       = titleRegexp.Match(qDetailsLink.GetAttribute("onmouseover")).Groups[1].Value;
                    var details     = new Uri(SiteLink + qDetailsLink.GetAttribute("href"));
                    var size        = ReleaseInfo.GetBytes(qColumn2[1].TextContent);
                    var seeders     = ParseUtil.CoerceInt(qColumn1[3].TextContent);
                    var leechers    = ParseUtil.CoerceInt(qColumn2[3].TextContent);
                    var publishDate = TimeZoneInfo.ConvertTime(dateGerman, germanyTz, TimeZoneInfo.Local);

                    var release = new ReleaseInfo
                    {
                        MinimumRatio         = 0.8,
                        MinimumSeedTime      = 0,
                        Title                = title,
                        Category             = MapTrackerCatToNewznab(catStr),
                        Details              = details,
                        Link                 = link,
                        Guid                 = link,
                        Size                 = size,
                        Seeders              = seeders,
                        Peers                = leechers + seeders,
                        PublishDate          = publishDate,
                        DownloadVolumeFactor = downloadFactor,
                        UploadVolumeFactor   = 1
                    };
                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(response.ContentString, ex);
            }

            return(releases);
        }
Esempio n. 12
0
        public async Task <bool> PostCreateNewMultiUserCode(dynamic data)
        {
            const string APP_KEY    = "X-AppKey";
            const string APP_SECRET = "X-Token";

            systemappuser user    = null;
            UserProfile   profile = null;

            if (Request.Headers.Contains(APP_KEY) && Request.Headers.Contains(APP_SECRET))
            {
                string appKey    = Request.Headers.GetValues(APP_KEY).First();
                string appSecret = Request.Headers.GetValues(APP_SECRET).First();

                using (var sysapps = new userappsEntities())
                {
                    user = sysapps.systemappusers.Where(usr => usr.appSecret.Equals(appSecret) && usr.apptoken.Equals(appKey)).FirstOrDefault();


                    if (user == null)
                    {
                        return(false);
                    }
                    else
                    {
                        using (var exgrip = new exgripEntities())
                        {
                            profile = exgrip.UserProfiles.Where(up => up.UserId == user.systemuserid).FirstOrDefault();

                            if (profile == null)
                            {
                                return(false);
                            }
                        }
                    }
                }
            }
            else
            {
                return(false);
            }

            WordGenerator gen = new WordGenerator();

            var userId         = profile.AlternateUserId;
            var timeZone       = (string)data.timeZone;
            var amountOfUsers  = (int)data.count;
            var dateString     = (string)data.dateString;
            var dateStringFrom = (string)data.dateStringFrom;
            var codeLink       = (string)data.codeLink;
            var count          = (int)data.count;

            int betacount = 200;

            if (string.IsNullOrEmpty(userId) || string.IsNullOrWhiteSpace(userId))
            {
                return(false);
            }

            if (string.IsNullOrEmpty(timeZone) || string.IsNullOrWhiteSpace(timeZone))
            {
                return(false);
            }

            if (amountOfUsers <= 0)
            {
                return(false);
            }

            DateTime outDate;

            var parseResult = DateTime.TryParse(dateString, out outDate);

            if (!parseResult)
            {
                return(false);
            }


            DateTime outDate2;

            var parseResult2 = DateTime.TryParse(dateStringFrom, out outDate2);

            if (!parseResult2)
            {
                return(false);
            }

            if (DateHelpers.GetTimeZoneInfoForTzdbId(timeZone) == null)
            {
                return(false);
            }

            if (!string.IsNullOrWhiteSpace(codeLink))
            {
                Uri  uriResult;
                bool result = Uri.TryCreate(codeLink, UriKind.Absolute, out uriResult);

                if (!result)
                {
                    return(false);
                }
            }

            if (amountOfUsers == 0 || amountOfUsers <= 0 || amountOfUsers > int.MaxValue)
            {
                return(false);
            }

            using (userappsEntities ctx = new userappsEntities())
            {
                try
                {
                    var customerTime = TimeZoneInfo.ConvertTime(new DateTime(outDate.Year, outDate.Month, outDate.Day, outDate.Hour, outDate.Minute, outDate.Second),
                                                                DateHelpers.GetTimeZoneInfoForTzdbId(timeZone),
                                                                DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));

                    var customerTime2 = TimeZoneInfo.ConvertTime(new DateTime(outDate2.Year, outDate2.Month, outDate2.Day, outDate2.Hour, outDate2.Minute, outDate2.Second),
                                                                 DateHelpers.GetTimeZoneInfoForTzdbId(timeZone),
                                                                 DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));

                    var allMultiCodes = ctx.promotioncodes.Where(x => x.userid == userId && x.ismulticode == true).ToList();


                    if ((allMultiCodes.Count()) > betacount)
                    {
                        throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);
                    }

                    if (count > 2000000)
                    {
                        throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);
                    }

                    if ((customerTime2.Ticks > customerTime.Ticks))
                    {
                        return(false);
                    }

                    var word = gen.RandomString(7);

                    promotioncode code = new promotioncode();
                    code.created = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));

                    code.redeemed          = false;
                    code.promocode         = word;
                    code.userid            = userId;
                    code.timezone          = timeZone;
                    code.multicodequantity = amountOfUsers;
                    code.validfrom         = customerTime2;
                    code.validuntil        = customerTime;
                    code.GetCodeLink       = codeLink;
                    code.IsActive          = true;
                    code.ismulticode       = true;

                    ctx.promotioncodes.Add(code);

                    await ctx.SaveChangesAsync();

                    return(true);
                }
                catch (Exception ex)
                {
                    return(false);
                }
            }
        }
Esempio n. 13
0
        public async Task <bool> PostCreateNewStack(dynamic data)
        {
            const string APP_KEY    = "X-AppKey";
            const string APP_SECRET = "X-Token";

            systemappuser user    = null;
            UserProfile   profile = null;

            if (Request.Headers.Contains(APP_KEY) && Request.Headers.Contains(APP_SECRET))
            {
                string appKey    = Request.Headers.GetValues(APP_KEY).First();
                string appSecret = Request.Headers.GetValues(APP_SECRET).First();

                using (var sysapps = new userappsEntities())
                {
                    user = sysapps.systemappusers.Where(usr => usr.appSecret.Equals(appSecret) && usr.apptoken.Equals(appKey)).FirstOrDefault();


                    if (user == null)
                    {
                        return(false);
                    }
                    else
                    {
                        using (var exgrip = new exgripEntities())
                        {
                            profile = exgrip.UserProfiles.Where(up => up.UserId == user.systemuserid).FirstOrDefault();

                            if (profile == null)
                            {
                                return(false);
                            }
                        }
                    }
                }
            }
            else
            {
                return(false);
            }


            int betaCount = 500;

            WordGenerator gen = new WordGenerator();



            var timeZone       = (string)data.timeZone;
            var dateString     = (string)data.dateString;
            var dateStringFrom = (string)data.dateStringFrom;
            var codeLink       = (string)data.codeLink;
            var userId         = profile.AlternateUserId;
            var count          = (int)data.count;



            DateTime outDate;

            var parseResult = DateTime.TryParse(dateString, out outDate);

            if (!parseResult)
            {
                return(false);
            }

            DateTime outDate2;

            var parseResult2 = DateTime.TryParse(dateStringFrom, out outDate2);

            if (!parseResult2)
            {
                return(false);
            }

            if (count > betaCount)
            {
                return(false);
            }

            using (userappsEntities ctx = new userappsEntities())
            {
                try
                {
                    var customerTime = TimeZoneInfo.ConvertTime(new DateTime(outDate.Year, outDate.Month, outDate.Day, outDate.Hour, outDate.Minute, outDate.Second),
                                                                DateHelpers.GetTimeZoneInfoForTzdbId(timeZone),
                                                                DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));

                    var customerTime2 = TimeZoneInfo.ConvertTime(new DateTime(outDate2.Year, outDate2.Month, outDate2.Day, outDate2.Hour, outDate2.Minute, outDate2.Second),
                                                                 DateHelpers.GetTimeZoneInfoForTzdbId(timeZone),
                                                                 DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));

                    if ((customerTime2.Ticks > customerTime.Ticks))
                    {
                        return(false);
                    }

                    var reedemedVouchers = ctx.promotioncodes.Where(x => x.userid == userId && x.redeemed == true && x.ismulticode == false).ToList();

                    var allOnetimes = ctx.promotioncodes.Where(x => x.userid == userId && x.ismulticode == false).ToList();

                    if ((count + allOnetimes.Count()) > betaCount)
                    {
                        throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);
                    }

                    if ((allOnetimes.Count() == betaCount) && (reedemedVouchers.Count < betaCount) && (reedemedVouchers.Count != 0))
                    {
                        return(false);
                    }
                    else
                    {
                        ctx.Configuration.AutoDetectChangesEnabled = false;
                        ctx.Configuration.ValidateOnSaveEnabled    = false;

                        for (int i = 1; i <= count; i++)
                        {
                            var word = gen.RandomString(7);

                            promotioncode code = new promotioncode();

                            code.created     = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, DateHelpers.GetTimeZoneInfoForTzdbId(timeZone));
                            code.validfrom   = customerTime2;
                            code.validuntil  = customerTime;
                            code.redeemed    = false;
                            code.promocode   = word;
                            code.userid      = userId;
                            code.ismulticode = false;
                            code.timezone    = timeZone;
                            code.GetCodeLink = codeLink;
                            code.IsActive    = true;
                            ctx.promotioncodes.Add(code);
                        }

                        await ctx.SaveChangesAsync();

                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    return(false);
                }
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Converte uma data para o horário oficil do Brasil (Brasília)
 /// </summary>
 /// <param name="input">Data que deverá ser convertida</param>
 public static DateTime ConverterHorarioOficialBrasil(this DateTime input)
 {
     return(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
         ? TimeZoneInfo.ConvertTime(input, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"))
         : TimeZoneInfo.ConvertTime(input, TimeZoneInfo.FindSystemTimeZoneById("America/Sao_Paulo")));
 }
Esempio n. 15
0
        public async Task <DialogTurnResult> AfterUpdateStartTime(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var events = new List <EventModel>();

                var calendarService  = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);
                var searchByEntities = state.OriginalStartDate.Any() || state.OriginalStartTime.Any() || state.Title != null;

                if (state.Events.Count < 1)
                {
                    if (state.OriginalStartDate.Any() || state.OriginalStartTime.Any())
                    {
                        events = await GetEventsByTime(state.OriginalStartDate, state.OriginalStartTime, state.OriginalEndDate, state.OriginalEndTime, state.GetUserTimeZone(), calendarService);

                        state.OriginalStartDate = new List <DateTime>();
                        state.OriginalStartTime = new List <DateTime>();
                        state.OriginalEndDate   = new List <DateTime>();
                        state.OriginalStartTime = new List <DateTime>();
                    }
                    else if (state.Title != null)
                    {
                        events = await calendarService.GetEventsByTitle(state.Title);

                        state.Title = null;
                    }
                    else
                    {
                        sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                        var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                        try
                        {
                            IList <DateTimeResolution> dateTimeResolutions = sc.Result as List <DateTimeResolution>;
                            if (dateTimeResolutions.Count > 0)
                            {
                                foreach (var resolution in dateTimeResolutions)
                                {
                                    if (resolution.Value == null)
                                    {
                                        continue;
                                    }

                                    var startTimeValue = DateTime.Parse(resolution.Value);
                                    if (startTimeValue == null)
                                    {
                                        continue;
                                    }

                                    var  dateTimeConvertType = resolution.Timex;
                                    bool isRelativeTime      = IsRelativeTime(sc.Context.Activity.Text, dateTimeResolutions.First().Value, dateTimeResolutions.First().Timex);
                                    startTimeValue = isRelativeTime ? TimeZoneInfo.ConvertTime(startTimeValue, TimeZoneInfo.Local, state.GetUserTimeZone()) : startTimeValue;

                                    startTimeValue = TimeConverter.ConvertLuisLocalToUtc(startTimeValue, state.GetUserTimeZone());
                                    events         = await calendarService.GetEventsByStartTime(startTimeValue);

                                    if (events != null && events.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }

                        if (events == null || events.Count <= 0)
                        {
                            state.Title = userInput;
                            events      = await calendarService.GetEventsByTitle(userInput);
                        }
                    }

                    state.Events = events;
                }

                if (state.Events.Count <= 0)
                {
                    if (searchByEntities)
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(UpdateEventResponses.EventWithStartTimeNotFound));

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NoEvent)));
                    }
                }
                else if (state.Events.Count > 1)
                {
                    var options = new PromptOptions()
                    {
                        Choices = new List <Choice>(),
                    };

                    for (var i = 0; i < state.Events.Count; i++)
                    {
                        var item   = state.Events[i];
                        var choice = new Choice()
                        {
                            Value    = string.Empty,
                            Synonyms = new List <string> {
                                (i + 1).ToString(), item.Title
                            },
                        };
                        options.Choices.Add(choice);
                    }

                    var replyToConversation = sc.Context.Activity.CreateReply(UpdateEventResponses.MultipleEventsStartAtSameTime);
                    replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    replyToConversation.Attachments      = new List <Microsoft.Bot.Schema.Attachment>();

                    var cardsData = new List <CalendarCardData>();
                    foreach (var item in state.Events)
                    {
                        var meetingCard = item.ToAdaptiveCardData(state.GetUserTimeZone());
                        var replyTemp   = sc.Context.Activity.CreateAdaptiveCardReply(CalendarMainResponses.GreetingMessage, item.OnlineMeetingUrl == null ? "Dialogs/Shared/Resources/Cards/CalendarCardNoJoinButton.json" : "Dialogs/Shared/Resources/Cards/CalendarCard.json", meetingCard);
                        replyToConversation.Attachments.Add(replyTemp.Attachments[0]);
                    }

                    options.Prompt = replyToConversation;

                    return(await sc.PromptAsync(Actions.EventChoice, options));
                }
                else
                {
                    return(await sc.EndDialogAsync(true));
                }
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Esempio n. 16
0
 public DateTime GetCurrentTime()
 {
     return(TimeZoneInfo.ConvertTime(DateTime.UtcNow, _timeZone));
 }
Esempio n. 17
0
 public static DateTime Brasil(DateTime dateTime)
 {
     //TimeZoneInfo hrBrasilia = TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time");
     return(TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time")));
 }
Esempio n. 18
0
        private async Task <ActionResult <DialogFlowResponseDTO> > HandleConsumeElectricityIntent(DialogFlowRequestDTO request)
        {
            try
            {
                Parameters parameters = request.queryResult.outputContexts
                                        .FirstOrDefault(oc => oc.name.EndsWith("consume-electricity-output-context"))
                                        .parameters;

                var nowUTC = DateTime.Now.ToUniversalTime();
                var now    = TimeZoneInfo.ConvertTime(nowUTC, _copenhagenTimeZoneInfo);

                DateTime finishNoLaterThanUTC;

                if (parameters.time != DateTime.MinValue && parameters.date != DateTime.MinValue)
                {
                    DateTime byTime = parameters.time.ToUniversalTime();
                    DateTime byDate = parameters.time.Date;
                    finishNoLaterThanUTC = new DateTime(byDate.Year, byDate.Month, byDate.Day, byTime.Hour, byTime.Minute, byTime.Second, DateTimeKind.Utc);
                }
                else
                {
                    finishNoLaterThanUTC = now.AddDays(1).Date.AddHours(6).ToUniversalTime();
                    if ((finishNoLaterThanUTC - nowUTC).TotalHours < 6)
                    {
                        finishNoLaterThanUTC = finishNoLaterThanUTC.AddDays(1);
                    }
                }

                if (parameters.duration == null)
                {
                    if (parameters.devicetype != null)
                    {
                        parameters.duration = LookupDefaultDeviceDuration(parameters.devicetype);
                    }
                    else
                    {
                        parameters.duration = new Duration {
                            amount = 1, unit = "h"
                        };
                    }
                }

                var prognosis = await PrognosisClient.OptimalConsumptionTimeAsync("DK1", parameters.duration.toHours(), DateTimeOffset.UtcNow.ToString("o"), finishNoLaterThanUTC.ToString("o"));

                // var best = await PrognosisClient.OptimalConsumptionTimeAsync(

                //     consumptionMinutes: parameters.duration.toMinutes(),
                //     consumptionRegion: "DK1",
                //     startNoEarlierThan: nowUTC,
                //     finishNoLaterThan: finishNoLaterThanUTC
                // );

                if (prognosis != null)
                {
                    DialogFlowResponseDTO response = new DialogFlowResponseDTO();
                    response.outputContexts = request.queryResult.outputContexts;

                    var optimalConsumptionStart = TimeZoneInfo.ConvertTime(prognosis.Best.StartUTC, _copenhagenTimeZoneInfo);
                    var prognosisEnd            = TimeZoneInfo.ConvertTime(prognosis.PrognosisEndUTC, _copenhagenTimeZoneInfo).AddMinutes(5);
                    var prognosisLookaheadHours = Math.Round((prognosis.PrognosisEndUTC - nowUTC).TotalHours, 0);
                    var finishNoLaterThan       = TimeZoneInfo.ConvertTime(finishNoLaterThanUTC, _copenhagenTimeZoneInfo);

                    var lang    = request.queryResult.languageCode;
                    var culture = CultureInfo.CreateSpecificCulture(lang);

                    double savingsPercentage = (prognosis.Earliest.Emissions - prognosis.Best.Emissions) / prognosis.Earliest.Emissions;

                    OutputContext ctx = response.outputContexts
                                        .Find(oc => oc.name.EndsWith("consumeelectricity-followup"));
                    ctx.parameters.prognosisend            = prognosis.PrognosisEndUTC;
                    ctx.parameters.savingspercentage       = (float)Math.Round(savingsPercentage * 100, 0);
                    ctx.parameters.optimalemissions        = Math.Round(prognosis.Best.Emissions, 0);
                    ctx.parameters.initialemissions        = Math.Round(prognosis.Earliest.Emissions, 0);
                    ctx.parameters.lastEmissions           = Math.Round(prognosis.Latest.Emissions, 0);
                    ctx.parameters.optimalconsumptionstart = optimalConsumptionStart.ToString("dddd HH:mm", culture);
                    ctx.parameters.finishnolaterthan       = finishNoLaterThan.ToString("dddd HH:mm", culture);
                    ctx.parameters.readableduration        = parameters.duration.toReadableString();
                    ctx.parameters.waitinghours            = Math.Round((prognosis.Best.StartUTC - nowUTC).TotalHours, 0);

                    // ctx.parameters.test1 = optimalConsumptionStart.ToUniversalTime().ToString("o");
                    // ctx.parameters.test2 = best.optimalConsumptionStart.ToUniversalTime().ToString("o");

                    if (ctx.parameters.savingspercentage < 2)
                    {
                        response.fulfillmentText = "Now is a good time! Do you want to know why?"
                                                   .Replace("$device", ctx.parameters.devicetype)
                                                   .Replace("$duration", parameters.duration.toReadableString());
                    }
                    else
                    {
                        response.fulfillmentText = request.queryResult.fulfillmentText
                                                   .Replace("$optimalEmissions", ctx.parameters.optimalemissions.ToString())
                                                   .Replace("$consumption-start", ctx.parameters.optimalconsumptionstart)
                                                   .Replace("$prognosis-end", prognosisEnd.ToString("dddd HH:mm", culture))
                                                   .Replace("$savingspercentage", ctx.parameters.savingspercentage.ToString())
                                                   .Replace("$prognosislookaheadhours", prognosisLookaheadHours.ToString() + " hours")
                                                   .Replace("$finishnolaterthan", ctx.parameters.finishnolaterthan)
                                                   .Replace("$readableduration", ctx.parameters.readableduration)
                                                   .Replace("$waitinghours", ctx.parameters.waitinghours.ToString());
                    }

                    return(response);
                }
                else
                {
                    _logger.LogError("Received null return value from OptimalFutureConsumptionTime");
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Esempio n. 19
0
        //Copied from https://en.bitcoin.it/wiki/Protocol_specification (19/04/2014)
        public void CanParseMessages()
        {
            var EST   = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            var tests = new[]
            {
                new
                {
                    Version = ProtocolVersion.INIT_PROTO_VERSION,
                    Message = "f9beb4d976657273696f6e0000000000550000009c7c00000100000000000000e615104d00000000010000000000000000000000000000000000ffff0a000001208d010000000000000000000000000000000000ffff0a000002208ddd9d202c3ab457130055810100",
                    Test    = new Action <object>(o =>
                    {
                        var version = (VersionPayload)o;
                        Assert.Equal((ulong)0x1357B43A2C209DDD, version.Nonce);
                        Assert.Equal("", version.UserAgent);
                        Assert.Equal("::ffff:10.0.0.2", version.AddressFrom.Address.ToString());
                        Assert.Equal(8333, version.AddressFrom.Port);
                        Assert.Equal(0x00018155, version.StartHeight);
                        Assert.Equal((ProtocolVersion)31900, version.Version);
                    })
                },
                new
                {
                    Version = ProtocolVersion.MEMPOOL_GD_VERSION,
                    Message = "f9beb4d976657273696f6e000000000064000000358d493262ea0000010000000000000011b2d05000000000010000000000000000000000000000000000ffff000000000000000000000000000000000000000000000000ffff0000000000003b2eb35d8ce617650f2f5361746f7368693a302e372e322fc03e0300",
                    Test    = new Action <object>(o =>
                    {
                        var version = (VersionPayload)o;
                        Assert.Equal("/Satoshi:0.7.2/", version.UserAgent);
                        Assert.Equal(0x00033EC0, version.StartHeight);
                    })
                },
                new
                {
                    Version = ProtocolVersion.PROTOCOL_VERSION,
                    Message = "f9beb4d976657261636b000000000000000000005df6e0e2",
                    Test    = new Action <object>(o =>
                    {
                        var verack = (VerAckPayload)o;
                    })
                },
                new
                {
                    Version = ProtocolVersion.MEMPOOL_GD_VERSION,
                    Message = "f9beb4d96164647200000000000000001f000000ed52399b01e215104d010000000000000000000000000000000000ffff0a000001208d",
                    Test    = new Action <object>(o =>
                    {
                        var addr = (AddrPayload)o;
                        Assert.Equal(1, addr.Addresses.Length);
                        //"Mon Dec 20 21:50:10 EST 2010"
                        var date = TimeZoneInfo.ConvertTime(addr.Addresses[0].Time, EST);
                        Assert.Equal(20, date.Day);
                        Assert.Equal(12, date.Month);
                        Assert.Equal(2010, date.Year);
                        Assert.Equal(21, date.Hour);
                    })
                },
            };

            foreach (var test in tests)
            {
                var message = Network.Main.ParseMessage(TestUtils.ParseHex(test.Message), test.Version);
                test.Test(message.Payload);
                var bytes = message.ToBytes(test.Version);
                var old   = message;
                message = new Message();
                message.FromBytes(bytes, test.Version);
                test.Test(message.Payload);
                Assert.Equal(test.Message, Encoders.Hex.EncodeData(message.ToBytes(test.Version)));
            }
        }
Esempio n. 20
0
 /// <summary>
 /// 转为本地时间
 /// </summary>
 /// <param name="time">时间</param>
 /// <returns></returns>
 public static DateTime ToLocalTime(this DateTime time)
 {
     return(TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Local));
 }
Esempio n. 21
0
        public static double ConvertTimeToTimestamp(this DateTime time)
        {
            TimeSpan span = (TimeSpan)(time - TimeZoneInfo.ConvertTime(new DateTime(0x7b2, 1, 1), TimeZoneInfo.Local));

            return(span.TotalSeconds);
        }
Esempio n. 22
0
        /// <summary>
        /// osu! API를 통해 기본 정보(랭크 상태, 비트맵의 ID와 이름, 갱신 날짜)를 가져옴.
        /// 여기서 기본 정보는 <code>LastUpdate, Status, Creator, CreatorId, Beatmaps[i].BeatmapID, Beatmaps[i].Version</code>입니다.
        /// </summary>
        /// <param name="id">맵셋 ID</param>
        /// <returns></returns>
        public static async Task <Set> GetSetFromAPIAsync(int id)
        {
            DateTime ConvertAPIDateTimeToLocal(DateTime dateTime)
            {
                // 호주 기준 UTC+8을 현지 시각으로 변환
                if (dateTime.Kind == DateTimeKind.Unspecified)
                {
                    return(TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.FindSystemTimeZoneById("W. Australia Standard Time"), TimeZoneInfo.Local));
                }
                // TimeZone을 삽입한 DateTime은 자동으로 Local로 바뀌어서 작업할 필요가 없다.
                return(dateTime);
            }

            Set set = null;
            //TODO last_update가 approved_date보다 최신이면 keep_synced로 업데이트 하기
            var inited = false;

            foreach (JObject i in await Request.Context.GetBeatmapsAPIAsync("s=" + id))
            {
                var rankedAt = i.Value <DateTime?>("approved_date");
                if (rankedAt != null)
                {
                    rankedAt = ConvertAPIDateTimeToLocal(rankedAt.Value);
                }
                var updatedAt = ConvertAPIDateTimeToLocal(i.Value <DateTime>("last_update"));

                if (!inited)
                {
                    inited = true;
                    set    = new Set
                    {
                        SetId     = id,
                        Title     = i.Value <string>("title"),
                        Artist    = i.Value <string>("artist"),
                        Creator   = i.Value <string>("creator"),
                        CreatorId = i.Value <int>("creator_id"),
                        //StatusId = i.Value<int>("approved"),
                        RankedAt   = rankedAt,
                        UpdatedAt  = updatedAt,
                        Favorites  = i.Value <int>("favourite_count"),
                        GenreId    = i.Value <int>("genre_id"),
                        LanguageId = i.Value <int>("language_id")
                    };
                }

                // 정보가 캐시된 비트맵들 때문에 더 최신 정보를 확인해줘야 한다.
                var isLatest = set.UpdatedAt < updatedAt ||
                               (set.RankedAt == null && rankedAt != null) ||
                               (set.RankedAt != null && rankedAt == null) ||
                               (set.RankedAt < rankedAt) ||
                               (set.RankedAt != null && set.StatusId < i.Value <int>("approved"));
                if (isLatest)
                {
                    set.Title     = i.Value <string>("title");
                    set.Artist    = i.Value <string>("artist");
                    set.Creator   = i.Value <string>("creator");
                    set.CreatorId = i.Value <int>("creator_id");
                    //set.StatusId = i.Value<int>("approved");
                    set.RankedAt   = rankedAt;
                    set.UpdatedAt  = updatedAt;
                    set.Favorites  = i.Value <int>("favourite_count");
                    set.GenreId    = i.Value <int>("genre_id");
                    set.LanguageId = i.Value <int>("language_id");
                }

                set.Beatmaps.Add(new Beatmap
                {
                    StatusId    = i.Value <int>("approved"),
                    BeatmapInfo = new BeatmapInfo
                    {
                        OnlineBeatmapID = i.Value <int>("beatmap_id"),
                        Version         = i.Value <string>("version"),
                        RulesetID       = i.Value <int>("mode"),
                        MD5Hash         = i.Value <string>("file_md5"),
                        StarDifficulty  = i.Value <double>("difficultyrating"),
                        Metadata        = new BeatmapMetadata
                        {
                            AuthorString = i.Value <string>("creator"),
                            Artist       = i.Value <string>("artist"),
                            Title        = i.Value <string>("title"),
                        },
                        //OnlineInfo = new BeatmapOnlineInfo
                        //{
                        //    Length = i.Value<double>("total_length")
                        //}
                    }
                });
            }
            return(set);
        }
Esempio n. 23
0
 /// <summary>Converts given local time to Eastern time.</summary>
 /// <param name="timestamp">Timestamp in local time to be converted to Eastern time.</param>
 /// <returns>
 /// <para>Timestamp in Eastern time.</para>
 /// </returns>
 public static DateTime LocalTimeToEasternTime(this DateTime timestamp) => TimeZoneInfo.ConvertTime(timestamp, TimeZoneInfo.Local, USTimeZones.Eastern);
    protected void WithdrawButton_Click(object sender, EventArgs e)
    {
        int balancedt = 0;
        int minbal    = 1500;

        cnn.Open();
        MySqlCommand cmd3 = cnn.CreateCommand();


        cmd3.CommandType = CommandType.Text;

        cmd3.CommandText = "select * from account where  username='******'";
        MySqlDataReader r2;

        r2 = cmd3.ExecuteReader();

        while (r2.Read())
        {
            // Username_label.Text = r2.GetString("username").ToString();
            balancedt = int.Parse(r2.GetString("balance"));
        }

        cnn.Close();


        cnn.Open();
        MySqlCommand cmd13 = cnn.CreateCommand();


        cmd13.CommandType = CommandType.Text;

        cmd13.CommandText = "select * from rule where  id=1 ";
        MySqlDataReader r12;

        r12 = cmd13.ExecuteReader();

        while (r12.Read())
        {
            // Username_label.Text = r2.GetString("username").ToString();
            minbal = int.Parse(r12.GetString("minb"));
        }

        cnn.Close();



        // string bal = minbal.ToString();
        int Baltext = int.Parse(Balance.Text);

        // Label1.Text = Baltext.ToString();
        if (minbal <= balancedt - Baltext)
        {
            cnn.Open();



            MySqlCommand cmd1 = cnn.CreateCommand();
            cmd1.CommandType = CommandType.Text;

            cmd1.CommandText = "update account set balance=balance-'" + Baltext + "' where username='******'";


            cmd1.ExecuteNonQuery();


            cnn.Close();

            cnn.Open();


            var      BnTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Bangladesh Standard Time");
            DateTime BaTime     = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, BnTimeZone);
            string   ss         = Convert.ToString(BaTime);



            MySqlCommand cmd2 = cnn.CreateCommand();
            cmd2.CommandType = CommandType.Text;
            // cmd.CommandText = "insert into user (name,email,password) values ('" + name.Text + "','" + email.Text + "',MD5 ('" + password.Text + "') )";
            cmd2.CommandText = "insert into balance_withdraw (username,balance,T_Date) values ('" + userName.Text + "','" + Balance.Text + "','" + ss + "')";
            // MySqlDataReader dr =  //data excute variable

            cmd2.ExecuteReader();

            Label1.Text = "Successfully Withdraw";


            cnn.Close();
        }
        else
        {
            Label1.Text = "Not Suficient Balance";
        }

        Balance.Text  = "";
        userName.Text = "";
    }
Esempio n. 25
0
 /// <summary>Converts given local time to Mountain time.</summary>
 /// <param name="timestamp">Timestamp in local time to be converted to Mountain time.</param>
 /// <returns>
 /// <para>Timestamp in Mountain time.</para>
 /// </returns>
 public static DateTime LocalTimeToMountainTime(this DateTime timestamp) => TimeZoneInfo.ConvertTime(timestamp, TimeZoneInfo.Local, USTimeZones.Mountain);
Esempio n. 26
0
        /// <summary>
        /// adds the header and footer details to the given pathTotempPdf, and creates the offical pdf location.
        /// </summary>
        public void AddHeaderAndFooter(string pathToTempPdfFile)
        {
            PdfFileStamp fileStamp = null;

            try
            {
                fileStamp = new PdfFileStamp();
                fileStamp.BindPdf(pathToTempPdfFile);
                FormattedText        ftSubjectID = null;
                FormattedText        ftMedrioID  = null;
                System.Drawing.Color fontColor   = System.Drawing.Color.Black;

                if (CustomSubjectID)
                {
                    ftSubjectID = new FormattedText(string.Format("Subject Identifier: {0}", SubjectIdentifier)
                                                    , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                }

                if (IsMedrioIDShown)
                {
                    ftMedrioID = new FormattedText(string.Format("Medrio ID: {0}", Subject.FormatMedrioSubjectID(MedrioSubjectID))
                                                   , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                }

                FormattedText ftSite = new FormattedText(HeaderItemText("Site: ", SiteName, HEADER_LABELWIDTH)
                                                         , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                FormattedText ftVisit = new FormattedText(HeaderItemText(Study.VisitLabelSingular + ": ", VisitName, HEADER_LABELWIDTH)
                                                          , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                FormattedText ftGroup = new FormattedText(HeaderItemText("Group: ", GroupName, HEADER_LABELWIDTH)
                                                          , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                FormattedText ftForm = new FormattedText(HeaderItemText("Form: ", FormName, HEADER_LABELWIDTH)
                                                         , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);
                FormattedText ftStudy = new FormattedText(string.Format("{0}", StudyTitle)
                                                          , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);

                //add header
                int medrioIdTopMargin = 20;
                if (null != ftSubjectID)
                {
                    fileStamp.AddHeader(ftSubjectID, 20, 25, 0);
                    medrioIdTopMargin = 30;
                }
                if (null != ftMedrioID)
                {
                    fileStamp.AddHeader(ftMedrioID, medrioIdTopMargin, 25, 0);
                }
                fileStamp.AddHeader(ftSite, 20, fileStamp.PageWidth / 2, fileStamp.PageWidth / 2);
                fileStamp.AddHeader(ftVisit, 30, fileStamp.PageWidth / 2, fileStamp.PageWidth / 2);
                fileStamp.AddHeader(ftGroup, 20, 0, 50);
                fileStamp.AddHeader(ftForm, 30, 0, 50);

                TimeZoneInfo tzi = null;
                try
                {
                    tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneFormatForCurrentUser);
                }
                catch
                {
                    tzi = TimeZoneInfo.Local;
                }

                DateTime dt = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tzi);

                FormattedText ftDatetime = new FormattedText(string.Format("{0} {1:HH:mm} ({2})", dt.ToString(ExportDateFormat), dt, TimeZoneFormatForCurrentUser)
                                                             , fontColor, FONT_STYLE, FONT_ENCODING, FONT_EMBEDED, FONT_SIZE);

                // add footer
                fileStamp.AddFooter(ftStudy, 20, fileStamp.PageWidth / 2, fileStamp.PageWidth / 2);
                fileStamp.AddFooter(ftDatetime, 20, 25, 0);
                fileStamp.Save(PathToPdf);
            }
            finally
            {
                if (fileStamp != null)
                {
                    //close
                    fileStamp.Dispose();
                }
            }
        }
Esempio n. 27
0
 /// <summary>
 /// 返回默认时间1970-01-01
 /// </summary>
 /// <param name="dt">时间日期</param>
 /// <returns></returns>
 public static DateTime LocalDefault(this DateTime dt)
 {
     return(TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0), TimeZoneInfo.Local));
 }
Esempio n. 28
0
        public async Task <DialogTurnResult> AfterGetNewEventTime(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                if (state.StartDate.Any() || state.StartTime.Any() || state.MoveTimeSpan != 0)
                {
                    var originalEvent         = state.Events[0];
                    var originalStartDateTime = TimeConverter.ConvertUtcToUserTime(originalEvent.StartTime, state.GetUserTimeZone());
                    var userNow = TimeConverter.ConvertUtcToUserTime(DateTime.UtcNow, state.GetUserTimeZone());

                    if (state.StartDate.Any() || state.StartTime.Any())
                    {
                        var newStartDate = state.StartDate.Any() ?
                                           state.StartDate.Last() :
                                           originalStartDateTime;

                        var newStartTime = new List <DateTime>();
                        if (state.StartTime.Any())
                        {
                            foreach (var time in state.StartTime)
                            {
                                var newStartDateTime = new DateTime(
                                    newStartDate.Year,
                                    newStartDate.Month,
                                    newStartDate.Day,
                                    time.Hour,
                                    time.Minute,
                                    time.Second);

                                if (state.NewStartDateTime == null)
                                {
                                    state.NewStartDateTime = newStartDateTime;
                                }

                                if (newStartDateTime >= userNow)
                                {
                                    state.NewStartDateTime = newStartDateTime;
                                    break;
                                }
                            }
                        }
                    }
                    else if (state.MoveTimeSpan != 0)
                    {
                        state.NewStartDateTime = originalStartDateTime.AddSeconds(state.MoveTimeSpan);
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotFound)));
                    }

                    state.NewStartDateTime = TimeZoneInfo.ConvertTimeToUtc(state.NewStartDateTime.Value, state.GetUserTimeZone());

                    return(await sc.ContinueDialogAsync());
                }
                else if (sc.Result != null)
                {
                    IList <DateTimeResolution> dateTimeResolutions = sc.Result as List <DateTimeResolution>;

                    DateTime?newStartTime = null;

                    foreach (var resolution in dateTimeResolutions)
                    {
                        var utcNow = DateTime.UtcNow;
                        var dateTimeConvertTypeString = resolution.Timex;
                        var dateTimeConvertType       = new TimexProperty(dateTimeConvertTypeString);
                        var dateTimeValue             = DateTime.Parse(resolution.Value);
                        if (dateTimeValue == null)
                        {
                            continue;
                        }

                        var isRelativeTime = IsRelativeTime(sc.Context.Activity.Text, resolution.Value, dateTimeConvertTypeString);
                        if (isRelativeTime)
                        {
                            dateTimeValue = DateTime.SpecifyKind(dateTimeValue, DateTimeKind.Local);
                        }

                        dateTimeValue = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTimeValue, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTimeValue;
                        var originalStartDateTime = TimeConverter.ConvertUtcToUserTime(state.Events[0].StartTime, state.GetUserTimeZone());
                        if (dateTimeConvertType.Types.Contains(Constants.TimexTypes.Date) && !dateTimeConvertType.Types.Contains(Constants.TimexTypes.DateTime))
                        {
                            dateTimeValue = new DateTime(
                                dateTimeValue.Year,
                                dateTimeValue.Month,
                                dateTimeValue.Day,
                                originalStartDateTime.Hour,
                                originalStartDateTime.Minute,
                                originalStartDateTime.Second);
                        }
                        else if (dateTimeConvertType.Types.Contains(Constants.TimexTypes.Time) && !dateTimeConvertType.Types.Contains(Constants.TimexTypes.DateTime))
                        {
                            dateTimeValue = new DateTime(
                                originalStartDateTime.Year,
                                originalStartDateTime.Month,
                                originalStartDateTime.Day,
                                dateTimeValue.Hour,
                                dateTimeValue.Minute,
                                dateTimeValue.Second);
                        }

                        dateTimeValue = TimeZoneInfo.ConvertTimeToUtc(dateTimeValue, state.GetUserTimeZone());

                        if (newStartTime == null)
                        {
                            newStartTime = dateTimeValue;
                        }

                        if (dateTimeValue >= utcNow)
                        {
                            newStartTime = dateTimeValue;
                            break;
                        }
                    }

                    if (newStartTime != null)
                    {
                        state.NewStartDateTime = newStartTime;

                        return(await sc.ContinueDialogAsync());
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotADateTime)));
                    }
                }
                else
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotADateTime)));
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Esempio n. 29
0
 public static string ToUTCDateStr(this DateTime date)
 {
     return(TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Utc).ToString("yyyy-MM-dd"));
 }
Esempio n. 30
0
 /// <summary>
 /// 时间戳转为C#格式时间
 /// </summary>
 /// <param name=”timeStamp”></param>
 /// <returns></returns>
 public static DateTime ToTime <T>(this int timeStamp)
 {
     var      dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
     long     lTime   = long.Parse(timeStamp + "0000000");
     TimeSpan toNow   = new TimeSpan(lTime); return(dtStart.Add(toNow));
 }