public SearchResultObject <UserEventLogSearchResult> SearchUserEventLog(UserEventLogSearchCondition searchCondition, string saveOption)
        {
            db = new TimeAttendanceEntities();
            SearchResultObject <UserEventLogSearchResult> searchResult = new SearchResultObject <UserEventLogSearchResult>();

            try
            {
                var listmodel = (from a in db.UserEventLog.AsNoTracking()
                                 join b in db.User.AsNoTracking() on a.UserId equals b.UserId into ab
                                 from abv in ab.DefaultIfEmpty()
                                 select new UserEventLogSearchResult()
                {
                    UserEventLogId = a.UserEventLogId,
                    UserId = a.UserId,
                    Description = a.Description,
                    LogType = a.LogType,
                    LogTypeName = a.LogType == 0 ? "Truy cập hệ thống" : "Khai thác dữ liệu",
                    Type = abv.Type,
                    CreateDate = a.CreateDate,
                    UserName = abv.Name,
                    FullName = abv.FullName
                }).AsQueryable();

                if (!string.IsNullOrEmpty(searchCondition.UserName))
                {
                    listmodel = listmodel.Where(r => r.UserName != null && r.UserName.ToUpper().Contains(searchCondition.UserName.ToUpper()));
                }
                if (!string.IsNullOrEmpty(searchCondition.UserType))
                {
                    listmodel = listmodel.Where(r => r.Type != null && r.Type.Equals(searchCondition.UserType));
                }
                if (!string.IsNullOrEmpty(searchCondition.UserIdSearch))
                {
                    listmodel = listmodel.Where(r => r.UserId != null && r.UserId.Equals(searchCondition.UserIdSearch));
                }
                if (!string.IsNullOrEmpty(searchCondition.FullName))
                {
                    listmodel = listmodel.Where(r => r.FullName != null && r.FullName.ToUpper().Contains(searchCondition.FullName.ToUpper()));
                }
                if (!string.IsNullOrEmpty(searchCondition.Description))
                {
                    listmodel = listmodel.Where(r => r.Description.ToUpper().Contains(searchCondition.Description.ToUpper()));
                }
                if (searchCondition.LogType.HasValue)
                {
                    listmodel = listmodel.Where(r => r.LogType.HasValue && r.LogType.Value == searchCondition.LogType.Value);
                }
                if (searchCondition.LogDateFrom.HasValue)
                {
                    searchCondition.LogDateFrom = DateTimeUtils.ConvertDateFrom(searchCondition.LogDateFrom);
                    listmodel = listmodel.Where(r => r.CreateDate.HasValue && r.CreateDate >= searchCondition.LogDateFrom);
                }
                if (searchCondition.LogDateTo.HasValue)
                {
                    searchCondition.LogDateTo = DateTimeUtils.ConvertDateTo(searchCondition.LogDateTo);
                    listmodel = listmodel.Where(r => r.CreateDate.HasValue && r.CreateDate <= searchCondition.LogDateTo);
                }

                searchResult.TotalItem = listmodel.Select(r => r.UserEventLogId).Count();
                var listResult = SQLHelpper.OrderBy(listmodel, searchCondition.OrderBy, searchCondition.OrderType).Skip((searchCondition.PageNumber - 1) * searchCondition.PageSize)
                                 .Take(searchCondition.PageSize)
                                 .ToList();


                string pathFile = string.Empty;
                if ((saveOption.Equals("PDF") || saveOption.Equals("XLSX")) && searchResult.TotalItem > 0)
                {
                    if (searchResult.TotalItem > Constants.MAX_RETURN_DATA_ROW)
                    {
                        throw new BusinessException(ErrorMessage.ERR007);
                    }
                    else
                    {
                        pathFile = this.Export(saveOption, listmodel.ToList(), searchCondition);
                    }
                }

                searchResult.ListResult = listResult;
                searchResult.PathFile   = pathFile;
            }
            catch (Exception ex)
            {
                throw new ErrorException(ErrorMessage.ERR001, ex.InnerException);
            }

            return(searchResult);
        }
示例#2
0
 /// <summary>
 /// Writes a <see cref="DateTime"/> value.
 /// </summary>
 /// <param name="value">The <see cref="DateTime"/> value to write.</param>
 public override void WriteValue(DateTime value)
 {
     base.WriteValue(value);
     value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
     AddValue(value, BsonType.Date);
 }
示例#3
0
 void m_encode(DateTime time, TimeZoneInfo zone, Boolean preciseTime)
 {
     tagValue = time;
     zoneInfo = zone;
     Init(new Asn1Reader(Asn1Utils.Encode(DateTimeUtils.Encode(time, zone, false, preciseTime), tag)));
 }
示例#4
0
 static Asn1Reader Decode(Asn1Reader asn1Reader, Asn1GeneralizedTime asn1GeneralizedTime)
 {
     Init(asn1Reader, asn1GeneralizedTime);
     asn1GeneralizedTime.tagValue = DateTimeUtils.Decode(asn1Reader);
     return(asn1Reader);
 }
示例#5
0
 public virtual void CheckWorkDaysPlan()
 {
     DateTimeUtils.CheckWorkDaysPlan(MondayIsWorkDay, TuesdayIsWorkDay, WednesdayIsWorkDay, ThursdayIsWorkDay, FridayIsWorkDay, SaturdayIsWorkDay, SundayIsWorkDay);
 }
示例#6
0
        public async Task <VideoListResult> GetVideoListAsync(string openId, string accessToken, int pageSize, long?cursor)
        {
            var logger = LoggerFactory.CreateLogger <OtherApi>();

            var url = Api + "/video/list/"
                      .AddQueryParam("access_token", accessToken)
                      .AddQueryParam("open_id", openId)
                      .AddQueryParam("cursor", (cursor ?? 0).ToString())
                      .AddQueryParam("count", pageSize);

            if (logger.IsEnabled(LogLevel.Trace))
            {
                logger.LogTrace($"GetVideoListAsync,url:{url}");
            }

            DefaultResultModel <VideoListModel> result;
            var httpClient = GetClient();
            {
                var response = await httpClient.GetAsync(url);

                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.LogTrace($"GetVideoListAsync,url:{url} statusCode:{response.StatusCode}");

                    var content = await response.Content.ReadAsStringAsync();

                    logger.LogTrace($"GetVideoListAsync,url:{url} content:{content}");
                }

                result = await response.Content.ReadAsAsync <DefaultResultModel <VideoListModel> >();
            }

            var data = result.data;

            if (data == null)
            {
                return(null);
            }
            ThrowExceptionIfError(data);

            return(new VideoListResult
            {
                Cursor = data.cursor,
                HasMore = data.has_more,
                List = data.list?.Select(m => new VideoItemInfo
                {
                    ItemId = m.item_id,
                    Cover = m.cover,
                    CreateTime = DateTimeUtils.ToDateTime(m.create_time),
                    IsReviewed = m.is_reviewed,
                    IsTop = m.is_top,
                    VideoStatus = Enum.Parse <VideoStatus>(m.video_status.ToString()),
                    ShareUrl = m.share_url,
                    Title = m.title,
                    Statistics = new VideoStatistics
                    {
                        CommentCount = m.statistics.comment_count,
                        DiggCount = m.statistics.digg_count,
                        DownloadCount = m.statistics.download_count,
                        ForwardCount = m.statistics.forward_count,
                        PlayCount = m.statistics.play_count,
                        ShareCount = m.statistics.share_count,
                    }
                }).ToList(),
            });
        }
示例#7
0
 public static string GetAge(this DateTime date)
 {
     return(DateTimeUtils.GetAge(date).ToString());
 }
示例#8
0
        public void Sleep(int millisecondsTimeout)
        {
            TimeSpan timeSpan = DateTimeUtils.GetTimeSpan(millisecondsTimeout);

            Sleep(timeSpan);
        }
示例#9
0
 public MovieService(ShowTimeService showTimeService, MovieRepository MovieRepository, FileService fileService, DateTimeUtils dateTimeUtils)
 {
     this.repository      = MovieRepository;
     this.fileService     = fileService;
     this.dateTimeUtils   = dateTimeUtils;
     this.showTimeService = showTimeService;
 }
示例#10
0
 public override string ToString() => Name ?? Selection?.ToString() ?? DateTimeUtils.FormatTimeRange(StartTime, EndTime);
