/// <summary> /// Sets the real start and end date of the match. /// Current data must be loaded from database before calling the method. /// </summary> /// <param name="newDate">New real date for the match.</param> /// <param name="duration">Duration of the match.</param> public void SetRealStart(DateTime?newDate, TimeSpan duration) { if (newDate == RealStart && newDate?.Add(duration) == RealEnd) { return; } RealStart = newDate; RealEnd = newDate?.Add(duration); }
public void FrequencyParameter_NoArgPassed_ThruDate() { FrequencyParameter testParameter = new FrequencyParameter(); DateTime expectedResult = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); expectedResult = expectedResult.Add(new TimeSpan(1, 0, 0, 0)); Assert.AreEqual(expectedResult, testParameter.ThruDate); }
public async Task <PaginacaoResultadoDto <AlunoEol> > ObterAlunosParaInclusaoAsync(Paginacao paginacao, int anoLetivo, DateTime?dataReferencia, long?codigoEol, ParametrosCargaInicialDto parametrosCargaInicialDto) { dataReferencia = dataReferencia?.Add(new TimeSpan(0, 0, 0)); var query = MontaQueryAlunosParaInclusao(paginacao, dataReferencia, codigoEol, parametrosCargaInicialDto); using var conn = ObterConexao(); using var multi = await conn.QueryMultipleAsync(query, new { anoLetivo, pagina = paginacao.Pagina, quantidadeRegistros = paginacao.QuantidadeRegistros, codigoEol, TiposUes = parametrosCargaInicialDto.TiposUes, parametrosCargaInicialDto.Ues, parametrosCargaInicialDto.Turmas, }, commandTimeout : 120); var retorno = new PaginacaoResultadoDto <AlunoEol> { Items = multi.Read <AlunoEol>(), TotalRegistros = multi.ReadFirst <int>() }; retorno.TotalPaginas = paginacao.QuantidadeRegistros > 0 ? (int)Math.Ceiling((double)retorno.TotalRegistros / paginacao.QuantidadeRegistros) : 1; return(retorno); }
public DateTime?GetExpirationDate() { DateTime?expirationDate = GetBaseExpirationDate(); TimeSpan extension = GetSpecialOfferExtension(); return(expirationDate?.Add(extension)); }
/// <summary> /// Deserializes command /// </summary> /// <param name="talkedId"></param> /// <param name="parts"></param> internal RMC(string talkedId, string[] parts) : base(talkedId) { if (!string.IsNullOrWhiteSpace(parts[8])) { DateTime = System.DateTime.ParseExact(parts[8], DATETIME_DDMMYY, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } if (!string.IsNullOrWhiteSpace(parts[8])) { DateTime time; /* * * if ( * !System.DateTime.TryParseExact(parts[0], HHMMSSfff, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out time)) * { * time = System.DateTime.ParseExact(parts[0], HHMMSS, DateTimeFormatInfo.InvariantInfo, * DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); * } */ try { time = System.DateTime.ParseExact(parts[0], DATETIME_HHMMSSfff, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } catch (FormatException) { time = System.DateTime.ParseExact(parts[0], DATETIME_HHMMSS, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } DateTime = DateTime?.Add(time.TimeOfDay) ?? time; } Status = MessageFormatting.ParseOneLetterEnumByValue <Flag>(parts[1]); Position = new Position(parts[2], parts[3], parts[4], parts[5]); SOG = float.Parse(parts[6]); TMG = !string.IsNullOrWhiteSpace(parts[7]) ? new TrueMessageCompassValue(double.Parse(parts[7])) : null; if (!string.IsNullOrWhiteSpace(parts[9])) { MagneticVariation = float.Parse(parts[9]); } if (!string.IsNullOrWhiteSpace(parts[10])) { MagneticVariationDirection = MessageFormatting.ParseOneLetterEnumByValue <EastWest>(parts[10]); } if (parts.Length > 11 && !string.IsNullOrWhiteSpace(parts[11])) { Mode = MessageFormatting.ParseOneLetterEnumByValue <FixMode>(parts[11]); } }
public void FrequencyParameter_NoArgPassed_ReportingPeriod() { FrequencyParameter testParameter = new FrequencyParameter(); DateTime fromResult = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); DateTime thruResult = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); thruResult = thruResult.Add(new TimeSpan(1, 0, 0, 0)); TimeSpan expectedResult = thruResult.Subtract(fromResult); Assert.AreEqual(expectedResult, testParameter.ReportingPeriod); }
public RolePrincipal (IIdentity identity) { if (identity == null) throw new ArgumentNullException ("identity"); this._identity = identity; this._cookiePath = RoleManagerConfig.CookiePath; this._issueDate = DateTime.Now; this._expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout); }
public void CreationAndAssigningWithTimeSpanAndSwap(DateTime?date1, TimeSpan?timeSpan) { var dtp = new DateTimePeriod(date1, timeSpan); Assert.Multiple(() => { Assert.AreEqual(date1, dtp.End); Assert.AreEqual(timeSpan.HasValue ? date1?.Add(timeSpan.Value) : null, dtp.Start); }); }
private string GetQuote() { if (_lastQuoteUpdateTime == null || _lastQuoteUpdateTime?.Add(_quoteUpdateInterval) <= DateTime.Now) { _lastQuoteUpdateTime = DateTime.Now; return(GetRandomQuote()); } return(_quote); }
private IEnumerable <EventViewModel> FilterData(List <EventViewModel> data, int?searchBy, string startDate, string endDate, string searchString) { IEnumerable <EventViewModel> query = data; if (searchBy.HasValue) { DateTime?_startDate = startDate.TryConvertToDateTime(); DateTime?_endDate = endDate.TryConvertToDateTime(); switch (searchBy) { case (int)SearchBy.Ongoing: query = query.Where(n => (n.StartDate <= DateTime.Now) && (n.EndDate != null && n.EndDate != null ? n.EndDate >= DateTime.Now : true)); break; case (int)SearchBy.Finished: query = query.Where(x => x.EndDate != null && x.EndDate < DateTime.Now); break; case (int)SearchBy.WillGoing: query = query.Where(x => x.StartDate > DateTime.Now); break; case (int)SearchBy.StartDate: query = query.Where(x => (_startDate != null ? _startDate <= x.StartDate && (_endDate != null ? x.StartDate <= _endDate?.Add(new TimeSpan(23, 59, 59)) : true) : true)); break; case (int)SearchBy.EndDate: query = query.Where(x => (_startDate != null ? _startDate <= x.EndDate && (_endDate != null && x.EndDate != null ? x.EndDate <= _endDate?.Add(new TimeSpan(23, 59, 59)) : true) : true)); break; } } return(SearchString(query, searchString)); }
/// <summary> /// Sets the planned start and end date of the match. /// If a new date is set, the original is stored to OrigPlannedStart and OrigPlannedEnd. /// Current data must be loaded from database before calling the method. /// </summary> /// <param name="newDate">New planned date for the match.</param> /// <param name="duration">Duration of the match.</param> public void SetPlannedStart(DateTime?newDate, TimeSpan duration) { if (newDate == PlannedStart) { return; } if (!OrigPlannedStart.HasValue) { OrigPlannedStart = PlannedStart; OrigPlannedEnd = PlannedEnd; } PlannedStart = newDate; PlannedEnd = newDate?.Add(duration); if (PlannedStart == OrigPlannedStart) { OrigPlannedStart = OrigPlannedEnd = null; } }
public static DateTimeOffset Default(DateTime dt, TimeZoneInfo timeZone) { if (dt.Kind != DateTimeKind.Unspecified) { var dto = new DateTimeOffset(dt); return TimeZoneInfo.ConvertTime(dto, timeZone); } if (timeZone.IsAmbiguousTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); return new DateTimeOffset(dt, earlierOffset); } if (timeZone.IsInvalidTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); var laterOffset = timeZone.GetUtcOffset(dt.AddDays(1)); var transitionGap = laterOffset - earlierOffset; return new DateTimeOffset(dt.Add(transitionGap), laterOffset); } return new DateTimeOffset(dt, timeZone.GetUtcOffset(dt)); }
public static DateTime scalar_invday(double span) { return(day_0.Add(TimeSpan.FromDays(span))); }
public static void scheduler_CustomDrawNavigationButton(object sender, DevExpress.XtraScheduler.CustomDrawObjectEventArgs e) { NavigationButtonNext navButton = e.ObjectInfo as NavigationButtonNext; SchedulerControl scheduler = sender as SchedulerControl; SchedulerStorage storage = scheduler.Storage as SchedulerStorage; // Do not count by resources. if (scheduler.GroupType != SchedulerGroupType.None) { return; } if (navButton != null && scheduler != null && storage != null) { // Count appointments within the interval used by the Next navigation button. AppointmentBaseCollection apts = scheduler.Storage.Appointments.Items; TimeSpan aptSearchInterval = scheduler.OptionsView.NavigationButtons.AppointmentSearchInterval; DateTime lastVisibleTime = scheduler.ActiveView.GetVisibleIntervals().Last().End; int aptCount = apts.Where(a => (a.Start > lastVisibleTime) && (a.Start < lastVisibleTime.Add(aptSearchInterval))).Count(); navButton.DisplayTextItem.Text = String.Format("Next {0} appointments", aptCount); } }
public override void Refresh() { if (lastRead.Add(this.client.UpdateInterval) > DateTime.Now) { return; } lastRead = DateTime.Now; StreamReader reader = null; try { FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(Fullname)); ftp.Credentials = this.client.Credentials; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = ftp.GetResponse() as FtpWebResponse; CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); while (line != null) { if (line.Length > 0) { string cutto = line.First("AM", "PM") == 0 ? "AM" : "PM"; cutto = line.CutToFirst(cutto, CutDirection.Right, false); cutto = culture.DateTimeFormat.GetMonthName(int.Parse(cutto.Substring(0, 2))) + " " + cutto.Substring(3, 2) + ", " + cutto.Substring(6); DateTime date; if (!DateTime.TryParse(cutto, out date)) { date = DateTime.MinValue; } string sName = line.Substring(39).Trim(); if (line.Contains("<DIR>")) { if (!directories.ContainsKey(sName)) { directories.Add(sName, new FTPDirectoryInfo(sName, date, this.client, this)); } } else { if (!files.ContainsKey(sName)) { files.Add(sName, new FTPFileInfo(sName, date, this.client, this)); } } } line = reader.ReadLine(); } reader.Close(); response.Close(); } catch (WebException ex) { ex.Response.Close(); //System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (reader != null) { reader.Dispose(); } } }
void UserLogin(HttpContext context) { var userType = context.Request.QueryString["user"];//index 普通用户账号;adminindex:单位管理员;sysadminindex:系统管理员 var LoginName = context.Request.Form["LoginName"]; var Password = context.Request.Form["Password"]; if (LoginName.Trim() == "") { context.Response.Write("请输入登录名!"); return; } if (Password.Trim() == "") { context.Response.Write("请输入密码!"); return; } //检验账户正确性 StringBuilder strAccount = new StringBuilder(); strAccount.Append(" SELECT ID, WB_ID,UserGroup_ID,strLoginName,strRealName,strPassword,ISEnable from Users"); strAccount.Append(" WHERE LOWER(strLoginName)=@strLoginName "); SqlParameter[] para = new SqlParameter[] { new SqlParameter("@strLoginName", LoginName.Trim().ToLower()) }; DataTable dtAccount = SQLHelper.ExecuteDataTable(strAccount.ToString(), para); if (dtAccount != null && dtAccount.Rows.Count != 0) { int UserGroup_ID = Convert.ToInt32(dtAccount.Rows[0]["UserGroup_ID"]); string UserGroupName = SQLHelper.ExecuteScalar(" SELECT strName FROM dbo.UserGroup WHERE ID=" + UserGroup_ID).ToString(); string UserGroupVerify = "OK"; switch (userType) { case "index": if (UserGroup_ID == 1 || UserGroup_ID == 2) //case "index": if (UserGroup_ID == 1) { UserGroupVerify = "不存在的登陆账号!"; } break; case "adminindex": if (UserGroup_ID != 2 && UserGroup_ID != 3) { UserGroupVerify = "不存在的登陆账号!"; } break; case "sysadminindex": if (UserGroup_ID != 1) { UserGroupVerify = "不存在的登陆账号!"; } break; } if (UserGroupVerify != "OK") { context.Response.Write(UserGroupVerify); return; } ////ip地址验证 //if (Convert.ToBoolean(common.GetWBAuthority()["ISWBControl"]) == true)//检验是否开启网点个数验证 //{ // if (UserGroupName == "营业员" || UserGroupName == "网点管理员") // { // //验证当前用户所在网点的ip地址是否可用 // object objIPaddress = SQLHelper.ExecuteScalar(" SELECT top 1 IPaddress FROM dbo.WB WHERE ID=" + dtAccount.Rows[0]["WB_ID"].ToString()); // if (objIPaddress == null || objIPaddress.ToString().Trim() == "") // { // UserGroupVerify = "!"; // context.Response.Write("系统没有为当前账户的网点配置可用的IP地址,请与系统管理员联系取得可用的IP地址!"); // return; // } // string ip = context.Request.QueryString["ip"].ToString(); // if (objIPaddress.ToString().Trim() != ip) // { // UserGroupVerify = ""; // context.Response.Write("当前计算机使用的IP地址无效,请与系统管理员联系取得可用的IP地址!"); // return; // } // } //} bool ErrorLoginCheck = false;//是否启用了秘密错误检验 if (UserGroup_ID == 3 || UserGroup_ID == 4) { if (Convert.ToBoolean(common.GetWBAuthority()["ErrorLogin_User"]) == true) { ErrorLoginCheck = true; } } else { if (Convert.ToBoolean(common.GetWBAuthority()["ErrorLogin_Admin"]) == true) { ErrorLoginCheck = true; } } string UserID = dtAccount.Rows[0]["ID"].ToString(); object objErrorTime = null; if (ErrorLoginCheck) { objErrorTime = SQLHelper.ExecuteScalar(" SELECT TOP 1 ErrorTime FROM dbo.UserOperate WHERE UserID=" + UserID + " ORDER BY dt_LoginIn desc"); if (objErrorTime != null && objErrorTime.ToString() != "") { if (Convert.ToInt32(objErrorTime) >= 3) { DateTime dt_LoginIn = Convert.ToDateTime(SQLHelper.ExecuteScalar(" SELECT TOP 1 dt_LoginIn FROM dbo.UserOperate WHERE UserID=" + UserID + " ORDER BY dt_LoginIn desc")); TimeSpan tsLogin = DateTime.Now.Subtract(dt_LoginIn); if (tsLogin.TotalHours < 24) { Fun.Alert("您的密码已经连续三次输入错误,请于24小时后重试,或请求管理员解除限制!"); return; } } } } string strPassword = dtAccount.Rows[0]["strPassword"].ToString(); bool ISEnable = Convert.ToBoolean(dtAccount.Rows[0]["ISEnable"]); if (Fun.GetMD5_32(Password.Trim()) == strPassword) //if (Fun.GetMD5_32(Password.Trim()) == strPassword || Password.Trim()==strPassword)//密码或价格后的信息 { if (ISEnable) { if (HttpContext.Current.Session != null) { HttpContext.Current.Session.Clear(); } DataTable dtwb = SQLHelper.ExecuteDataTable(" select * from WB where ID=" + dtAccount.Rows[0]["WB_ID"].ToString()); context.Session["WB_ID"] = dtAccount.Rows[0]["WB_ID"].ToString(); //该用户所在的网点ID context.Session["ISHQ"] = dtwb.Rows[0]["ISHQ"].ToString(); //是否是总部网点 context.Session["ISSimulate"] = dtwb.Rows[0]["ISSimulate"].ToString(); //是否是模拟网点 context.Session["UserGroup_ID"] = UserGroup_ID; context.Session["UserGroup_Name"] = UserGroupName; context.Session["ID"] = dtAccount.Rows[0]["ID"].ToString();//用户ID context.Session["strLoginName"] = dtAccount.Rows[0]["strLoginName"].ToString();//用户登录名 context.Session["strRealName"] = dtAccount.Rows[0]["strRealName"].ToString(); //设置保存session的Cookies值 context.Request.Cookies.Clear(); context.Response.Cookies.Clear(); HttpCookie cookie = new HttpCookie("LoginInfo"); DateTime dtNow = DateTime.Now; TimeSpan ts = new TimeSpan(1, 0, 0, 0);//设置cookie的保存时间为一天 cookie.Expires = dtNow.Add(ts); cookie.Values.Add("ID", dtAccount.Rows[0]["ID"].ToString()); HttpContext.Current.Response.Cookies.Add(cookie); //添加营业员访问记录 AddUserOperate(false, dtAccount, context); string userinfo = JsonHelper.ToJson(dtAccount); //userinfo = userinfo.Substring(1); //userinfo = userinfo.Substring(0, userinfo.Length - 1); string wbinfo = JsonHelper.ToJson(dtwb); //wbinfo = wbinfo.Substring(1); //wbinfo = wbinfo.Substring(0, userinfo.Length - 1); var returnValue = "{\"wbinfo\":" + wbinfo + ",\"userinfo\":" + userinfo + "}"; //context.Response.Write("Success"); context.Response.Write(returnValue); return; } else { context.Response.Write("当前账户已被禁用,请与管理员联系!"); return; } } else { AddUserOperate(true, dtAccount, context); if (ErrorLoginCheck) { int numErrorTime = 0; if (objErrorTime != null && objErrorTime.ToString() != "") { numErrorTime = Convert.ToInt32(objErrorTime) + 1; } context.Response.Write("这是您第" + numErrorTime + "次输入密码错误,连续输入错误3次以上您的账号将被禁用24小时!"); return; } else { context.Response.Write("您输入的密码不正确"); return; } } } else { context.Response.Write("不存在的登陆账号!"); return; } }
public void FrequencyParameter_NullPassed() { DateTime testFrom = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); DateTime testThru = testFrom.Add(new TimeSpan(1, 0, 0, 0)); FrequencyParameter testParameter = new FrequencyParameter(null); Assert.Greater(testParameter.Errors.Count, 0); Assert.AreEqual(testFrom, testParameter.FromDate); Assert.AreEqual(testThru, testParameter.ThruDate); }
private dynamic ProcessScheduleIntent(dynamic request) { string date = Convert.ToString(request.request.intent.slots.when.value); string time = Convert.ToString(request.request.intent.slots.time.value); string duration = Convert.ToString(request.request.intent.slots.duration.value); string responsible = Convert.ToString(request.request.intent.slots.responsible.value); if (string.IsNullOrEmpty(date) && string.IsNullOrEmpty(time) && string.IsNullOrEmpty(responsible)) { return(GenerateTextResponse("Sorry! I didn't understand what you're saying. Could you repeat, please?")); } else if (string.IsNullOrEmpty(responsible)) { return(GenerateTextResponse("Sorry! I couldn't understant who is the responsible for the meeting. Could you repeat your request, please?")); } else { if (string.IsNullOrEmpty(date)) { date = DateTime.Now.ToString("yyyy-MM-dd"); } if (string.IsNullOrEmpty(time)) { time = DateTime.Now.ToString("HH:mm"); } if (string.IsNullOrEmpty(duration)) { duration = "PT1H"; } if (time.Length <= 2) { time += ":00"; } DateTime parsedDate = Convert.ToDateTime(string.Concat(date, " ", time)); TimeSpan parsedDuration = System.Xml.XmlConvert.ToTimeSpan(duration); var parsedEndTime = parsedDate.Add(parsedDuration); try { var httpResponse = SchedulingMeeting(parsedDate, parsedEndTime, responsible); switch (httpResponse.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Created: return(GenerateTextResponse("Great! Your meeting is scheduled. Don't forget it!")); default: return(GenerateTextResponse("Sorry! The service is not availabe now. Try againg later!")); } } catch (WebException ex) { if (ex.Message.Equals("The remote server returned an error: (409) Conflict.")) { return(GenerateTextResponse("There is a reservation for this room in the request time. Do you want to try another time?")); } else { return(GenerateTextResponse("Sorry! The service is not availabe now. Try againg later!")); } } } }
/// <summary> /// Process study migration candidates retrieved from the <see cref="Model.FilesystemQueue"/> table /// </summary> /// <param name="candidateList">The list of candidate studies for deleting.</param> private void ProcessStudyMigrateCandidates(IList <FilesystemQueue> candidateList) { Platform.CheckForNullReference(candidateList, "candidateList"); if (candidateList.Count > 0) { Platform.Log(LogLevel.Debug, "Scheduling tier-migration for {0} eligible studies...", candidateList.Count); } FilesystemProcessStatistics summaryStats = new FilesystemProcessStatistics("FilesystemTierMigrateInsert"); foreach (FilesystemQueue queueItem in candidateList) { if (_bytesToRemove < 0 || CancelPending) { Platform.Log(LogLevel.Debug, "Estimated disk space has been reached."); break; } StudyProcessStatistics stats = new StudyProcessStatistics("TierMigrateStudy"); stats.TotalTime.Start(); stats.StudyStorageTime.Start(); // First, get the StudyStorage locations for the study, and calculate the disk usage. StudyStorageLocation location; if (!FilesystemMonitor.Instance.GetWritableStudyStorageLocation(queueItem.StudyStorageKey, out location)) { continue; } stats.StudyStorageTime.End(); stats.CalculateDirectorySizeTime.Start(); // Get the disk usage float studySize = EstimateFolderSizeFromStudyXml(location); stats.CalculateDirectorySizeTime.End(); stats.DirectorySize = (ulong)studySize; stats.DbUpdateTime.Start(); using ( IUpdateContext update = PersistentStoreRegistry.GetDefaultStore().OpenUpdateContext(UpdateContextSyncMode.Flush)) { ILockStudy lockstudy = update.GetBroker <ILockStudy>(); LockStudyParameters lockParms = new LockStudyParameters { StudyStorageKey = location.Key, QueueStudyStateEnum = QueueStudyStateEnum.MigrationScheduled }; if (!lockstudy.Execute(lockParms) || !lockParms.Successful) { Platform.Log(LogLevel.Warn, "Unable to lock study for inserting Tier Migration. Reason:{0}. Skipping study ({1})", lockParms.FailureReason, location.StudyInstanceUid); continue; } IInsertWorkQueueFromFilesystemQueue broker = update.GetBroker <IInsertWorkQueueFromFilesystemQueue>(); InsertWorkQueueFromFilesystemQueueParameters insertParms = new InsertWorkQueueFromFilesystemQueueParameters { StudyStorageKey = location.GetKey(), ServerPartitionKey = location.ServerPartitionKey, ScheduledTime = _scheduledTime, DeleteFilesystemQueue = true, WorkQueueTypeEnum = WorkQueueTypeEnum.MigrateStudy, FilesystemQueueTypeEnum = FilesystemQueueTypeEnum.TierMigrate }; Platform.Log(LogLevel.Debug, "Scheduling tier-migration for study {0} from {1} at {2}...", location.StudyInstanceUid, location.FilesystemTierEnum, _scheduledTime); WorkQueue insertItem = broker.FindOne(insertParms); if (insertItem == null) { Platform.Log(LogLevel.Error, "Unexpected problem inserting 'MigrateStudy' record into WorkQueue for Study {0}", location.StudyInstanceUid); } else { update.Commit(); _bytesToRemove -= studySize; _studiesMigrated++; // spread out the scheduled migration entries based on the size // assuming that the larger the study the longer it will take to migrate // The assumed migration speed is arbitarily chosen. double migrationSpeed = ServiceLockSettings.Default.TierMigrationSpeed * 1024 * 1024; // MB / sec TimeSpan estMigrateTime = TimeSpan.FromSeconds(studySize / migrationSpeed); _scheduledTime = _scheduledTime.Add(estMigrateTime); } } stats.DbUpdateTime.End(); stats.TotalTime.End(); summaryStats.AddSubStats(stats); StatisticsLogger.Log(LogLevel.Debug, stats); } summaryStats.CalculateAverage(); StatisticsLogger.Log(LogLevel.Info, false, summaryStats); }
void DecryptTicket (string encryptedTicket) { if (encryptedTicket == null || encryptedTicket == String.Empty) throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket"); byte [] ticketBytes = GetBytesFromBase64 (encryptedTicket); byte [] decryptedTicketBytes = null; CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; if (cookieProtection == CookieProtection.All) { decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt (MachineConfig, ticketBytes); } else if (cookieProtection == CookieProtection.Encryption) { decryptedTicketBytes = MachineKeySectionUtils.Decrypt (MachineConfig, ticketBytes); } else if (cookieProtection == CookieProtection.Validation) { decryptedTicketBytes = MachineKeySectionUtils.Verify (MachineConfig, ticketBytes); } if (decryptedTicketBytes == null) throw new HttpException ("ticket validation failed"); MemoryStream ticket = new MemoryStream (decryptedTicketBytes); BinaryReader reader = new BinaryReader (ticket); // version _version = reader.ReadInt32 (); // issued date _issueDate = new DateTime (reader.ReadInt64 ()); // expire date _expireDate = new DateTime (reader.ReadInt64 ()); // cookie path _cookiePath = reader.ReadString (); // roles string roles = reader.ReadString (); if (!Expired) { InitializeRoles (roles); //update ticket if less than half of CookieTimeout remaining. if (Roles.CookieSlidingExpiration){ if (_expireDate-DateTime.Now < TimeSpan.FromTicks (RoleManagerConfig.CookieTimeout.Ticks/2)) { _issueDate = DateTime.Now; _expireDate = DateTime.Now.Add (RoleManagerConfig.CookieTimeout); SetDirty (); } } } else { // issue a new ticket _issueDate = DateTime.Now; _expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout); } }
override protected void triggerInternal(GameStateData previousGameState, GameStateData currentGameState) { if (currentGameState.CarDamageData.DamageEnabled && currentGameState.SessionData.SessionRunningTime > 10 && currentGameState.Now > nextPunctureCheck) { nextPunctureCheck = currentGameState.Now + timeToWaitForDamageToSettle; CornerData.Corners puncture = getPuncture(currentGameState.TyreData); if (puncture != lastReportedPunctureCorner) { lastReportedPunctureCorner = puncture; switch (puncture) { case CornerData.Corners.FRONT_LEFT: audioPlayer.playMessage(new QueuedMessage(folderLeftFrontPuncture, 0, this)); break; case CornerData.Corners.FRONT_RIGHT: audioPlayer.playMessage(new QueuedMessage(folderRightFrontPuncture, 0, this)); break; case CornerData.Corners.REAR_LEFT: audioPlayer.playMessage(new QueuedMessage(folderLeftRearPuncture, 0, this)); break; case CornerData.Corners.REAR_RIGHT: audioPlayer.playMessage(new QueuedMessage(folderRightRearPuncture, 0, this)); break; } } } if (currentGameState.CarDamageData.DamageEnabled) { aeroDamage = currentGameState.CarDamageData.OverallAeroDamage; trannyDamage = currentGameState.CarDamageData.OverallTransmissionDamage; engineDamage = currentGameState.CarDamageData.OverallEngineDamage; if (currentGameState.CarDamageData.BrakeDamageStatus.hasValueAtLevel(DamageLevel.DESTROYED)) { maxBrakeDamage = DamageLevel.DESTROYED; } else if (currentGameState.CarDamageData.BrakeDamageStatus.hasValueAtLevel(DamageLevel.MAJOR)) { maxBrakeDamage = DamageLevel.MAJOR; } else if (currentGameState.CarDamageData.BrakeDamageStatus.hasValueAtLevel(DamageLevel.MINOR)) { maxBrakeDamage = DamageLevel.MINOR; } else if (currentGameState.CarDamageData.BrakeDamageStatus.hasValueAtLevel(DamageLevel.TRIVIAL)) { maxBrakeDamage = DamageLevel.TRIVIAL; } if (currentGameState.CarDamageData.SuspensionDamageStatus.hasValueAtLevel(DamageLevel.DESTROYED)) { maxSuspensionDamage = DamageLevel.DESTROYED; } else if (currentGameState.CarDamageData.SuspensionDamageStatus.hasValueAtLevel(DamageLevel.MAJOR)) { maxSuspensionDamage = DamageLevel.MAJOR; } else if (currentGameState.CarDamageData.SuspensionDamageStatus.hasValueAtLevel(DamageLevel.MINOR)) { maxSuspensionDamage = DamageLevel.MINOR; } else if (currentGameState.CarDamageData.SuspensionDamageStatus.hasValueAtLevel(DamageLevel.TRIVIAL)) { maxSuspensionDamage = DamageLevel.TRIVIAL; } isMissingWheel = !currentGameState.PitData.InPitlane && (!currentGameState.TyreData.LeftFrontAttached || !currentGameState.TyreData.RightFrontAttached || !currentGameState.TyreData.LeftRearAttached || !currentGameState.TyreData.RightRearAttached); if (engineDamage < getLastReportedDamageLevel(Component.ENGINE)) { resetReportedDamage(Component.ENGINE, engineDamage); } if (trannyDamage < getLastReportedDamageLevel(Component.TRANNY)) { resetReportedDamage(Component.TRANNY, trannyDamage); } if (maxSuspensionDamage < getLastReportedDamageLevel(Component.SUSPENSION)) { resetReportedDamage(Component.SUSPENSION, maxSuspensionDamage); } if (maxBrakeDamage < getLastReportedDamageLevel(Component.BRAKES)) { resetReportedDamage(Component.BRAKES, maxBrakeDamage); } if (aeroDamage < getLastReportedDamageLevel(Component.AERO)) { resetReportedDamage(Component.AERO, aeroDamage); } minDamageToReport = (DamageLevel)Math.Max((int)engineDamage, Math.Max((int)trannyDamage, Math.Max((int)maxSuspensionDamage, Math.Max((int)maxBrakeDamage, (int)aeroDamage)))); Tuple <Component, DamageLevel> worstUnreportedDamage = getWorstUnreportedDamage(); if (worstUnreportedDamage != null && worstUnreportedDamage.Item2 >= minDamageToReport) { if (damageToReportNext == null || worstUnreportedDamage.Item1 != damageToReportNext.Item1 || worstUnreportedDamage.Item2 != damageToReportNext.Item2) { timeWhenDamageLastChanged = currentGameState.Now; damageToReportNext = worstUnreportedDamage; } else if (timeWhenDamageLastChanged.Add(timeToWaitForDamageToSettle) < currentGameState.Now) { Console.WriteLine("reporting ..."); Console.WriteLine(damageToReportNext.Item1 + ", " + damageToReportNext.Item2); // put *all* the damage levels in the 'reported' set, even though we haven't actually reported them. // This ensure we only ever play the worst damage on the car when damage has just increased // Only do this if the component damage is *less* than the one we just reported if (Component.AERO == damageToReportNext.Item1 || aeroDamage < damageToReportNext.Item2) { addReportedDamage(Component.AERO, aeroDamage); } if (Component.BRAKES == damageToReportNext.Item1 || maxBrakeDamage < damageToReportNext.Item2) { addReportedDamage(Component.BRAKES, maxBrakeDamage); } if (Component.ENGINE == damageToReportNext.Item1 || engineDamage < damageToReportNext.Item2) { addReportedDamage(Component.ENGINE, engineDamage); } if (Component.SUSPENSION == damageToReportNext.Item1 || maxSuspensionDamage < damageToReportNext.Item2) { addReportedDamage(Component.SUSPENSION, maxSuspensionDamage); } if (Component.TRANNY == damageToReportNext.Item1 || trannyDamage < damageToReportNext.Item2) { addReportedDamage(Component.TRANNY, trannyDamage); } if (enableDamageMessages) { playDamageToReport(); } } } } }
protected override void PopulateEntities(Session session) { new SingleDateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset, MillisecondDateTimeOffset = FirstMillisecondDateTimeOffset, NullableDateTimeOffset = NullableDateTimeOffset }; DateTime[] dateTimes = new[] { FirstDateTime, FirstDateTime, FirstDateTime.Date, SecondDateTime, SecondDateTime.Date, new DateTime(FirstDateTime.Year, FirstDateTime.Month, FirstDateTime.Day, FirstDateTime.Hour, FirstDateTime.Minute, 0), new DateTime(FirstDateTime.Ticks, DateTimeKind.Unspecified), FirstDateTime.Add(new TimeSpan(987, 23, 34, 45)),FirstDateTime.AddYears(1),FirstDateTime.AddYears(-2), FirstDateTime.AddMonths(44), FirstDateTime.AddMonths(-55), SecondDateTime.AddHours(5), SecondDateTime.AddHours(-15), SecondDateTime.AddMinutes(59), SecondDateTime.AddMinutes(-49), SecondDateTime.AddSeconds(57), SecondDateTime.AddSeconds(-5), }; DateTime[] dateTimesWithMilliseconds = new[] { FirstMillisecondDateTime, FirstMillisecondDateTime, FirstMillisecondDateTime.Date, SecondMillisecondDateTime, SecondMillisecondDateTime.Date, new DateTime(FirstMillisecondDateTime.Year, FirstMillisecondDateTime.Month, FirstMillisecondDateTime.Day, FirstMillisecondDateTime.Hour, FirstMillisecondDateTime.Minute, 0), new DateTime(FirstMillisecondDateTime.Year, FirstMillisecondDateTime.Month, FirstMillisecondDateTime.Day, FirstMillisecondDateTime.Hour, FirstMillisecondDateTime.Minute, FirstMillisecondDateTime.Second, 0), new DateTime(FirstMillisecondDateTime.Ticks, DateTimeKind.Unspecified), FirstMillisecondDateTime.Add(new TimeSpan(987, 23, 34, 45)), }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset.ToOffset(FirstOffset) }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset.ToOffset(SecondOffset) }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset.ToOffset(TimeSpan.Zero) }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTimeOffset.Date }; new DateTimeOffsetEntity { DateTimeOffset = SecondDateTimeOffset }; new DateTimeOffsetEntity { DateTimeOffset = SecondDateTimeOffset.ToOffset(FirstOffset) }; new DateTimeOffsetEntity { DateTimeOffset = SecondDateTimeOffset.ToOffset(SecondOffset) }; new DateTimeOffsetEntity { DateTimeOffset = SecondDateTimeOffset.Date }; new DateTimeOffsetEntity { DateTimeOffset = FirstDateTime }; new DateTimeOffsetEntity { DateTimeOffset = new DateTimeOffset(FirstDateTime, TimeSpan.Zero) }; var index = 0; foreach (var dateTime in dateTimes) new DateTimeOffsetEntity(dateTime, ++index % 3==0 ? FirstOffset : SecondOffset); new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset.ToOffset(FirstOffset) }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset.ToOffset(SecondOffset) }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset.ToOffset(TimeSpan.Zero) }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = FirstMillisecondDateTimeOffset.Date }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondMillisecondDateTimeOffset }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondMillisecondDateTimeOffset.ToOffset(FirstOffset) }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondMillisecondDateTimeOffset.ToOffset(SecondOffset) }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondMillisecondDateTimeOffset.Date }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondDateTimeOffset }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = SecondDateTime }; new MillisecondDateTimeOffsetEntity { DateTimeOffset = new DateTimeOffset(SecondDateTime, TimeSpan.Zero) }; index = 0; foreach (var dateTime in dateTimesWithMilliseconds) new MillisecondDateTimeOffsetEntity(dateTime, ++index % 3==0 ? FirstOffset : SecondOffset); var dateTimeOffset = FirstMillisecondDateTimeOffset.AddYears(10); for (var i = 0; i < 1000; ++i) new MillisecondDateTimeOffsetEntity { DateTimeOffset = dateTimeOffset.AddMilliseconds(i) }; foreach (var dateTimeEntity in Query.All<DateTimeOffsetEntity>()) new NullableDateTimeOffsetEntity(dateTimeEntity); new NullableDateTimeOffsetEntity { DateTimeOffset = null }; new NullableDateTimeOffsetEntity { DateTimeOffset = null }; }
void DecryptTicket (string encryptedTicket) { if (encryptedTicket == null || encryptedTicket == String.Empty) throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket"); byte [] ticketBytes = GetBytesFromBase64 (encryptedTicket); byte [] decryptedTicketBytes = null; CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { ICryptoTransform decryptor; decryptor = TripleDES.Create ().CreateDecryptor ( MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig), InitVector); decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length); } else decryptedTicketBytes = ticketBytes; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig); byte [] rolesWithValidationBytes = null; byte [] tmpValidation = null; int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length]; Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize); Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length); switch (MachineConfig.Validation) { case MachineKeyValidation.MD5: tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes); break; case MachineKeyValidation.TripleDES: case MachineKeyValidation.SHA1: tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes); break; } for (int i = 0; i < tmpValidation.Length; i++) { if (i >= decryptedTicketBytes.Length || tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize]) throw new HttpException ("ticket validation failed"); } } MemoryStream ticket = new MemoryStream (decryptedTicketBytes); BinaryReader reader = new BinaryReader (ticket); // version _version = reader.ReadInt32 (); // issued date _issueDate = new DateTime (reader.ReadInt64 ()); // expire date _expireDate = new DateTime (reader.ReadInt64 ()); // cookie path _cookiePath = reader.ReadString (); // roles string roles = reader.ReadString (); if (!Expired) { InitializeRoles (roles); //update ticket if less than half of CookieTimeout remaining. if (Roles.CookieSlidingExpiration){ if (_expireDate-DateTime.Now < TimeSpan.FromTicks (RoleManagerConfig.CookieTimeout.Ticks/2)) { _issueDate = DateTime.Now; _expireDate = DateTime.Now.Add (RoleManagerConfig.CookieTimeout); SetDirty (); } } } else { // issue a new ticket _issueDate = DateTime.Now; _expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout); } }
/////////////////////////////////// private static void RunForWeekly(JobScheduleWeekly schedule, int weekNumber) { bool isLast = (weekNumber == 0)?true:false; JobSchedule WeeklyDaySchedule = new JobSchedule(); WeeklyDaySchedule.ScheduleConfig = schedule; DateTime dt = startTestTime.AddMonths(-2); System.Collections.Generic.Dictionary <DateTime, DateTime> validRanges = new System.Collections.Generic.Dictionary <DateTime, DateTime>(); int n = 0; DayOfWeek dw = DayOfWeek.Sunday; while (dt <= endTestTime) { dt = dt.AddDays(1); //dt = DateTime.Parse("1/22/2012 8:00:00 PM"); if (dt.Day == 1) { n = 0; dw = dt.DayOfWeek; } if (dt.DayOfWeek == dw) { n++; } bool isValid = false; if (isLast) { if ((IsLastDayOccuranceForMonth(dt)) && ((int)dt.DayOfWeek == (int)schedule.Day.DayName)) { isValid = true; } } else if ((n == weekNumber) && ((int)dt.DayOfWeek == (int)schedule.Day.DayName)) { isValid = true; } if (!isValid) { continue; } DateTime s = new DateTime(dt.Year, dt.Month, dt.Day); DateTime e = s; s = s.Add(schedule.Day.Time.StartTime.TimeOfDay); e = e.Add(schedule.Day.Time.EndTime.TimeOfDay); if (s.TimeOfDay > e.TimeOfDay) { e = e.AddDays(1); } validRanges.Add(s, e); } RunTests(WeeklyDaySchedule, validRanges); }
public TimeSpan GetEndTime() { return(new TimeSpan(DateTime.Add(TimeSpan).TimeOfDay.Hours, 0, 0)); }
private dynamic ProcessCheckIntent(dynamic request) { string dateCheck = Convert.ToString(request.request.intent.slots.when.value); string timeCheck = Convert.ToString(request.request.intent.slots.time.value); string durationCheck = Convert.ToString(request.request.intent.slots.duration.value); if (string.IsNullOrEmpty(dateCheck) && string.IsNullOrEmpty(timeCheck) && string.IsNullOrEmpty(durationCheck)) { return(GenerateTextResponse("Sorry! I didn't understand when and what time you're trying to check. Could you repeat, please?")); } else { if (string.IsNullOrEmpty(dateCheck)) { dateCheck = DateTime.Now.ToString("yyyy-MM-dd"); } if (string.IsNullOrEmpty(timeCheck)) { timeCheck = DateTime.Now.ToString("HH"); } if (string.IsNullOrEmpty(durationCheck)) { durationCheck = "PT1H"; } if (timeCheck.Length <= 2) { timeCheck += ":00"; } DateTime parsedDateCheck = Convert.ToDateTime(string.Concat(dateCheck, " ", timeCheck)); TimeSpan parsedDurationCheck = System.Xml.XmlConvert.ToTimeSpan(durationCheck); var parsedEndTimeCheck = parsedDateCheck.Add(parsedDurationCheck); try { HttpWebResponse httpResponse = VerifyMeeting(parsedDateCheck, parsedEndTimeCheck); switch (httpResponse.StatusCode) { case HttpStatusCode.OK: return(GenerateTextResponse("Great! The room is free for use!")); default: return(GenerateTextResponse("Sorry! The service is not availabe now. Try againg later!")); } } catch (WebException ex) { if (ex.Message.Equals("The remote server returned an error: (409) Conflict.")) { return(GenerateTextResponse("There is a reservation for this room in the request time. Do you want to try another time?")); } else { return(GenerateTextResponse("Sorry! The service is not availabe now. Try againg later!")); } } } }
static void Main(string[] args) { // http://flotaoccidental.co/horarios is better source, but contains no route information. List <CIBusOrigens> _Origens = new List <CIBusOrigens> { }; List <CIBusOrigensDestino> _OrigensDestino = new List <CIBusOrigensDestino> { }; List <CIBusRoutes> _Routes = new List <CIBusRoutes> { }; DateTime Date = DateTime.Now; string APIPathBusAgency = "bus/agency/"; string APIPathBusAgencyStop = "bus/agencystop/{0}/{1}"; CookieContainer cookieContainer = new CookieContainer(); CookieCollection cookieCollection = new CookieCollection(); String OrigensHtml = String.Empty; using (System.Net.WebClient wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); wc.Headers.Add("Referer", "http://flotaoccidental.co/transporte-de-pasajeros/"); wc.Proxy = null; Console.WriteLine("Download Origens list"); OrigensHtml = wc.DownloadString("http://flotaoccidental.co/horarios"); Console.WriteLine("Download ready..."); } HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(OrigensHtml); var origens = doc.DocumentNode.SelectNodes("//select[@id='origen']/option"); foreach (var origen in origens) { string OrigenName = origen.NextSibling.InnerText; OrigenName = OrigenName.Trim(); _Origens.Add(new CIBusOrigens { Ciudad_Nombre = OrigenName }); } Console.WriteLine("Parsing through the from to get the destionations for each from locations..."); foreach (var Origen in _Origens) { var request = (HttpWebRequest)WebRequest.Create("http://flotaoccidental.co/horarios/destinos"); var postData = String.Format("origen={0}", Origen.Ciudad_Nombre); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; request.Referer = "http://flotaoccidental.co/horarios"; request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.CookieContainer = cookieContainer; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); // Parse the Response. dynamic DestinationResponseJson = JArray.Parse(responseString); foreach (var destino in DestinationResponseJson) { string Destino_CIUDAD_NOMBRE = destino.destino; _OrigensDestino.Add(new CIBusOrigensDestino { Origen_Ciudad_Nombre = Origen.Ciudad_Nombre, Destino_Ciudad_Nombre = Destino_CIUDAD_NOMBRE }); } // Response JSON: [{"coddes":"401","descripcion":"Medell\u00edn"},{"coddes":"503","descripcion":"Condoto"},{"coddes":"506","descripcion":"Istmina"},{"coddes":"501","descripcion":"Quibdo"},{"coddes":"508","descripcion":"Tado"}] } // Begin parsing route information Console.WriteLine("Found: {0} combinations", _OrigensDestino.Count.ToString()); foreach (var FromToCombo in _OrigensDestino) { var request = (HttpWebRequest)WebRequest.Create("http://flotaoccidental.co/horarios/consultaHorarios"); //fecha=2017%2F01%2F27&origen=101&destino=401&title=Viajes+de+Ida&seleccion=Ida&lang=spanish var postData = String.Format("origen={0}", FromToCombo.Origen_Ciudad_Nombre); postData += String.Format("&destino={0}", FromToCombo.Destino_Ciudad_Nombre); postData += String.Format("&fecha={0}", Date.ToString("yyyy-MM-dd")); //postData += String.Format("&title=Viajes+de+Ida&seleccion=Ida&lang=spanish"); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.ContentLength = data.Length; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; request.Referer = "http://flotaoccidental.co/horarios"; request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Accept = "gzip,deflate"; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.CookieContainer = cookieContainer; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); // Reponse is html. HtmlDocument RouteTimesHtml = new HtmlDocument(); RouteTimesHtml.LoadHtml(responseString); var RouteTimes = RouteTimesHtml.DocumentNode.SelectNodes("//table//tbody//tr"); if (RouteTimes != null) { foreach (var RouteTime in RouteTimes) { /* * <tr> * <td>CORRIENTE</td> * <td>2017-05-10</td> datum * <td>9:00 am</td> vertrektijd * <td>00:40:00</td> duur rit. * <td>28</td> * </tr> */ string DepartTime = RouteTime.SelectSingleNode("./td[3]").InnerText.ToString(); DateTime DepartTimeDT = DateTime.Parse(DepartTime); string Duration = RouteTime.SelectSingleNode("./td[4]").InnerText.ToString(); TimeSpan DurationTS = TimeSpan.Parse(Duration); DateTime ArrivalTimeDT = DepartTimeDT.Add(DurationTS); string TypeVehicle = RouteTime.SelectSingleNode("./td[1]").InnerText.ToString(); Boolean FlightMonday = false; Boolean FlightTuesday = false; Boolean FlightWednesday = false; Boolean FlightThursday = false; Boolean FlightFriday = false; Boolean FlightSaterday = false; Boolean FlightSunday = false; int dayofweek = Convert.ToInt32(Date.DayOfWeek); if (dayofweek == 0) { FlightSunday = true; } if (dayofweek == 1) { FlightMonday = true; } if (dayofweek == 2) { FlightTuesday = true; } if (dayofweek == 3) { FlightWednesday = true; } if (dayofweek == 4) { FlightThursday = true; } if (dayofweek == 5) { FlightFriday = true; } if (dayofweek == 6) { FlightSaterday = true; } _Routes.Add(new CIBusRoutes { From = FromToCombo.Origen_Ciudad_Nombre, To = FromToCombo.Destino_Ciudad_Nombre, DepartTime = DepartTimeDT, ArrivalTime = ArrivalTimeDT, TypeVehicle = TypeVehicle, FromDate = Date.Date, ToDate = Date.Date, FlightMonday = FlightMonday, FlightTuesday = FlightTuesday, FlightWednesday = FlightWednesday, FlightThursday = FlightThursday, FlightFriday = FlightFriday, FlightSaterday = FlightSaterday, FlightSunday = FlightSunday, FlightNextDayArrival = false }); } } } // Export XML // Write the list of objects to a file. System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(_Routes.GetType()); string myDir = AppDomain.CurrentDomain.BaseDirectory + "\\output"; Directory.CreateDirectory(myDir); StreamWriter file = new System.IO.StreamWriter("output\\output.xml"); writer.Serialize(file, _Routes); file.Close(); // GTFS Support string gtfsDir = AppDomain.CurrentDomain.BaseDirectory + "\\gtfs"; System.IO.Directory.CreateDirectory(gtfsDir); Console.WriteLine("Creating GTFS Files..."); Console.WriteLine("Creating GTFS File agency.txt..."); using (var gtfsagency = new StreamWriter(@"gtfs\\agency.txt")) { var csv = new CsvWriter(gtfsagency); csv.Configuration.Delimiter = ","; csv.Configuration.Encoding = Encoding.UTF8; csv.Configuration.TrimFields = true; // header csv.WriteField("agency_id"); csv.WriteField("agency_name"); csv.WriteField("agency_url"); csv.WriteField("agency_timezone"); csv.WriteField("agency_lang"); csv.WriteField("agency_phone"); csv.WriteField("agency_fare_url"); csv.WriteField("agency_email"); csv.NextRecord(); string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + APIPathBusAgency + "FO"; string RequestAirlineJson = String.Empty; HttpWebRequest requestAirline = (HttpWebRequest)WebRequest.Create(urlapi); requestAirline.Method = "GET"; requestAirline.Proxy = null; requestAirline.KeepAlive = false; using (HttpWebResponse Airlineresponse = (HttpWebResponse)requestAirline.GetResponse()) using (StreamReader reader = new StreamReader(Airlineresponse.GetResponseStream())) { RequestAirlineJson = reader.ReadToEnd(); } dynamic AirlineResponseJson = JsonConvert.DeserializeObject(RequestAirlineJson); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_id)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_name)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_url)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_timezone)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_lang)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_phone)); csv.WriteField(Convert.ToString(AirlineResponseJson[0].agency_fare_url)); csv.WriteField(""); csv.NextRecord(); } Console.WriteLine("Creating GTFS File routes.txt ..."); using (var gtfsroutes = new StreamWriter(@"gtfs\\routes.txt")) { // Route record var csvroutes = new CsvWriter(gtfsroutes); csvroutes.Configuration.Delimiter = ","; csvroutes.Configuration.Encoding = Encoding.UTF8; csvroutes.Configuration.TrimFields = true; // header csvroutes.WriteField("route_id"); csvroutes.WriteField("agency_id"); csvroutes.WriteField("route_short_name"); csvroutes.WriteField("route_long_name"); csvroutes.WriteField("route_desc"); csvroutes.WriteField("route_type"); csvroutes.WriteField("route_url"); csvroutes.WriteField("route_color"); csvroutes.WriteField("route_text_color"); csvroutes.NextRecord(); var routes = _Routes.Select(m => new { m.From, m.To }).Distinct().ToList(); for (int i = 0; i < routes.Count; i++) // Loop through List with for) { string FromAirportName = null; string ToAirportName = null; //using (var client = new WebClient()) //{ // client.Encoding = Encoding.UTF8; // string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + string.Format(APIPathBusAgencyStop); // var jsonapi = client.DownloadString(urlapi); // dynamic AirportResponseJson = JsonConvert.DeserializeObject(jsonapi); // FromAirportName = Convert.ToString(AirportResponseJson[0].name); //} //using (var client = new WebClient()) //{ // client.Encoding = Encoding.UTF8; // string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + APIPathAirport + routes[i].ToIATA; // var jsonapi = client.DownloadString(urlapi); // dynamic AirportResponseJson = JsonConvert.DeserializeObject(jsonapi); // ToAirportName = Convert.ToString(AirportResponseJson[0].name); //} csvroutes.WriteField(routes[i].From + routes[i].To); csvroutes.WriteField("Flota Occidental"); csvroutes.WriteField(routes[i].From + routes[i].To); csvroutes.WriteField(routes[i].From + " - " + routes[i].To); csvroutes.WriteField(""); // routes[i].FlightAircraft + ";" + _Routes[i].FlightAirline + ";" + _Routes[i].FlightOperator + ";" + _Routes[i].FlightCodeShare csvroutes.WriteField(700); csvroutes.WriteField(""); csvroutes.WriteField(""); csvroutes.WriteField(""); csvroutes.NextRecord(); } } // stops.txt List <string> agencyairportsiata = _Routes.SelectMany(m => new string[] { m.From, m.To }) .Distinct() .ToList(); using (var gtfsstops = new StreamWriter(@"gtfs\\stops.txt")) { // Route record var csvstops = new CsvWriter(gtfsstops); csvstops.Configuration.Delimiter = ","; csvstops.Configuration.Encoding = Encoding.UTF8; csvstops.Configuration.TrimFields = true; // header csvstops.WriteField("stop_id"); csvstops.WriteField("stop_name"); csvstops.WriteField("stop_desc"); csvstops.WriteField("stop_lat"); csvstops.WriteField("stop_lon"); csvstops.WriteField("zone_id"); csvstops.WriteField("stop_url"); csvstops.WriteField("stop_timezone"); csvstops.NextRecord(); for (int i = 0; i < agencyairportsiata.Count; i++) // Loop through List with for) { // Using API for airport Data. //using (var client = new WebClient()) //{ // client.Encoding = Encoding.UTF8; // string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + APIPathAirport + agencyairportsiata[i]; // var jsonapi = client.DownloadString(urlapi); // dynamic AirportResponseJson = JsonConvert.DeserializeObject(jsonapi); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].code)); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].name)); //csvstops.WriteField(""); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].lat)); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].lng)); //csvstops.WriteField(""); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].website)); //csvstops.WriteField(Convert.ToString(AirportResponseJson[0].timezone)); //csvstops.NextRecord(); csvstops.WriteField("FO-BUS-" + agencyairportsiata[i]); csvstops.WriteField(agencyairportsiata[i]); csvstops.WriteField(""); csvstops.WriteField("LAT"); csvstops.WriteField("LNG"); csvstops.WriteField(""); csvstops.WriteField(""); csvstops.WriteField("America/Bogota"); csvstops.NextRecord(); //} } } Console.WriteLine("Creating GTFS File trips.txt, stop_times.txt, calendar.txt ..."); using (var gtfscalendar = new StreamWriter(@"gtfs\\calendar.txt")) { using (var gtfstrips = new StreamWriter(@"gtfs\\trips.txt")) { using (var gtfsstoptimes = new StreamWriter(@"gtfs\\stop_times.txt")) { // Headers var csvstoptimes = new CsvWriter(gtfsstoptimes); csvstoptimes.Configuration.Delimiter = ","; csvstoptimes.Configuration.Encoding = Encoding.UTF8; csvstoptimes.Configuration.TrimFields = true; // header csvstoptimes.WriteField("trip_id"); csvstoptimes.WriteField("arrival_time"); csvstoptimes.WriteField("departure_time"); csvstoptimes.WriteField("stop_id"); csvstoptimes.WriteField("stop_sequence"); csvstoptimes.WriteField("stop_headsign"); csvstoptimes.WriteField("pickup_type"); csvstoptimes.WriteField("drop_off_type"); csvstoptimes.WriteField("shape_dist_traveled"); csvstoptimes.WriteField("timepoint"); csvstoptimes.NextRecord(); var csvtrips = new CsvWriter(gtfstrips); csvtrips.Configuration.Delimiter = ","; csvtrips.Configuration.Encoding = Encoding.UTF8; csvtrips.Configuration.TrimFields = true; // header csvtrips.WriteField("route_id"); csvtrips.WriteField("service_id"); csvtrips.WriteField("trip_id"); csvtrips.WriteField("trip_headsign"); csvtrips.WriteField("trip_short_name"); csvtrips.WriteField("direction_id"); csvtrips.WriteField("block_id"); csvtrips.WriteField("shape_id"); csvtrips.WriteField("wheelchair_accessible"); csvtrips.WriteField("bikes_allowed"); csvtrips.NextRecord(); var csvcalendar = new CsvWriter(gtfscalendar); csvcalendar.Configuration.Delimiter = ","; csvcalendar.Configuration.Encoding = Encoding.UTF8; csvcalendar.Configuration.TrimFields = true; // header csvcalendar.WriteField("service_id"); csvcalendar.WriteField("monday"); csvcalendar.WriteField("tuesday"); csvcalendar.WriteField("wednesday"); csvcalendar.WriteField("thursday"); csvcalendar.WriteField("friday"); csvcalendar.WriteField("saturday"); csvcalendar.WriteField("sunday"); csvcalendar.WriteField("start_date"); csvcalendar.WriteField("end_date"); csvcalendar.NextRecord(); //1101 International Air Service //1102 Domestic Air Service //1103 Intercontinental Air Service //1104 Domestic Scheduled Air Service for (int i = 0; i < _Routes.Count; i++) // Loop through List with for) { // Calender csvcalendar.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightMonday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightTuesday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightWednesday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightThursday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightFriday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightSaterday)); csvcalendar.WriteField(Convert.ToInt32(_Routes[i].FlightSunday)); csvcalendar.WriteField(String.Format("{0:yyyyMMdd}", _Routes[i].FromDate)); csvcalendar.WriteField(String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvcalendar.NextRecord(); // Trips string FromAirportName = null; string ToAirportName = null; //using (var client = new WebClient()) //{ // client.Encoding = Encoding.UTF8; // string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + APIPathAirport + _Routes[i].FromIATA; // var jsonapi = client.DownloadString(urlapi); // dynamic AirportResponseJson = JsonConvert.DeserializeObject(jsonapi); // FromAirportName = Convert.ToString(AirportResponseJson[0].name); //} //using (var client = new WebClient()) //{ // client.Encoding = Encoding.UTF8; // string urlapi = ConfigurationManager.AppSettings.Get("APIUrl") + APIPathAirport + _Routes[i].ToIATA; // var jsonapi = client.DownloadString(urlapi); // dynamic AirportResponseJson = JsonConvert.DeserializeObject(jsonapi); // ToAirportName = Convert.ToString(AirportResponseJson[0].name); //} csvtrips.WriteField(_Routes[i].From + _Routes[i].To); csvtrips.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvtrips.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvtrips.WriteField(_Routes[i].To); csvtrips.WriteField(_Routes[i].From + _Routes[i].To); csvtrips.WriteField(""); csvtrips.WriteField(""); csvtrips.WriteField(""); csvtrips.WriteField("1"); csvtrips.WriteField(""); csvtrips.NextRecord(); // Depart Record csvstoptimes.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvstoptimes.WriteField(String.Format("{0:HH:mm:ss}", _Routes[i].DepartTime)); csvstoptimes.WriteField(String.Format("{0:HH:mm:ss}", _Routes[i].DepartTime)); csvstoptimes.WriteField(_Routes[i].From); csvstoptimes.WriteField("0"); csvstoptimes.WriteField(""); csvstoptimes.WriteField("0"); csvstoptimes.WriteField("0"); csvstoptimes.WriteField(""); csvstoptimes.WriteField(""); csvstoptimes.NextRecord(); // Arrival Record if (!_Routes[i].FlightNextDayArrival) { csvstoptimes.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvstoptimes.WriteField(String.Format("{0:HH:mm:ss}", _Routes[i].ArrivalTime)); csvstoptimes.WriteField(String.Format("{0:HH:mm:ss}", _Routes[i].ArrivalTime)); csvstoptimes.WriteField(_Routes[i].To); csvstoptimes.WriteField("2"); csvstoptimes.WriteField(""); csvstoptimes.WriteField("0"); csvstoptimes.WriteField("0"); csvstoptimes.WriteField(""); csvstoptimes.WriteField(""); csvstoptimes.NextRecord(); } else { //add 24 hour for the gtfs time int hour = _Routes[i].ArrivalTime.Hour; hour = hour + 24; int minute = _Routes[i].ArrivalTime.Minute; string strminute = minute.ToString(); if (strminute.Length == 1) { strminute = "0" + strminute; } csvstoptimes.WriteField(_Routes[i].From + _Routes[i].To + String.Format("{0:yyyyMMdd}", _Routes[i].FromDate) + String.Format("{0:yyyyMMdd}", _Routes[i].ToDate)); csvstoptimes.WriteField(hour + ":" + strminute + ":00"); csvstoptimes.WriteField(hour + ":" + strminute + ":00"); csvstoptimes.WriteField(_Routes[i].To); csvstoptimes.WriteField("2"); csvstoptimes.WriteField(""); csvstoptimes.WriteField("0"); csvstoptimes.WriteField("0"); csvstoptimes.WriteField(""); csvstoptimes.WriteField(""); csvstoptimes.NextRecord(); } } } } } // Create Zip File string startPath = gtfsDir; string zipPath = myDir + "\\BUS-FlotaOccidental.zip"; if (File.Exists(zipPath)) { File.Delete(zipPath); } ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, false); }
private static bool TryParseDateMicrosoft(string text, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt) { string value = text.Substring(6, text.Length - 8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index == -1) { index = value.IndexOf('-', 1); } #if !NET20 TimeSpan offset = TimeSpan.Zero; #endif if (index != -1) { kind = DateTimeKind.Local; #if !NET20 offset = ReadOffset(value.Substring(index)); #endif value = value.Substring(0, index); } long javaScriptTicks; if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out javaScriptTicks)) { dt = null; return(false); } DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(javaScriptTicks); #if !NET20 if (dateParseHandling == DateParseHandling.DateTimeOffset) { dt = new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset); return(true); } #endif DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } dt = EnsureDateTime(dateTime, dateTimeZoneHandling); return(true); }
public OpeningPeriod(TimeSpan startTime, TimeSpan duration, DateTime?specificDate = null) { this.StartTime = specificDate?.Add(startTime) ?? DateTime.Today.Add(startTime); this.EndTime = this.StartTime.Add(duration); }
public static object ChangeType(object value, Type type) { if (value == null) { return(null); } MethodInfo mi; #warning [FB] REFACTOR: TYPE OBTAINED FROM SQLCLIENT. WILL CAUSE CONFLICTS WHEN OTHER DBs ARE ADDED. Type toType = TypeSystem.GetNonNullableType(type); Type fromType = value.GetType(); if (toType.IsAssignableFrom(fromType)) { return(value); } if (toType == typeof(Binary)) { if (fromType == typeof(byte[])) { return(new Binary((byte[])value)); } else if (fromType == typeof(Guid)) { return(new Binary(((Guid)value).ToByteArray())); } else { BinaryFormatter formatter = new BinaryFormatter(); byte[] streamArray; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, value); streamArray = stream.ToArray(); } return(new Binary(streamArray)); } } else if (toType == typeof(byte[])) { if (fromType == typeof(Binary)) { return(((Binary)value).ToArray()); } else if (fromType == typeof(Guid)) { return(((Guid)value).ToByteArray()); } else { BinaryFormatter formatter = new BinaryFormatter(); byte[] returnValue; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, value); returnValue = stream.ToArray(); } return(returnValue); } } else if (fromType == typeof(byte[])) { if (toType == typeof(Guid)) { return(new Guid((byte[])value)); } else { BinaryFormatter formatter = new BinaryFormatter(); object returnValue; using (MemoryStream stream = new MemoryStream((byte[])value)) { returnValue = ChangeType(formatter.Deserialize(stream), toType); } return(returnValue); } } else if (fromType == typeof(Binary)) { if (toType == typeof(Guid)) { return(new Guid(((Binary)value).ToArray())); } else { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(((Binary)value).ToArray(), false)) { return(ChangeType(formatter.Deserialize(stream), toType)); } } } else if (toType.IsEnum) { if (fromType == typeof(string)) { string text = ((string)value).Trim(); return(Enum.Parse(toType, text)); } else { return(Enum.ToObject(toType, Convert.ChangeType(value, Enum.GetUnderlyingType(toType), Globalization.CultureInfo.InvariantCulture))); } } else if (fromType.IsEnum) { if (toType == typeof(string)) { return(Enum.GetName(fromType, value)); } else { return(Convert.ChangeType(Convert.ChangeType(value, Enum.GetUnderlyingType(fromType), Globalization.CultureInfo.InvariantCulture), toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType == typeof(TimeSpan)) { if (fromType == typeof(string)) { return(TimeSpan.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture)); } else if (fromType == typeof(DateTime)) { return(DateTime.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay); } else if (fromType == typeof(DateTimeOffset)) { return(DateTimeOffset.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay); } else { return(new TimeSpan((long)Convert.ChangeType(value, typeof(long), Globalization.CultureInfo.InvariantCulture))); } } else if (fromType == typeof(TimeSpan)) { if (toType == typeof(string)) { return(((TimeSpan)value).ToString("", Globalization.CultureInfo.InvariantCulture)); } else if (toType == typeof(DateTime)) { DateTime dt = new DateTime(); return(dt.Add((TimeSpan)value)); } else if (toType == typeof(DateTimeOffset)) { DateTimeOffset dto = new DateTimeOffset(); return(dto.Add((TimeSpan)value)); } else { return(Convert.ChangeType(((TimeSpan)value).Ticks, toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType == typeof(DateTime) && fromType == typeof(DateTimeOffset)) { return(((DateTimeOffset)value).DateTime); } else if (toType == typeof(DateTimeOffset) && fromType == typeof(DateTime)) { return(new DateTimeOffset((DateTime)value)); } else if (toType == typeof(string) && !(typeof(IConvertible).IsAssignableFrom(fromType))) { if (fromType == typeof(char[])) { return(new String((char[])value)); } else { return(value.ToString()); } } else if (fromType == typeof(string)) { if (toType == typeof(Guid)) { return(new Guid((string)value)); } else if (toType == typeof(char[])) { return(((String)value).ToCharArray()); } else if (toType == typeof(System.Xml.Linq.XDocument) && (string)value == string.Empty) { return(new System.Xml.Linq.XDocument()); } else if (!(typeof(IConvertible).IsAssignableFrom(toType)) && (mi = toType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, StringArg, null)) != null) { try { return(SecurityUtils.MethodInfoInvoke(mi, null, new object[] { value })); } catch (TargetInvocationException t) { throw t.GetBaseException(); } } else { return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(IQueryable <>) && typeof(IEnumerable <>).MakeGenericType(toType.GetGenericArguments()[0]).IsAssignableFrom(fromType) ) { return(Queryable.AsQueryable((IEnumerable)value)); } else { try { return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture)); } catch (InvalidCastException) { throw Error.CouldNotConvert(fromType, toType); } } }
private void Get_Time(out Int64 currentTime) //获取时间并返回该值 { currentTime = 0; DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); Get_goodsinfo(out String[] goodsinfo); if (unifritl.Text == "联通时间:") { try { String unifritimep = "m.client.10010.com/welfare-mall-front-activity/mobile/activity/getCurrentTimeMillis/v2"; String unifritimepr = Urlresp(unifritimep, null, null, 2000); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); Dictionary <String, Object> unifritimeprd = (Dictionary <String, Object>)javaScriptSerializer.DeserializeObject(unifritimepr); Object resdata = unifritimeprd["resdata"]; Dictionary <String, Object> resdataD = (Dictionary <String, Object>)(resdata); currentTime = Int64.Parse(resdataD["currentTime"].ToString()); } catch (System.Net.WebException) { Get_Time(out currentTime); } catch (System.NullReferenceException) { Get_Time(out currentTime); } } else if (unifritl.Text == "本地时间:") { currentTime = (DateTime.Now.Ticks - startTime.Ticks) / 10000; } if (String.Compare(startTime.AddMilliseconds(currentTime).ToString("HH:mm:ss.fff"), startTime.Add(TimeSpan.FromMilliseconds(Double.Parse(goodsinfo[0]))).AddMinutes(-1).ToString("HH:mm:ss.fff")) < 0 || String.Compare(startTime.AddMilliseconds(currentTime).ToString("HH:mm:ss.fff"), startTime.Add(TimeSpan.FromMilliseconds(Double.Parse(goodsinfo[0]))).AddSeconds(3).ToString("HH:mm:ss.fff")) > 0) { System.Threading.Thread.Sleep(1000); unifrit.Text = startTime.AddMilliseconds(currentTime).ToString("yyyy-MM-dd HH:mm:ss"); } else { System.Threading.Thread.Sleep(10); unifrit.Text = startTime.AddMilliseconds(currentTime).ToString("yyyy-MM-dd HH:mm:ss.fff"); } }
/// <summary> /// Calculate and set the EndTimeOfDay using count, interval and StarTimeOfDay. This means /// that these must be set before this method is call. /// </summary> /// <param name="count"></param> /// <returns>the updated DailyTimeIntervalScheduleBuilder</returns> public DailyTimeIntervalScheduleBuilder EndingDailyAfterCount(int count) { if (count <= 0) { throw new ArgumentException("Ending daily after count must be a positive number!"); } if (startTimeOfDayUtc == null) { throw new ArgumentException("You must set the StartDailyAt() before calling this EndingDailyAfterCount()!"); } DateTimeOffset today = SystemTime.UtcNow(); DateTimeOffset startTimeOfDayDate = startTimeOfDayUtc.GetTimeOfDayForDate(today).Value; DateTimeOffset maxEndTimeOfDayDate = TimeOfDay.HourMinuteAndSecondOfDay(23, 59, 59).GetTimeOfDayForDate(today).Value; //apply proper offsets according to timezone TimeZoneInfo targetTimeZone = timeZone ?? TimeZoneInfo.Local; startTimeOfDayDate = new DateTimeOffset(startTimeOfDayDate.DateTime, targetTimeZone.GetUtcOffset(startTimeOfDayDate.DateTime)); maxEndTimeOfDayDate = new DateTimeOffset(maxEndTimeOfDayDate.DateTime, targetTimeZone.GetUtcOffset(maxEndTimeOfDayDate.DateTime)); TimeSpan remainingMillisInDay = maxEndTimeOfDayDate - startTimeOfDayDate; TimeSpan intervalInMillis = TimeSpan.Zero; if (intervalUnit == IntervalUnit.Second) { intervalInMillis = TimeSpan.FromSeconds(interval); } else if (intervalUnit == IntervalUnit.Minute) { intervalInMillis = TimeSpan.FromSeconds(interval * 60); } else if (intervalUnit == IntervalUnit.Hour) { intervalInMillis = TimeSpan.FromSeconds(interval * 60 * 24); } else { throw new ArgumentException("The IntervalUnit: " + intervalUnit + " is invalid for this trigger."); } if (remainingMillisInDay < intervalInMillis) { throw new ArgumentException("The startTimeOfDay is too late with given Interval and IntervalUnit values."); } long maxNumOfCount = (remainingMillisInDay.Ticks / intervalInMillis.Ticks); if (count > maxNumOfCount) { throw new ArgumentException("The given count " + count + " is too large! The max you can set is " + maxNumOfCount); } TimeSpan incrementInMillis = TimeSpan.FromTicks((count - 1) * intervalInMillis.Ticks); DateTimeOffset endTimeOfDayDate = startTimeOfDayDate.Add(incrementInMillis); if (endTimeOfDayDate > maxEndTimeOfDayDate) { throw new ArgumentException("The given count " + count + " is too large! The max you can set is " + maxNumOfCount); } DateTime cal = SystemTime.UtcNow().Date; cal = cal.Add(endTimeOfDayDate.TimeOfDay); endTimeOfDayUtc = TimeOfDay.HourMinuteAndSecondOfDay(cal.Hour, cal.Minute, cal.Second); return(this); }
private static bool TryParseDateTime(byte[] chars, int offset, int count, out DateTime result) { int offsetMax = offset + count; result = DateTime.MaxValue; if (count < 19) { return(false); } // 1 2 3 // 012345678901234567890123456789012 // "yyyy-MM-ddTHH:mm:ss" // "yyyy-MM-ddTHH:mm:ss.fffffff" // "yyyy-MM-ddTHH:mm:ss.fffffffZ" // "yyyy-MM-ddTHH:mm:ss.fffffff+xx:yy" // "yyyy-MM-ddTHH:mm:ss.fffffff-xx:yy" if (chars[offset + 4] != '-' || chars[offset + 7] != '-' || chars[offset + 10] != 'T' || chars[offset + 13] != ':' || chars[offset + 16] != ':') { return(false); } int year = ToInt32D4(chars, offset + 0, 4); int month = ToInt32D2(chars, offset + 5); int day = ToInt32D2(chars, offset + 8); int hour = ToInt32D2(chars, offset + 11); int minute = ToInt32D2(chars, offset + 14); int second = ToInt32D2(chars, offset + 17); if ((year | month | day | hour | minute | second) < 0) { return(false); } DateTimeKind kind = DateTimeKind.Unspecified; offset += 19; int ticks = 0; if (offset < offsetMax && chars[offset] == '.') { offset++; int digitOffset = offset; while (offset < offsetMax) { byte ch = chars[offset]; if (ch < '0' || ch > '9') { break; } offset++; } int digitCount = offset - digitOffset; if (digitCount < 1 || digitCount > 7) { return(false); } ticks = ToInt32D7(chars, digitOffset, digitCount); if (ticks < 0) { return(false); } for (int i = digitCount; i < 7; ++i) { ticks *= 10; } } bool isLocal = false; int hourDelta = 0; int minuteDelta = 0; if (offset < offsetMax) { byte ch = chars[offset]; if (ch == 'Z') { offset++; kind = DateTimeKind.Utc; } else if (ch == '+' || ch == '-') { offset++; if (offset + 5 > offsetMax || chars[offset + 2] != ':') { return(false); } kind = DateTimeKind.Utc; isLocal = true; hourDelta = ToInt32D2(chars, offset); minuteDelta = ToInt32D2(chars, offset + 3); if ((hourDelta | minuteDelta) < 0) { return(false); } if (ch == '+') { hourDelta = -hourDelta; minuteDelta = -minuteDelta; } offset += 5; } } if (offset < offsetMax) { return(false); } DateTime value; try { value = new DateTime(year, month, day, hour, minute, second, kind); } catch (ArgumentException) { return(false); } if (ticks > 0) { value = value.AddTicks(ticks); } if (isLocal) { try { TimeSpan ts = new TimeSpan(hourDelta, minuteDelta, 0); if (hourDelta >= 0 && (value < DateTime.MaxValue - ts) || hourDelta < 0 && (value > DateTime.MinValue - ts)) { value = value.Add(ts).ToLocalTime(); } else { value = value.ToLocalTime().Add(ts); } } catch (ArgumentOutOfRangeException) // Overflow { return(false); } } result = value; return(true); }
//Sätter tiden public void setTime() { tiSp = new TimeSpan(hour, minute, 0); alarmTime.Add(tiSp); }
public static DateTime?Add(this DateTime?dateTime, TimeSpan?time) { return(dateTime?.Add(time ?? TimeSpan.Zero)); }
public MatchReadyQueue() { playersConnected = new List <int>(); timeEnd = DateTime.Now; timeEnd.Add(MatchMakerConfig.MatchReadyQueueTime); }
/// <summary> /// Performs addition of a date time and a time span in a global context. /// </summary> /// <param name="value">The value.</param> /// <param name="timeSpan">The time span.</param> /// <returns>The DateTime after incrementing by TimeSpan.</returns> public virtual DateTime OnIncrement(DateTime value, TimeSpan timeSpan) { // special case: value is at DateTime.MaxValue if (DateTime.MaxValue.Date == value.Date && value.TimeOfDay.Add(timeSpan) > TimeSpan.FromDays(1)) { return value.AddDays(-1).Add(timeSpan); } return value.Add(timeSpan); }
/// <summary> /// 初始化常用数据 /// </summary> /// <returns>如果有错误,返回-1,如果考试结束或不存在,则返回0;正常返回1</returns> private int initData() { //如果为空,则返回-1,表示错误 if (result == "") { return(-1); } resXml.LoadXml(result, false); XmlNode xn = resXml.SelectSingleNode("results"); //试卷id,考试id int tpid; int.TryParse(xn.Attributes["tpid"].Value, out tpid); int examid; int.TryParse(xn.Attributes["examid"].Value, out examid); //考试结束时间 long lover; long.TryParse(xn.Attributes["overtime"].Value, out lover); lover = lover * 10000; DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); TimeSpan toNow = new TimeSpan(lover); DateTime overTime = dtStart.Add(toNow); //得到转换后的时间 //学生Id,学生名称 int stid; int.TryParse(xn.Attributes["stid"].Value, out stid); string stname = xn.Attributes["stname"].Value.ToString(); //学生性别,分组,身份证号 int stsex; int.TryParse(xn.Attributes["stsex"].Value, out stsex); int stsid; int.TryParse(xn.Attributes["stsid"].Value, out stsid); string stcardid = xn.Attributes["stcardid"].Value.ToString(); //学科Id,学科名称 int sbjid; int.TryParse(xn.Attributes["sbjid"].Value, out sbjid); string sbjname = xn.Attributes["sbjname"].Value.ToString(); //UID与考试主题 string uid = xn.Attributes["uid"].Value.ToString(); string theme = xn.Attributes["theme"].Value.ToString(); //提交方式,1为自动提交,2为交卷 int patter = Convert.ToInt32(xn.Attributes["patter"].Value); // Song.Entities.Examination exam = Business.Do <IExamination>().ExamSingle(examid); //如果考试不存在 if (exam == null) { return(0); } //如果考试已经结束 int span = (int)exam.Exam_Span; //if (DateTime.Now > ((DateTime)exam.Exam_Date).AddMinutes(span + 5)) return 0; try { Song.Entities.ExamResults exr = new ExamResults(); exr.Exr_IsSubmit = patter == 2; exr.Exam_ID = examid; exr.Exam_Name = exam.Exam_Name; exr.Tp_Id = tpid; exr.Ac_ID = stid; exr.Ac_Name = stname; exr.Sts_ID = stsid; exr.Ac_Sex = stsex; exr.Ac_IDCardNumber = stcardid; exr.Sbj_ID = sbjid; exr.Sbj_Name = sbjname; exr.Exr_IP = WeiSha.Common.Browser.IP; exr.Exr_Mac = WeiSha.Common.Request.UniqueID(); //原本是网卡的mac地址,此处不再记录 exr.Exr_Results = result; exr.Exam_UID = uid; exr.Exam_Title = theme; exr.Exr_IsSubmit = patter == 2; if (exr.Exr_IsSubmit) { exr.Exr_SubmitTime = DateTime.Now; } exr.Exr_OverTime = overTime; exr.Exr_CrtTime = DateTime.Now; exr.Exr_LastTime = DateTime.Now; //Business.Do<IExamination>().ResultSubmit(exr); string cacheUid = string.Format("ExamResults:{0}-{1}-{2}", examid, tpid, stid); //缓存的uid Business.Do <IQuestions>().CacheUpdate(exr, -1, cacheUid); return(1); } catch { return(0); } }