public static Statistics GetStatistics(IList<PlayTime> playTimes, IList<Program> programs, TimePeriod timePeriod) { var helper = new DateTimeHelper(); List<PlayTime> times; switch (timePeriod) { case TimePeriod.Day: times = playTimes.Where(x => helper.IsToday(x.Timestamp)).ToList(); break; case TimePeriod.Week: times = playTimes.Where(x => helper.IsCurrentWeek(x.Timestamp)).ToList(); break; case TimePeriod.Month: times = playTimes.Where(x => helper.IsCurrentMonth(x.Timestamp)).ToList(); break; case TimePeriod.Year: times = playTimes.Where(x => helper.IsCurrentYear(x.Timestamp)).ToList(); break; case TimePeriod.Ever: times = playTimes.ToList(); break; default: throw new ArgumentOutOfRangeException(nameof(timePeriod), timePeriod, null); } var statistic = new Statistics { TimePeriod = timePeriod, TimePlayed = TimeSpan.FromMilliseconds(times.Select(x => x.Duration.TotalMilliseconds).Sum()) }; var games = new List<GameStatistic>(); foreach (var gameId in times.Select(x => x.Program).Distinct()) { var game = programs.FirstOrDefault(x => x.Guid == gameId); if (game == null) continue; games.Add(new GameStatistic { Name = game.Name, Icon = game.Icon, Guid = game.Guid, ChartColor = GetColor(game), TimePlayed = TimeSpan.FromMilliseconds( times.Where(x => x.Program == game.Guid).Select(x => x.Duration.TotalMilliseconds).Sum()) }); } statistic.Games = games.OrderByDescending(x => x.TimePlayed).ToList(); return statistic; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //filterContext.HttpContext.Response.Write("Before action:"); var configs = new ConfigsController(null); var startDate = ((IEnumerable<dynamic>)configs.Get("StartDate")).FirstOrDefault().Value; var endDate = ((IEnumerable<dynamic>)configs.Get("EndDate")).FirstOrDefault().Value; if (startDate == null || endDate == null) { throw new Exception("Configuration Error: StartDate or EndDate is NULL"); } var parseDate = new DateTime(); if (DateTime.TryParse(startDate, out parseDate) == false || DateTime.TryParse(endDate, out parseDate) == false) { throw new Exception("Configuration Error: StartDate or EndDate is not of type DateTime"); } var date = new DateTime(); if (filterContext.HttpContext.Session["SessionDate"] != null) { date = DateTime.Parse(filterContext.HttpContext.Session["SessionDate"].ToString()); } else { date = new DateTimeHelper().GetAdjustedDate; //DateTime.Now; } var appStart = DateTime.Parse(startDate); var appEnd = DateTime.Parse(endDate); if (date < appStart) { //Logger.LogInfo("Coming Soon"); filterContext.HttpContext.Response.Redirect("/Public/ComingSoon"); } if (date >= appEnd) { //Logger.LogInfo("Closed"); filterContext.HttpContext.Response.Redirect("/Public/Closed"); } }
public virtual ActionResult Edit(int id, FormCollection collection) { collection["UpdatedAt"] = new DateTimeHelper().GetAdjustedDate.ToString(); //DateTime.Now.ToString(); var model = _table.CreateFrom(collection); try { // TODO: Add update logic here _table.Update(model, id); this.FlashInfo("Item Saved"); return RedirectToAction("Index"); } catch (Exception x) { TempData["Error"] = "There was a problem editing this record"; ModelState.AddModelError(string.Empty, x.Message); return View(model); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var sign_key = ConfigurationManager.AppSettings[ConfigKey]; if (!ValidateHelper.IsPlumpString(sign_key)) { throw new Exception("没有配置签名的约定key"); } var reqparams = new NameValueCollection(); AddToNameValueCollection(ref reqparams, filterContext.HttpContext.Request.Form); AddToNameValueCollection(ref reqparams, filterContext.HttpContext.Request.QueryString); #region 验证时间戳 var timespan = ConvertHelper.GetInt64(reqparams["timespan"], -1); if (timespan < 0) { filterContext.Result = ResultHelper.BadRequest("缺少时间戳"); return; } var server_timestamp = DateTimeHelper.GetTimeStamp(); if (server_timestamp - timespan > 5 || server_timestamp < timespan) { filterContext.Result = ResultHelper.BadRequest("请求内容已经过期"); return; } #endregion #region 验证签名 var signKey = "sign"; var sign = ConvertHelper.GetString(reqparams[signKey]).ToUpper(); if (!ValidateHelper.IsAllPlumpString(sign)) { filterContext.Result = ResultHelper.BadRequest("请求被拦截,获取不到签名"); return; } //排序的字典 var dict = new SortedDictionary <string, string>(new MyStringComparer()); foreach (var p in reqparams.AllKeys) { if (!ValidateHelper.IsAllPlumpString(p) || p == signKey) { continue; } if (p.Length > 32 || reqparams[p]?.Length > 32) { continue; } dict[p] = ConvertHelper.GetString(reqparams[p]); } var strdata = dict.ToUrlParam(); strdata += sign_key; strdata = strdata.ToLower(); var md5 = strdata.ToMD5().ToUpper(); if (sign != md5) { var msg = $"服务器加密:{md5}客户端加密:{sign}服务器排序:{strdata}"; filterContext.Result = ResultHelper.BadRequest(msg); return; } #endregion base.OnActionExecuting(filterContext); }
/// <summary> /// First day of the year of the passed in date /// </summary> public static DateTime StartOfYear(this DateTime referenceDate) => DateTimeHelper.StartOfYear(referenceDate);
/// <summary> /// Check if two dates are in the same year ignoring time /// </summary> public static bool IsSameYearAs(this DateTime?referenceDate, DateTime?otherDate) => DateTimeHelper.IsSameYearAs(referenceDate, otherDate);
/// <summary> /// Check if referenceDate is at least one day after the otherDate ignoring time /// </summary> public static bool IsAtLeastOneDayAfter(this DateTime?referenceDate, DateTime?otherDate) => DateTimeHelper.IsAtLeastOneDayAfter(referenceDate, otherDate);
/// <summary> /// The bind data. /// </summary> private void BindData() { DataSet ds = this.Get <YafDbBroker>().BoardLayout( this.PageContext.PageBoardID, this.PageContext.PageUserID, this.PageContext.PageCategoryID, this.PageContext.PageForumID); if (ds.Tables["Forum"].HasRows()) { this.ForumList.DataSource = ds.Tables["Forum"].Rows; this.SubForums.Visible = true; } this.Pager.PageSize = this.Get <YafBoardSettings>().TopicsPerPage; // when userId is null it returns the count of all deleted messages int?userId = null; // get the userID to use for the deleted posts count... if (!this.Get <YafBoardSettings>().ShowDeletedMessagesToAll) { // only show deleted messages that belong to this user if they are not admin/mod if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess) { userId = this.PageContext.PageUserID; } } DataTable dt = LegacyDb.announcements_list( this.PageContext.PageForumID, userId, null, DateTime.UtcNow, 0, 10, this.Get <YafBoardSettings>().UseStyledNicks, true, this.Get <YafBoardSettings>().UseReadTrackingByDatabase); if (dt != null) { dt = this.StyleTransformDataTable(dt); } int baseSize = this.Get <YafBoardSettings>().TopicsPerPage; this.Announcements.DataSource = dt; /*if (!m_bIgnoreQueryString && Request.QueryString["p"] != null) * { * // show specific page (p is 1 based) * int tPage = (int)Security.StringToLongOrRedirect(Request.QueryString["p"]); * * if (tPage > 0) * { * Pager.CurrentPageIndex = tPage - 1; * } * }*/ int nCurrentPageIndex = this.Pager.CurrentPageIndex; DataTable dtTopics; if (this._showTopicListSelected == 0) { dtTopics = LegacyDb.topic_list( this.PageContext.PageForumID, userId, DateTimeHelper.SqlDbMinTime(), DateTime.UtcNow, nCurrentPageIndex, baseSize, this.Get <YafBoardSettings>().UseStyledNicks, true, this.Get <YafBoardSettings>().UseReadTrackingByDatabase); if (dtTopics != null) { dtTopics = this.StyleTransformDataTable(dtTopics); } } else { int[] days = { 1, 2, 7, 14, 31, 2 * 31, 6 * 31, 356 }; DateTime date = DateTime.UtcNow.AddDays(-days[this._showTopicListSelected]); dtTopics = LegacyDb.topic_list( this.PageContext.PageForumID, userId, date, DateTime.UtcNow, nCurrentPageIndex, baseSize, this.Get <YafBoardSettings>().UseStyledNicks, true, this.Get <YafBoardSettings>().UseReadTrackingByDatabase); if (dtTopics != null) { dtTopics = this.StyleTransformDataTable(dtTopics); } } this.TopicList.DataSource = dtTopics; this.DataBind(); // setup the show topic list selection after data binding this.ShowList.SelectedIndex = this._showTopicListSelected; this.Get <IYafSession>().ShowList = this._showTopicListSelected; if (dtTopics != null && dtTopics.HasRows()) { this.Pager.Count = dtTopics.AsEnumerable().First().Field <int>("TotalRows"); } }
private void BindList() { lvList.Items.Clear(); int iCount = 1; string sql = @" SELECT PaymentFactorId, WorkplaceId, WorkplaceCode, CurrencyCode, EventCode, StartOn, EndOn, FactorRate, CreatedOn, CreatedBy, ModifiedOn, ModifiedBy FROM vwPaymentFactorList"; sql += _CampaignType == EnumHelper.CampaignType.TenderType ? " WHERE Retired = 0 AND TypeId IS NOT NULL" : _CampaignType == EnumHelper.CampaignType.EventCode ? " WHERE Retired = 0 AND EventCode IS NOT NULL AND EventCode <> ''" : ""; /** * System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); * cmd.CommandText = sql; * cmd.CommandTimeout = ConfigHelper.CommandTimeout; * cmd.CommandType = CommandType.Text; * * using (SqlDataReader reader = SqlHelper.Default.ExecuteReader(cmd)) * { * while (reader.Read()) * { * ListViewItem listItem = lvList.Items.Add(reader.GetGuid(0).ToString()); * listItem.SubItems.Add(reader.GetGuid(1).ToString()); * listItem.SubItems.Add(iCount.ToString()); * listItem.SubItems.Add(reader.GetString(2)); // Workplace * * if (this.PaymentFactorType == FactorType.Currency) * { * listItem.SubItems.Add(reader.GetString(3)); // Currency * } * else if (this.PaymentFactorType == FactorType.EventCode) * { * listItem.SubItems.Add(reader.GetString(4)); // Event Code * } * * listItem.SubItems.Add(DateTimeHelper.DateTimeToString(reader.GetDateTime(5), false)); // Start date * listItem.SubItems.Add(DateTimeHelper.DateTimeToString(reader.GetDateTime(6), false)); // End date * listItem.SubItems.Add(reader.GetDecimal(7).ToString("n" + SystemInfoHelper.Settings.GetQtyDecimalPoint().ToString())); // Factor rate * listItem.SubItems.Add(DateTimeHelper.DateTimeToString(reader.GetDateTime(8), true)); // Created On * listItem.SubItems.Add(DateTimeHelper.DateTimeToString(reader.GetDateTime(10), true)); // Modified On * * iCount++; * } * } */ using (var ctx = new EF6.RT2020Entities()) { var list = ctx.PromotionPaymentFactor .SqlQuery(string.Format("Select * from PromotionPaymentFactor {0}", sql.Substring(sql.IndexOf("WHERE")))) .AsNoTracking() .ToList(); foreach (var item in list) { ListViewItem listItem = lvList.Items.Add(item.PaymentFactorId.ToString()); listItem.SubItems.Add(item.WorkplaceId.ToString()); listItem.SubItems.Add(iCount.ToString()); listItem.SubItems.Add(item.Workplace != null ? item.Workplace.WorkplaceCode : ""); listItem.SubItems.Add(item.TypeId != null ? item.PosTenderType.TypeName : ""); listItem.SubItems.Add(item.EventCode); listItem.SubItems.Add(DateTimeHelper.DateTimeToString(item.StartOn.Value, false)); listItem.SubItems.Add(DateTimeHelper.DateTimeToString(item.EndOn.Value, false)); listItem.SubItems.Add(item.FactorRate.ToString("n2")); // " + SystemInfoHelper.Settings.GetQtyDecimalPoint().ToString())); listItem.SubItems.Add(DateTimeHelper.DateTimeToString(item.CreatedOn, true)); listItem.SubItems.Add(DateTimeHelper.DateTimeToString(item.ModifiedOn, true)); iCount++; } } lvList.SelectedIndex = -1; }
/// <summary> /// 将实体转为XML /// </summary> /// <typeparam name="T">RequestMessage或ResponseMessage</typeparam> /// <param name="entity">实体</param> /// <returns></returns> public static XDocument ConvertEntityToXml <T>(this T entity) where T : class { //entity = entity ?? new T(); if (entity == null) { throw new Senparc.CO2NET.Exceptions.BaseException("entity 参数不能为 null"); } //XmlSerializer xmldes = new XmlSerializer(typeof(T)); var doc = new XDocument(); doc.Add(new XElement("xml")); var root = doc.Root; /* 注意! * 经过测试,微信对字段排序有严格要求,这里对排序进行强制约束 —— 目前已经不敏感 20180904 */ //var propNameOrder = new List<string>() { "ToUserName", "FromUserName", "CreateTime", "MsgType" }; //不同返回类型需要对应不同特殊格式的排序 //if (entity is ResponseMessageNews) //{ // propNameOrder.AddRange(new[] { "ArticleCount", "Articles", "FuncFlag",/*以下是Atricle属性*/ "Title ", "Description ", "PicUrl", "Url" }); //} //else if (entity is ResponseMessageTransfer_Customer_Service) //{ // propNameOrder.AddRange(new[] { "TransInfo", "KfAccount", "FuncFlag" }); //} //else if (entity is ResponseMessageMusic) //{ // propNameOrder.AddRange(new[] { "Music", "FuncFlag", "ThumbMediaId",/*以下是Music属性*/ "Title ", "Description ", "MusicUrl", "HQMusicUrl" }); //} //else if (entity is ResponseMessageImage) //{ // propNameOrder.AddRange(new[] { "Image",/*以下是Image属性*/ "MediaId " }); //} //else if (entity is ResponseMessageVoice) //{ // propNameOrder.AddRange(new[] { "Voice",/*以下是Voice属性*/ "MediaId " }); //} //else if (entity is ResponseMessageVideo) //{ // propNameOrder.AddRange(new[] { "Video",/*以下是Video属性*/ "MediaId ", "Title", "Description" }); //} //else //{ // //如Text类型 // propNameOrder.AddRange(new[] { "Content", "FuncFlag" }); //} //Func<string, int> orderByPropName = propNameOrder.IndexOf; var props = entity.GetType().GetProperties();//.OrderBy(p => orderByPropName(p.Name)).ToList(); foreach (var prop in props) { var propName = prop.Name; if (propName == "Articles") { //文章列表 var atriclesElement = new XElement("Articles"); var articales = prop.GetValue(entity, null) as List <Article>; foreach (var articale in articales) { var subNodes = ConvertEntityToXml(articale).Root.Elements(); atriclesElement.Add(new XElement("item", subNodes)); } root.Add(atriclesElement); } else if (propName == "TransInfo") { var transInfoElement = new XElement("TransInfo"); var transInfo = prop.GetValue(entity, null) as List <CustomerServiceAccount>; foreach (var account in transInfo) { var trans = ConvertEntityToXml(account).Root.Elements(); transInfoElement.Add(trans); } root.Add(transInfoElement); } else if (propName == "Music" || propName == "Image" || propName == "Video" || propName == "Voice") { //音乐、图片、视频、语音格式 var musicElement = new XElement(propName); var media = prop.GetValue(entity, null);// as Music; var subNodes = ConvertEntityToXml(media).Root.Elements(); musicElement.Add(subNodes); root.Add(musicElement); } else if (propName == "PicList") { var picListElement = new XElement("PicList"); var picItems = prop.GetValue(entity, null) as List <PicItem>; foreach (var picItem in picItems) { var item = ConvertEntityToXml(picItem).Root.Elements(); picListElement.Add(item); } root.Add(picListElement); } else if (propName == "KfAccount") { //TODO:可以交给string处理 root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower())); } else { //其他非特殊类型 switch (prop.PropertyType.Name) { case "String": root.Add(new XElement(propName, new XCData(prop.GetValue(entity, null) as string ?? ""))); break; case "DateTime": root.Add(new XElement(propName, DateTimeHelper.GetUnixDateTime(((DateTime)prop.GetValue(entity, null))))); break; case "DateTimeOffset": root.Add(new XElement(propName, DateTimeHelper.GetUnixDateTime((DateTimeOffset)prop.GetValue(entity, null)))); break; case "Boolean": if (propName == "FuncFlag") { root.Add(new XElement(propName, (bool)prop.GetValue(entity, null) ? "1" : "0")); } else { goto default; } break; case "ResponseMsgType": root.Add(new XElement(propName, new XCData(prop.GetValue(entity, null).ToString().ToLower()))); break; case "Article": root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower())); break; case "TransInfo": root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower())); break; default: #if NET35 || NET40 || NET45 if (prop.PropertyType.IsClass && prop.PropertyType.IsPublic) #else if (prop.PropertyType.GetTypeInfo().IsClass&& prop.PropertyType.GetTypeInfo().IsPublic) #endif { //自动处理其他实体属性 var subEntity = prop.GetValue(entity, null); var subNodes = ConvertEntityToXml(subEntity).Root.Elements(); root.Add(new XElement(propName, subNodes)); } else { root.Add(new XElement(propName, prop.GetValue(entity, null))); } break; } } } return(doc); }
protected string GetPurchasedOnInfo(GiftCard gc) { string result = DateTimeHelper.ConvertToUserTime(gc.CreatedOn, DateTimeKind.Utc).ToString(); return(result); }
public ActionResult AddOrder(CleanOrderDto dto, int rid) { dto.Hoster = Guid.Parse(User.Identity.GetUserId()); dto.Creation_Date = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY); dto.Creation_Time = DateTimeHelper.ConvertTimeToString(Utils.ServerNow.TimeOfDay, TimeFormats.HH_MM_AM); dto.Creation_At = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY) + " " + DateTimeHelper.ConvertTimeToString(Utils.ServerNow.TimeOfDay, TimeFormats.HH_MM_AM); dto.Room_ID = rid; dto.moshId = _fixOrderServices.getmoshbyroomId((int)rid); int i = _orderService.addOrder(dto); var room = _RoomService.GetById(rid); room.Isrequisted = true; _RoomService.Edit(room); roomrecDto roomrecDto = new roomrecDto(); roomrecDto.Room_Id = rid; roomrecDto.Recoed = " تم أضافة طلب تنظيف على الغرفة "; _roomrec.Add(roomrecDto); //NotifictationDto dto1 = new NotifictationDto(); //dto1.senderId = Guid.Parse(User.Identity.GetUserId()); //dto1.RevieverId = _RoomService.getMangerIdForRoom(Convert.ToInt32( rid)); //var roomnum = _RoomService.GetById(dto.Room_ID.Value).RoomNum; //var s1 = "الغرفة رقم"; //var s2 = roomnum; //var s3 = " بحاجة الى "; //var s4 = "&"; //var s5 = i; //var s6 = "تنظيف"; //dto1.NotDateTime = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY); //dto1.Room_ID = dto.Room_ID; //_notifictationService.Add(dto1); return(RedirectToAction("getAllRoom", "Room")); }
public ActionResult EndCleanOrder1(int id) { var cleanOrderDto = _orderService.GetById(id); var userdto = _userService.GetById(new Guid(User.Identity.GetUserId())); userdto.IsBusy = false; _userService.Edit(userdto, new Guid(User.Identity.GetUserId())); cleanOrderDto.enddate = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY) + " " + DateTimeHelper.ConvertTimeToString(Utils.ServerNow.TimeOfDay, TimeFormats.HH_MM_AM); cleanOrderDto.isFinished = true; _orderService.edit(cleanOrderDto); var rom = _RoomService.GetById(Convert.ToInt32(cleanOrderDto.Room_ID)); rom.isneedclean = false; rom.Isrequisted = false; _RoomService.Edit(rom); MysqlFetchingRoomData.SetCleanStatus(rom.RoomNum, rom.isneedclean); return(RedirectToAction("Check", "Equipment", rom.Id)); }
public ActionResult EndCleanOrder(CleanOrderDto dto) { var cleanOrderDto = _orderService.GetById(dto.Id); var id = User.Identity.GetUserId(); var guid = new Guid(id); var userdto = _userService.GetById(new Guid(User.Identity.GetUserId())); userdto.IsBusy = false; _userService.Edit(userdto, new Guid(User.Identity.GetUserId())); cleanOrderDto.enddate = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY) + " " + DateTimeHelper.ConvertTimeToString(Utils.ServerNow.TimeOfDay, TimeFormats.HH_MM_AM); cleanOrderDto.isFinished = true; cleanOrderDto.Istaked = true; var rom = _RoomService.GetById(Convert.ToInt32(cleanOrderDto.Room_ID)); cleanOrderDto.Roomnu = rom.RoomNum; _orderService.edit(cleanOrderDto); rom.isneedclean = false; rom.Isrequisted = false; _RoomService.Edit(rom); MysqlFetchingRoomData.SetCleanStatus(rom.RoomNum, rom.isneedclean); roomrecDto roomrecDto = new roomrecDto(); roomrecDto.Room_Id = (int)cleanOrderDto.Room_ID; roomrecDto.Recoed = _userService.GetById(guid).FullName.ToString() + "تم إنهاء طلب تنظيف من العامل "; _roomrec.Add(roomrecDto); return(RedirectToAction("getAllEquipmentsForcleaningEmp", "Equipment", new { Rid = rom.Id })); }
public ActionResult takeCleanOrder(CleanOrderDto ordd) { var dto = _orderService.GetById(ordd.Id); dto.startdate = DateTimeHelper.ConvertDateToString(Utils.ServerNow.Date, DateFormats.DD_MM_YYYY) + " " + DateTimeHelper.ConvertTimeToString(Utils.ServerNow.TimeOfDay, TimeFormats.HH_MM_AM); var id = User.Identity.GetUserId(); var guid = new Guid(id); var userdto = _userService.GetById(guid); dto.Istaked = true; userdto.IsBusy = true; dto.isFinished = false; _userService.Edit(userdto, guid); _orderService.edit(dto); TempData["ord"] = dto.Id; var rom = _RoomService.GetById(Convert.ToInt32(dto.Room_ID)); MysqlFetchingRoomData.setincleaning(rom.RoomNum.ToString(), false); roomrecDto roomrecDto = new roomrecDto(); roomrecDto.Room_Id = Convert.ToInt32(_orderService.GetById(dto.Id).Room_ID); roomrecDto.Recoed = "تم أستلام طلب تنظيف من العامل " + _userService.GetById(guid).FullName.ToString(); _roomrec.Add(roomrecDto); return(RedirectToAction("EndCleanOrder", new { Oid = dto.Id })); }
protected void btnSave_Click(object sender, EventArgs e) { try { UserProfileInfo objinfo = new UserProfileInfo(); string filename = ""; string thumbTarget = Server.MapPath("~/Modules/Admin/UserManagement/UserPic"); if (!Directory.Exists(thumbTarget)) { Directory.CreateDirectory(thumbTarget); } System.Drawing.Image.GetThumbnailImageAbort thumbnailImageAbortDelegate = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); if (fuImage.HasFile) { string fName = fuImage.PostedFile.FileName; FileInfo fi = new FileInfo(fName); fName = Path.GetFileName(fName); string ext = fi.Extension.ToLower(); if (ext == ".jpeg" || ext == ".jpg" || ext == ".png") { double fs = fuImage.PostedFile.ContentLength / (1024 * 1024); if (fs > 3) { ShowHideProfile(); ShowMessage("", GetSageMessage("UserManagement", "ImageTooLarge"), "", SageMessageType.Alert); return; } else { Random ran = new Random(); int rand = ran.Next(1111111, 9999999); if (!File.Exists(Server.MapPath("~/Modules/Admin/UserManagement/UserPic/" + fName))) { string fullfileName = Path.GetFileNameWithoutExtension(fName) + rand + ext; imgUser.ImageUrl = "~/Modules/Admin/UserManagement/UserPic/" + fullfileName; using (System.Drawing.Bitmap originalImage = new System.Drawing.Bitmap(fuImage.PostedFile.InputStream)) { using (System.Drawing.Image thumbnail = originalImage.GetThumbnailImage(500, 500, thumbnailImageAbortDelegate, IntPtr.Zero)) { thumbnail.Save(System.IO.Path.Combine(thumbTarget, fullfileName)); } } filename = fullfileName; } } } else { { ShowHideProfile(); ShowMessage("", GetSageMessage("UserManagement", "InvalidImageFormat"), "", SageMessageType.Error); return; } } } if (filename == "") { if (Session[SessionKeys.SageFrame_UserProfilePic] != null) { filename = Session[SessionKeys.SageFrame_UserProfilePic].ToString(); } btnDeleteProfilePic.Visible = false; } else { btnDeleteProfilePic.Visible = true; } objinfo.Image = filename; objinfo.UserName = GetUsername; objinfo.FirstName = txtFName.Text; objinfo.LastName = txtLName.Text; objinfo.FullName = txtFullName.Text; objinfo.Location = txtLocation.Text; objinfo.AboutYou = txtAboutYou.Text; //objinfo.Email = txtEmail1.Text + (txtEmail2.Text != "" ? "," + txtEmail2.Text : "") + (txtEmail3.Text != "" ? ',' + txtEmail3.Text : ""); objinfo.Email = txtEmail1.Text; objinfo.ResPhone = txtResPhone.Text; objinfo.MobilePhone = txtMobile.Text; objinfo.Others = txtOthers.Text; objinfo.AddedOn = DateTimeHelper.GetUtcTime(DateTime.Now); objinfo.AddedBy = GetUsername; objinfo.UpdatedOn = DateTimeHelper.GetUtcTime(DateTime.Now); objinfo.PortalID = GetPortalID; objinfo.UpdatedBy = GetUsername; objinfo.BirthDate = txtBirthDate.Text == string.Empty ? DateTimeHelper.GetUtcTime(falseDate) : DateTimeHelper.GetUtcTime(txtBirthDate.Text); objinfo.Gender = rdbGender.SelectedIndex; UserProfileController.AddUpdateProfile(objinfo); Session.Remove(SessionKeys.SageFrame_UserProfilePic); ShowMessage("", GetSageMessage("UserManagement", "UserProfileSavedSuccessfully"), "", SageMessageType.Success); } catch (Exception ex) { ProcessException(ex); } }
//========================================================================= /// <summary> /// �t�H�[�}�b�g���ꂽ�t�@�C������擾���� /// </summary> /// <remarks> /// </remarks> /// <history>2006/XX/XX �V�K�쐬</history> //========================================================================= public string GetFormattedFileName() { string formattedName, titleName, subTitleName; titleName = PathHelper.ToFileTitle(mParent.title); subTitleName = PathHelper.ToFileTitle(mSubTitle); try { string dateStr = ""; string timeStr = ""; string station = ""; if(this.HasPlan) { var helper = new DateTimeHelper( this.StartDateTime, Settings.Default.hoursPerDay - 24); dateStr = helper.ToShortDateString().Replace("/", ""); timeStr = helper.ToShortTimeString().Replace(":", ""); } station = Parent.tvStation; formattedName = string.Format( Settings.Default.saveNameFormat, titleName, mStoryNumber, subTitleName, dateStr, timeStr, station); } catch(Exception ex) { throw new UpdatingException("�ۑ��t�@�C��������������������܂���B"); } return formattedName; }
public ActionResult Index() { ISession session = NHibernateManager.OpenSession(); try { String cookieUsername = new CookieHelper().GetUserFromCookie(); User cookieUser = Glimpse.Models.User.FindByUsername(cookieUsername, session); if (cookieUser == null) { return(this.LogOut()); } User sessionUser = (User)Session[AccountController.USER_NAME]; if (sessionUser == null) { sessionUser = cookieUser; //cookieUser no tiene mailAccounts sessionUser.UpdateAccounts(session); Session[AccountController.USER_NAME] = sessionUser; } else if (sessionUser.Entity.Id != cookieUser.Entity.Id || sessionUser.Entity.Password != cookieUser.Entity.Password) { return(this.LogOut()); } ViewBag.MailErrors = ""; IList <MailAccount> mailAccounts = sessionUser.GetAccounts(); List <LabelEntity> accountLabels = new List <LabelEntity>(); List <LabelViewModel> viewLabels = new List <LabelViewModel>(); foreach (MailAccount mailAccount in mailAccounts) { accountLabels.AddRange(Label.FindByAccount(mailAccount.Entity, session)); try { if (!mailAccount.IsFullyConnected()) { mailAccount.ConnectFull(session); } Task.Factory.StartNew(() => MailsTasksHandler.StartSynchronization(mailAccount.Entity.Address)); } catch (InvalidAuthenticationException exc) { Log.LogException(exc, "No se puede conectar con IMAP, cambio el password de :" + mailAccount.Entity.Address + "."); ViewBag.MailErrors += "Glimpse no puede conectarse con la cuenta: " + mailAccount.Entity.Address + ". Por favor reconfigure la contraseña."; //TODO: ver como mostrar los mailAccounts que no se pudieron conectar en la Vista } catch (SocketException exc) { Log.LogException(exc, "Error al conectar con IMAP."); } } accountLabels = Label.RemoveDuplicates(accountLabels); DateTime oldestMailDate = mailAccounts.OrderBy(x => x.Entity.OldestMailDate) .Take(1) .Select(x => x.Entity.OldestMailDate) .Single(); foreach (LabelEntity label in accountLabels) { viewLabels.Add(new LabelViewModel(label.Name, label.SystemName, label.Color)); } ViewBag.Username = sessionUser.Entity.Username; ViewBag.Labels = viewLabels; ViewBag.OldestAge = DateTimeHelper.GetAgeInSeconds(oldestMailDate); ViewBag.Firstname = sessionUser.Entity.Firstname ?? ""; ViewBag.Lastname = sessionUser.Entity.Lastname ?? ""; ViewBag.Country = sessionUser.Entity.Country ?? ""; ViewBag.City = sessionUser.Entity.City ?? ""; ViewBag.Telephone = sessionUser.Entity.Telephone ?? ""; ViewBag.MailAccounts = sessionUser.GetAccounts().Select(x => new { address = x.Entity.Address, mainAccount = x.Entity.IsMainAccount, mailAccountId = x.Entity.Id }); ViewBag.IsGlimpseUser = Glimpse.Models.User.IsGlimpseUser(sessionUser.Entity.Username); return(View()); } catch (Exception exc) { Log.LogException(exc); return(this.LogOut()); } finally { session.Close(); } }
/// <summary> /// 生成Dashboard数据 /// </summary> /// <param name="websiteOwnerList">站点列表</param> /// <param name="sDate">开始日期</param> /// <param name="eDate">结束日期</param> public void BuildDashboardLog(List <string> websiteList, DateTime sDate, DateTime eDate) { if (websiteList.Count == 0) { return; } List <UserInfo> userList = GetDashboardRegUserList(null, sDate.ToString("yyyy-MM-dd"), eDate.ToString("yyyy-MM-dd")); List <WXMallOrderInfo> orderList = GetDashboardOrderList(null, sDate.ToString("yyyy-MM-dd"), eDate.ToString("yyyy-MM-dd"), "0,1,2,3"); List <MonitorEventDetailsInfo> webAccesslogList = GetDashboardMonitorEventDetailsInfoList(null, sDate.ToString("yyyy-MM-dd"), eDate.ToString("yyyy-MM-dd")); int sDateInt = DateTimeHelper.ToDateInt8ByDateTime(sDate); int eDateInt = ZentCloud.Common.DateTimeHelper.ToDateInt8ByDateTime(eDate); //历史记录 List <DashboardLog> oDashlogList = GetDashboardLogList(null, sDateInt, eDateInt); #region 汇总记录 List <DashboardLog> userDashboardLogList = userList.GroupBy(p => new { p.WebsiteOwner, Value = DateTimeHelper.ToDateInt8ByDateTime(p.Regtime.Value) }).Select(g => new DashboardLog { WebsiteOwner = g.Key.WebsiteOwner, Date = g.Key.Value, DashboardType = "Member", Num = g.Count() }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList(); List <DashboardLog> orderDashboardLogList = orderList.GroupBy(p => new { p.WebsiteOwner, Value = DateTimeHelper.ToDateInt8ByDateTime(p.InsertDate) }).Select(g => new DashboardLog { WebsiteOwner = g.Key.WebsiteOwner, Date = g.Key.Value, DashboardType = "WXMallOrder", Num = g.Count() }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList(); List <DashboardLog> webAccesslogDashboardLogList = webAccesslogList.GroupBy(p => new { p.WebsiteOwner, Value = DateTimeHelper.ToDateInt8ByDateTime(p.EventDate.Value) }).Select(g => new DashboardLog { WebsiteOwner = g.Key.WebsiteOwner, Date = g.Key.Value, DashboardType = "WebAccessLog", Num = g.Count() }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList(); #endregion 汇总记录 #region 更新记录 for (DateTime i = eDate; i >= sDate; i = i.AddDays(-1)) { int iInt = DateTimeHelper.ToDateInt8ByDateTime(i); foreach (string web in websiteList) { DashboardLog nu = userDashboardLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt); DashboardLog no = orderDashboardLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt); DashboardLog nw = webAccesslogDashboardLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt); DashboardLog om = oDashlogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt && p.DashboardType == "Member"); DashboardLog oo = oDashlogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt && p.DashboardType == "WXMallOrder"); DashboardLog ow = oDashlogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == iInt && p.DashboardType == "WebAccessLog"); if (om == null && nu != null) { Add(nu); } else if (om != null && nu != null) { Update(nu); } else if (om != null && nu == null) { Delete(om); } if (oo == null && no != null) { Add(no); } else if (oo != null && no != null) { Update(no); } else if (oo != null && no == null) { Delete(oo); } if (ow == null && nw != null) { Add(nw); } else if (ow != null && nw != null) { Update(nw); } else if (ow != null && nw == null) { Delete(ow); } } } #endregion 更新记录 }
public Data.RestResponse Execute(string baseAddress, Data.RestRequest requestDetails) { this.BaseUrlString = baseAddress; RestSharp.IRestClient client = this.Client; // We're using RestSharp to execute HTTP requests. RestSharp copes with trailing "/" // on BaseUrl and leading "/" on Resource, whether one or both of the "/" are present // or absent. ValidateRequest(client, requestDetails); if (requestDetails.TransactionId == null) { requestDetails.TransactionId = Convert.ToInt64(DateTimeHelper.CurrentUnixTimeMillis()); } client.FollowRedirects = requestDetails.FollowRedirect; RestSharp.RestRequest request = BuildRequest(requestDetails); if (LOG.IsDebugEnabled) { try { LOG.Info("Http Request : {0} {1}", request.Method, client.BuildUri(request).AbsoluteUri); } catch (Exception e) { LOG.Error(e, "Exception in debug : {0}", e.Message); } // Request Header LogRequestHeaders(request); // Request Body if (IsEntityEnclosingMethod(request.Method)) { try { Parameter body = request.Parameters .Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault(); LOG.Debug("Http Request Body : {0}", body.Value); } catch (IOException e) { LOG.Error(e, "Error in reading request body in debug : {0}", e.Message); } } } // Prepare Response Data.RestResponse responseDetails = new Data.RestResponse(); responseDetails.TransactionId = requestDetails.TransactionId; responseDetails.Resource = requestDetails.Resource; try { IRestResponse response = client.Execute(request); foreach (RestSharp.Parameter responseHeader in response.Headers) { responseDetails.addHeader(responseHeader.Name, responseHeader.Value.ToString()); } responseDetails.StatusCode = (int)response.StatusCode; responseDetails.StatusText = response.StatusDescription; // The Java byte data type is actually a signed byte, equivalent to sbyte in .NET. // Data.RestResponse is a direct port of the Java class so it uses // the sbyte data type. The strange conversion from byte[] to sbyte[] was from // the answer to Stackoverflow question http://stackoverflow.com/questions/25759878/convert-byte-to-sbyte // TODO: Check RestFixture code to see whether Data.RestResponse.RawBody can be converted to byte[]. responseDetails.RawBody = response.RawBytes; // Debug if (LOG.IsDebugEnabled) { // Not necessarily the same as the request URI. The response URI is the URI // that finally responds to the request, after any redirects. LOG.Debug("Http Request Path : {0}", response.ResponseUri); LogRequestHeaders(request); // Apache HttpClient.HttpMethod.getStatusLine() returns the HTTP response // status line. Can't do this with RestSharp as it cannot retrieve the // protocol version which is at the start of the status line. So just log // the status code and description. // Looks like they added ProtocolVersion to RestSharp in issue 795 (commit // 52c18a8) but it's only available in the FRAMEWORK builds. LOG.Debug("Http Response Status : {0} {1}", (int)response.StatusCode, response.StatusDescription); LOG.Debug("Http Response Body : {0}", response.Content); } if (IsResponseError(response)) { LOG.Error(response.ErrorException, response.ErrorMessage); string message = "Http call failed"; if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { message = response.ErrorMessage.Trim(); } throw new System.InvalidOperationException(message, response.ErrorException); } } catch (Exception e) { string message = "Http call failed"; throw new System.InvalidOperationException(message, e); } LOG.Debug("response: {0}", responseDetails); return(responseDetails); }
/// <summary> /// 处理文字请求 /// </summary> /// <returns></returns> public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs #region 书中例子 //if (requestMessage.Content == "你好") //{ // var responseMessage = base.CreateResponseMessage<ResponseMessageNews>(); // var title = "Title"; // var description = "Description"; // var picUrl = "PicUrl"; // var url = "Url"; // responseMessage.Articles.Add(new Article() // { // Title = title, // Description = description, // PicUrl = picUrl, // Url = url // }); // return responseMessage; //} //else if (requestMessage.Content == "Senparc") //{ // //相似处理逻辑 //} //else //{ // //... //} #endregion #region 历史方法 //方法一(v0.1),此方法调用太过繁琐,已过时(但仍是所有方法的核心基础),建议使用方法二到四 //var responseMessage = // ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as // ResponseMessageText; //方法二(v0.4) //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage); //方法三(v0.4),扩展方法,需要using Senparc.Weixin.MP.Helpers; //var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>(); //方法四(v0.6+),仅适合在HandlerMessage内部使用,本质上是对方法三的封装 //注意:下面泛型ResponseMessageText即返回给客户端的类型,可以根据自己的需要填写ResponseMessageNews等不同类型。 #endregion var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>(); var requestHandler = requestMessage.StartHandler() //关键字不区分大小写,按照顺序匹配成功后将不再运行下面的逻辑 .Keyword("约束", () => { defaultResponseMessage.Content = @"您正在进行微信内置浏览器约束判断测试。您可以: <a href=""http://sdk.weixin.senparc.com/FilterTest/"">点击这里</a>进行客户端约束测试(地址:http://sdk.weixin.senparc.com/FilterTest/),如果在微信外打开将直接返回文字。 或: <a href=""http://sdk.weixin.senparc.com/FilterTest/Redirect"">点击这里</a>进行客户端约束测试(地址:http://sdk.weixin.senparc.com/FilterTest/Redirect),如果在微信外打开将重定向一次URL。"; return(defaultResponseMessage); }). //匹配任一关键字 Keywords(new[] { "托管", "代理" }, () => { //开始用代理托管,把请求转到其他服务器上去,然后拿回结果 //甚至也可以将所有请求在DefaultResponseMessage()中托管到外部。 DateTime dt1 = DateTime.Now; //计时开始 var agentXml = RequestDocument.ToString(); #region 暂时转发到SDK线上Demo agentUrl = "http://sdk.weixin.senparc.com/weixin"; //agentToken = WebConfigurationManager.AppSettings["WeixinToken"];//Token //修改内容,防止死循环 var agentDoc = XDocument.Parse(agentXml); agentDoc.Root.Element("Content").SetValue("代理转发文字:" + requestMessage.Content); agentDoc.Root.Element("CreateTime").SetValue(DateTimeHelper.GetWeixinDateTime(DateTime.Now)); //修改时间,防止去重 agentDoc.Root.Element("MsgId").SetValue("123"); //防止去重 agentXml = agentDoc.ToString(); #endregion var responseXml = MessageAgent.RequestXml(this, agentUrl, agentToken, agentXml); //获取返回的XML //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString()); /* 如果有WeiweihiKey,可以直接使用下面的这个MessageAgent.RequestWeiweihiXml()方法。 * WeiweihiKey专门用于对接www.weiweihi.com平台,获取方式见:https://www.weiweihi.com/ApiDocuments/Item/25#51 */ //var responseXml = MessageAgent.RequestWeiweihiXml(weiweihiKey, RequestDocument.ToString());//获取Weiweihi返回的XML DateTime dt2 = DateTime.Now; //计时结束 //转成实体。 /* 如果要写成一行,可以直接用: * responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString()); * 或 * */ var msg = string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds); var agentResponseMessage = responseXml.CreateResponseMessage(); if (agentResponseMessage is ResponseMessageText) { (agentResponseMessage as ResponseMessageText).Content += msg; } else if (agentResponseMessage is ResponseMessageNews) { (agentResponseMessage as ResponseMessageNews).Articles[0].Description += msg; } return(agentResponseMessage); //可能出现多种类型,直接在这里返回 }) .Keywords(new[] { "测试", "退出" }, () => { /* * 这是一个特殊的过程,此请求通常来自于微微嗨(http://www.weiweihi.com)的“盛派网络小助手”应用请求(https://www.weiweihi.com/User/App/Detail/1), * 用于演示微微嗨应用商店的处理过程,由于微微嗨的应用内部可以单独设置对话过期时间,所以这里通常不需要考虑对话状态,只要做最简单的响应。 */ if (defaultResponseMessage.Content == "测试") { //进入APP测试 defaultResponseMessage.Content = "您已经进入【盛派网络小助手】的测试程序,请发送任意信息进行测试。发送文字【退出】退出测试对话。10分钟内无任何交互将自动退出应用对话状态。"; } else { //退出APP测试 defaultResponseMessage.Content = "您已经退出【盛派网络小助手】的测试程序。"; } return(defaultResponseMessage); }) .Keyword("AsyncTest", () => { //异步并发测试(提供给单元测试使用) #if NET45 DateTime begin = DateTime.Now; int t1, t2, t3; System.Threading.ThreadPool.GetAvailableThreads(out t1, out t3); System.Threading.ThreadPool.GetMaxThreads(out t2, out t3); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4)); DateTime end = DateTime.Now; var thread = System.Threading.Thread.CurrentThread; defaultResponseMessage.Content = string.Format("TId:{0}\tApp:{1}\tBegin:{2:mm:ss,ffff}\tEnd:{3:mm:ss,ffff}\tTPool:{4}", thread.ManagedThreadId, HttpContext.Current != null ? HttpContext.Current.ApplicationInstance.GetHashCode() : -1, begin, end, t2 - t1 ); #endif return(defaultResponseMessage); }) .Keyword("OPEN", () => { var openResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageNews>(); openResponseMessage.Articles.Add(new Article() { Title = "开放平台微信授权测试", Description = @"点击进入Open授权页面。 授权之后,您的微信所收到的消息将转发到第三方(盛派网络小助手)的服务器上,并获得对应的回复。 测试完成后,您可以登陆公众号后台取消授权。", Url = "http://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth" }); return(openResponseMessage); }) .Keyword("错误", () => { var errorResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>(); //因为没有设置errorResponseMessage.Content,所以这小消息将无法正确返回。 return(errorResponseMessage); }) .Keyword("容错", () => { Thread.Sleep(4900); //故意延时1.5秒,让微信多次发送消息过来,观察返回结果 var faultTolerantResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>(); faultTolerantResponseMessage.Content = string.Format("测试容错,MsgId:{0},Ticks:{1}", requestMessage.MsgId, DateTime.Now.Ticks); return(faultTolerantResponseMessage); }) .Keyword("TM", () => { var openId = requestMessage.FromUserName; var checkCode = Guid.NewGuid().ToString("n").Substring(0, 3); //为了防止openId泄露造成骚扰,这里启用验证码 TemplateMessageCollection[checkCode] = openId; defaultResponseMessage.Content = string.Format(@"新的验证码为:{0},请在网页上输入。网址:http://sdk.weixin.senparc.com/AsyncMethods", checkCode); return(defaultResponseMessage); }) .Keyword("OPENID", () => { var openId = requestMessage.FromUserName; //获取OpenId var userInfo = AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN); defaultResponseMessage.Content = string.Format( "您的OpenID为:{0}\r\n昵称:{1}\r\n性别:{2}\r\n地区(国家/省/市):{3}/{4}/{5}\r\n关注时间:{6}\r\n关注状态:{7}", requestMessage.FromUserName, userInfo.nickname, (Sex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe); return(defaultResponseMessage); }) .Keyword("EX", () => { var ex = new WeixinException("openid:" + requestMessage.FromUserName + ":这是一条测试异常信息"); //回调过程在global的ConfigWeixinTraceLog()方法中 defaultResponseMessage.Content = "请等待异步模板消息发送到此界面上(自动延时数秒)。\r\n当前时间:" + DateTime.Now.ToString(); return(defaultResponseMessage); }) .Keyword("MUTE", () => //不回复任何消息 { //方案一: return(new SuccessResponseMessage()); //方案二: var muteResponseMessage = base.CreateResponseMessage <ResponseMessageNoResponse>(); return(muteResponseMessage); //方案三: base.TextResponseMessage = "success"; return(null); }) .Keyword("JSSDK", () => { defaultResponseMessage.Content = "点击打开:http://sdk.weixin.senparc.com/WeixinJsSdk"; return(defaultResponseMessage); }) //Default不一定要在最后一个 .Default(() => { var result = new StringBuilder(); result.AppendFormat("您刚才发送了文字信息:{0}\r\n\r\n", requestMessage.Content); if (CurrentMessageContext.RequestMessages.Count > 1) { result.AppendFormat("您刚才还发送了如下消息({0}/{1}):\r\n", CurrentMessageContext.RequestMessages.Count, CurrentMessageContext.StorageData); for (int i = CurrentMessageContext.RequestMessages.Count - 2; i >= 0; i--) { var historyMessage = CurrentMessageContext.RequestMessages[i]; result.AppendFormat("{0} 【{1}】{2}\r\n", historyMessage.CreateTime.ToString("HH:mm:ss"), historyMessage.MsgType.ToString(), (historyMessage is RequestMessageText) ? (historyMessage as RequestMessageText).Content : "[非文字类型]" ); } result.AppendLine("\r\n"); } result.AppendFormat("如果您在{0}分钟内连续发送消息,记录将被自动保留(当前设置:最多记录{1}条)。过期后记录将会自动清除。\r\n", WeixinContext.ExpireMinutes, WeixinContext.MaxRecordCount); result.AppendLine("\r\n"); result.AppendLine( "您还可以发送【位置】【图片】【语音】【视频】等类型的信息(注意是这几种类型,不是这几个文字),查看不同格式的回复。\r\nSDK官方地址:http://sdk.weixin.senparc.com"); defaultResponseMessage.Content = result.ToString(); return(defaultResponseMessage); }) //“一次订阅消息”接口测试 .Keyword("订阅", () => { defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/SubscribeMsg"; return(defaultResponseMessage); }) //正则表达式 .Regex(@"^\d+#\d+$", () => { defaultResponseMessage.Content = string.Format("您输入了:{0},符合正则表达式:^\\d+#\\d+$", requestMessage.Content); return(defaultResponseMessage); }); return(requestHandler.GetResponseMessage() as IResponseMessageBase); }
public StoreBufferHoursAvailableManager(long storeid, DateTime monday) { StoreId = storeid; Year = DateTimeHelper.GetYearByDate(monday); Init(null); }
private void LoadData() { using (var ctx = new EF6.RT2020Entities()) { var item = ctx.PromotionPaymentFactor.Find(_CampaignId); if (item != null) { cboWorkplace.SelectedValue = item.WorkplaceId.HasValue ? item.WorkplaceId : Guid.Empty; cboTender.SelectedValue = item.TypeId.HasValue ? item.TypeId : Guid.Empty; txtEventCode.Text = item.EventCode; txtFactorRate.Text = item.FactorRate.ToString("n2"); dtpStartDate.Value = item.StartOn.HasValue ? item.StartOn.Value : DateTimeHelper.DateZero(); dtpEndDate.Value = item.EndOn.HasValue ? item.EndOn.Value : DateTimeHelper.DateZero(); txtCreatedOn.Text = DateTimeHelper.DateTimeToString(item.CreatedOn, false); txtLastUpdatedBy.Text = StaffEx.GetStaffNumberById(item.ModifiedBy); txtLastUpdatedOn.Text = DateTimeHelper.DateTimeToString(item.ModifiedOn, false); } } }
public StoreBufferHoursAvailableManager(long storeid, DateTime monday, List <StoreToWorld> lstWorlds) { StoreId = storeid; Year = DateTimeHelper.GetYearByDate(monday); Init(lstWorlds); }
/// <summary> /// Check if referenceDate is at least the day before the otherDate ignoring time /// </summary> public static bool IsAtLeastOneDayBefore(this DateTime referenceDate, DateTime?otherDate) => DateTimeHelper.IsAtLeastOneDayBefore(referenceDate, otherDate);
private void PreviewReportDetail() { var periode = string.Empty; IReportPembayaranHutangBeliProdukBll reportBll = new ReportPembayaranHutangBeliProdukBll(_log); IList <ReportPembayaranHutangPembelianProdukDetail> listOfReportPembayaranHutangPembelian = new List <ReportPembayaranHutangPembelianProdukDetail>(); IList <string> listOfSupplierId = new List <string>(); if (chkBoxTitle.Checked) { listOfSupplierId = base.GetSupplierId(_listOfSupplier); if (listOfSupplierId.Count == 0) { MsgHelper.MsgWarning("Minimal 1 supplier harus dipilih"); return; } } if (rdoTanggal.Checked) { if (!DateTimeHelper.IsValidRangeTanggal(dtpTanggalMulai.Value, dtpTanggalSelesai.Value)) { MsgHelper.MsgNotValidRangeTanggal(); return; } var tanggalMulai = DateTimeHelper.DateToString(dtpTanggalMulai.Value); var tanggalSelesai = DateTimeHelper.DateToString(dtpTanggalSelesai.Value); periode = dtpTanggalMulai.Value == dtpTanggalSelesai.Value ? string.Format("Periode : {0}", tanggalMulai) : string.Format("Periode : {0} s.d {1}", tanggalMulai, tanggalSelesai); listOfReportPembayaranHutangPembelian = reportBll.DetailGetByTanggal(dtpTanggalMulai.Value, dtpTanggalSelesai.Value); } else { periode = string.Format("Periode : {0} {1}", cmbBulan.Text, cmbTahun.Text); var bulan = cmbBulan.SelectedIndex + 1; var tahun = int.Parse(cmbTahun.Text); listOfReportPembayaranHutangPembelian = reportBll.DetailGetByBulan(bulan, tahun); } if (listOfSupplierId.Count > 0 && listOfReportPembayaranHutangPembelian.Count > 0) { listOfReportPembayaranHutangPembelian = listOfReportPembayaranHutangPembelian.Where(f => listOfSupplierId.Contains(f.supplier_id)) .ToList(); } if (listOfReportPembayaranHutangPembelian.Count > 0) { var reportDataSource = new ReportDataSource { Name = "ReportPembayaranHutangPembelianProdukDetail", Value = listOfReportPembayaranHutangPembelian }; var parameters = new List <ReportParameter>(); parameters.Add(new ReportParameter("periode", periode)); base.ShowReport(this.Text, "RvPembayaranHutangPembelianProdukDetail", reportDataSource, parameters); } else { MsgHelper.MsgInfo("Maaf laporan data pembayaran hutang pembelian tidak ditemukan"); } }
/// <summary> /// First day of the month of the passed in date /// </summary> public static DateTime StartOfMonth(this DateTime referenceDate) => DateTimeHelper.StartOfMonth(referenceDate);
public void CheckTime() { if (_serviceManager.IsFreeDay) return; //We don't even care if (ShutdownAction?.IsEnabled == true) return; var helper = new DateTimeHelper(); _serviceManager.RefreshTimePlayedToday(); switch (_serviceManager.Config.Mode) { case Mode.PerDay: TimeLeft = _serviceManager.Config.GamingTimePerDay - _serviceManager.TimePlayedToday; break; case Mode.PerWeek: TimeLeft = TimeSpan.FromHours(_serviceManager.Config.GamingTimePerDay.TotalHours*7) - TimeSpan.FromMilliseconds( _serviceManager.DatabaseManager.PlayTimes.Where( x => helper.IsCurrentWeek(x.Timestamp)) .Select(x => x.Duration.TotalMilliseconds) .Sum()).Add(_serviceManager.Service.TimePlayed); break; case Mode.PerDayWithSave: var savedTime = TimeSpan.FromHours(((int) DateTime.Now.DayOfWeek - 1)* _serviceManager.Config.GamingTimePerDay.TotalHours) - TimeSpan.FromMilliseconds( _serviceManager.DatabaseManager.PlayTimes.Where(x => helper.IsCurrentWeek(x.Timestamp)) .Select(x => x.Duration.TotalMilliseconds) .Sum()); if (savedTime > TimeSpan.Zero) { TimeLeft = (_serviceManager.Config.GamingTimePerDay + savedTime) - _serviceManager.TimePlayedToday; } else { TimeLeft = _serviceManager.Config.GamingTimePerDay - _serviceManager.TimePlayedToday; } break; default: throw new ArgumentOutOfRangeException(); } // ReSharper disable CompareOfFloatsByEqualityOperator if (_serviceManager.Config.TimeSpan.FromTime != 4 && _serviceManager.Config.TimeSpan.ToTime != 28) // ReSharper restore CompareOfFloatsByEqualityOperator { if (DateTime.Now < DateTimeHelper.GetToday().AddHours(_serviceManager.Config.TimeSpan.FromTime) || DateTime.Now > DateTimeHelper.GetToday() .AddHours(_serviceManager.Config.TimeSpan.ToTime)) { TimeLeft = TimeSpan.Zero; } else { var time = DateTimeHelper.GetToday().AddMinutes(_serviceManager.Config.TimeSpan.ToTime*30) - DateTime.Now; if (TimeLeft < time) TimeLeft = time; } } if (_serviceManager.Service.CurrentProgram == null) //No actions when no game is running return; if (TimeLeft < TimeSpan.FromMinutes(30) && TimeLeft > TimeSpan.FromMinutes(5)) { CurrentState = State.ComingToEnd; } else if (TimeLeft < TimeSpan.FromMinutes(5) && TimeLeft > TimeSpan.Zero) { CurrentState = State.Critical; } else if (TimeLeft < TimeSpan.Zero || TimeLeft == TimeSpan.Zero) { CurrentState = State.StopDaShitImmediately; ShutdownAction = new ShutdownAction(); ShutdownAction.Start(); ShutdownAction.InvokeActions += (sender, args) => NothingIsAwesome?.Invoke(this, EventArgs.Empty); } else { CurrentState = State.EverythingIsAwesome; } }
/// <summary> /// Last day of the week of the passed in date /// </summary> /// <remarks> /// Uses <see cref="CultureInfo.CurrentCulture" /> to determine <i>first</i> day of week /// and then assumes 7 day week /// </remarks> public static DateTime EndOfWeek(this DateTime referenceDate) => DateTimeHelper.EndOfWeek(referenceDate);
// [i] �G�s�\�[�h //========================================================================= /// <summary> /// �u�܂�Ȃ��������ԁv�o���[����|�b�v�A�b�v /// </summary> /// <remarks> /// </remarks> /// <history>2008/10/01 �V�K�쐬</history> //========================================================================= internal void PopupSoonBalloon( AnimeEpisode episode ) { if( mNotifyIcon.Visible) { string t; if( !episode.HasPlan ) return; DateTimeHelper dateTime = new DateTimeHelper( episode.StartDateTime , Settings.Default.hoursPerDay -24 ); t = "�܂�Ȃ��������Ԃł�\n\n" + dateTime.ToShortTimeString() + "���� " + episode.ToString(); mNotifyIcon.BalloonTipText = t; mNotifyIcon.ShowBalloonTip(3000); } }
public void ProcessRequest(HttpContext context) { int rows = Convert.ToInt32(context.Request["rows"]); int page = Convert.ToInt32(context.Request["page"]); string category_id = context.Request["category_id"]; string city = context.Request["city"]; string user_name = context.Request["user_name"]; string activity_ex1 = context.Request["activity_ex1"]; string activity_ex2 = context.Request["activity_ex2"]; string activity_ex3 = context.Request["activity_ex3"]; string activity_ex4 = context.Request["activity_ex4"]; string activity_ex5 = context.Request["activity_ex5"]; string activity_ex6 = context.Request["activity_ex6"]; string activity_ex7 = context.Request["activity_ex7"]; string activity_ex8 = context.Request["activity_ex8"]; string activity_ex9 = context.Request["activity_ex9"]; string activity_ex10 = context.Request["activity_ex10"]; string start_time = context.Request["start_time"]; string stop_time = context.Request["stop_time"]; string longitude = context.Request["longitude"]; string latitude = context.Request["latitude"]; string keyword = context.Request["keyword"]; string tag = context.Request["tag"]; string sort = context.Request["sort"]; string status = context.Request["status"]; status = string.IsNullOrWhiteSpace(status) ? "0" : status; int range = string.IsNullOrWhiteSpace(context.Request["range"]) ? 3 : Convert.ToInt32(context.Request["range"]); if (string.IsNullOrWhiteSpace(longitude) || string.IsNullOrWhiteSpace(latitude)) { CurrentUserInfo = bllUser.GetCurrentUserInfo(); if (CurrentUserInfo != null && !string.IsNullOrWhiteSpace(CurrentUserInfo.LastLoginLongitude) && !string.IsNullOrWhiteSpace(CurrentUserInfo.LastLoginLatitude)) { longitude = CurrentUserInfo.LastLoginLongitude; latitude = CurrentUserInfo.LastLoginLatitude; } } int total = 0; List <JuActivityInfo> list = bllActivity.GetRangeUserList(rows, page, bllActivity.WebsiteOwner, user_name, "Appointment", category_id, city, longitude, latitude , activity_ex1, activity_ex2, activity_ex3, activity_ex4, activity_ex5, activity_ex6, activity_ex7, activity_ex8, activity_ex9, activity_ex10 , keyword, tag, sort, start_time, stop_time, out total, range, status); List <dynamic> result = new List <dynamic>(); foreach (var item in list) { UserInfo userTemp = bllUser.GetUserInfo(item.UserID); if (userTemp == null) { continue; } result.Add(new { activity_id = item.JuActivityID, activity_name = item.ActivityName, activity_address = item.ActivityAddress, activity_summary = item.Summary, create_time = DateTimeHelper.DateTimeToUnixTimestamp(item.CreateDate), create_time_str = DateTimeHelper.DateTimeToString(item.CreateDate), activity_start_time = item.ActivityStartDate.HasValue ? DateTimeHelper.DateTimeToUnixTimestamp(item.ActivityStartDate.Value) : 0, activity_start_time_str = item.ActivityStartDate.HasValue ? DateTimeHelper.DateTimeToString(item.ActivityStartDate.Value) : "", activity_pv = item.PV, activity_commentcount = item.CommentCount, activity_signcount = item.SignUpCount, category_id = item.CategoryId, category_name = item.CategoryName, activity_ex1 = item.K1, activity_ex2 = item.K2, activity_ex3 = item.K3, activity_ex4 = item.K4, activity_ex5 = item.K5, activity_ex6 = item.K6, activity_ex7 = item.K7, activity_ex8 = item.K8, activity_ex9 = item.K9, activity_ex10 = item.K10, credit_acount = item.CreditAcount, publish_user = new { id = userTemp.AutoID, user_name = userTemp.UserID, nick_name = userTemp.WXNickname, gender = userTemp.Gender, birthday = DateTimeHelper.DateTimeToUnixTimestamp(userTemp.Birthday), birthday_str = DateTimeHelper.DateTimeToString(userTemp.Birthday), identification = userTemp.Ex5, avatar = userTemp.Avatar }, status = item.TStatus, distance = item.Distance }); } apiResp.status = true; apiResp.code = 0; apiResp.result = new { totalcount = total, list = result }; apiResp.msg = "查询完成"; bllActivity.ContextResponse(context, apiResp); }
/// <summary> /// 生成首页数据 /// </summary> /// <param name="websiteOwnerList">站点列表</param> /// <param name="date">日期</param> public void BuildDashboardInfo(List <string> websiteList, DateTime nDate) { if (websiteList.Count == 0) { return; } int nDateInt = DateTimeHelper.ToDateInt8ByDateTime(nDate); int lastDate7Int = DateTimeHelper.ToDateInt8ByDateTime(nDate.AddDays(-6)); int lastDate30Int = DateTimeHelper.ToDateInt8ByDateTime(nDate.AddDays(-29)); List <DashboardLog> dashLogList = GetDashboardLogList(null, lastDate30Int, nDateInt); List <DashboardInfo> dashInfoList = GetDashboardInfoList(); List <DashboardLog> uvDashLogList = new List <DashboardLog>(); #region 访客记录统计 List <MonitorEventDetailsInfo> uvList = GetDashboardUVList(null, nDate.AddDays(-29).ToString("yyyy-MM-dd"), nDate.ToString("yyyy-MM-dd")); List <DashboardMonitorInfo> uvDashboardLogList = GetColList <DashboardMonitorInfo>(int.MaxValue, 1, "1=1", "DetailID"); //ExecuteSql("truncate table ZCJ_DashboardMonitorInfo");//清除原30天UV记录 if (uvList.Count > 0) { List <DashboardMonitorInfo> uvGroupList = uvList.GroupBy(p => new { p.WebsiteOwner, p.EventUserID }).Select(g => new DashboardMonitorInfo { WebsiteOwner = g.Key.WebsiteOwner, EventUserID = g.Key.EventUserID, DetailID = g.Max(p => p.DetailID).Value }).OrderByDescending(x => x.DetailID).ToList(); //删除数据 List <int> delIdList = uvDashboardLogList.Where(p => !uvGroupList.Exists(pi => pi.DetailID == p.DetailID)).Select(pid => pid.DetailID).ToList(); if (delIdList.Count > 0) { DeleteMultByKey <DashboardMonitorInfo>("DetailID", ZentCloud.Common.MyStringHelper.ListToStr(delIdList, "", ",")); } List <int> addIdList = uvGroupList.Where(p => !uvDashboardLogList.Exists(pi => pi.DetailID == p.DetailID)).Select(pid => pid.DetailID).ToList(); List <DashboardMonitorInfo> uvAddDashboardList = uvList.Where(p => addIdList.Exists(pi => pi == p.DetailID.Value)).Select(g => new DashboardMonitorInfo { DetailID = g.DetailID.Value, WebsiteOwner = g.WebsiteOwner, EventUserID = g.EventUserID, EventDate = g.EventDate.Value, SourceIP = g.SourceIP, IPLocation = g.IPLocation, EventBrowserID = g.EventBrowserID }).ToList(); if (uvAddDashboardList.Count > 0) { string userIds = MyStringHelper.ListToStr(uvAddDashboardList.Select(p => p.EventUserID).Distinct().ToList(), "'", ","); List <UserInfo> userList = GetColMultListByKey <UserInfo>(int.MaxValue, 1, "UserID", userIds, "AutoID,UserID,TrueName,Phone,WXNickname,WXHeadimgurl"); for (int i = 0; i < uvAddDashboardList.Count; i++) { UserInfo nuser = userList.FirstOrDefault(p => p.UserID == uvAddDashboardList[i].EventUserID); if (nuser != null) { uvAddDashboardList[i].EventUserWXNikeName = nuser.WXNickname; uvAddDashboardList[i].EventUserTrueName = nuser.TrueName; uvAddDashboardList[i].EventUserWXImg = nuser.WXHeadimgurl; uvAddDashboardList[i].EventUserPhone = nuser.Phone; } Add(uvAddDashboardList[i]); } } uvDashLogList = uvList.Where(ni => uvGroupList.Exists(pi => pi.DetailID == ni.DetailID)).GroupBy(p => new { p.WebsiteOwner, Value = DateTimeHelper.ToDateInt8ByDateTime(p.EventDate.Value) }).Select(g => new DashboardLog { WebsiteOwner = g.Key.WebsiteOwner, Date = g.Key.Value, DashboardType = "UV", Num = g.Count() }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList(); } #endregion List <DashboardLog> fansDashLogList = new List <DashboardLog>(); #region 粉丝记录统计 List <Log> fansList = GetDashboardSubscribeList(null, nDate.AddDays(-29).ToString("yyyy-MM-dd"), nDate.ToString("yyyy-MM-dd")); if (fansList.Count > 0) { fansDashLogList = fansList.GroupBy(p => new { p.WebsiteOwner, p.UserID }).Select(g => new Log { WebsiteOwner = g.Key.WebsiteOwner, UserID = g.Key.UserID, InsertDate = g.Max(p => p.InsertDate) }).GroupBy(e => new { e.WebsiteOwner, Value = DateTimeHelper.ToDateInt8ByDateTime(e.InsertDate) }).Select(f => new DashboardLog { WebsiteOwner = f.Key.WebsiteOwner, Date = f.Key.Value, DashboardType = "Fans", Num = f.Count() }).OrderByDescending(x => x.Date).ThenBy(x => x.WebsiteOwner).ToList(); } #endregion List <TotalInfo> memberTotalList = GetAllDashboardRegUserTotal(); List <TotalInfo> uvTotalList = GetAllDashboardUVTotal(); List <TotalInfo> fansTotalList = GetAllDashboardSubscribeTotal(); List <TotalInfo> orderTotalList = GetAllDashboardOrderTotal("0,1,2,3"); List <TotalInfo> visitTotalList = GetAllDashboardMonitorEventDetailsTotal(); foreach (string web in websiteList) { DashboardInfo ndi = dashInfoList.FirstOrDefault(p => p.WebsiteOwner == web); //if (ndi!=null && ndi.Date == nDateInt) continue; DashboardJson nDashboardJson = new DashboardJson(); nDashboardJson.visit_num_lastday = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date == nDateInt).Sum(p => p.Num); nDashboardJson.order_num_lastday = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date == nDateInt).Sum(p => p.Num); nDashboardJson.member_num_lastday = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date == nDateInt).Sum(p => p.Num); nDashboardJson.uv_num_lastday = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date == nDateInt).Sum(p => p.Num); nDashboardJson.fans_num_lastday = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date == nDateInt).Sum(p => p.Num); nDashboardJson.visit_num_lastweek = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.order_num_lastweek = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.member_num_lastweek = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.uv_num_lastweek = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.fans_num_lastweek = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate7Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.visit_num_lastmonth = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.order_num_lastmonth = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.member_num_lastmonth = dashLogList.Where(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.uv_num_lastmonth = uvDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num); nDashboardJson.fans_num_lastmonth = fansDashLogList.Where(p => p.WebsiteOwner == web && p.Date >= lastDate30Int && p.Date <= nDateInt).Sum(p => p.Num); TotalInfo memberTotal = memberTotalList.FirstOrDefault(p => p.WebsiteOwner == web); if (memberTotal != null) { nDashboardJson.member_total = memberTotal.Total; } TotalInfo uvTotal = uvTotalList.FirstOrDefault(p => p.WebsiteOwner == web); if (uvTotal != null) { nDashboardJson.uv_total = uvTotal.Total; } TotalInfo fansTotal = fansTotalList.FirstOrDefault(p => p.WebsiteOwner == web); if (fansTotal != null) { nDashboardJson.fans_total = fansTotal.Total; } TotalInfo orderTotal = orderTotalList.FirstOrDefault(p => p.WebsiteOwner == web); if (orderTotal != null) { nDashboardJson.order_total = orderTotal.Total; } TotalInfo visitTotal = visitTotalList.FirstOrDefault(p => p.WebsiteOwner == web); if (visitTotal != null) { nDashboardJson.visit_total = visitTotal.Total; } for (DateTime i = nDate; i >= nDate.AddDays(-29); i = i.AddDays(-1)) { int rDateInt = ZentCloud.Common.DateTimeHelper.ToDateInt8ByDateTime(i); string rDateString = i.ToString("yyyy-MM-dd"); nDashboardJson.day_list.Add(rDateString); DashboardLog rVisitLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "WebAccessLog" && p.Date == rDateInt); if (rVisitLog == null) { nDashboardJson.visit_num_list.Add(0); } else { nDashboardJson.visit_num_list.Add(rVisitLog.Num); } DashboardLog rOrderLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "WXMallOrder" && p.Date == rDateInt); if (rOrderLog == null) { nDashboardJson.order_num_list.Add(0); } else { nDashboardJson.order_num_list.Add(rOrderLog.Num); } DashboardLog rMemberLog = dashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.DashboardType == "Member" && p.Date == rDateInt); if (rMemberLog == null) { nDashboardJson.member_num_list.Add(0); } else { nDashboardJson.member_num_list.Add(rMemberLog.Num); } DashboardLog rUVLog = uvDashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == rDateInt); if (rUVLog == null) { nDashboardJson.uv_num_list.Add(0); } else { nDashboardJson.uv_num_list.Add(rUVLog.Num); } DashboardLog rFansLog = fansDashLogList.FirstOrDefault(p => p.WebsiteOwner == web && p.Date == rDateInt); if (rFansLog == null) { nDashboardJson.fans_num_list.Add(0); } else { nDashboardJson.fans_num_list.Add(rFansLog.Num); } } nDashboardJson.timestamp = DateTimeHelper.DateTimeToUnixTimestamp(DateTime.Now); string nJson = JsonConvert.SerializeObject(nDashboardJson); if (ndi == null) { Add(new DashboardInfo() { WebsiteOwner = web, Date = nDateInt, Json = nJson }); } else { Update(new DashboardInfo() { WebsiteOwner = web, Date = nDateInt, Json = nJson }); } } }
public void RefreshTimePlayedToday() { var dateTimeHelper = new DateTimeHelper(); TimePlayedToday = TimeSpan.FromMilliseconds( DatabaseManager.PlayTimes.Where(x => dateTimeHelper.IsToday(x.Timestamp)) .Sum(x => x.Duration.TotalMilliseconds)).Add(Service.TimePlayed); }
public PageClosedEventRequestBuilder(string padeId, DateTime timeStamp) : base() { base.AddCustomValues(UTGrammar.UTV1Grammar().PageClosedFieldName, DateTimeHelper.ConvertToUnixTime(timeStamp).ToString()); base.AddCustomValues(UTGrammar.UTV1Grammar().PageIdFieldName, padeId); }
public void DateTimeHelper_EarliestTime_NullOnBothNull() { DateTimeHelper.EarliestTime(null, null) .Should().NotHaveValue("earliest of null and null is null"); }
public OutboxMessage UpdateProcessedDate() { ProcessedDate = DateTimeHelper.GenerateDateTime(); return(this); }
//========================================================================= /// <summary> /// �t�H�[�}�b�g���ꂽ�ԑg�G�s�\�[�h�������Ԃ� /// </summary> /// <remarks> /// </remarks> /// <history>2006/XX/XX �V�K�쐬</history> //========================================================================= public override string ToString() { string myName; try { string dateStr = ""; string timeStr = ""; string station = ""; if(this.HasPlan) { var helper = new DateTimeHelper( this.StartDateTime, Settings.Default.hoursPerDay - 24); dateStr = helper.ToShortDateString(); timeStr = helper.ToShortTimeString(); } station = Parent.tvStation; myName = string.Format( Settings.Default.saveNameFormat, mParent.title, mStoryNumber, mSubTitle, dateStr, timeStr, station); } catch(Exception ex) { throw new UpdatingException("�ۑ��t�@�C��������������������܂���B"); } return myName; }
public Entity GetPersonPreviewInfo(Guid personID, int mode) { //Modes: //1: get person phone numbers in a separate list //2: add an item to connected persons to view person phone numbers //DebugHelper.Break(); var dbHelper = CoreComponent.Instance.MainDbHelper; var personEntity = dbHelper.FetchSingleByID("cmn.Person", personID, new string[] { "PhoneNumbers", "ConnectedPersons.ConnectedPerson.PhoneNumbers", "ConnectedPersons", "PersonRoleRelations.PersonRole" }); var connectedPersonsPosts = dbHelper.FetchMultiple("cmn.ConnectedPersonPost", null, null, null, null, null).Entities; var connectedPersonsOrgUnits = dbHelper.FetchMultiple("cmn.ConnectedPersonsOrganizationUnit", null, null, null, null, null).Entities; var personInfoEntity = new Entity(); var isRealPerson = personEntity.GetFieldValue <Guid>("PersonType") == OptionSetHelper.GetOptionSetItemID("cmn.PersonTypes", "Haghighi"); var state_PreNumber = ""; var state_Text = ""; if (personEntity.GetFieldValue <Guid?>("State") != null) { var state = dbHelper.FetchSingleByID("cmn.State", personEntity.GetFieldValue <Guid>("State"), null); state_Text = state.GetFieldValue <string>("Name"); state_PreNumber = state.GetFieldValue <string>("StatePreNumber"); } var recognitionMethod_Text = ""; if (personEntity.GetFieldValue <Guid?>("RecognitionMethod") != null) { var recognitionMethod = dbHelper.FetchSingleByID("crm.RecognitionMethod", personEntity.GetFieldValue <Guid>("RecognitionMethod"), null); recognitionMethod_Text = recognitionMethod.GetFieldValue <string>("Title"); } var rolesText = ""; foreach (var personRoleRelation in personEntity.GetFieldValue <EntityList>("PersonRoleRelations").Entities) { if (rolesText != "") { rolesText += ", "; } rolesText += personRoleRelation.GetFieldValue <Entity>("PersonRole_Entity").GetFieldValue <string>("Title"); } var connectedPersonsInfos = new EntityList(); if (mode == 2) { var selfConnectedPersonsInfo = new Entity(); selfConnectedPersonsInfo.AddField("ID", personEntity.GetFieldValue <Guid>("ID")); selfConnectedPersonsInfo.AddField("DisplayName", "تلفن های اصلی"); selfConnectedPersonsInfo.AddField("IsActive", true); var genderText = ""; if (personEntity.GetFieldValue <Guid?>("Gender") != null) { genderText = OptionSetHelper.GetOptionSetItemTitle(personEntity.GetFieldValue <Guid>("Gender")); } selfConnectedPersonsInfo.AddField("Gender_Text", genderText); selfConnectedPersonsInfo.AddField("Post_Text", "-"); selfConnectedPersonsInfo.AddField("OrganizationUnit_Text", "-"); selfConnectedPersonsInfo.AddField("OnvaneSazemani", "-"); selfConnectedPersonsInfo.AddField("Email", personEntity.GetFieldValue <string>("Email")); selfConnectedPersonsInfo.AddField("PhoneNumbers", GetPersonPreviewInfo_PersonPhoneNumberInfos(personEntity)); connectedPersonsInfos.Entities.Add(selfConnectedPersonsInfo); } foreach (var personConnectedPerson in personEntity.GetFieldValue <EntityList>("ConnectedPersons").Entities) { var connectedPersonInfo = new Entity(); var connectedPerson = personConnectedPerson.GetFieldValue <Entity>("ConnectedPerson_Entity"); connectedPersonInfo.AddField("ID", personConnectedPerson.GetFieldValue <Guid>("ID")); connectedPersonInfo.AddField("DisplayName", GetPersonDisplayName(connectedPerson)); connectedPersonInfo.AddField("IsActive", personConnectedPerson.GetFieldValue <bool>("IsActive")); var genderText = ""; if (connectedPerson.GetFieldValue <Guid?>("Gender") != null) { genderText = OptionSetHelper.GetOptionSetItemTitle(connectedPerson.GetFieldValue <Guid>("Gender")); } connectedPersonInfo.AddField("Gender_Text", genderText); var post_Text = ""; if (personConnectedPerson.GetFieldValue <Guid?>("ConnectedPersonPost") != null) { post_Text = connectedPersonsPosts.First(o => o.GetFieldValue <Guid>("ID") == personConnectedPerson.GetFieldValue <Guid>("ConnectedPersonPost")).GetFieldValue <string>("Title"); } connectedPersonInfo.AddField("Post_Text", post_Text); var organizationUnit_Text = ""; if (personConnectedPerson.GetFieldValue <Guid?>("OrganizationUnit") != null) { organizationUnit_Text = connectedPersonsOrgUnits.First( o => o.GetFieldValue <Guid>("ID") == personConnectedPerson.GetFieldValue <Guid>("OrganizationUnit")).GetFieldValue <string>("Title"); } connectedPersonInfo.AddField("OrganizationUnit_Text", organizationUnit_Text); connectedPersonInfo.AddField("OnvaneSazemani", personConnectedPerson.GetFieldValue <string>("OnvaneSazemani")); connectedPersonInfo.AddField("Email", connectedPerson.GetFieldValue <string>("Email")); connectedPersonInfo.AddField("PhoneNumbers", GetPersonPreviewInfo_PersonConnectedPersonPhoneNumberInfos(personConnectedPerson)); connectedPersonsInfos.Entities.Add(connectedPersonInfo); } personInfoEntity.AddField("ID", personEntity.GetFieldValue <Guid>("ID")); personInfoEntity.AddField("DisplayName", GetPersonDisplayName(personEntity)); personInfoEntity.AddField("IsRealPerson", isRealPerson); personInfoEntity.AddField("FinancialAccountCode", personEntity.GetFieldValue <string>("FinancialAccountCode")); personInfoEntity.AddField("RecognitionMethod_Text", recognitionMethod_Text); personInfoEntity.AddField("State_Text", state_Text); personInfoEntity.AddField("State_PreNumber", state_PreNumber); personInfoEntity.AddField("CodeEghtesadi", personEntity.GetFieldValue <string>("CodeEghtesadi")); personInfoEntity.AddField("NationalID", personEntity.GetFieldValue <string>("NationalID")); personInfoEntity.AddField("Address1", personEntity.GetFieldValue <string>("Address1")); personInfoEntity.AddField("PostalCode", personEntity.GetFieldValue <string>("PostalCode")); personInfoEntity.AddField("WebsiteAddress", personEntity.GetFieldValue <string>("WebsiteAddress")); personInfoEntity.AddField("Email", personEntity.GetFieldValue <string>("Email")); personInfoEntity.AddField("RolesText", rolesText); var creatorUser_Text = ""; if (personEntity.GetFieldValue <Guid?>("CreatorUser") != null) { creatorUser_Text = dbHelper.FetchSingleByID("afw_SystemUsersView", personEntity.GetFieldValue <Guid>("CreatorUser"), null).GetFieldValue <string>("DisplayName"); } personInfoEntity.AddField("CreatorUser_Text", creatorUser_Text); var creationTime_Text = ""; if (personEntity.GetFieldValue <DateTime?>("CreationTime") != null) { creationTime_Text = DateTimeHelper.GregorianDateToPersian(personEntity.GetFieldValue <DateTime>("CreationTime")); } personInfoEntity.AddField("CreationTime_Text", creationTime_Text); var lastModifierUser_Text = ""; if (personEntity.GetFieldValue <Guid?>("LastModifierUser") != null) { lastModifierUser_Text = dbHelper.FetchSingleByID("afw_SystemUsersView", personEntity.GetFieldValue <Guid>("LastModifierUser"), null).GetFieldValue <string>("DisplayName"); } personInfoEntity.AddField("LastModifierUser_Text", lastModifierUser_Text); var lastModifyTime_Text = ""; if (personEntity.GetFieldValue <DateTime?>("LastModifyTime") != null) { lastModifyTime_Text = DateTimeHelper.GregorianDateToPersian(personEntity.GetFieldValue <DateTime>("LastModifyTime")); } personInfoEntity.AddField("LastModifyTime_Text", lastModifyTime_Text); if (mode == 1) { personInfoEntity.AddField("PhoneNumbers", GetPersonPreviewInfo_PersonPhoneNumberInfos(personEntity)); } personInfoEntity.AddField("ConnectedPersons", connectedPersonsInfos); return(personInfoEntity); }