示例#11
0
        /// <summary>
        /// Get information regarding a specific transfer.
        /// </summary>
        public static PhpValue curl_getinfo(CURLResource ch, int opt = 0)
        {
            if (ch != null && ch.Result != null)
            {
                var r = ch.Result;

                switch (opt)
                {
                case 0:
                    // array of all information
                    var arr = new PhpArray()
                    {
                        { "url", r.ResponseUri?.AbsoluteUri },
                        { "content_type", r.ContentType },
                        { "http_code", (long)r.StatusCode },
                        { "header_size", r.HeaderSize },
                        { "filetime", DateTimeUtils.UtcToUnixTimeStamp(r.LastModified) },
                        { "total_time", r.TotalTime.TotalSeconds },
                        { "download_content_length", r.ContentLength },
                        { "redirect_url", ch.FollowLocation&& r.ResponseUri != null ? string.Empty : r.ResponseUri.AbsoluteUri }
                    };

                    if (ch.RequestHeaders != null)
                    {
                        arr["request_header"] = ch.RequestHeaders;
                    }

                    return(arr);

                case CURLConstants.CURLINFO_EFFECTIVE_URL:
                    return(r.ResponseUri?.AbsoluteUri);

                case CURLConstants.CURLINFO_REDIRECT_URL:
                    return(ch.FollowLocation && r.ResponseUri != null ? string.Empty : r.ResponseUri.AbsoluteUri);

                case CURLConstants.CURLINFO_HTTP_CODE:
                    return((int)r.StatusCode);

                case CURLConstants.CURLINFO_FILETIME:
                    return(DateTimeUtils.UtcToUnixTimeStamp(r.LastModified));

                case CURLConstants.CURLINFO_CONTENT_TYPE:
                    return(r.ContentType);

                case CURLConstants.CURLINFO_CONTENT_LENGTH_DOWNLOAD:
                    return(r.ContentLength);

                case CURLConstants.CURLINFO_TOTAL_TIME:
                    return(r.TotalTime.TotalSeconds);

                case CURLConstants.CURLINFO_PRIVATE:
                    return(r.Private.IsSet ? r.Private : PhpValue.False);

                case CURLConstants.CURLINFO_COOKIELIST:
                    return((ch.CookieFileSet && ch.Result != null) ? CreateCookieArray(ch.Result.Cookies) : PhpArray.Empty);

                case CURLConstants.CURLINFO_HEADER_SIZE:
                    return(r.HeaderSize);

                case CURLConstants.CURLINFO_HEADER_OUT:
                    return(r.RequestHeaders ?? PhpValue.False);

                default:
                    PhpException.ArgumentValueNotSupported(nameof(opt), opt);
                    break;
                }
            }

            // failure:
            return(PhpValue.False);
        }
示例#12
0
        private void ReadType(BsonType type)
        {
            DateTime time2;

            switch (type)
            {
            case BsonType.Number:
            {
                double num = this.ReadDouble();
                if (base._floatParseHandling != FloatParseHandling.Decimal)
                {
                    base.SetToken(JsonToken.Float, num);
                    return;
                }
                base.SetToken(JsonToken.Float, Convert.ToDecimal(num, CultureInfo.InvariantCulture));
                return;
            }

            case BsonType.String:
            case BsonType.Symbol:
                base.SetToken(JsonToken.String, this.ReadLengthString());
                return;

            case BsonType.Object:
            {
                base.SetToken(JsonToken.StartObject);
                ContainerContext newContext = new ContainerContext(BsonType.Object);
                this.PushContext(newContext);
                newContext.Length = this.ReadInt32();
                return;
            }

            case BsonType.Array:
            {
                base.SetToken(JsonToken.StartArray);
                ContainerContext newContext = new ContainerContext(BsonType.Array);
                this.PushContext(newContext);
                newContext.Length = this.ReadInt32();
                return;
            }

            case BsonType.Binary:
            {
                byte[] b    = this.ReadBinary(out BsonBinaryType type2);
                object obj2 = (type2 != BsonBinaryType.Uuid) ? ((object)b) : ((object)new Guid(b));
                base.SetToken(JsonToken.Bytes, obj2);
                return;
            }

            case BsonType.Undefined:
                base.SetToken(JsonToken.Undefined);
                return;

            case BsonType.Oid:
            {
                byte[] buffer2 = this.ReadBytes(12);
                base.SetToken(JsonToken.Bytes, buffer2);
                return;
            }

            case BsonType.Boolean:
            {
                bool flag = Convert.ToBoolean(this.ReadByte());
                base.SetToken(JsonToken.Boolean, flag);
                return;
            }

            case BsonType.Date:
            {
                DateTime time = DateTimeUtils.ConvertJavaScriptTicksToDateTime(this.ReadInt64());
                switch (this.DateTimeKindHandling)
                {
                case DateTimeKind.Unspecified:
                    time2 = DateTime.SpecifyKind(time, DateTimeKind.Unspecified);
                    goto Label_019C;

                case DateTimeKind.Local:
                    time2 = time.ToLocalTime();
                    goto Label_019C;
                }
                time2 = time;
                break;
            }

            case BsonType.Null:
                base.SetToken(JsonToken.Null);
                return;

            case BsonType.Regex:
            {
                string str  = this.ReadString();
                string str2 = this.ReadString();
                string str3 = "/" + str + "/" + str2;
                base.SetToken(JsonToken.String, str3);
                return;
            }

            case BsonType.Reference:
                base.SetToken(JsonToken.StartObject);
                this._bsonReaderState = BsonReaderState.ReferenceStart;
                return;

            case BsonType.Code:
                base.SetToken(JsonToken.String, this.ReadLengthString());
                return;

            case BsonType.CodeWScope:
                base.SetToken(JsonToken.StartObject);
                this._bsonReaderState = BsonReaderState.CodeWScopeStart;
                return;

            case BsonType.Integer:
                base.SetToken(JsonToken.Integer, (long)this.ReadInt32());
                return;

            case BsonType.TimeStamp:
            case BsonType.Long:
                base.SetToken(JsonToken.Integer, this.ReadInt64());
                return;

            default:
                throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
            }
Label_019C:
            base.SetToken(JsonToken.Date, time2);
        }
示例#13
0
        protected override async void ConvertAsync(RecyclerView.ViewHolder holder, QuestionAnswersModel model)
        {
            var baseHolder   = holder as BaseAdapter.BaseViewHolder;
            var linearLayout = (baseHolder.GetView(Resource.Id.linearLayout) as LinearLayout);

            linearLayout.Tag = model.AnswerID;
            linearLayout.SetOnClickListener(this);
            (baseHolder.GetView(Resource.Id.txtDateAdded) as TextView).Text = DateTimeUtils.CommonTime(Convert.ToDateTime(model.DateAdded));
            (baseHolder.GetView(Resource.Id.txtContent) as TextView).SetText(Html.FromHtml(model.Answer), TextView.BufferType.Spannable);
            (baseHolder.GetView(Resource.Id.progressBar) as ProgressBar).Visibility = ViewStates.Gone;
            var imgUserUrl = (baseHolder.GetView(Resource.Id.imgIconName) as ImageView);
            var imgDelete  = (baseHolder.GetView(Resource.Id.imgDelete) as ImageButton);

            imgDelete.Tag = model.AnswerID;
            imgDelete.SetOnClickListener(this);
            (baseHolder.GetView(Resource.Id.progressBar) as ProgressBar).Visibility = ViewStates.Gone;
            var txtCommentCount = (baseHolder.GetView(Resource.Id.txtCommentCount) as TextView);

            if (model.CommentCounts > 0)
            {
                txtCommentCount.Text = " " + model.CommentCounts;
            }
            else
            {
                txtCommentCount.Text = "";
            }
            var txtIsBest = (baseHolder.GetView(Resource.Id.txtIsBest) as TextView);

            txtIsBest.Selected = false;
            if (model.IsBest)
            {
                txtIsBest.Visibility = ViewStates.Visible;
            }
            else
            {
                txtIsBest.Visibility = ViewStates.Gone;
            }
            if (User != null && User.UserId == model.AnswerUserInfo.UCUserID)
            {
                User.Score = model.AnswerUserInfo.QScore;
                await SQLiteUtils.Instance().UpdateUser(User);

                imgDelete.Visibility = ViewStates.Visible;
            }
            else
            {
                imgDelete.Visibility = ViewStates.Gone;
            }
            if (model.AnswerUserInfo != null && model.AnswerUserInfo.UserID > 0)
            {
                (baseHolder.GetView(Resource.Id.txtUserName) as TextView).Text = Html.FromHtml(model.AnswerUserInfo.UserName).ToString();
                (baseHolder.GetView(Resource.Id.txtScore) as TextView).Text    = HtmlUtils.GetScoreName(model.AnswerUserInfo.QScore) + " ¡¤ " + model.AnswerUserInfo.QScore + "Ô°¶¹ ¡¤ ";
                try
                {
                    Picasso.With(context)
                    .Load("https://pic.cnblogs.com/face/" + model.AnswerUserInfo.IconName)
                    .Placeholder(Resource.Drawable.placeholder)
                    .Error(Resource.Drawable.placeholder)
                    .Transform(new CircleTransform())
                    .Into(imgUserUrl);
                }
                catch
                {
                }
            }
        }
示例#14
0
        private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
        {
            if (contract.ContractType == JsonContractType.Primitive)
            {
                JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
                switch (primitiveContract.TypeCode)
                {
                case PrimitiveTypeCode.DateTime:
                case PrimitiveTypeCode.DateTimeNullable:
                {
                    DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling);

                    escape = false;
                    StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
                    DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
                    return(sw.ToString());
                }

#if HAVE_DATE_TIME_OFFSET
                case PrimitiveTypeCode.DateTimeOffset:
                case PrimitiveTypeCode.DateTimeOffsetNullable:
                {
                    escape = false;
                    StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
                    DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
                    return(sw.ToString());
                }
#endif
                case PrimitiveTypeCode.Double:
                case PrimitiveTypeCode.DoubleNullable:
                {
                    double d = (double)name;

                    escape = false;
                    return(d.ToString("R", CultureInfo.InvariantCulture));
                }

                case PrimitiveTypeCode.Single:
                case PrimitiveTypeCode.SingleNullable:
                {
                    float f = (float)name;

                    escape = false;
                    return(f.ToString("R", CultureInfo.InvariantCulture));
                }

                default:
                {
                    escape = true;

                    if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string enumName))
                    {
                        return(enumName);
                    }

                    return(Convert.ToString(name, CultureInfo.InvariantCulture));
                }
                }
            }
            else if (TryConvertToString(name, name.GetType(), out string propertyName))
            {
                escape = true;
                return(propertyName);
            }
            else
            {
                escape = true;
                return(name.ToString());
            }
        }
示例#15
0
        public void WriteDateTime()
        {
            DateTimeResult result = null;

            result = TestDateTime("DateTime Max", DateTime.MaxValue);
            Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
            Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
            Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);

            DateTime year2000local  = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
            string   localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

            result = TestDateTime("DateTime Local", year2000local);
            Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
            Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
            Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);

            DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);

            localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

            result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
            Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
            Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
            Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);

            DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);

            localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

            result = TestDateTime("DateTime Local with ticks", ticksLocal);
            Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
            Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
            Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);

            DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);

            result = TestDateTime("DateTime Unspecified", year2000Unspecified);
            Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
            Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
            Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);

            DateTime year2000Utc    = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
            string   utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");

            result = TestDateTime("DateTime Utc", year2000Utc);
            Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
            Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
            Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);

            DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);

            utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");

            result = TestDateTime("DateTime Unix Epoc", unixEpoc);
            Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
            Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
            Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);

            result = TestDateTime("DateTime Min", DateTime.MinValue);
            Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
            Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
            Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);

            result = TestDateTime("DateTime Default", default(DateTime));
            Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
            Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
            Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
            Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
            Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
            Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);

#if !NET20
            result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
            Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
            Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
            Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
            Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
            Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
            Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
            Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);

            result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
            Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
            Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
        }
示例#16
0
        public void GetClientArticleSuccess(ArticlesModel model)
        {
            if (model != null)
            {
                handler.Post(() =>
                {
                    article          = model;
                    txtTitle.Text    = article.Title;
                    txtAuthor.Text   = HtmlUtils.GetHtml(article.Author).ToString();
                    txtPostdate.Text = DateTimeUtils.CommonTime(article.PostDate);

                    if (article.DiggCount > 0)
                    {
                        txtDigg.Text = article.DiggCount.ToString();
                    }
                    if (article.ViewCount > 0)
                    {
                        txtRead.Text = article.ViewCount.ToString();
                    }
                    if (article.CommentCount > 0)
                    {
                        txtComments.Text = article.CommentCount.ToString();
                    }
                    (txtComments.Parent as FrameLayout).Click += delegate
                    {
                        ArticleCommentsActivity.Start(this, article.BlogApp, article.Id);
                    };
                    (txtBookmark.Parent as FrameLayout).Click += delegate
                    {
                        var linkurl = article.Url;
                        var title   = article.Title + " - " + article.Author + " - ²©¿ÍÔ°";
                        BookmarkAddActivity.Start(this, linkurl, title, true);
                    };

                    if (article.Body == null || article.Body == "")
                    {
                        OnRefresh();
                    }
                    else
                    {
                        GetServiceArticleSuccess(model);
                    }
                    try
                    {
                        Picasso.With(this)
                        .Load(article.Avatar)
                        .Placeholder(Resource.Drawable.placeholder)
                        .Error(Resource.Drawable.placeholder)
                        .Transform(new CircleTransform())
                        .Into(imgAvatar);
                    }
                    catch (Exception)
                    {
                    }
                });
            }
            else
            {
                OnRefresh();
            }
        }
示例#17
0
        public override void Init(ISpider spider)
        {
            base.Init(spider);
            RedisConnection = Cache.Instance.Get(ConnectString);
            if (RedisConnection == null)
            {
                RedisConnection = new RedisConnection(ConnectString);
                Cache.Instance.Set(ConnectString, RedisConnection);
            }

            var md5 = Encrypt.Md5Encrypt(spider.Identity);

            _itemKey         = $"dotnetspider:scheduler:{md5}:items";
            _setKey          = $"dotnetspider:scheduler:{md5}:set";
            _queueKey        = $"dotnetspider:scheduler:{md5}:queue";
            _errorCountKey   = $"dotnetspider:scheduler:{md5}:numberOfFailures";
            _successCountKey = $"dotnetspider:scheduler:{md5}:numberOfSuccessful";
            _identityMd5     = md5;

            NetworkCenter.Current.Execute("rds-in", () =>
            {
                RedisConnection.Database.SortedSetAdd(TasksKey, spider.Identity, (long)DateTimeUtils.GetCurrentTimeStamp());
            });
        }
示例#18
0
        protected override void OnParametersSet()
        {
            _condition = FilterSettings.SingleOrDefault(r => r != ColumnFilterValue.Null &&
                                                        r.FilterType == GridFilterType.Condition).FilterValue;
            if (string.IsNullOrWhiteSpace(_condition))
            {
                _condition = GridFilterCondition.And.ToString("d");
            }

            var filterSettings = FilterSettings.Where(r => r != ColumnFilterValue.Null &&
                                                      r.FilterType != GridFilterType.Condition).Select(r =>
                                                                                                       new Filter(r.FilterType.ToString("d"), DateTimeUtils.GetWeekDateTimeString(r.FilterValue)))
                                 .ToList();

            _clearVisible = filterSettings.Count() > 0;
            if (filterSettings.Count() == 0)
            {
                filterSettings.Add(new Filter(GridFilterType.Equals.ToString("d"), ""));
            }
            _filters = filterSettings.ToArray();
        }
示例#19
0
        public async Task <List <VideoItemInfo> > GetVideoDataAsync(string openId, string accessToken, string[] itemIds)
        {
            var logger = LoggerFactory.CreateLogger <OtherApi>();

            var url = Api + "/video/data/"
                      .AddQueryParam("access_token", accessToken)
                      .AddQueryParam("open_id", openId);

            if (logger.IsEnabled(LogLevel.Trace))
            {
                logger.LogTrace($"GetVideoDataAsync,url:{url}");
            }

            DefaultResultModel <VideoDataModel> result;
            var httpClient = GetClient();
            {
                var response = await httpClient.PostAsJsonAsync(url, new
                {
                    item_ids = itemIds
                });

                if (logger.IsEnabled(LogLevel.Trace))
                {
                    var requestContent = await response.RequestMessage.Content.ReadAsStringAsync();

                    logger.LogTrace($"GetVideoDataAsync,url:{url} requestContent:{requestContent}");

                    logger.LogTrace($"GetVideoDataAsync,url:{url} statusCode:{response.StatusCode}");

                    var content = await response.Content.ReadAsStringAsync();

                    logger.LogTrace($"GetVideoDataAsync,url:{url} content:{content}");
                }

                result = await response.Content.ReadAsAsync <DefaultResultModel <VideoDataModel> >();
            }

            var data = result.data;

            ThrowExceptionIfError(data);

            return(data.list?.Select(m => new VideoItemInfo
            {
                ItemId = m.item_id,
                Cover = m.cover,
                CreateTime = DateTimeUtils.ToDateTime(m.create_time),
                VideoStatus = Enum.Parse <VideoStatus>(m.video_status.ToString()),
                IsReviewed = m.is_reviewed,
                IsTop = m.is_top,
                ShareUrl = m.share_url,
                Title = m.title,
                Statistics = new VideoStatistics
                {
                    CommentCount = m.statistics.comment_count,
                    DiggCount = m.statistics.digg_count,
                    DownloadCount = m.statistics.download_count,
                    ForwardCount = m.statistics.forward_count,
                    PlayCount = m.statistics.play_count,
                    ShareCount = m.statistics.share_count,
                }
            }).ToList());
        }
示例#20
0
        public DeviceStatus ParsePosition()
        {
            // orden del array

            //0   Encabezado del paquete
            //1   IMEI del equipo
            //2   Número de paquete            string[] parse = _command.Split(new[] { "<", ">" }, StringSplitOptions.RemoveEmptyEntries);
            //3   Evento que generó el paquete            var eventoLength = (_command.Length == 48 || _command.Length == 46 ? 3 : 2);
            //4   Nivel de señal GSM. (Entre 0 y 31)            var evento = (byte)0;
            //5   U1 en voltios            var hdop = (byte)0;
            //6   I1 en Ampere por 10. (10 equivale a 1.0 Amp)            var entradas = Convert.ToByte("0", 16);
            //7   U2 en voltios            var time = DateTimeUtils.SafeParseFormat(parse[10] + parse[2].Split('.')[0], "ddMMyyHHmmss");
            //8   I2 en Ampere por 10. (27 equivale a 2.7 Amp)
            //9   D1 Entrada DIN1 inactiva            /*
            //10  D2 Entrada D2 activa                Latitude: DD MM.MMMM
            //11  T1 Temperatura 25ºC                Longitude: DDD MM.MMMM   T1:valor,T2:valor
            //12  T2 Temperatura 23ºC             3259.816776,N
            //13  T3 Sensor NTC3 abierto             09642.858868,W
            //14  T4 Sensor NTC4 en cortocircuito             latitud max -90 +90
            //15  Latitud             32*59.816776
            //16  Longitud             longitud max -180 + 180
            //17  Modelo y versión de firmware del equipo             096*42.858868
            //18  Fecha y hora de la generación del evento GMT0             */
            //19  Fin de paquete


            string[] parse    = _command.Split(new[] { "<", ">" }, StringSplitOptions.RemoveEmptyEntries);
            var      entradas = Convert.ToByte("0", 16);
            var      time     = DateTimeUtils.SafeParseFormat(parse[17], "yyyy-MM-dd HH:mm:ss");

            //-34.603718 Latitud
            //-58.38158 Longitud
            var lat    = Convert.ToSingle(parse[14].Split('.')[0]);
            var lon    = Convert.ToSingle(parse[15].Split('.')[0]);
            var hdop   = Convert.ToByte(parse[3]);
            var evento = Convert.ToByte(parse[3]);
            var vel    = Convert.ToSingle(0);
            var dir    = Convert.ToSingle(1); // (0 ..359), Norte = 0, Este = 90, Sur = 180, Oeste = 270

            _node.Imei = parse[3];

            var devId = (Int32?)null;

            if (_node != null)
            {
                devId = _node.Id;
            }


            GPSPoint gpoint = null;

            try
            {
                gpoint = new GPSPoint(time, lat, lon, vel, GPSPoint.SourceProviders.Unespecified, 0)
                {
                    Course         = new Course(dir),
                    HDOP           = hdop,
                    IgnitionStatus = BitHelper.AreBitsSet(entradas, 7) ? IgnitionStatus.On : IgnitionStatus.Off
                };
                if (devId != null)
                {
                    gpoint.DeviceId = devId.Value;
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                STrace.Exception(typeof(AbsolutDeviceCommand).FullName, e, IdNum ?? 0, String.Format("Posición inválida {0}", getCommand()));
                gpoint = null;
            }

            var result = new DeviceStatus(devId, gpoint, evento, entradas);

            return(result);
        }
示例#21
0
        private void WriteTokenInternal(BsonToken t)
        {
            switch (t.Type)
            {
            case BsonType.Object:
            {
                BsonObject value = (BsonObject)t;
                _writer.Write(value.CalculatedSize);
                foreach (BsonProperty property in value)
                {
                    _writer.Write((sbyte)property.Value.Type);
                    WriteString((string)property.Name.Value, property.Name.ByteCount, null);
                    WriteTokenInternal(property.Value);
                }
                _writer.Write((byte)0);
            }
            break;

            case BsonType.Array:
            {
                BsonArray value = (BsonArray)t;
                _writer.Write(value.CalculatedSize);
                ulong index = 0;
                foreach (BsonToken c in value)
                {
                    _writer.Write((sbyte)c.Type);
                    WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
                    WriteTokenInternal(c);
                    index++;
                }
                _writer.Write((byte)0);
            }
            break;

            case BsonType.Integer:
            {
                BsonValue value = (BsonValue)t;
                _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
            }
            break;

            case BsonType.Long:
            {
                BsonValue value = (BsonValue)t;
                _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
            }
            break;

            case BsonType.Number:
            {
                BsonValue value = (BsonValue)t;
                _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
            }
            break;

            case BsonType.String:
            {
                BsonString value = (BsonString)t;
                WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
            }
            break;

            case BsonType.Boolean:
            {
                BsonValue value = (BsonValue)t;
                _writer.Write((bool)value.Value);
            }
            break;

            case BsonType.Null:
            case BsonType.Undefined:
                break;

            case BsonType.Date:
            {
                BsonValue value = (BsonValue)t;

                long ticks = 0;

                if (value.Value is DateTime)
                {
                    DateTime dateTime = (DateTime)value.Value;
                    if (DateTimeKindHandling == DateTimeKind.Utc)
                    {
                        dateTime = dateTime.ToUniversalTime();
                    }
                    else if (DateTimeKindHandling == DateTimeKind.Local)
                    {
                        dateTime = dateTime.ToLocalTime();
                    }

                    ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
                }
#if !NET20
                else
                {
                    DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
                    ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
                }
#endif

                _writer.Write(ticks);
            }
            break;

            case BsonType.Binary:
            {
                BsonBinary value = (BsonBinary)t;

                byte[] data = (byte[])value.Value;
                _writer.Write(data.Length);
                _writer.Write((byte)value.BinaryType);
                _writer.Write(data);
            }
            break;

            case BsonType.Oid:
            {
                BsonValue value = (BsonValue)t;

                byte[] data = (byte[])value.Value;
                _writer.Write(data);
            }
            break;

            case BsonType.Regex:
            {
                BsonRegex value = (BsonRegex)t;

                WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
                WriteString((string)value.Options.Value, value.Options.ByteCount, null);
            }
            break;

            default:
                throw new ArgumentOutOfRangeException("t", "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
            }
        }
示例#22
0
        public bool SyncTimeAttendance(DateTime day)
        {
            try
            {
                db = new TimeAttendanceEntities();
                DateTime dateFrom     = DateTimeUtils.ConvertDateFrom(day);
                DateTime dateTo       = DateTimeUtils.ConvertDateTo(day);
                var      listDataSync = (from a in db.Employee
                                         join b in db.Department on a.DepartmentId equals b.DepartmentId
                                         join c in db.JobTitle on a.JobTitleId equals c.JobTitleId
                                         join d in db.TimeAttendanceLog.Where(r => r.Date >= dateFrom && r.Date <= dateTo) on a.EmployeeId equals d.EmployeeId into ad
                                         from adv in ad.DefaultIfEmpty()
                                         select new
                {
                    a.EmployeeId,
                    a.Name,
                    a.Code,
                    DepartmentName = b.Name,
                    JobTitleName = c.Name,
                    Gender = !a.Gender.HasValue ? "Khác" : a.Gender.Value == Constants.Male ? "Nam" : "Nữ",
                    Date = adv != null ? adv.TimeIn : dateFrom,
                    TimeIn = adv != null ? adv.TimeIn : null,
                    TimeOut = adv != null ? adv.TimeOut : null,
                    Total = adv != null ? adv.Total : null,
                    LateMinutes = adv != null ? adv.LateMinutes : null,
                    EarlyMinutes = adv != null ? adv.EarlyMinutes : null,
                }).ToList();
                using (var trans = db.Database.BeginTransaction())
                {
                    try
                    {
                        var checkSyncTimeAttendance = db.SyncTimeAttendance.Where(r => r.Date >= dateFrom && r.Date <= dateTo);
                        if (checkSyncTimeAttendance != null && checkSyncTimeAttendance.Count() > 0)
                        {
                            db.SyncTimeAttendance.RemoveRange(checkSyncTimeAttendance);
                        }

                        List <SyncTimeAttendance> listSync = new List <SyncTimeAttendance>();
                        SyncTimeAttendance        model;
                        foreach (var itemSync in listDataSync)
                        {
                            model = new SyncTimeAttendance()
                            {
                                SyncAttendanceId = Guid.NewGuid().ToString(),
                                EmployeeId       = itemSync.EmployeeId,
                                EmployeeName     = itemSync.Name,
                                Code             = itemSync.Code,
                                DepartmentName   = itemSync.DepartmentName,
                                JobTitleName     = itemSync.JobTitleName,
                                Gender           = itemSync.Gender,
                                Date             = itemSync.Date.Value,
                                TimeIn           = itemSync.TimeIn,
                                TimeOut          = itemSync.TimeOut,
                                Total            = itemSync.Total,
                                LateMinutes      = itemSync.LateMinutes,
                                EarlyMinutes     = itemSync.EarlyMinutes,
                            };
                            model.IsLate   = false;
                            model.IsEarly  = false;
                            model.IsAbsent = false;
                            //Đi muộn
                            if (model.TimeIn != null && model.LateMinutes != null && model.LateMinutes > 0)
                            {
                                model.IsLate = true;
                            }
                            //Về sớm
                            if (model.TimeOut != null && model.EarlyMinutes != null && model.EarlyMinutes > 0)
                            {
                                model.IsEarly = true;
                            }
                            //Nghỉ
                            if (model.TimeIn == null && model.TimeOut == null)
                            {
                                model.IsAbsent = true;
                            }
                            listSync.Add(model);
                        }
                        db.SyncTimeAttendance.AddRange(listSync);
                        db.SaveChanges();
                        trans.Commit();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#23
0
        public static void EnsureSeedDataForContext(this AirlineSystemContext context)
        {
            var italy = new Country {
                Name = "Italy"
            };
            var spain = new Country {
                Name = "Spain"
            };
            var bg = new Country {
                Name = "Bulgaria"
            };
            var uk = new Country {
                Name = "UK"
            };
            var germany = new Country {
                Name = "Germany"
            };
            var france = new Country {
                Name = "France"
            };

            if (!context.Countries.Any())
            {
                context.Countries.AddRange(italy, spain, bg, uk, germany, france);
                context.SaveChanges();
            }

            var sf = new City {
                Name = "Sofia", Country = bg
            };
            var rome = new City {
                Name = "Rome", Country = italy
            };
            var milan = new City {
                Name = "Milan", Country = italy
            };
            var madrid = new City {
                Name = "Madrid", Country = spain
            };
            var barcelona = new City {
                Name = "Barcelona", Country = spain
            };
            var london = new City {
                Name = "London", Country = uk
            };
            var berlin = new City {
                Name = "Berlin", Country = germany
            };
            var cologne = new City {
                Name = "Cologne", Country = germany
            };
            var hamburg = new City {
                Name = "Hamburg", Country = germany
            };
            var frankfurt = new City {
                Name = "Frankfurt", Country = germany
            };
            var paris = new City {
                Name = "Paris", Country = france
            };
            var nice = new City {
                Name = "Nice", Country = france
            };

            if (!context.Cities.Any())
            {
                context.Cities.AddRange(sf, rome, milan, madrid, barcelona, london, berlin, cologne, hamburg, frankfurt, paris, nice);
                context.SaveChanges();
            }

            var sfAirport = new Airport {
                Name = "Vrajdebna", IataAirportCode = "SOF", City = sf
            };
            var fiumicino = new Airport {
                Name = "Fiumicino", IataAirportCode = "FCO", City = rome
            };
            var ciampino = new Airport {
                Name = "Ciampino", IataAirportCode = "CIA", City = rome
            };
            var malpensa = new Airport {
                Name = "Malpensa", IataAirportCode = "MXP", City = milan
            };
            var barajas = new Airport {
                Name = "Barajas", IataAirportCode = "MAD", City = madrid
            };
            var elprat = new Airport {
                Name = "El Prat", IataAirportCode = "BCN", City = barcelona
            };
            var heathrow = new Airport {
                Name = "Heathrow", IataAirportCode = "LHA", City = london
            };
            var gatwick = new Airport {
                Name = "Gatwick", IataAirportCode = "LGA", City = london
            };
            var luton = new Airport {
                Name = "Luton", IataAirportCode = "LTN", City = london
            };
            var tegel = new Airport {
                Name = "Tegel", IataAirportCode = "TXL", City = berlin
            };
            var cologneAirport = new Airport {
                Name = "Koeln-Bonn", IataAirportCode = "CGN", City = cologne
            };
            var hamburgAirport = new Airport {
                Name = "Hamburg", IataAirportCode = "HAM", City = hamburg
            };
            var frankfurtAirport = new Airport {
                Name = "Frankfurt/Main", IataAirportCode = "FRA", City = frankfurt
            };
            var beauvais = new Airport {
                Name = "Beauvais", IataAirportCode = "BVA", City = paris
            };
            var orly = new Airport {
                Name = "Orly", IataAirportCode = "ORY", City = paris
            };
            var charlesDeGaulle = new Airport {
                Name = "Charles de Gaulle", IataAirportCode = "CDG", City = paris
            };
            var niceAirport = new Airport {
                Name = "Côte d'Azur", IataAirportCode = "NCE", City = nice
            };

            if (!context.Airorts.Any())
            {
                context.Airorts.AddRange(sfAirport, fiumicino, ciampino, malpensa, barajas, elprat, heathrow, gatwick, luton, tegel, cologneAirport, hamburgAirport, frankfurtAirport, beauvais, orly, charlesDeGaulle, niceAirport);
                context.SaveChanges();
            }

            if (!context.Flights.Any())
            {
                var startDate  = new DateTime(2019, 07, 01);
                var endDate    = new DateTime(2019, 12, 31);
                var mondays    = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Monday);
                var tuesdays   = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Tuesday);
                var wednesdays = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Wednesday);
                var thursdays  = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Thursday);
                var fridays    = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Friday);
                var saturdays  = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Saturday);
                var sundays    = DateTimeUtils.GetDatesByDayOfWeek(startDate, endDate, DayOfWeek.Sunday);

                foreach (var date in mondays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = beauvais,
                        ArrivalAirport    = hamburgAirport,
                        FlightPrice       = 55,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 8, 05, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 20, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = hamburgAirport,
                        ArrivalAirport    = beauvais,
                        FlightPrice       = 55,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 12, 20, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 14, 40, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = charlesDeGaulle,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 60,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 6, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 7, 30, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = charlesDeGaulle,
                        FlightPrice       = 60,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 8, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 9, 30, 0)
                    };
                    var outboundFlight_3 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 40, 0)
                    };
                    var inboundFlight_3 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 40, 0)
                    };
                    var outboundFlight_4 = new Flight
                    {
                        DepartureAirport  = charlesDeGaulle,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 54,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 15, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 16, 35, 0)
                    };
                    var inboundFlight_4 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = charlesDeGaulle,
                        FlightPrice       = 54,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 17, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 18, 35, 0)
                    };
                    var outboundFlight_5 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 26, 0)
                    };
                    var inboundFlight_5 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 26, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                    context.Flights.Add(outboundFlight_3);
                    context.Flights.Add(inboundFlight_3);
                    context.Flights.Add(outboundFlight_4);
                    context.Flights.Add(inboundFlight_4);
                    context.Flights.Add(outboundFlight_5);
                    context.Flights.Add(inboundFlight_5);
                }

                foreach (var date in tuesdays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = sfAirport,
                        ArrivalAirport    = malpensa,
                        FlightPrice       = 30,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 13, 25, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = malpensa,
                        ArrivalAirport    = sfAirport,
                        FlightPrice       = 30,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 15, 25, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 17, 30, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 40, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 36, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 40, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 36, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                }

                foreach (var date in wednesdays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = barajas,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 35,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 05, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 11, 45, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = barajas,
                        FlightPrice       = 35,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 13, 45, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 16, 25, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 40, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 40, 0)
                    };
                    var outboundFlight_3 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 26, 0)
                    };
                    var inboundFlight_3 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 26, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                    context.Flights.Add(outboundFlight_3);
                    context.Flights.Add(inboundFlight_3);
                }

                foreach (var date in thursdays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = sfAirport,
                        ArrivalAirport    = malpensa,
                        FlightPrice       = 30,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 18, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 20, 40, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = malpensa,
                        ArrivalAirport    = sfAirport,
                        FlightPrice       = 30,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 21, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 23, 35, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 23,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 13, 05, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 23,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 13, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 15, 05, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                }

                foreach (var date in fridays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = charlesDeGaulle,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 60,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 9, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 10, 30, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = charlesDeGaulle,
                        FlightPrice       = 60,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 11, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 30, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 12, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 14, 10, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 88,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 15, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 16, 35, 0)
                    };
                    var outboundFlight_3 = new Flight
                    {
                        DepartureAirport  = charlesDeGaulle,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 54,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 10, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 11, 35, 0)
                    };
                    var inboundFlight_3 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = charlesDeGaulle,
                        FlightPrice       = 54,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 12, 15, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 13, 35, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                    context.Flights.Add(outboundFlight_3);
                    context.Flights.Add(inboundFlight_3);
                }

                foreach (var date in saturdays)
                {
                    var outboundFlight = new Flight
                    {
                        DepartureAirport  = frankfurtAirport,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 12, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 13, 26, 0)
                    };
                    var inboundFlight = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = frankfurtAirport,
                        FlightPrice       = 18,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 14, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 15, 26, 0)
                    };
                    context.Flights.Add(outboundFlight);
                    context.Flights.Add(inboundFlight);
                }

                foreach (var date in sundays)
                {
                    var outboundFlight_1 = new Flight
                    {
                        DepartureAirport  = barajas,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 35,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 10, 00, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 12, 50, 0)
                    };
                    var inboundFlight_1 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = barajas,
                        FlightPrice       = 35,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 13, 50, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 16, 30, 0)
                    };
                    var outboundFlight_2 = new Flight
                    {
                        DepartureAirport  = cologneAirport,
                        ArrivalAirport    = heathrow,
                        FlightPrice       = 23,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 13, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 15, 05, 0)
                    };
                    var inboundFlight_2 = new Flight
                    {
                        DepartureAirport  = heathrow,
                        ArrivalAirport    = cologneAirport,
                        FlightPrice       = 23,
                        DepartureTime_UTC = new DateTime(date.Year, date.Month, date.Day, 16, 30, 0),
                        ArrivalTime_UTC   = new DateTime(date.Year, date.Month, date.Day, 17, 05, 0)
                    };
                    context.Flights.Add(outboundFlight_1);
                    context.Flights.Add(inboundFlight_1);
                    context.Flights.Add(outboundFlight_2);
                    context.Flights.Add(inboundFlight_2);
                }

                context.SaveChanges();
            }
        }
示例#24
0
 public override void WriteValue(DateTime value)
 {
     base.WriteValue(value);
     value = DateTimeUtils.EnsureDateTime(value, base.DateTimeZoneHandling);
     this.AddValue(value, JsonToken.Date);
 }
示例#25
0
        // Token: 0x060015D3 RID: 5587 RVA: 0x00072C00 File Offset: 0x00070E00
        private void ReadType(BsonType type)
        {
            switch (type)
            {
            case BsonType.Number:
            {
                double num = this.ReadDouble();
                if (this._floatParseHandling == FloatParseHandling.Decimal)
                {
                    base.SetToken(JsonToken.Float, Convert.ToDecimal(num, CultureInfo.InvariantCulture));
                    return;
                }
                base.SetToken(JsonToken.Float, num);
                return;
            }

            case BsonType.String:
            case BsonType.Symbol:
                base.SetToken(JsonToken.String, this.ReadLengthString());
                return;

            case BsonType.Object:
            {
                base.SetToken(JsonToken.StartObject);
                BsonReader.ContainerContext containerContext = new BsonReader.ContainerContext(BsonType.Object);
                this.PushContext(containerContext);
                containerContext.Length = this.ReadInt32();
                return;
            }

            case BsonType.Array:
            {
                base.SetToken(JsonToken.StartArray);
                BsonReader.ContainerContext containerContext2 = new BsonReader.ContainerContext(BsonType.Array);
                this.PushContext(containerContext2);
                containerContext2.Length = this.ReadInt32();
                return;
            }

            case BsonType.Binary:
            {
                BsonBinaryType bsonBinaryType;
                byte[]         array = this.ReadBinary(out bsonBinaryType);
                object         value = (bsonBinaryType != BsonBinaryType.Uuid) ? array : new Guid(array);
                base.SetToken(JsonToken.Bytes, value);
                return;
            }

            case BsonType.Undefined:
                base.SetToken(JsonToken.Undefined);
                return;

            case BsonType.Oid:
            {
                byte[] value2 = this.ReadBytes(12);
                base.SetToken(JsonToken.Bytes, value2);
                return;
            }

            case BsonType.Boolean:
            {
                bool flag = Convert.ToBoolean(this.ReadByte());
                base.SetToken(JsonToken.Boolean, flag);
                return;
            }

            case BsonType.Date:
            {
                DateTime     dateTime             = DateTimeUtils.ConvertJavaScriptTicksToDateTime(this.ReadInt64());
                DateTimeKind dateTimeKindHandling = this.DateTimeKindHandling;
                DateTime     dateTime2;
                if (dateTimeKindHandling != DateTimeKind.Unspecified)
                {
                    if (dateTimeKindHandling != DateTimeKind.Local)
                    {
                        dateTime2 = dateTime;
                    }
                    else
                    {
                        dateTime2 = dateTime.ToLocalTime();
                    }
                }
                else
                {
                    dateTime2 = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
                }
                base.SetToken(JsonToken.Date, dateTime2);
                return;
            }

            case BsonType.Null:
                base.SetToken(JsonToken.Null);
                return;

            case BsonType.Regex:
            {
                string str    = this.ReadString();
                string str2   = this.ReadString();
                string value3 = "/" + str + "/" + str2;
                base.SetToken(JsonToken.String, value3);
                return;
            }

            case BsonType.Reference:
                base.SetToken(JsonToken.StartObject);
                this._bsonReaderState = BsonReader.BsonReaderState.ReferenceStart;
                return;

            case BsonType.Code:
                base.SetToken(JsonToken.String, this.ReadLengthString());
                return;

            case BsonType.CodeWScope:
                base.SetToken(JsonToken.StartObject);
                this._bsonReaderState = BsonReader.BsonReaderState.CodeWScopeStart;
                return;

            case BsonType.Integer:
                base.SetToken(JsonToken.Integer, (long)this.ReadInt32());
                return;

            case BsonType.TimeStamp:
            case BsonType.Long:
                base.SetToken(JsonToken.Integer, this.ReadInt64());
                return;

            default:
                throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type.ToString());
            }
        }
示例#26
0
 public long getTimestamp()
 {
     return(DateTimeUtils.UtcToUnixTimeStamp(Time));
 }
示例#27
0
        private void ReadType(BsonType type)
        {
            switch (type)
            {
            case BsonType.Number:
                double d = ReadDouble();

                if (_floatParseHandling == FloatParseHandling.Decimal)
                {
                    SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
                }
                else
                {
                    SetToken(JsonToken.Float, d);
                }
                break;

            case BsonType.String:
            case BsonType.Symbol:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.Object:
            {
                SetToken(JsonToken.StartObject);

                ContainerContext newContext = new ContainerContext(BsonType.Object);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Array:
            {
                SetToken(JsonToken.StartArray);

                ContainerContext newContext = new ContainerContext(BsonType.Array);
                PushContext(newContext);
                newContext.Length = ReadInt32();
                break;
            }

            case BsonType.Binary:
                BsonBinaryType binaryType;
                byte[]         data = ReadBinary(out binaryType);

                object value = (binaryType != BsonBinaryType.Uuid)
                        ? data
                        : (object)new Guid(data);

                SetToken(JsonToken.Bytes, value);
                break;

            case BsonType.Undefined:
                SetToken(JsonToken.Undefined);
                break;

            case BsonType.Oid:
                byte[] oid = ReadBytes(12);
                SetToken(JsonToken.Bytes, oid);
                break;

            case BsonType.Boolean:
                bool b = Convert.ToBoolean(ReadByte());
                SetToken(JsonToken.Boolean, b);
                break;

            case BsonType.Date:
                long     ticks       = ReadInt64();
                DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);

                DateTime dateTime;
                switch (DateTimeKindHandling)
                {
                case DateTimeKind.Unspecified:
                    dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
                    break;

                case DateTimeKind.Local:
                    dateTime = utcDateTime.ToLocalTime();
                    break;

                default:
                    dateTime = utcDateTime;
                    break;
                }

                SetToken(JsonToken.Date, dateTime);
                break;

            case BsonType.Null:
                SetToken(JsonToken.Null);
                break;

            case BsonType.Regex:
                string expression = ReadString();
                string modifiers  = ReadString();

                string regex = @"/" + expression + @"/" + modifiers;
                SetToken(JsonToken.String, regex);
                break;

            case BsonType.Reference:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.ReferenceStart;
                break;

            case BsonType.Code:
                SetToken(JsonToken.String, ReadLengthString());
                break;

            case BsonType.CodeWScope:
                SetToken(JsonToken.StartObject);
                _bsonReaderState = BsonReaderState.CodeWScopeStart;
                break;

            case BsonType.Integer:
                SetToken(JsonToken.Integer, (long)ReadInt32());
                break;

            case BsonType.TimeStamp:
            case BsonType.Long:
                SetToken(JsonToken.Integer, ReadInt64());
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
            }
        }
示例#28
0
        private void webServerProc()
        {
            // 管理者権限がない場合は起動しない
            if (!WindowsUtils.IsExecuteAdminRole())
            {
                MessageUtils.showMessage(MessageBoxIcon.Warning, MessageResource.W0005);
                return;
            }

            listener = new HttpListener();
            listener.Prefixes.Add(prefix); // プレフィックスの登録
            try
            {
                listener.Start();
            }
            catch (HttpListenerException httpListenerException)
            {
                // すでにポートが使用中もしくは管理者権限なし
                LinearAudioPlayer.writeErrorMessage(httpListenerException);
                return;
            }

            while (true)
            {
                HttpListenerContext context = null;
                try
                {
                    context = listener.GetContext();
                }
                catch (HttpListenerException)
                {
                    // HTTP通信中に終了されたらどうしようもないので例外を握りつぶす
                }

                HttpListenerRequest  req = context.Request;
                HttpListenerResponse res = context.Response;

                Debug.WriteLine("request url: " + req.RawUrl);

                if (req.RawUrl.IndexOf("/LinearWebService") == -1)
                {
                    // WEBサーバ

                    string reqPath = req.RawUrl;
                    if (reqPath == "/")
                    {
                        reqPath = "ui/" + LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme + ".html";
                    }

                    reqPath = reqPath.Replace("/", "\\");
                    reqPath = Regex.Replace(reqPath, "\\?.*", "");

                    // リクエストされたURLからファイルのパスを求める
                    string path = docRoot + reqPath;

                    // ファイルが存在すればレスポンス・ストリームに書き出す
                    if (File.Exists(path))
                    {
                        byte[] content = File.ReadAllBytes(path);
                        //string s = File.ReadAllText(path, Encoding.UTF8);
                        //byte[] content = Encoding.UTF8.GetBytes(s);
                        res.Headers[HttpResponseHeader.ContentType] = GuessContentType(Path.GetExtension(path));
                        res.OutputStream.Write(content, 0, content.Length);
                    }
                }
                else
                {
                    // RESTサービス
                    // TODO:変なもの受け取ったら落ちる

                    WebServiceResponseInfo response = new WebServiceResponseInfo();
                    var dict = req.QueryString;
                    var reqParamJsonString = JsonConvert.SerializeObject(
                        dict.AllKeys.ToDictionary(k => k, k => dict[k])
                        );

                    Debug.WriteLine("req data: " + reqParamJsonString);
                    WebServiceRequestInfo request =
                        JsonConvert.DeserializeObject <WebServiceRequestInfo>(reqParamJsonString);

                    response.action = request.action;
                    switch (request.action)
                    {
                    case "play":
                        Action playAction = () =>
                        {
                            LinearAudioPlayer.PlayController.play(LinearGlobal.CurrentPlayItemInfo.Id,
                                                                  false, false);
                        };
                        LinearGlobal.MainForm.BeginInvoke(playAction);
                        break;

                    case "pause":
                        Action pauseAction = () =>
                        {
                            LinearAudioPlayer.PlayController.pause();
                        };
                        LinearGlobal.MainForm.BeginInvoke(pauseAction);
                        break;

                    case "stop":
                        Action stopAction = () =>
                        {
                            LinearAudioPlayer.PlayController.stop();
                        };
                        LinearGlobal.MainForm.BeginInvoke(stopAction);
                        break;

                    case "previous":
                        Action previouspAction = () =>
                        {
                            LinearAudioPlayer.PlayController.previousPlay();
                        };
                        LinearGlobal.MainForm.BeginInvoke(previouspAction);
                        break;

                    case "forward":
                        Action forwardAction = () =>
                        {
                            if (LinearAudioPlayer.PlayController.isPlaying())
                            {
                                LinearAudioPlayer.PlayController.endOfStream();
                            }
                        };
                        LinearGlobal.MainForm.BeginInvoke(forwardAction);
                        break;

                    case "voldown":
                        Action volDownAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol -= 5;
                            if (vol < 0)
                            {
                                vol = 0;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var voldownActionResult = LinearGlobal.MainForm.BeginInvoke(volDownAction);
                        voldownActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "volup":
                        Action volUpAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol += 5;
                            if (vol > 100)
                            {
                                vol = 100;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var volupActionResult = LinearGlobal.MainForm.BeginInvoke(volUpAction);
                        volupActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "getplayinfo":
                        if (LinearAudioPlayer.PlayController != null)
                        {
                            response.playInfo  = LinearGlobal.CurrentPlayItemInfo;
                            response.isPlaying = LinearAudioPlayer.PlayController.isPlaying();
                            response.isPaused  = LinearAudioPlayer.PlayController.isPaused();
                            response.seekRatio = (int)(((float)LinearAudioPlayer.PlayController.getPosition() /
                                                        (float)LinearAudioPlayer.PlayController.getLength()) * 100);
                            if (response.seekRatio == 100)
                            {
                                response.seekRatio = 0;
                            }
                        }

                        break;

                    case "seek":
                        Action seekAction = () =>
                        {
                            double value = ((double)LinearAudioPlayer.PlayController.getLength()) *
                                           request.seekPosition;
                            LinearAudioPlayer.PlayController.setPosition((uint)value);
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(seekAction);
                        break;

                    case "getthemelist":
                        var themelist = new List <string>();
                        var filePaths = FileUtils.getFilePathList(
                            Application.StartupPath + LinearConst.WEB_DIRECTORY_NAME + "ui", SearchOption.TopDirectoryOnly);
                        foreach (string path in filePaths)
                        {
                            themelist.Add(Path.GetFileNameWithoutExtension(path));
                        }
                        response.themeList    = themelist.ToArray().Reverse().ToArray();
                        response.nowThemeName = LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme;
                        break;

                    case "switchtheme":
                        LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme = request.theme;
                        break;

                    case "getnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(10).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "addnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(request.skip, request.take).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "getanalyzeinfo":
                        var ai        = new AnalyzeInfo();
                        var startDate = SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL056);
                        if (startDate != null)
                        {
                            ai.StartDate         = startDate.ToString().Substring(0, 10);
                            ai.StartDateRelative = DateTimeUtils.getRelativeTimeString(startDate.ToString());
                        }
                        ai.TotalTracksCount         = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL057);
                        ai.TotalFavoriteTracksCount = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL058);
                        ai.TotalPlayCount           = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL059);
                        ai.TotalPalyHistoryCount    = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL060);
                        response.analyzeOverview    = ai;
                        break;

                    case "getrecentlist":
                        var paramList  = new List <DbParameter>();
                        var recentlist = new List <TrackInfo>();
                        var limit      = request.limit;
                        if (LinearGlobal.CurrentPlayItemInfo != null && request.offset == 0)
                        {
                            var ci = LinearGlobal.CurrentPlayItemInfo;
                            recentlist.Add(new TrackInfo(ci.Id, ci.Title, ci.Artist, "", "", ci.Rating));     // NowPlaying
                            limit--;
                        }
                        paramList.Add(new SQLiteParameter("Limit", limit));
                        paramList.Add(new SQLiteParameter("Offset", request.offset));
                        recentlist.AddRange(SQLiteManager.Instance.executeQueryNormal(SQLResource.SQL061, paramList).Select(o => new TrackInfo((long)o[0], o[1].ToString(), o[2].ToString(), o[3].ToString(), o[4].ToString(), int.Parse(o[5].ToString()))));
                        response.recentListen = recentlist.ToArray();

                        var offset = request.offset - limit < 0 ? 0 : request.offset - limit;
                        response.pagerPrevious = request.offset == 0 ? -1 : offset;
                        response.pagerNext     = response.recentListen.Length < limit ? -1 : request.offset + limit;
                        break;

                    case "gettopartist":
                        var sql       = SQLResource.SQL062;
                        var rangeType = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where = "";
                        if (rangeType != RangeType.ALL)
                        {
                            where =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType]);
                        }
                        else
                        {
                            sql = SQLResource.SQL064;
                        }
                        sql = sql.Replace(":Condition", where);
                        var topArtists = SQLiteManager.Instance.executeQueryNormal(sql, new SQLiteParameter("Limit", request.limit));
                        if (topArtists.Length > 0)
                        {
                            double maxcount = topArtists.Max(o => (long)o[1]);
                            response.topLists =
                                topArtists.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString(), (long)o[1],
                                                  (int)((int.Parse(o[1].ToString()) / maxcount) * 100), o[2].ToString()))
                                .ToArray();
                        }
                        break;

                    case "gettoptrack":
                        var sql2       = SQLResource.SQL063;
                        var rangeType2 = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where2     = "";
                        if (rangeType2 != RangeType.ALL)
                        {
                            where2 =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType2]);
                        }
                        else
                        {
                            sql2 = SQLResource.SQL065;
                        }
                        sql2 = sql2.Replace(":Condition", where2);
                        var topTracks = SQLiteManager.Instance.executeQueryNormal(sql2, new SQLiteParameter("Limit", request.limit));
                        if (topTracks.Length > 0)
                        {
                            double maxcount2 = topTracks.Max(o => (long)o[2]);
                            response.topLists =
                                topTracks.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString() + " - " + o[1].ToString(), (long)o[2],
                                                  (int)((int.Parse(o[2].ToString()) / maxcount2) * 100), o[3].ToString(),
                                                  int.Parse(o[4].ToString()))).ToArray();
                        }
                        break;

                    case "ratingon":
                    case "ratingoff":
                        if (request.id == -1)
                        {
                            break;
                        }
                        LinearEnum.RatingValue rating = request.action == "ratingon" ? LinearEnum.RatingValue.FAVORITE : LinearEnum.RatingValue.NORMAL;

                        Action setRatingAction = () =>
                        {
                            var rowIndex = LinearAudioPlayer.GridController.Find((int)GridController.EnuGrid.ID, request.id.ToString());
                            if (rowIndex != -1)
                            {
                                LinearAudioPlayer.GridController.setRatingIcon(rowIndex, rating);
                            }
                            if (request.id == LinearGlobal.CurrentPlayItemInfo.Id)
                            {
                                LinearGlobal.MainForm.setRating((int)rating);
                            }
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(setRatingAction);

                        SQLiteManager.Instance.executeNonQuery(
                            SQLBuilder.updateRating(
                                request.id, rating));
                        break;

                    case "skipnowplaying":
                        Action skipNowPlayingAction = () =>
                        {
                            LinearAudioPlayer.PlayController.skipPlayingList(request.id);
                            LinearAudioPlayer.PlayController.play(request.id, false, true);
                        };
                        LinearGlobal.MainForm.BeginInvoke(skipNowPlayingAction);

                        break;

                    case "getartwork":
                        if (LinearGlobal.CurrentPlayItemInfo.Artwork != null)
                        {
                            try
                            {
                                if (request.artworkSize == 0)
                                {
                                    request.artworkSize = 150;
                                }
                                Bitmap thumbnail = new Bitmap(request.artworkSize, request.artworkSize);
                                using (Graphics g = Graphics.FromImage(thumbnail))
                                {
                                    g.InterpolationMode =
                                        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                    g.DrawImage(LinearGlobal.CurrentPlayItemInfo.Artwork, 0, 0, request.artworkSize, request.artworkSize);
                                }
                                var artworkDirectoy = Application.StartupPath +
                                                      Path.Combine(Path.Combine(LinearConst.WEB_DIRECTORY_NAME, "img"), "artwork");
                                Directory.CreateDirectory(artworkDirectoy);
                                var artworkFileName = string.Format("{0}.png",
                                                                    LinearGlobal.CurrentPlayItemInfo.Id);
                                var artworkThumbFileName = string.Format("{0}-thumb.png",
                                                                         LinearGlobal.CurrentPlayItemInfo.Id);
                                LinearGlobal.CurrentPlayItemInfo.Artwork.Save(artworkDirectoy + "\\" + artworkFileName,
                                                                              System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Save(artworkDirectoy + "\\" + artworkThumbFileName,
                                               System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Dispose();
                                var oldfiles =
                                    Directory.GetFiles(artworkDirectoy, "*.png")
                                    .Where(a => Path.GetFileName(a).IndexOf(LinearGlobal.CurrentPlayItemInfo.Id.ToString()) == -1);
                                foreach (var file in oldfiles)
                                {
                                    File.Delete(file);
                                }
                                response.artworkUrl      = "../img/artwork/" + artworkFileName;
                                response.artworkThumbUrl = "../img/artwork/" + artworkThumbFileName;
                            }
                            catch (Exception)
                            {
                                response.artworkUrl = "";
                            }
                        }
                        else
                        {
                            response.artworkUrl = "";
                        }
                        break;
                    }


                    string resJsonString = JsonConvert.SerializeObject(response);
                    byte[] responseByte  = Encoding.UTF8.GetBytes(resJsonString);
                    res.OutputStream.Write(responseByte, 0, responseByte.Length);
                }
                res.Close();
            }
        }
示例#29
0
        internal DateTimeOffset?ReadAsDateTimeOffsetInternal()
        {
            _readType = ReadType.ReadAsDateTimeOffset;

            JsonToken t;

            do
            {
                if (!ReadInternal())
                {
                    SetToken(JsonToken.None);
                    return(null);
                }
                else
                {
                    t = TokenType;
                }
            } while (t == JsonToken.Comment);

            if (t == JsonToken.Date)
            {
                if (Value is DateTime)
                {
                    SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false);
                }

                return((DateTimeOffset)Value);
            }

            if (t == JsonToken.Null)
            {
                return(null);
            }

            if (t == JsonToken.String)
            {
                string s = (string)Value;
                if (string.IsNullOrEmpty(s))
                {
                    SetToken(JsonToken.Null);
                    return(null);
                }

                object         temp;
                DateTimeOffset dt;
                if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTimeOffset, DateTimeZoneHandling, _dateFormatString, Culture, out temp))
                {
                    dt = (DateTimeOffset)temp;
                    SetToken(JsonToken.Date, dt, false);
                    return(dt);
                }

                if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
                {
                    SetToken(JsonToken.Date, dt, false);
                    return(dt);
                }

                throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
            }

            if (t == JsonToken.EndArray)
            {
                return(null);
            }

            throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
        }
示例#30
0
        private bool Modified()
        {
            if (_lastModifiedTime == DateTime.MinValue)
            {
                return(true);
            }

            string modifiedSinceHeader = StringUtils.MaskNullString(Request.Headers["If-Modified-Since"]);

            //
            // Apparently, Netscape added a non-standard extension to the
            // If-Modified-Since header in HTTP/1.0 where extra parameters
            // can be sent using a semi-colon as the delimiter. One such
            // parameter is the original content length, which was meant
            // to improve the accuracy of If-Modified-Since in case a
            // document is updated twice in the same second. Here's an
            // example:
            //
            // If-Modified-Since: Thu, 11 May 2006 07:59:51 GMT; length=3419
            //
            // HTTP/1.1 solved the same problem in a better way via the ETag
            // header and If-None-Match. However, it looks like that some
            // proxies still use this technique, so the following checks for
            // a semi-colon in the header value and clips it to everything
            // before it.
            //
            // This is a fix for bug #7462:
            // http://developer.berlios.de/bugs/?func=detailbug&bug_id=7462&group_id=4638
            //

            int paramsIndex = modifiedSinceHeader.IndexOf(';');

            if (paramsIndex >= 0)
            {
                modifiedSinceHeader = modifiedSinceHeader.Substring(0, paramsIndex);
            }

            if (modifiedSinceHeader.Length == 0)
            {
                return(true);
            }

            DateTime modifiedSinceTime;

            try
            {
                modifiedSinceTime = DateTimeUtils.ParseInternetDate(modifiedSinceHeader);
            }
            catch (FormatException)
            {
                //
                // Accorinding to the HTTP specification, if the passed
                // If-Modified-Since date is invalid, the response is
                // exactly the same as for a normal GET. See section
                // 14.25 of RFC 2616 for more information:
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25
                //

                return(true);
            }

            DateTime time = _lastModifiedTime;

            time = new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);

            if (time > modifiedSinceTime)
            {
                return(true);
            }

            return(false);
        }