public static string ToString(this DateTime dt, DateTimeFormat format)
 {
     if (dt == DateTime.MinValue || dt == DateTime.MaxValue)
     {
         return string.Empty;
     }
     switch (format)
     {
         case DateTimeFormat.ShortDate:
             return dt.ToString("g");
         case DateTimeFormat.LongDate:
             return dt.ToString("D");
         case DateTimeFormat.Date:
             return dt.ToString("d");
         case DateTimeFormat.Time:
             return dt.ToString("t");
         case DateTimeFormat.DayOfWeek:
             return dt.GetLocalizedDayOfWeek();
         case DateTimeFormat.CardDate:
             return dt.ToString("dd MMM");
         case DateTimeFormat.CardTime:
             return dt.ToString("HH mm");
         default:
             return string.Empty;
     }
 }
 internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     _dateTimeFormat = serializer.DateTimeFormat;
     _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
 }
 public SQLiteConnectionStringBuilder()
 {
     _DataSource = String.Empty;
     _NewDatabase = false;
     _Encoding = Encoding.UTF8;
     _CacheSize = 2000;
     _Synchronous = SynchronousMode.Normal;
     _DateTimeFormat = DateTimeFormat.ISO8601;
 }
Esempio n. 4
0
 public sqlite2( bool UTF8Encoding, DateTimeFormat dateTimeFormat, bool oldDateTimeFormat, bool oldBinaryFormat )
 {
     if( UTF8Encoding )
         _encoding = Encoding.UTF8;
     else
         _encoding = Encoding.ASCII;
     _DateTimeFormat = dateTimeFormat;
     _oldDateTimeFormat = oldDateTimeFormat;
     _oldBinaryFormat = oldBinaryFormat;
 }
 public static string ToString(this DateTime? dt, DateTimeFormat format)
 {
     if (dt.HasValue)
     {
         return dt.Value.ToString(format);
     }
     else
     {
         return string.Empty;
     }
 }
 public EntityAttributeMetadataBuilder DateTimeAttribute(string schemaName, string displayName, string description,
                                                          AttributeRequiredLevel requiredLevel,
                                                          DateTimeFormat format, ImeMode imeMode)
 {
     int languageCode = 1033;
     // Create a date time attribute
     var dtAttribute = new DateTimeAttributeMetadata
     {
         // Set base properties
         SchemaName = schemaName,
         DisplayName = new Label(displayName, languageCode),
         RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
         Description = new Label(description, languageCode),
         // Set extended properties
         Format = format,
         ImeMode = imeMode
     };
     this.Attributes.Add(dtAttribute);
     return this;
 }
Esempio n. 7
0
        protected override void OnFormatChanged(DateTimeFormat oldValue, DateTimeFormat newValue)
        {
            base.OnFormatChanged(oldValue, newValue);

            switch (newValue)
            {
                case DateTimeFormat.LongDate:
                case DateTimeFormat.ShortDate:
                    this.CalenderVisibility = Visibility.Visible;
                    this.TimePickerVisibility = Visibility.Collapsed;
                    break;
                case DateTimeFormat.LongTime:
                case DateTimeFormat.ShortTime:
                    this.CalenderVisibility = Visibility.Collapsed;
                    this.TimePickerVisibility = Visibility.Visible;
                    break;
                default:
                    break;
            }
        }
        void Initialize(Type type,
            IEnumerable<Type> knownTypes,
            int maxItemsInObjectGraph,
            bool ignoreExtensionDataObject,
            IDataContractSurrogate dataContractSurrogate,
            EmitTypeInformation emitTypeInformation,
            bool serializeReadOnlyTypes,
            DateTimeFormat dateTimeFormat,
            bool useSimpleDictionaryFormat)
        {
            CheckNull(type, "type");
            this.rootType = type;

            if (knownTypes != null)
            {
                this.knownTypeList = new List<Type>();
                foreach (Type knownType in knownTypes)
                {
                    this.knownTypeList.Add(knownType);
                    if (knownType != null)
                    {
                        AddCollectionItemTypeToKnownTypes(knownType);
                    }
                }
            }

            if (maxItemsInObjectGraph < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.ValueMustBeNonNegative)));
            }
            this.maxItemsInObjectGraph = maxItemsInObjectGraph;
            this.ignoreExtensionDataObject = ignoreExtensionDataObject;
            this.dataContractSurrogate = dataContractSurrogate;
            this.emitTypeInformation = emitTypeInformation;
            this.serializeReadOnlyTypes = serializeReadOnlyTypes;
            this.dateTimeFormat = dateTimeFormat;
            this.useSimpleDictionaryFormat = useSimpleDictionaryFormat;
        }
 public JsonSerializer(DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
 {
     DateFormat = dateTimeFormat;
 }
        public static string GetDateTime(DateTime dt, DateTimeFormat format)
        {
            switch (format)
            {
                case DateTimeFormat.MMDDhhmmss:
                    return dt.ToString("MMddHHmmss");

                case DateTimeFormat.hhmmss:
                    return dt.ToString("HHmmss");

                case DateTimeFormat.MMDD:
                    return dt.ToString("MMdd");

                default:
                    throw new ArgumentOutOfRangeException("format");
            }

        }
Esempio n. 11
0
        /*
         * <propertyDescription name="Microsoft.SDKSample.DirectoryLevel" formatID="{581CF603-2925-4acf-BB5A-3D3EB39EACD3}" propID="3">
         *  <description>Number of directory levels to this item.</description>
         *  <searchInfo inInvertedIndex="false" isColumn="false,
         *  <typeInfo canStackBy="false" type="Int32"/>
         *  <labelInfo label="Directory Level"/>
         * </propertyDescription>
         */
        internal XmlElement GetXmlPropertyDescription(XmlDocument doc)
        {
            var desc = doc.CreateElement("propertyDescription");

            desc.SetAttribute("name", CanonicalName);
            desc.SetAttribute("formatID", FormatId.ToString("B").ToUpper());
            desc.SetAttribute("propID", PropertyId.ToString());

            var search = doc.CreateElement("searchInfo");

            search.SetAttribute("inInvertedIndex", InInvertedIndex.ToString());
            if (IsColumn)
            {
                search.SetAttribute("isColumn", IsColumn.ToString());
                search.SetAttribute("isColumnSparse", IsColumnSparse.ToString());
                search.SetAttribute("columnIndexType", ColumnIndexType.ToString());
            }
            if (MaxSize != 512)
            {
                search.SetAttribute("maxSize", MaxSize.ToString());
            }
            if (Mnemonics != null && Mnemonics.Length > 0)
            {
                search.SetAttribute("mnemonics", Mnemonics);
            }
            desc.AppendChild(search);

            var label = doc.CreateElement("labelInfo");

            label.SetAttribute("label", DisplayName);
            label.SetAttribute("sortDescription", SortDescription.ToString());
            if (EditInvitation != null && EditInvitation.Length > 0)
            {
                label.SetAttribute("invitationText", EditInvitation);
            }
            if (HideLabel)
            {
                label.SetAttribute("hideLabel", HideLabel.ToString());
            }
            desc.AppendChild(label);

            var type = doc.CreateElement("typeInfo");

            type.SetAttribute("type", Type.ToString());
            if (GroupingRange != PropertyGroupingRange.Discrete)
            {
                type.SetAttribute("groupingRange", GroupingRange.ToString());
            }
            if (IsInnate)
            {
                type.SetAttribute("isInnate", IsInnate.ToString());
            }
            if (IsInnate && CanBePurged)
            {
                type.SetAttribute("canBePurged", CanBePurged.ToString());
            }
            //if (MultipleValues)
            type.SetAttribute("multipleValues", MultipleValues.ToString());
            if (IsGroup)
            {
                type.SetAttribute("isGroup", IsGroup.ToString());
            }
            if (AggregationType != PropertyAggregationType.Default)
            {
                type.SetAttribute("aggregationType", AggregationType.ToString());
            }
            if (IsTreeProperty)
            {
                type.SetAttribute("isTreeProperty", IsTreeProperty.ToString());
            }
            if (IsViewable)
            {
                type.SetAttribute("isViewable", IsViewable.ToString());
            }
            if (SearchRawValue)
            {
                type.SetAttribute("searchRawValue", SearchRawValue.ToString());
            }
            if (ConditionType != PropertyConditionType.String)
            {
                type.SetAttribute("conditionType", ConditionType.ToString());
            }
            if (ConditionOperation != ConditionOperationConfigured.Equal)
            {
                type.SetAttribute("defaultOperation", ConditionOperation.ToString());
            }
            desc.AppendChild(type);

            var display = doc.CreateElement("displayInfo");

            display.SetAttribute("displayType", DisplayType.ToString());
            if (DisplayType == PropertyDisplayType.String && StringFormat != StringFormat.General)
            {
                var format = doc.CreateElement("stringFormat");
                format.SetAttribute("formatAs", StringFormat.ToString());
                display.AppendChild(format);
            }
            if (DisplayType == PropertyDisplayType.Boolean && BooleanFormat != BooleanFormat.YesNo)
            {
                var format = doc.CreateElement("booleanFormat");
                format.SetAttribute("formatAs", BooleanFormat.ToString());
                display.AppendChild(format);
            }
            if (DisplayType == PropertyDisplayType.Number && NumberFormat != NumberFormat.General)
            {
                var format = doc.CreateElement("numberFormat");
                format.SetAttribute("formatAs", NumberFormat.ToString());
                display.AppendChild(format);
            }
            if (DisplayType == PropertyDisplayType.DateTime && DateTimeFormat != DateTimeFormat.General)
            {
                var format = doc.CreateElement("dateTimeFormat");
                format.SetAttribute("formatAs", DateTimeFormat.ToString());
                display.AppendChild(format);
            }



            if (DefaultColumnWidth != 20)
            {
                display.SetAttribute("defaultColumnWidth", DefaultColumnWidth.ToString());
            }
            if (Alignment != PropertyAlignmentType.Left)
            {
                display.SetAttribute("alignment", Alignment.ToString());
            }
            //if (RelativeDescriptionType != RelativeDescriptionType.General)
            //  display.SetAttribute("relativeDescriptionType", RelativeDescriptionType.ToString());
            if (DefaultSortDirection != SortDirection.Ascending)
            {
                display.SetAttribute("defaultSortDirection", DefaultSortDirection.ToString());
            }
            if (EditControl != EditControl.Default)
            {
                var edit = doc.CreateElement("editControl");
                edit.SetAttribute("control", EditControl.ToString());
                display.AppendChild(edit);
            }
            desc.AppendChild(display);

            return(desc);
        }
Esempio n. 12
0
        public async Task <ModifyTask_out> ModifyTask([FromBody] ModifyTask_in pIn)
        {
            var Response = new ModifyTask_out
            {
                bRet   = true,
                errStr = "OK"
            };

            try
            {
                string CaptureMeta  = string.Empty;
                string ContentMeta  = string.Empty;
                string MatiralMeta  = string.Empty;
                string PlanningMeta = string.Empty;
                foreach (var item in pIn.metadatas)
                {
                    if (item.emtype == MetaDataType.emCapatureMetaData)
                    {
                        CaptureMeta = item.strMetadata;
                    }
                    else if (item.emtype == MetaDataType.emStoreMetaData)
                    {
                        MatiralMeta = item.strMetadata;
                    }
                    else if (item.emtype == MetaDataType.emContentMetaData)
                    {
                        ContentMeta = item.strMetadata;
                    }
                    else if (item.emtype == MetaDataType.emPlanMetaData)
                    {
                        PlanningMeta = item.strMetadata;
                    }
                }

                await _taskManage.ModifyTask <TaskContent>(pIn.taskModify, CaptureMeta, ContentMeta, MatiralMeta, PlanningMeta);

                //添加后如果开始时间在2分钟以内,需要调度一次
                if ((DateTimeFormat.DateTimeFromString(pIn.taskModify.strBegin) - DateTime.Now).TotalSeconds < 120)
                {
                    await _taskManage.UpdateComingTasks();
                }

                var _globalinterface = ApplicationContext.Current.ServiceProvider.GetRequiredService <IIngestGlobalInterface>();
                if (_globalinterface != null)
                {
                    GlobalInternals re = new GlobalInternals()
                    {
                        funtype = IngestDBCore.GlobalInternals.FunctionType.SetGlobalState, State = GlobalStateName.MODTASK
                    };
                    var response1 = await _globalinterface.SubmitGlobalCallBack(re);

                    if (response1.Code != ResponseCodeDefines.SuccessCode)
                    {
                        Logger.Error("SetGlobalState modtask error");
                    }
                }

                return(Response);
            }
            catch (Exception e)
            {
                if (e.GetType() == typeof(SobeyRecException))//sobeyexcep会自动打印错误
                {
                    SobeyRecException se = e as SobeyRecException;
                    Response.errStr = se.ErrorCode.ToString();
                }
                else
                {
                    Response.errStr = "error info:" + e.ToString();
                    Logger.Error("GetAllChannelCapturingTask" + e.ToString());
                }
                return(Response);
            }
            return(Response);
        }
Esempio n. 13
0
 /// <summary>
 /// 将日期时间转成常用的日期时间格式字符串,默认不移除【秒】
 /// <para>https://docs.microsoft.com/zh-cn/dotnet/api/system.globalization.cultureinfo.createspecificculture?view=netcore-3.1</para>
 /// </summary>
 /// <param name="datetime">要转的日期时间</param>
 /// <param name="format">格式枚举类</param>
 /// <param name="removeSecond">是否移除【秒】</param>
 /// <returns></returns>
 public static string ToString(this DateTimeOffset datetime, DateTimeFormat format, bool removeSecond = false) => format switch
 {
Esempio n. 14
0
        public async Task <ActionResult> Save(string hoten, string phone, string phone2, string ngayNhanDon, int hoSoCuaAi, string cmnd, int gioiTinh
                                              , int maKhuVuc, string diaChi, int sanPhamVay, string tenCuaHang,
                                              bool baoHiem, int thoiHanVay, string soTienVay, int trangthai, string ghiChu,
                                              string birthDayStr, string cmndDayStr, int courier = 0, List <int> FileRequireIds = null)
        {
            string error = "";

            if (GlobalData.User.UserType == (int)UserTypeEnum.Sale ||
                trangthai == (int)TrangThaiHoSo.Nhap)
            {
                trangthai = (int)TrangThaiHoSo.NhapLieu;
            }
            try
            {
                if (hoten == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập họ tên"));
                }
                if (phone == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập số điện thoại"));
                }
                if (ngayNhanDon == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày nhận đơn"));
                }
                if (cmnd == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập CMND"));
                }
                if (diaChi == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập địa chỉ"));
                }
                if (maKhuVuc == 0)
                {
                    return(ToJsonResponse(false, "Vui lòng chọn quận/ huyện"));
                }
                else if (sanPhamVay == 0)
                {
                    return(ToJsonResponse(false, "Vui lòng chọn sản phẩm vay"));
                }
                if (soTienVay == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập số tiền vay"));
                }
                if (string.IsNullOrWhiteSpace(birthDayStr))
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày sinh"));
                }
                if (string.IsNullOrWhiteSpace(cmndDayStr))
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày cấp cmnd"));
                }
                if (trangthai <= 0)
                {
                    return(ToJsonResponse(false, "Vui lòng chọn trạng thái"));
                }
                if (!string.IsNullOrWhiteSpace(ghiChu) && ghiChu.Length > 300)
                {
                    return(ToJsonResponse(false, "Nội dung ghi chú không được nhiều hơn 300 ký tự"));
                }
                try
                {
                    var lstLoaiTaiLieu = await _rpTailieu.LayDS();

                    if (lstLoaiTaiLieu == null)
                    {
                        await _rpLog.InsertLog("Update-Quanlyhoso", "lstLoaiTaiLieu = null");
                    }

                    if (lstLoaiTaiLieu != null)
                    {
                        lstLoaiTaiLieu.RemoveAll(x => x.BatBuoc == 0);
                        var missingNames = BusinessExtension.GetFilesMissingV2(lstLoaiTaiLieu, FileRequireIds);
                        if (!string.IsNullOrWhiteSpace(missingNames))
                        {
                            return(ToJsonResponse(false, $"Vui lòng nhập: {missingNames}"));
                        }
                    }
                }
                catch (Exception e)
                {
                    error = e.Dump();
                }
                if (!string.IsNullOrWhiteSpace(error))
                {
                    await _rpLog.InsertLog("Update-Quanlyhoso", error);
                }

                HoSoModel hs = new HoSoModel();
                hs.ID           = (int)Session["QL_HoSoID"];
                hs.TenKhachHang = hoten;
                hs.SDT          = phone;
                hs.SDT2         = phone2;
                if (ngayNhanDon != string.Empty)
                {
                    hs.NgayNhanDon = DateTimeFormat.ConvertddMMyyyyToDateTime(ngayNhanDon);
                }
                hs.HoSoCuaAi      = hoSoCuaAi;
                hs.MaNguoiCapNhat = GlobalData.User.IDUser;
                hs.NgayCapNhat    = DateTime.Now;
                hs.CMND           = cmnd;
                hs.GioiTinh       = gioiTinh;
                hs.MaKhuVuc       = maKhuVuc;
                hs.DiaChi         = diaChi;
                hs.CourierCode    = courier;
                hs.SanPhamVay     = sanPhamVay;
                hs.TenCuaHang     = tenCuaHang;
                hs.CoBaoHiem      = baoHiem ? 1 : 0;
                hs.MaTrangThai    = trangthai;
                hs.HanVay         = thoiHanVay;
                if (soTienVay == string.Empty)
                {
                    soTienVay = "0";
                }
                hs.SoTienVay = Convert.ToDecimal(soTienVay);
                var dtBirthDayConvert = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(birthDayStr);
                if (!dtBirthDayConvert.Success)
                {
                    return(ToJsonResponse(false, dtBirthDayConvert.Message));
                }
                else
                {
                    hs.BirthDay = dtBirthDayConvert.Value;
                }

                var dtCmnd = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(cmndDayStr);
                if (!dtCmnd.Success)
                {
                    return(ToJsonResponse(false, dtCmnd.Message));
                }
                else
                {
                    hs.CmndDay = dtCmnd.Value;
                }
                //hs.MaTrangThai = (int)TrangThaiHoSo.NhapLieu;
                hs.MaKetQua = (int)KetQuaHoSo.Trong;
                if (hs.ID > 0)
                {
                    var hoso = new HoSoBLL().LayChiTiet(hs.ID);
                    if (hoso == null)
                    {
                        return(ToJsonResponse(false, "Hồ sơ không tồn tại", hs.ID));
                    }
                    hs.DisbursementDate = hoso.DisbursementDate;
                    if (hs.MaTrangThai == (int)TrangThaiHoSo.GiaiNgan)
                    {
                        hs.DisbursementDate = DateTime.Now;
                    }

                    bool isCheckMaSanPham = false;
                    //// chỉnh sửa
                    if (new HoSoBLL().CapNhatHoSo(hs, null, ref isCheckMaSanPham))
                    {
                        new HoSoDuyetXemBLL().Them(hs.ID);
                    }
                    else
                    {
                        if (isCheckMaSanPham)
                        {
                            return(ToJsonResponse(false, "Mã sản phẩm đã được sử dụng bởi 1 hồ sơ khác, vui lòng chọn mã sản phẩm khác"));
                        }
                    }
                }

                await AddGhichu(hs.ID, ghiChu);

                return(ToJsonResponse(true, Resources.Global.Message_Succ, hs.ID));
            }
            catch (Exception ex)
            {
                error = error.Dump();
                await _rpLog.InsertLog("quanlyhoso", error);

                return(ToJsonResponse(false, ex.Message));
            }
        }
Esempio n. 15
0
        public async Task <JsonResult> CapNhat(int id, string hoten, string phone, string phone2, string ngayNhanDon, int hoSoCuaAi, string cmnd, int gioiTinh
                                               , int maKhuVuc, string diaChi, int sanPhamVay, string tenCuaHang,
                                               int baoHiem, int thoiHanVay, string soTienVay, int trangThai,
                                               int ketQua, string ghiChu, string birthDayStr, string cmndDayStr, int courier = 0, List <int> FileRequireIds = null)
        {
            try
            {
                if (hoten == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập họ tên"));
                }
                if (phone == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập số điện thoại"));
                }
                if (ngayNhanDon == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày nhận đơn"));
                }
                if (cmnd == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập CMND"));
                }
                if (diaChi == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập địa chỉ"));
                }
                if (maKhuVuc == 0)
                {
                    return(ToJsonResponse(false, "Vui lòng chọn quận/ huyện"));
                }
                if (sanPhamVay == 0)
                {
                    return(ToJsonResponse(false, "Vui lòng chọn sản phẩm vay"));
                }
                if (soTienVay == string.Empty)
                {
                    return(ToJsonResponse(false, "Vui lòng nhập số tiền vay"));
                }
                if (string.IsNullOrWhiteSpace(birthDayStr))
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày sinh"));
                }
                if (string.IsNullOrWhiteSpace(cmndDayStr))
                {
                    return(ToJsonResponse(false, "Vui lòng nhập ngày cấp cmnd"));
                }
                //List<TaiLieuModel> lstTaiLieu = (List<TaiLieuModel>)Session["Duyet_LstFileHoSo"];
                List <LoaiTaiLieuModel> lstLoaiTaiLieu = new LoaiTaiLieuBLL().LayDS();
                lstLoaiTaiLieu.RemoveAll(x => x.BatBuoc == 0);
                if (lstLoaiTaiLieu != null)
                {
                    var missingNames = BusinessExtension.GetFilesMissingV2(lstLoaiTaiLieu, FileRequireIds);
                    if (!string.IsNullOrWhiteSpace(missingNames))
                    {
                        return(ToJsonResponse(false, $"Vui lòng nhập: {missingNames}"));
                    }
                }

                HoSoModel hs = new HoSoModel();
                hs.ID           = id;
                hs.TenKhachHang = hoten;
                hs.SDT          = phone;
                hs.SDT2         = phone2;
                if (ngayNhanDon != string.Empty)
                {
                    hs.NgayNhanDon = DateTimeFormat.ConvertddMMyyyyToDateTime(ngayNhanDon);
                }
                hs.HoSoCuaAi      = hoSoCuaAi;
                hs.MaNguoiCapNhat = GlobalData.User.IDUser;
                hs.NgayCapNhat    = DateTime.Now;
                hs.CMND           = cmnd;
                hs.GioiTinh       = gioiTinh;
                hs.MaKhuVuc       = maKhuVuc;
                hs.DiaChi         = diaChi;
                hs.CourierCode    = courier;
                hs.SanPhamVay     = sanPhamVay;
                hs.TenCuaHang     = tenCuaHang;
                hs.CoBaoHiem      = baoHiem;
                hs.HanVay         = thoiHanVay;
                var dtBirthDayConvert = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(birthDayStr);
                if (!dtBirthDayConvert.Success)
                {
                    return(ToJsonResponse(false, dtBirthDayConvert.Message));
                }
                else
                {
                    hs.BirthDay = dtBirthDayConvert.Value;
                }

                var dtCmnd = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(cmndDayStr);
                if (!dtCmnd.Success)
                {
                    return(ToJsonResponse(false, dtCmnd.Message));
                }
                else
                {
                    hs.CmndDay = dtCmnd.Value;
                }

                if (soTienVay == string.Empty)
                {
                    soTienVay = "0";
                }
                hs.SoTienVay   = Convert.ToDecimal(soTienVay);
                hs.MaTrangThai = trangThai;
                hs.MaKetQua    = ketQua;
                int result = 0;
                if (hs.ID > 0)
                {
                    var hosoOld = new HoSoBLL().LayChiTiet(id);
                    if (!(hosoOld.MaTrangThai == trangThai && hosoOld.MaKetQua == ketQua))
                    {
                        new HoSoXemBLL().Them(hosoOld.ID);
                    }

                    hs.DisbursementDate = hosoOld.DisbursementDate;
                    if (hs.MaTrangThai == (int)TrangThaiHoSo.GiaiNgan)
                    {
                        hs.DisbursementDate = DateTime.Now;
                    }
                    bool isCheckMaSanPham = false;
                    //// chỉnh sửa
                    if (new HoSoBLL().CapNhatHoSo(hs, null, ref isCheckMaSanPham))
                    {
                        result = 1;
                    }
                    else
                    {
                        if (isCheckMaSanPham)
                        {
                            return(ToJsonResponse(false, "Mã sản phẩm đã được sử dụng bởi 1 hồ sơ khác, vui lòng chọn mã sản phẩm khác"));
                        }
                    }
                }

                if (result > 0)
                {
                    bool rs = new HoSoBLL().CapNhatTrangThaiHS(id, GlobalData.User.IDUser, DateTime.Now, trangThai, ketQua, ghiChu);

                    if (rs)
                    {
                        GhichuModel ghichu = new GhichuModel
                        {
                            UserId      = GlobalData.User.IDUser,
                            HosoId      = hs.ID,
                            Noidung     = ghiChu,
                            CommentTime = DateTime.Now,
                            TypeId      = (int)NoteType.Hoso
                        };

                        await _rpNote.AddNoteAsync(ghichu);

                        return(ToJsonResponse(true, Resources.Global.Message_Succ, hs.ID));
                    }
                    return(ToJsonResponse(false, "Không thành công, xin thử lại sau"));
                }
                return(ToJsonResponse(false, "Không thành công, xin thử lại sau"));
            }
            catch (Exception e)
            {
                return(ToJsonResponse(false, e.Message));
            }
        }
Esempio n. 16
0
        public ActionResult DownloadReport(int maNhom, int maThanhVien, string fromDate, string toDate, string maHS, string cmnd, int loaiNgay)
        {
            string newUrl = string.Empty;

            try
            {
                List <HoSoDuyetModel> rs = new List <HoSoDuyetModel>();
                DateTime dtFromDate = DateTime.MinValue, dtToDate = DateTime.MinValue;
                if (fromDate != "")
                {
                    dtFromDate = DateTimeFormat.ConvertddMMyyyyToDateTime(fromDate);
                }
                if (toDate != "")
                {
                    dtToDate = DateTimeFormat.ConvertddMMyyyyToDateTime(toDate);
                }
                string trangthai = "";
                trangthai += ((int)TrangThaiHoSo.TuChoi).ToString() + ","
                             + ((int)TrangThaiHoSo.NhapLieu).ToString() + ","
                             + ((int)TrangThaiHoSo.ThamDinh).ToString() + ","
                             + ((int)TrangThaiHoSo.BoSungHoSo).ToString() + ","
                             + ((int)TrangThaiHoSo.Cancel).ToString() + ","
                             + ((int)TrangThaiHoSo.DaDoiChieu).ToString() + ","
                             + ((int)TrangThaiHoSo.PCB).ToString() + ","
                             + ((int)TrangThaiHoSo.GiaiNgan).ToString();
                int totalRecord = new HoSoBLL().CountHosoDuyet(GlobalData.User.IDUser, maNhom, maThanhVien, dtFromDate, dtToDate, maHS, cmnd, loaiNgay, trangthai);
                rs = new HoSoBLL().TimHoSoDuyet(GlobalData.User.IDUser, maNhom, maThanhVien, dtFromDate, dtToDate, maHS, cmnd, loaiNgay, trangthai, string.Empty, 1, totalRecord, true);
                if (rs == null)
                {
                    rs = new List <HoSoDuyetModel>();
                }
                string destDirectory = VS_LOAN.Core.Utility.Path.DownloadBill + "/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
                bool   exists        = System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + destDirectory);
                if (!exists)
                {
                    System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + destDirectory);
                }
                string fileName = "Report-DSHS" + DateTime.Now.ToString("ddMMyyyyHHmmssfff") + ".xlsx";
                using (FileStream stream = new FileStream(Server.MapPath(destDirectory + fileName), FileMode.CreateNew))
                {
                    Byte[] info = System.IO.File.ReadAllBytes(Server.MapPath(VS_LOAN.Core.Utility.Path.ReportTemplate + "Report-DSHS.xlsx"));
                    stream.Write(info, 0, info.Length);
                    using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update))
                    {
                        string     nameSheet  = "DSHS";
                        ExcelOOXML excelOOXML = new ExcelOOXML(archive);
                        int        rowindex   = 4;
                        if (rs != null)
                        {
                            excelOOXML.InsertRow(nameSheet, rowindex, rs.Count - 1, true);
                            for (int i = 0; i < rs.Count; i++)// dòng
                            {
                                excelOOXML.SetCellData(nameSheet, "A" + rowindex, (i + 1).ToString());
                                excelOOXML.SetCellData(nameSheet, "B" + rowindex, rs[i].MaHoSo.ToString());
                                excelOOXML.SetCellData(nameSheet, "C" + rowindex, rs[i].NgayTao.ToString("dd/MM/yyyy"));
                                excelOOXML.SetCellData(nameSheet, "D" + rowindex, rs[i].DoiTac);
                                excelOOXML.SetCellData(nameSheet, "E" + rowindex, rs[i].CMND);
                                excelOOXML.SetCellData(nameSheet, "F" + rowindex, rs[i].TenKH);
                                excelOOXML.SetCellData(nameSheet, "G" + rowindex, rs[i].TrangThaiHS);
                                excelOOXML.SetCellData(nameSheet, "H" + rowindex, rs[i].KetQuaHS);
                                excelOOXML.SetCellData(nameSheet, "I" + rowindex, rs[i].NgayCapNhat == DateTime.MinValue ? "" : rs[i].NgayCapNhat.ToString("dd/MM/yyyy"));
                                excelOOXML.SetCellData(nameSheet, "J" + rowindex, rs[i].MaNV);
                                excelOOXML.SetCellData(nameSheet, "K" + rowindex, rs[i].NhanVienBanHang);
                                excelOOXML.SetCellData(nameSheet, "L" + rowindex, rs[i].DoiNguBanHang);
                                excelOOXML.SetCellData(nameSheet, "M" + rowindex, rs[i].CoBaoHiem == true ? "N" : "Y");
                                excelOOXML.SetCellData(nameSheet, "N" + rowindex, rs[i].DiaChiKH);
                                excelOOXML.SetCellData(nameSheet, "O" + rowindex, rs[i].GhiChu);
                                excelOOXML.SetCellData(nameSheet, "P" + rowindex, rs[i].MaNVLayHS);
                                rowindex++;
                            }
                        }
                        archive.Dispose();
                    }
                    stream.Dispose();
                }

                bool result = true;
                if (result)
                {
                    newUrl = "/File/GetFile?path=" + destDirectory + fileName;
                    return(ToJsonResponse(true, null, newUrl));
                }
                return(ToJsonResponse(false));
            }
            catch (BusinessException ex)
            {
                return(ToJsonResponse(false, ex.Message));
            }
        }
Esempio n. 17
0
        public static ReformatFormatForgeDesc ValidateGetFormatterType(
            EPType inputType,
            string methodName,
            ExprNode exprNode)
        {
            if (!(inputType is ClassEPType)) {
                throw new ExprValidationException(
                    GetMessage(methodName) + " requires a datetime input value but received " + inputType);
            }

            if (!exprNode.Forge.ForgeConstantType.IsConstant) {
                throw new ExprValidationException(GetMessage(methodName) + " requires a constant-value format");
            }

            var formatForge = exprNode.Forge;
            var formatType = formatForge.EvaluationType;
            if (formatType == null) {
                throw new ExprValidationException(GetMessage(methodName) + " invalid null format object");
            }

            object format = null;
            if (formatForge.ForgeConstantType.IsCompileTimeConstant) {
                format = ExprNodeUtilityEvaluate.EvaluateValidationTimeNoStreams(
                    exprNode.Forge.ExprEvaluator,
                    null,
                    "date format");
                if (format == null) {
                    throw new ExprValidationException(GetMessage(methodName) + " invalid null format object");
                }
            }

            // handle legacy date
            var input = (ClassEPType) inputType;
            if (input.Clazz.GetBoxedType() == typeof(long?) ||
                TypeHelper.IsSubclassOrImplementsInterface(input.Clazz, typeof(DateTime)) ||
                TypeHelper.IsSubclassOrImplementsInterface(input.Clazz, typeof(DateTimeOffset)) ||
                TypeHelper.IsSubclassOrImplementsInterface(input.Clazz, typeof(DateTimeEx))) {
                if (TypeHelper.IsSubclassOrImplementsInterface(formatType, typeof(DateFormat))) {
                    return new ReformatFormatForgeDesc(typeof(DateFormat));
                }

                if (TypeHelper.IsSubclassOrImplementsInterface(formatType, typeof(string))) {
                    if (format != null) {
                        try {
                            new SimpleDateFormat((string) format);
                        }
                        catch (Exception ex) {
                            throw new ExprValidationException(
                                GetMessage(methodName) + " invalid format string (SimpleDateFormat): " + ex.Message,
                                ex);
                        }
                    }

                    return new ReformatFormatForgeDesc(typeof(string));
                }

                throw GetFailedExpected(methodName, typeof(DateFormat), formatType);
            }

            if (TypeHelper.IsSubclassOrImplementsInterface(formatType, typeof(DateTimeFormat))) {
                return new ReformatFormatForgeDesc(typeof(DateTimeFormat));
            }

            if (TypeHelper.IsSubclassOrImplementsInterface(formatType, typeof(string))) {
                if (format != null) {
                    try {
                        DateTimeFormat.For((string) format);
                    }
                    catch (Exception ex) {
                        throw new ExprValidationException(
                            GetMessage(methodName) + " invalid format string (DateTimeFormatter): " + ex.Message,
                            ex);
                    }
                }

                return new ReformatFormatForgeDesc(typeof(string));
            }

            throw GetFailedExpected(methodName, typeof(DateTimeFormat), formatType);
        }
Esempio n. 18
0
 public static Func <DateTime, String> DateTimeToRestTypeDelegate(DateTimeFormat dateFormat)
 {
     return(dt => DateTimeToRestType(dt, dateFormat));
 }
Esempio n. 19
0
 public static Func <String, DateTime> TextToDateTimeDelegate(DateTimeFormat dateFormat)
 {
     return(s => TextToDateTime(s, dateFormat));
 }
Esempio n. 20
0
 protected override void OnFormatChanged( DateTimeFormat oldValue, DateTimeFormat newValue )
 {
   base.OnFormatChanged( oldValue, newValue );
   InvalidateListBoxItems();
 }
Esempio n. 21
0
 /// <summary>
 /// Converts datetime to string per portal
 /// </summary>
 public abstract string DateTimeToString(DateTime dt,
                                         DateTimeFormat format = DateTimeFormat.LongDateTime,
                                         ISession session      = null);
Esempio n. 22
0
 /// <summary>
 /// Returns a <see cref="System.String" /> that represents this instance.
 /// </summary>
 /// <param name="date">The date.</param>
 /// <param name="dateTimeFormat">The date time format.</param>
 /// <param name="culture">The culture.</param>
 /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
 public static string ToString(this DateTime date, DateTimeFormat dateTimeFormat, CultureInfo culture = null)
 {
     return ((DateTime?)date).ToString(dateTimeFormat, culture);
 }
Esempio n. 23
0
 protected virtual void OnFormatChanged(DateTimeFormat oldValue, DateTimeFormat newValue)
 {
     FormatUpdated();
 }
Esempio n. 24
0
 protected String ConvertDateTimeToRestWithoutDefaults(DateTime value, DateTime defaultValue, DateTimeFormat dateFormat)
 {
     if (value.Equals(defaultValue) || Conversions.NullDateTime == value)
     {
         return(null);
     }
     return(ConvertDateTimeToRest(value, dateFormat));
 }
Esempio n. 25
0
        private string GetFormatString(DateTimeFormat dateTimeFormat)
        {
            switch (dateTimeFormat)
            {
            case DateTimeFormat.ShortDate:
                return(CultureInfo.DateTimeFormat.ShortDatePattern);

            case DateTimeFormat.LongDate:
                return(CultureInfo.DateTimeFormat.LongDatePattern);

            case DateTimeFormat.ShortTime:
                return(CultureInfo.DateTimeFormat.ShortTimePattern);

            case DateTimeFormat.LongTime:
                return(CultureInfo.DateTimeFormat.LongTimePattern);

            case DateTimeFormat.FullDateTime:
                return(CultureInfo.DateTimeFormat.FullDateTimePattern);

            case DateTimeFormat.MonthDay:
                return(CultureInfo.DateTimeFormat.MonthDayPattern);

            case DateTimeFormat.RFC1123:
                return(CultureInfo.DateTimeFormat.RFC1123Pattern);

            case DateTimeFormat.SortableDateTime:
                return(CultureInfo.DateTimeFormat.SortableDateTimePattern);

            case DateTimeFormat.UniversalSortableDateTime:
                return(CultureInfo.DateTimeFormat.UniversalSortableDateTimePattern);

            case DateTimeFormat.YearMonth:
                return(CultureInfo.DateTimeFormat.YearMonthPattern);

            case DateTimeFormat.Custom:
            {
                switch (this.FormatString)
                {
                case "d":
                    return(CultureInfo.DateTimeFormat.ShortDatePattern);

                case "t":
                    return(CultureInfo.DateTimeFormat.ShortTimePattern);

                case "T":
                    return(CultureInfo.DateTimeFormat.LongTimePattern);

                case "D":
                    return(CultureInfo.DateTimeFormat.LongDatePattern);

                case "f":
                    return(CultureInfo.DateTimeFormat.LongDatePattern + " " + CultureInfo.DateTimeFormat.ShortTimePattern);

                case "F":
                    return(CultureInfo.DateTimeFormat.FullDateTimePattern);

                case "g":
                    return(CultureInfo.DateTimeFormat.ShortDatePattern + " " + CultureInfo.DateTimeFormat.ShortTimePattern);

                case "G":
                    return(CultureInfo.DateTimeFormat.ShortDatePattern + " " + CultureInfo.DateTimeFormat.LongTimePattern);

                case "m":
                    return(CultureInfo.DateTimeFormat.MonthDayPattern);

                case "y":
                    return(CultureInfo.DateTimeFormat.YearMonthPattern);

                case "r":
                    return(CultureInfo.DateTimeFormat.RFC1123Pattern);

                case "s":
                    return(CultureInfo.DateTimeFormat.SortableDateTimePattern);

                case "u":
                    return(CultureInfo.DateTimeFormat.UniversalSortableDateTimePattern);

                default:
                    return(FormatString);
                }
            }

            default:
                throw new ArgumentException("Not a supported format");
            }
        }
Esempio n. 26
0
 public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat)
     : this(writer)
 {
     this.dateTimeFormat = dateTimeFormat;
 }
Esempio n. 27
0
        private static ParseMakePropertiesDesc SetupProperties(bool requireOneMatch,
                                                               string[] propertyNamesOffered,
                                                               EventType outputEventType,
                                                               StatementContext statementContext,
                                                               string dateFormat)
        {
            var writeables = EventTypeUtility.GetWriteableProperties(outputEventType, false);

            IList <int> indexesList = new List <int>();
            IList <SimpleTypeParser>            parserList    = new List <SimpleTypeParser>();
            IList <WriteablePropertyDescriptor> writablesList = new List <WriteablePropertyDescriptor>();

            for (var i = 0; i < propertyNamesOffered.Length; i++)
            {
                var  propertyName = propertyNamesOffered[i];
                Type propertyType;
                try {
                    propertyType = outputEventType.GetPropertyType(propertyName);
                }
                catch (PropertyAccessException ex) {
                    throw new EPException("Invalid property name '" + propertyName + "': " + ex.Message, ex);
                }

                if (propertyType == null)
                {
                    continue;
                }

                SimpleTypeParser parser;
                if ((propertyType == typeof(DateTime)) ||
                    (propertyType == typeof(DateTimeOffset)) ||
                    (propertyType == typeof(DateTimeEx)))
                {
                    var dateTimeFormat = dateFormat != null
                                                ? DateTimeFormat.For(dateFormat)
                                                : DateTimeFormat.ISO_DATE_TIME;

                    if (propertyType == typeof(DateTime?))
                    {
                        parser = new ProxySimpleTypeParser(
                            text => (dateTimeFormat.Parse(text)?.DateTime)?.DateTime);
                    }
                    else if (propertyType == typeof(DateTime))
                    {
                        parser = new ProxySimpleTypeParser(
                            text => dateTimeFormat.Parse(text).DateTime.DateTime);
                    }
                    else if (propertyType == typeof(DateTimeOffset?))
                    {
                        parser = new ProxySimpleTypeParser(
                            text => dateTimeFormat.Parse(text)?.DateTime);
                    }
                    else if (propertyType == typeof(DateTimeOffset))
                    {
                        parser = new ProxySimpleTypeParser(
                            text => dateTimeFormat.Parse(text).DateTime);
                    }
                    else
                    {
                        parser = new ProxySimpleTypeParser(
                            text => dateTimeFormat.Parse(text));
                    }
                }
                else
                {
                    parser = SimpleTypeParserFactory.GetParser(propertyType);
                }

                var writable = EventTypeUtility.FindWritable(propertyName, writeables);
                if (writable == null)
                {
                    continue;
                }

                indexesList.Add(i);
                parserList.Add(parser);
                writablesList.Add(writable);
            }

            if (indexesList.IsEmpty() && requireOneMatch)
            {
                throw new EPException(
                          "Failed to match any of the properties " +
                          CompatExtensions.RenderAny(propertyNamesOffered) +
                          " to the event type properties of event type '" +
                          outputEventType.Name +
                          "'");
            }

            var parsers   = parserList.ToArray();
            var writables = writablesList.ToArray();
            var indexes   = CollectionUtil.IntArray(indexesList);
            EventBeanManufacturer manufacturer;

            try {
                manufacturer = EventTypeUtility.GetManufacturer(
                    outputEventType,
                    writables,
                    statementContext.ImportServiceRuntime,
                    false,
                    statementContext.EventTypeAvroHandler)
                               .GetManufacturer(statementContext.EventBeanTypedEventFactory);
            }
            catch (EventBeanManufactureException e) {
                throw new EPException("Event type '" + outputEventType.Name + "' cannot be written to: " + e.Message, e);
            }

            return(new ParseMakePropertiesDesc(indexes, parsers, manufacturer));
        }
Esempio n. 28
0
        public static DateTime Parse(string s, DateTimeFormat format)
        {
            bool b = false;
            DateTime r = new DateTime();
            switch (format)
            {
                case DateTimeFormat.W3_dateTime:
                    b = r.ParseDateTime(s, DateTimePart.Date|DateTimePart.Time);
                    break;

                case DateTimeFormat.W3_date:
                    b = r.ParseDateTime(s, DateTimePart.Date);
                    break;

                case DateTimeFormat.W3_time:
                    b = r.ParseDateTime(s, DateTimePart.Time);
                    break;

                case DateTimeFormat.W3_gYear:
                    b = r.ParseDateTime(s, DateTimePart.Year);
                    break;

                case DateTimeFormat.W3_gYearMonth:
                    b = r.ParseDateTime(s, DateTimePart.Year|DateTimePart.Month);
                    break;

                case DateTimeFormat.W3_gMonth:
                    b = r.ParseDateTime(s, DateTimePart.Month);
                    break;

                case DateTimeFormat.W3_gMonthDay:
                    b = r.ParseDateTime(s, DateTimePart.Month|DateTimePart.Day);
                    break;

                case DateTimeFormat.W3_gDay:
                    b = r.ParseDateTime(s, DateTimePart.Day);
                    break;
            }
            if (!b)
                throw new StringParseException(s + " cannot be converted to a dateTime value");
            return r;
        }
Esempio n. 29
0
        /// <summary>
        /// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format to be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
        {
            parsed_time = null;

            string time_zone_r;

            if (default_format == DateTimeFormat.USA_DATE)
            {
                time_zone_r = @"(?:\s*(?'time_zone'UTC|GMT|CST|EST))?";
            }
            else
            {
                time_zone_r = @"(?:\s*(?'time_zone'UTC|GMT))?";
            }

            Match m;

            if (parsed_date != null && parsed_date.IndexOfDate > -1)
            {//look around the found date
                //look for <date> hh:mm:ss <UTC offset>
                m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{2})\s*:\s*(?'minute'\d{2})\s*:\s*(?'second'\d{2})\s+(?'offset_sign'[\+\-])(?'offset_hh'\d{2}):?(?'offset_mm'\d{2})(?=$|[^\d\w])", RegexOptions.Compiled);
                if (!m.Success)
                {
                    //look for <date> [h]h:mm[:ss] [PM/AM] [UTC/GMT]
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[^\d\w])", RegexOptions.Compiled);
                    if (!m.Success)
                    {
                        //look for [h]h:mm:ss [PM/AM] [UTC/GMT] <date>
                        m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[\s,]+)", RegexOptions.Compiled);
                        if (!m.Success)
                        {
                            //look for [h]h:mm:ss [PM/AM] [UTC/GMT] within <date>
                            m = Regex.Match(str.Substring(parsed_date.IndexOfDate, parsed_date.LengthOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[\s,]+)", RegexOptions.Compiled);
                        }
                    }
                }
            }
            else//look anywhere within string
            {
                //look for hh:mm:ss <UTC offset>
                m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{2})\s*:\s*(?'minute'\d{2})\s*:\s*(?'second'\d{2})\s+(?'offset_sign'[\+\-])(?'offset_hh'\d{2}):?(?'offset_mm'\d{2})?(?=$|[^\d\w])", RegexOptions.Compiled);
                if (!m.Success)
                {
                    //look for [h]h:mm[:ss] [PM/AM] [UTC/GMT]
                    m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*(?'ampm'AM|am|PM|pm))?" + time_zone_r + @"(?=$|[^\d\w])", RegexOptions.Compiled);
                }
            }

            if (!m.Success)
            {
                return(false);
            }

            //try
            //{
            int hour = int.Parse(m.Groups["hour"].Value);

            if (hour < 0 || hour > 23)
            {
                return(false);
            }

            int minute = int.Parse(m.Groups["minute"].Value);

            if (minute < 0 || minute > 59)
            {
                return(false);
            }

            int second = 0;

            if (!string.IsNullOrEmpty(m.Groups["second"].Value))
            {
                second = int.Parse(m.Groups["second"].Value);
                if (second < 0 || second > 59)
                {
                    return(false);
                }
            }

            if (string.Compare(m.Groups["ampm"].Value, "PM", true) == 0 && hour < 12)
            {
                hour += 12;
            }
            else if (string.Compare(m.Groups["ampm"].Value, "AM", true) == 0 && hour == 12)
            {
                hour -= 12;
            }

            DateTime date_time = new DateTime(1, 1, 1, hour, minute, second);

            if (m.Groups["offset_hh"].Success)
            {
                int offset_hh = int.Parse(m.Groups["offset_hh"].Value);
                int offset_mm = 0;
                if (m.Groups["offset_mm"].Success)
                {
                    offset_mm = int.Parse(m.Groups["offset_mm"].Value);
                }
                TimeSpan utc_offset = new TimeSpan(offset_hh, offset_mm, 0);
                if (m.Groups["offset_sign"].Value == "-")
                {
                    utc_offset = -utc_offset;
                }
                parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time, utc_offset);
                return(true);
            }

            if (m.Groups["time_zone"].Success)
            {
                TimeSpan utc_offset;
                switch (m.Groups["time_zone"].Value)
                {
                case "UTC":
                case "GMT":
                    utc_offset = new TimeSpan(0, 0, 0);
                    break;

                case "CST":
                    utc_offset = new TimeSpan(-6, 0, 0);
                    break;

                case "EST":
                    utc_offset = new TimeSpan(-5, 0, 0);
                    break;

                default:
                    throw new Exception("Time zone: " + m.Groups["time_zone"].Value + " is not defined.");
                }
                parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time, utc_offset);
                return(true);
            }

            parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
            //}
            //catch(Exception e)
            //{
            //    return false;
            //}
            return(true);
        }
        /// <summary>
        /// Convert an object to a JSON string.
        /// </summary>
        /// <param name="o">The value to convert. Supported types are: Boolean, String, Byte, (U)Int16, (U)Int32, Float, Double, Decimal, Array, IDictionary, IEnumerable, Guid, Datetime, DictionaryEntry, Object and null.</param>
        /// <returns>The JSON object as a string or null when the value type is not supported.</returns>
        /// <remarks>For objects, only public properties with getters are converted.</remarks>
        public static string SerializeObject(object o, DateTimeFormat dateTimeFormat = DateTimeFormat.Default)
        {
            if (o == null)
            {
                return("null");
            }

            Type type = o.GetType();

            switch (type.Name)
            {
            case "Boolean":
            {
                return((bool)o ? "true" : "false");
            }

            case "String":
            case "Char":
            case "Guid":
            {
                return("\"" + SerializeString(o as String) + "\"");
            }

            case "Single":
            case "Double":
            case "Decimal":
            case "Float":
            case "Byte":
            case "SByte":
            case "Int16":
            case "UInt16":
            case "Int32":
            case "UInt32":
            case "Int64":
            case "UInt64":
            {
                return(o.ToString());
            }

            case "DateTime":
            {
                switch (dateTimeFormat)
                {
                case DateTimeFormat.Ajax:
                    // This MSDN page describes the problem with JSON dates:
                    // http://msdn.microsoft.com/en-us/library/bb299886.aspx
                    return("\"" + DateTimeExtensions.ToASPNetAjax((DateTime)o) + "\"");

                case DateTimeFormat.ISO8601:
                case DateTimeFormat.Default:
                default:
                    return("\"" + DateTimeExtensions.ToIso8601((DateTime)o) + "\"");
                }
            }
            }

            if (o is IDictionary && !type.IsArray)
            {
                IDictionary dictionary = o as IDictionary;
                return(SerializeIDictionary(dictionary, dateTimeFormat));
            }

            if (o is IEnumerable)
            {
                IEnumerable enumerable = o as IEnumerable;
                return(SerializeIEnumerable(enumerable, dateTimeFormat));
            }

            if (type == typeof(System.Collections.DictionaryEntry))
            {
                DictionaryEntry entry     = o as DictionaryEntry;
                Hashtable       hashtable = new Hashtable();
                hashtable.Add(entry.Key, entry.Value);
                return(SerializeIDictionary(hashtable, dateTimeFormat));
            }

            if (type.IsClass)
            {
                Hashtable hashtable = new Hashtable();

                // Iterate through all of the methods, looking for public GET properties
                MethodInfo[] methods = type.GetMethods();
                foreach (MethodInfo method in methods)
                {
                    // We care only about property getters when serializing
                    if (method.Name.StartsWith("get_"))
                    {
                        // Ignore abstract and virtual objects
                        if (method.IsAbstract)
                        {
                            continue;
                        }

                        // Ignore delegates and MethodInfos
                        if ((method.ReturnType == typeof(System.Delegate)) ||
                            (method.ReturnType == typeof(System.MulticastDelegate)) ||
                            (method.ReturnType == typeof(System.Reflection.MethodInfo)))
                        {
                            continue;
                        }
                        // Ditto for DeclaringType
                        if ((method.DeclaringType == typeof(System.Delegate)) ||
                            (method.DeclaringType == typeof(System.MulticastDelegate)))
                        {
                            continue;
                        }

                        object returnObject = method.Invoke(o, null);
                        hashtable.Add(method.Name.Substring(4), returnObject);
                    }
                }
                return(SerializeIDictionary(hashtable, dateTimeFormat));
            }

            return(null);
        }
Esempio n. 31
0
        protected virtual string FormatGroupVersionPart(ApiVersion apiVersion, string format, IFormatProvider formatProvider)
        {
            Arg.NotNull(apiVersion, nameof(apiVersion));
            Arg.NotNullOrEmpty(format, nameof(format));
            Arg.NotNull(formatProvider, nameof(formatProvider));
            Contract.Ensures(!IsNullOrEmpty(Contract.Result <string>()));

            if (apiVersion.GroupVersion == null)
            {
                return(Empty);
            }

            var groupVersion = apiVersion.GroupVersion.Value;

            switch (format[0])
            {
            case 'G':
                // G, GG
                var text = new StringBuilder(groupVersion.ToString(GroupVersionFormat, formatProvider));

                // GG
                if (format.Length == 2)
                {
                    AppendStatus(text, apiVersion.Status);
                }

                return(text.ToString());

            case 'M':
                var month = Calendar.GetMonth(groupVersion);

                switch (format.Length)
                {
                case 1:         // M
                    return(month.ToString(formatProvider));

                case 2:         // MM
                    return(month.ToString("00", formatProvider));

                case 3:         // MMM
                    return(DateTimeFormat.GetAbbreviatedMonthName(month));
                }

                // MMMM*
                return(DateTimeFormat.GetMonthName(month));

            case 'd':
                switch (format.Length)
                {
                case 1:         // d
                    return(Calendar.GetDayOfMonth(groupVersion).ToString(formatProvider));

                case 2:         // dd
                    return(Calendar.GetDayOfMonth(groupVersion).ToString("00", formatProvider));

                case 3:         // ddd
                    return(DateTimeFormat.GetAbbreviatedDayName(Calendar.GetDayOfWeek(groupVersion)));
                }

                // dddd*
                return(DateTimeFormat.GetDayName(Calendar.GetDayOfWeek(groupVersion)));

            case 'y':
                var year = Calendar.GetYear(groupVersion);

                switch (format.Length)
                {
                case 1:         // y
                    return((year % 100).ToString(formatProvider));

                case 2:         // yy
                    return((year % 100).ToString("00", formatProvider));

                case 3:         // yyy
                    return(year.ToString("000", formatProvider));
                }

                // yyyy*
                return(year.ToString(formatProvider));
            }

            return(groupVersion.ToString(format, formatProvider));
        }
Esempio n. 32
0
 private string GetFormatString(DateTimeFormat dateTimeFormat)
 {
     switch (dateTimeFormat)
     {
         case DateTimeFormat.Custom:
             return this.FormatString;
         case DateTimeFormat.FullDateTime:
             return base.CultureInfo.DateTimeFormat.FullDateTimePattern;
         case DateTimeFormat.LongDate:
             return base.CultureInfo.DateTimeFormat.LongDatePattern;
         case DateTimeFormat.LongTime:
             return base.CultureInfo.DateTimeFormat.LongTimePattern;
         case DateTimeFormat.MonthDay:
             return base.CultureInfo.DateTimeFormat.MonthDayPattern;
         case DateTimeFormat.RFC1123:
             return base.CultureInfo.DateTimeFormat.RFC1123Pattern;
         case DateTimeFormat.ShortDate:
             return base.CultureInfo.DateTimeFormat.ShortDatePattern;
         case DateTimeFormat.ShortTime:
             return base.CultureInfo.DateTimeFormat.ShortTimePattern;
         case DateTimeFormat.SortableDateTime:
             return base.CultureInfo.DateTimeFormat.SortableDateTimePattern;
         case DateTimeFormat.UniversalSortableDateTime:
             return base.CultureInfo.DateTimeFormat.UniversalSortableDateTimePattern;
         case DateTimeFormat.YearMonth:
             return base.CultureInfo.DateTimeFormat.YearMonthPattern;
         default:
             throw new ArgumentException("Not a supported format");
     }
 }
Esempio n. 33
0
 /// <summary>
 /// Creates a new instance of the class with the specified parameters.
 /// </summary>
 /// <param name="dateTimeFormat">A DateTimeFormat indicating the format to use when serialising DateTime types</param>
 /// <param name="emitTypeInformation">A bool that indicates whether to emit type information for custom types.</param>
 public SerializerOptions(DateTimeFormat dateTimeFormat, bool emitTypeInformation)
 {
     DateTimeFormat      = dateTimeFormat;
     EmitTypeInformation = emitTypeInformation;
 }
        /// <summary>
        /// Parses datetime format string
        /// </summary>
        /// <param name="format">Datetime format string</param>
        /// <returns>DateTimeFormat will be returned on successful parse, otherwise null</returns>
        public static DateTimeFormat Parse([NotNull] string format)
        {
            if (format.Length == 0)
                return null;

            var result = new DateTimeFormat();

            var startIndex = 0;
            DateTimeFormatToken token;

            while ((token = GetToken(format, startIndex)) != null)
            {
                if (token.FormatType == DateTimeFormatType.Hour)
                    result.Is24HoursInTime = true;

                result.Tokens.Add(token);

                startIndex += token.Length;
            }

            return result.Tokens.Count == 0 ? null : result;
        }
Esempio n. 35
0
        public string ToString(DateTimeFormat format)
        {
            switch (format)
            {
                case DateTimeFormat.W3_dateTime:
                    return killFraction(myValue.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture)) + doTimezone();

                case DateTimeFormat.W3_date:
                    return myValue.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.W3_time:
                    return killFraction(myValue.ToString("HH\\:mm\\:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture)) + doTimezone();

                case DateTimeFormat.W3_gYear:
                    return myValue.ToString("yyyy", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.W3_gYearMonth:
                    return myValue.ToString("yyyy-MM", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.W3_gMonth:
                    return myValue.ToString("--MM", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.W3_gMonthDay:
                    return myValue.ToString("--MM-dd", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.W3_gDay:
                    return myValue.ToString("---dd", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.S_DateTime:
                    return myValue.ToString("yyyy-MM-dd HH\\:mm\\:ss.fffffff", System.Globalization.CultureInfo.InvariantCulture) + doTimezone();

                case DateTimeFormat.S_Seconds:
                {
                    decimal d = myValue.Ticks;
                    d /= TicksPerSecond;
                    return killFraction(d.ToString());
                }

                case DateTimeFormat.S_Days:
                {
                    decimal d = myValue.Ticks;
                    d /= 86400 * TicksPerSecond;
                    return killFraction(d.ToString());
                }
            }
            throw new ArgumentException("Invalid format.");
        }
Esempio n. 36
0
 /// <summary>
 /// Converts the date to the given format, using the current thread's CurrentCulture value.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="format"></param>
 /// <returns></returns>
 public static string ToString(this DateTime value, DateTimeFormat format)
 {
     var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
     var formatter = culture.DateTimeFormat;
     string formatString = null;
     switch (format)
     {
         case DateTimeFormat.ShortDate:
             formatString = formatter.ShortDatePattern;
             break;
         case DateTimeFormat.ShortTime:
             formatString = formatter.ShortTimePattern;
             break;
         case DateTimeFormat.LongDate:
             formatString = formatter.LongDatePattern;
             break;
         case DateTimeFormat.LongTime:
             formatString = formatter.LongTimePattern;
             break;
         case DateTimeFormat.ShortDateTime:
             formatString = formatter.ShortDatePattern + " " + formatter.ShortTimePattern;//not gonna be correct for all cultures
             break;
         case DateTimeFormat.LongDateTime:
             formatString = formatter.FullDateTimePattern;
             break;
         case DateTimeFormat.MonthDay:
             formatString = formatter.MonthDayPattern;
             break;
         case DateTimeFormat.YearMonth:
             formatString = formatter.YearMonthPattern;
             break;
     }
     return formatString == null ? value.ToString(formatter) : value.ToString(formatString, formatter);
 }
        private void Initialize(Type type,
            IEnumerable<Type> knownTypes,
            int maxItemsInObjectGraph,
            bool ignoreExtensionDataObject,
            EmitTypeInformation emitTypeInformation,
            bool serializeReadOnlyTypes,
            DateTimeFormat dateTimeFormat,
            bool useSimpleDictionaryFormat)
        {
            CheckNull(type, "type");
            _rootType = type;

            if (knownTypes != null)
            {
                this.knownTypeList = new List<Type>();
                foreach (Type knownType in knownTypes)
                {
                    this.knownTypeList.Add(knownType);
                    if (knownType != null)
                    {
                        AddCollectionItemTypeToKnownTypes(knownType);
                    }
                }
            }

            if (maxItemsInObjectGraph < 0)
            {
                throw new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.ValueMustBeNonNegative);
            }
            _maxItemsInObjectGraph = maxItemsInObjectGraph;
            _ignoreExtensionDataObject = ignoreExtensionDataObject;
            _emitTypeInformation = emitTypeInformation;
            _serializeReadOnlyTypes = serializeReadOnlyTypes;
            _dateTimeFormat = dateTimeFormat;
            _useSimpleDictionaryFormat = useSimpleDictionaryFormat;
        }
Esempio n. 38
0
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <param name="dateTimeFormat">The date time format.</param>
        /// <param name="culture">The culture.</param>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public static string ToString(this DateTime? date, DateTimeFormat dateTimeFormat, CultureInfo culture = null)
        {
            var cultureInfo = culture ?? CultureInfo.InvariantCulture;

            if (date.HasValue)
            {
                switch (dateTimeFormat)
                {
                    case DateTimeFormat.Date:
                        return date.Value.ToString(Constants.DefaultShortDateFormat, cultureInfo);

                    case DateTimeFormat.Time:
                        return date.Value.ToString(Constants.DefaultShortTimeFormat, cultureInfo);

                    default:
                        return date.Value.ToString(Constants.DefaultShortDateTimeFormat, cultureInfo);
                }
            }

            return null;
        }
Esempio n. 39
0
        private HttpResponseMessage CreateExcelFile(List <PrimaerdatenReportRecord> response)
        {
            var retVal      = new HttpResponseMessage(HttpStatusCode.OK);
            var file        = $"Viaduc-Primaerdaten-{DateTime.Now:s}.xlsx";
            var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(file));
            var format      = new DateTimeFormat("dd.MM.yyyy HH:mm:ss");

            using (var stream = exportHelper.ExportToExcel(response, new ExcelColumnInfos
            {
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.AufbereitungsArt), ColumnHeader = "Auftragstyp", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.OrderId), ColumnHeader = "Auftrags-ID", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.VeId), ColumnHeader = "VE-ID", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.MutationsId), ColumnHeader = "Mutations-ID", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.PrimaerdatenAuftragId), ColumnHeader = "Primärdaten Auftrag-ID", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.Size), ColumnHeader = "Grösse SIP in MB", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.FileCount), ColumnHeader = "Anzahl Files im SIP", MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.FileFormats), ColumnHeader = "Dateiformat im SIP", MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.Source),
                    ColumnHeader = "Quelle: digitale Ablieferung oder Digitalisierung durch Vecteur?",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.NeuEingegangen),
                    ColumnHeader = "Zeitstempel Status 'Neu Eingegangen'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.FreigabePrüfen),
                    ColumnHeader = "Zeitstempel Status 'Freigabe prüfen'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.FürDigitalisierungBereit),
                    ColumnHeader = "Zeitstempel Status 'Für Digitalisierung bereit'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerManuelleFreigabe),
                    ColumnHeader = "Dauer manuelle Freigabe durch BAR-MA  in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.FürAushebungBereit), ColumnHeader = "Zeitstempel Status 'Für Aushebung bereit'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAuftragsabrufVecteur),
                    ColumnHeader = "Dauer Auftragsabruf durch Vecteur  in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.Ausgeliehen), ColumnHeader = "Zeitstempel Status 'Ausgeliehen'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAusleiheLogistik),
                    ColumnHeader = "Dauer Ausleihe durch Logistik in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo {
                    ColumnName = nameof(PrimaerdatenReportRecord.ZumReponierenBereit),
                    ColumnHeader = "Zeitstempel Status 'Zum Reponieren bereit'",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerDigitalisierungVecteur),
                    ColumnHeader = "Dauer Digitalisierung durch Vecteur inkl. Ingest DIR in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.PrimaryDataLinkCreationDate),
                    ColumnHeader = "Zeitstempel Status 'Identifikation digitales Magazin' in AIS",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerUpdateAIPAdresseAIS),
                    ColumnHeader = "Dauer Update AIP-Adresse in AIS in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.StartFirstSynchronizationAttempt),
                    ColumnHeader = "Zeitstempel Start erster Synchronisierungsversuch (Status 1)",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerStartSynchronisierungWebOZ),
                    ColumnHeader = "Dauer Start Synchronisierung durch WebOZ in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.StartLastSynchronizationAttempt),
                    ColumnHeader = "Zeitstempel Start letzter Synchronisierungsversuch bevor Synchronisierung erfolgreich war (Status 2)",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.CompletionLastSynchronizationAttempt),
                    ColumnHeader = "Zeitstempel Abschluss Synchronisierung (Status 2)",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.CountSynchronizationAttempts),
                    ColumnHeader = "Anzahl notwendiger Synchronisierungsversuche bis Status 2",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerErfolgreicherSyncVersuch),
                    ColumnHeader = "Dauer erfolgreicher Sync-Versuch in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAlleSyncVersuche),
                    ColumnHeader = "Dauer alle Sync-Versuche  in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerZumReponierenBereitSyncCompleted),
                    ColumnHeader = "Dauer von 'Zum Reponieren bereit' / 'Ingest completed DIR' bis Sync completed Viaduc  in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.ClickButtonPrepareDigitalCopy),
                    ColumnHeader = "Zeitstempel Klick Button 'Digitalisat aufbereiten'",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.EstimatedPreparationTimeVeAccordingDetailPage),
                    ColumnHeader = "Geschätzte Aufbereitungszeit der VE gem. Anzeige auf Detailseite in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.StartFirstPreparationAttempt),
                    ColumnHeader = "Zeitstempel Start erster Aufbereitungsversuch Gebrauchskopie",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.StartLastPreparationAttempt),
                    ColumnHeader = "Zeitstempel Start letzter Aufbereitungsversuch bevor Aufbereitung erfolgreich war",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.CompletionLastPreparationAttempt),
                    ColumnHeader = "Zeitstempel Abschluss Aufbereitung Gebrauchskopie",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.CountPreparationAttempts),
                    ColumnHeader = "Aufbereitung erfolgreich",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerErfolgreicherAufbereitungsversuch),
                    ColumnHeader = "Dauer erfolgreicher Aufbereitungsversuch in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAllAufbereitungsversuch),
                    ColumnHeader = "Dauer alle Aufbereitungsversuche in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerSyncCompletedAufbereitungErfolgreich),
                    ColumnHeader = "Dauer von 'Sync completed Viaduc' bis zu 'Aufbereitung erfolgreich' in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.StorageUseCopyCache),
                    ColumnHeader = "Zeitstempel Speicherung Gebrauchskopie im Cache",
                    FormatSpecification = format.FormatString, MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAufbereitungErfolgreichSpeicherungGebrauchskopieCache),
                    ColumnHeader = "Dauer von 'Aufbereitung erfolgreich' bis Speicherung Gebrauchskopie im Cache in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.ShippingMailReadForDownload),
                    ColumnHeader = "Zeitstempel Versand Mail 'Fur Download bereit' an User",
                    FormatSpecification = format.FormatString,
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.DauerAufbereitungErfolgreichMailVersandt),
                    ColumnHeader = "Dauer von 'Aufbereitung erfolgreich' bis Mail versandt in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.EingangBestellungVersandEMailZumDownloadBereit),
                    ColumnHeader = "Eingang Bestellung bis Versand der E-Mail 'Zum Download bereit' in [h]:mm",
                    MakeAutoWidth = true
                },
                new ExcelColumnInfo
                {
                    ColumnName = nameof(PrimaerdatenReportRecord.KlickButtonDigitalisatAufbereitenVersandEMailZumDownloadBereit),
                    ColumnHeader = "Klick Button 'Digitalisat aufbereiten' bis Versand E-Mail 'Zum Download bereit'  in [h]:mm",
                    MakeAutoWidth = true
                }
            }))
                retVal.Content = new ByteArrayContent(stream.ToArray());
            retVal.Content.Headers.ContentType        = new MediaTypeHeaderValue(contentType);
            retVal.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = file
            };
            return(retVal);
        }
Esempio n. 40
0
        public async Task <ActionResult> SaveDaft(string hoten, string phone, string phone2, string ngayNhanDon, int hoSoCuaAi, string cmnd, int gioiTinh
                                                  , int maKhuVuc, string diaChi, int sanPhamVay, string tenCuaHang, int baoHiem, int thoiHanVay, string soTienVay, int trangthai,
                                                  string ghiChu, string birthDayStr, string cmndDayStr, int courier = 0)
        {
            if (trangthai <= 0 && GlobalData.User.UserType != (int)UserTypeEnum.Sale)
            {
                return(ToJsonResponse(false, "Vui lòng chọn trạng thái"));
            }
            if (hoten == string.Empty)
            {
                return(ToJsonResponse(false, "Vui lòng nhập họ tên"));
            }
            if (string.IsNullOrWhiteSpace(birthDayStr))
            {
                return(ToJsonResponse(false, "Vui lòng nhập ngày sinh"));
            }
            if (string.IsNullOrWhiteSpace(cmndDayStr))
            {
                return(ToJsonResponse(false, "Vui lòng nhập ngày cấp cmnd"));
            }
            try
            {
                HoSoModel hs = new HoSoModel();
                hs.ID           = (int)Session["QL_HoSoID"];
                hs.TenKhachHang = hoten;
                hs.SDT          = phone;
                hs.SDT2         = phone2;
                if (ngayNhanDon != string.Empty)
                {
                    hs.NgayNhanDon = DateTimeFormat.ConvertddMMyyyyToDateTime(ngayNhanDon);
                }
                hs.HoSoCuaAi   = hoSoCuaAi;
                hs.MaNguoiTao  = GlobalData.User.IDUser;
                hs.NgayTao     = DateTime.Now;
                hs.CMND        = cmnd;
                hs.GioiTinh    = gioiTinh;
                hs.MaKhuVuc    = maKhuVuc;
                hs.DiaChi      = diaChi;
                hs.CourierCode = courier;
                hs.SanPhamVay  = sanPhamVay;
                hs.TenCuaHang  = tenCuaHang;
                hs.CoBaoHiem   = baoHiem;
                hs.HanVay      = thoiHanVay;
                if (soTienVay == string.Empty)
                {
                    soTienVay = "0";
                }
                hs.SoTienVay   = Convert.ToDecimal(soTienVay);
                hs.MaTrangThai = (int)TrangThaiHoSo.Nhap;
                hs.MaKetQua    = (int)KetQuaHoSo.Trong;
                var dtBirthDayConvert = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(birthDayStr);
                if (!dtBirthDayConvert.Success)
                {
                    return(ToJsonResponse(false, dtBirthDayConvert.Message));
                }
                else
                {
                    hs.BirthDay = dtBirthDayConvert.Value;
                }

                var dtCmnd = DateTimeFormat.ConvertddMMyyyyToDateTimeV2(cmndDayStr);
                if (!dtCmnd.Success)
                {
                    return(ToJsonResponse(false, dtCmnd.Message));
                }
                else
                {
                    hs.CmndDay = dtCmnd.Value;
                }
                List <TaiLieuModel> lstTaiLieu = null;
                int result = 0;
                if (hs.ID > 0)
                {
                    bool isCheckMaSanPham = false;
                    //// chỉnh sửa
                    if (new HoSoBLL().Luu(hs, lstTaiLieu, ref isCheckMaSanPham))
                    {
                        result = 1;
                    }
                    else
                    {
                        if (isCheckMaSanPham)
                        {
                            return(ToJsonResponse(false, "Mã sản phẩm đã được sử dụng bởi 1 hồ sơ khác, vui lòng chọn mã sản phẩm khác"));
                        }
                    }
                }
                else
                {
                    bool isCheckMaSanPham = false;
                    result = new HoSoBLL().Them(hs, lstTaiLieu, ref isCheckMaSanPham);
                    if (result > 0)
                    {
                        Session["QL_LstFileHoSo"] = result;
                    }
                    else
                    {
                        if (isCheckMaSanPham)
                        {
                            return(ToJsonResponse(false, "Mã sản phẩm đã được sử dụng bởi 1 hồ sơ khác, vui lòng chọn mã sản phẩm khác"));
                        }
                    }
                }
                await AddGhichu(hs.ID, ghiChu);

                if (result > 0)
                {
                    return(ToJsonResponse(true, Resources.Global.Message_Succ, hs.ID));
                }
                return(ToJsonResponse(false, "Không thành công, xin thử lại sau"));
            }
            catch (BusinessException ex)
            {
                return(ToJsonResponse(false, ex.Message));
            }
        }
Esempio n. 41
0
        public ActionResult DownloadReport(int maNhom, int maThanhVien, string fromDate, string toDate, string maHS, string cmnd, int loaiNgay)
        {
            if (GlobalData.User.IDUser != 1)
            {
                return(RedirectToAction("DanhSachHoSo"));
            }
            string newUrl = string.Empty;

            try
            {
                List <HoSoQuanLyModel> rs = new List <HoSoQuanLyModel>();
                DateTime dtFromDate = DateTime.MinValue, dtToDate = DateTime.MinValue;
                if (fromDate != "")
                {
                    dtFromDate = DateTimeFormat.ConvertddMMyyyyToDateTime(fromDate);
                }
                if (toDate != "")
                {
                    dtToDate = DateTimeFormat.ConvertddMMyyyyToDateTime(toDate);
                }

                string trangthai   = Helpers.Helpers.GetAllStatusString();
                int    totalRecord = new HoSoBLL().CountHoSoQuanLy(GlobalData.User.IDUser, maNhom, maThanhVien, dtFromDate, dtToDate, maHS, cmnd, trangthai, loaiNgay, freeText: null);
                if (totalRecord <= 0)
                {
                    return(ToResponse(false, "Không có dữ liệu"));
                }
                rs = new HoSoBLL().TimHoSoQuanLy(maNVDangNhap: GlobalData.User.IDUser,
                                                 maNhom: maNhom,
                                                 maThanhVien: maThanhVien,
                                                 tuNgay: dtFromDate,
                                                 denNgay: dtToDate,
                                                 maHS: maHS,
                                                 cmnd: cmnd,
                                                 trangthai: trangthai,
                                                 loaiNgay: loaiNgay,
                                                 freeText: string.Empty,
                                                 page: 1,
                                                 limit: totalRecord,
                                                 isDownload: true);
                if (rs == null)
                {
                    rs = new List <HoSoQuanLyModel>();
                }
                string destDirectory = VS_LOAN.Core.Utility.Path.DownloadBill + "/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
                bool   exists        = System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + destDirectory);
                if (!exists)
                {
                    System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + destDirectory);
                }
                string fileName = "Report-DSHS" + DateTime.Now.ToString("ddMMyyyyHHmmssfff") + ".xlsx";
                using (FileStream stream = new FileStream(Server.MapPath(destDirectory + fileName), FileMode.CreateNew))
                {
                    Byte[] info = System.IO.File.ReadAllBytes(Server.MapPath(VS_LOAN.Core.Utility.Path.ReportTemplate + "Report-DSHS.xlsx"));
                    stream.Write(info, 0, info.Length);
                    using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update))
                    {
                        string     nameSheet  = "DSHS";
                        ExcelOOXML excelOOXML = new ExcelOOXML(archive);
                        int        rowindex   = 4;
                        if (rs != null)
                        {
                            excelOOXML.InsertRow(nameSheet, rowindex, rs.Count - 1, true);
                            for (int i = 0; i < rs.Count; i++)// dòng
                            {
                                excelOOXML.SetCellData(nameSheet, "A" + rowindex, (i + 1).ToString());
                                excelOOXML.SetCellData(nameSheet, "B" + rowindex, rs[i].MaHoSo.ToString());
                                excelOOXML.SetCellData(nameSheet, "C" + rowindex, rs[i].NgayTao.ToString("dd/MM/yyyy"));
                                excelOOXML.SetCellData(nameSheet, "D" + rowindex, rs[i].DoiTac);
                                excelOOXML.SetCellData(nameSheet, "E" + rowindex, rs[i].CMND);
                                excelOOXML.SetCellData(nameSheet, "F" + rowindex, rs[i].Phone);
                                excelOOXML.SetCellData(nameSheet, "G" + rowindex, rs[i].TenKH);
                                excelOOXML.SetCellData(nameSheet, "H" + rowindex, rs[i].TrangThaiHS);
                                excelOOXML.SetCellData(nameSheet, "I" + rowindex, rs[i].KetQuaHS);
                                excelOOXML.SetCellData(nameSheet, "J" + rowindex, rs[i].NgayCapNhat == DateTime.MinValue ? "" : rs[i].NgayCapNhat.ToString("dd/MM/yyyy"));
                                excelOOXML.SetCellData(nameSheet, "K" + rowindex, rs[i].MaNV);
                                excelOOXML.SetCellData(nameSheet, "L" + rowindex, rs[i].NhanVienBanHang);
                                excelOOXML.SetCellData(nameSheet, "M" + rowindex, rs[i].DoiNguBanHang);
                                excelOOXML.SetCellData(nameSheet, "N" + rowindex, rs[i].CoBaoHiem == true ? "N" : "Y");
                                excelOOXML.SetCellData(nameSheet, "O" + rowindex, rs[i].KhuVucText);
                                excelOOXML.SetCellData(nameSheet, "P" + rowindex, rs[i].GhiChu);
                                excelOOXML.SetCellData(nameSheet, "Q" + rowindex, rs[i].MaNVLayHS);
                                rowindex++;
                            }
                        }
                        archive.Dispose();
                    }
                    stream.Dispose();
                }

                bool result = true;
                if (result)
                {
                    newUrl = "/File/GetFile?path=" + destDirectory + fileName;
                    return(ToResponse(true, newUrl));
                }
                return(ToResponse(false, null));
            }
            catch (BusinessException ex)
            {
                return(ToResponse(false, ex.Message));
            }
        }
Esempio n. 42
0
 /// <summary>
 /// Tries to find time within the passed string and return it as ParsedDateTime object.
 /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
 /// </summary>
 /// <param name="str">string that contains date-time</param>
 /// <param name="default_format">format to be used preferably in ambivalent instances</param>
 /// <param name="parsed_time">parsed date-time output</param>
 /// <returns>true if time was found, else false</returns>
 static public bool TryParseTime(this string str, DateTimeFormat default_format, out ParsedDateTime parsed_time)
 {
     return(TryParseTime(str, default_format, out parsed_time, null));
 }
Esempio n. 43
0
 protected String ConvertDateTimeToRest(DateTime value, DateTimeFormat dateFormat)
 {
     return(Conversions.DateTimeToRestType(value, dateFormat));
 }
 public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
     : this(reader)
 {
     this.dateTimeFormat = dateTimeFormat;
 }
 public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
 {
     this.dateTimeFormat = dateTimeFormat;
 }
 private void Initialize(Type type,
     XmlDictionaryString rootName,
     IEnumerable<Type> knownTypes,
     int maxItemsInObjectGraph,
     bool ignoreExtensionDataObject,
     EmitTypeInformation emitTypeInformation,
     bool serializeReadOnlyTypes,
     DateTimeFormat dateTimeFormat,
     bool useSimpleDictionaryFormat)
 {
     Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat);
     _rootName = ConvertXmlNameToJsonName(rootName);
     _rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(_rootName);
 }
        /// <summary>
        /// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
        {
            lock (lock_variable)
            {
                parsed_time = null;

                Match m;
                if (parsed_date != null && parsed_date.IndexOfDate > -1)
                {//look around the found date
                    //look for <date> [h]h:mm[:ss] [PM/AM]
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    if (!m.Success)
                    {
                        //look for [h]h:mm:ss <date>
                        m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[\s,]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    }
                }
                else//look anywere within string
                    //look for [h]h:mm[:ss] [PM/AM]
                {
                    m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }

                if (m.Success)
                {
                    try
                    {
                        int hour = int.Parse(m.Groups["hour"].Value);
                        if (hour < 0 || hour > 23)
                        {
                            return(false);
                        }

                        int minute = int.Parse(m.Groups["minute"].Value);
                        if (minute < 0 || minute > 59)
                        {
                            return(false);
                        }

                        int second = 0;
                        if (!string.IsNullOrEmpty(m.Groups["second"].Value))
                        {
                            second = int.Parse(m.Groups["second"].Value);
                            if (second < 0 || second > 59)
                            {
                                return(false);
                            }
                        }

                        if (string.Compare(m.Groups[4].Value, "PM", true) > -1)
                        {
                            hour += 12;
                        }

                        DateTime date_time = new DateTime(1, 1, 1, hour, minute, second);
                        parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
                    }
                    catch
                    {
                        return(false);
                    }
                    return(true);
                }

                return(false);
            }
        }
        private void Parse(string connectionString)
        {
            String helpMessage =
                "Valid parameters:\n" +
                "Data Source=<database file>  (required)\n" +
                "NewDatabase=True|False  (default: False)\n" +
                "Encoding=UTF8|UTF16  (default: UTF8)\n" +
                "Cache Size=<N>  (default: 2000)\n" +
                "Synchronous=Full|Normal|Off  (default: Normal)\n" +
                "DateTimeFormat=ISO8601|Ticks|CurrentCulture  (default: ISO8601)\n";

            // Parse connection string
            String[] parameters = connectionString.Split(";".ToCharArray());

            if (parameters.Length == 0) throw new SQLiteException(helpMessage);

            for (int i = 0; i < parameters.Length; i++)
            {
                String parameter = parameters[i].Trim();
                if (parameter.Length == 0) continue;

                int index = parameter.IndexOf('=');
                if (index < 0) throw new SQLiteException(helpMessage);

                String paramName = parameter.Substring(0, index).Trim();
                String paramValue = parameter.Substring(index + 1).Trim();

                if (paramName.Equals("Data Source"))_DataSource = paramValue;
                else if (paramName.Equals("NewDatabase")) _NewDatabase = paramValue.ToUpper().Equals("TRUE");
                else if (paramName.Equals("Encoding"))
                {
                    switch (paramValue.ToUpper())
                    {
                        case "UTF8":
                            _Encoding = Encoding.UTF8;
                            break;
                        case "UTF16":
                            _Encoding = Encoding.Unicode;
                            break;
                        default:
                            throw new SQLiteException(string.Format("Unknown encoding specified: {0}", paramValue));
                    }
                }
                else if (paramName.Equals("Synchronous"))
                {
                    switch (paramValue.ToUpper())
                    {
                        case "FULL":
                            _Synchronous = SynchronousMode.Full;
                            break;
                        case "NORMAL":
                            _Synchronous = SynchronousMode.Normal;
                            break;
                        case "OFF":
                            _Synchronous = SynchronousMode.Off;
                            break;
                        default:
                            throw new SQLiteException(string.Format("Unknown synchronisation mode specified: {0}", paramValue));
                    }
                }
                else if (paramName.Equals("Cache Size"))
                {
                    try
                    {
                        _CacheSize = Convert.ToInt32(paramValue);
                    }
                    catch
                    {
                        throw new SQLiteException(string.Format("Invalid cache size specified: {0}", paramValue));
                    }
                }
                else if (paramName.Equals("DateTimeFormat"))
                {
                    switch (paramValue.ToUpper())
                    {
                        case "ISO8601":
                            _DateTimeFormat = DateTimeFormat.ISO8601;
                            break;
                        case "TICKS":
                            _DateTimeFormat = DateTimeFormat.Ticks;
                            break;
                        case "CURRENTCULTURE":
                            _DateTimeFormat = DateTimeFormat.CurrentCulture;
                            break;
                        default:
                            throw new SQLiteException(string.Format("Unknown DateTimeFormat specified: {0}", paramValue));
                    }
                }
                else
                {
                    throw new SQLiteException(string.Format("Unknown parameter specified: {0}.\r\n{1}", paramName, helpMessage));
                }
            }
        }
        /// <summary>
        /// Tries to find date within the passed string and return it as ParsedDateTime object.
        /// It recognizes only date while ignoring time, so time in the returned ParsedDateTime is always 0:0:0.
        /// If year of the date was not found then it accepts the current year.
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_date">parsed date output</param>
        /// <returns>true if date was found, else false</returns>
        static public bool TryParseDate(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date)
        {
            lock (lock_variable)
            {
                parsed_date = null;

                if (string.IsNullOrEmpty(str))
                {
                    return(false);
                }

                //look for dd/mm/yy
                Match m = Regex.Match(str, @"(?<=^|[^\d])(?'day'\d{1,2})\s*(?'separator'[\\/\.])+\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'year'\d{2,4})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success && m.Groups["year"].Value.Length != 3)
                {
                    DateTime date;
                    if ((default_format ^ DateTimeFormat.USA_DATE) == DateTimeFormat.USA_DATE)
                    {
                        if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["day"].Value), int.Parse(m.Groups["month"].Value), out date))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                        {
                            return(false);
                        }
                    }
                    parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                    return(true);
                }

                //look for yy-mm-dd
                m = Regex.Match(str, @"(?<=^|[^\d])(?'year'\d{2,4})\s*(?'separator'[\-])\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'day'\d{1,2})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success && m.Groups["year"].Value.Length != 3)
                {
                    DateTime date;
                    if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                    {
                        return(false);
                    }
                    parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                    return(true);
                }

                //look for month dd yyyy
                m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?\s*,?\s*(?'year'\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (!m.Success)
                {
                    //look for dd month [yy]yy
                    m = Regex.Match(str, @"(?:^|[^\d\w:])(?'day'\d{1,2})(?:-?st\s+|-?th\s+|-?rd\s+|-?nd\s+|-|\s+)(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*(?:\s*,?\s*|-)(?:'?(?'year'\d{2})|(?'year'\d{4}))(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                if (!m.Success)
                {
                    //look for yyyy month dd
                    m = Regex.Match(str, @"(?:^|[^\d\w])(?'year'\d{4})\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                if (!m.Success)
                {
                    //look for  month dd [yyyy]
                    m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th|-?rd|-?nd)?(?:\s*,?\s*(?'year'\d{4}))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                if (m.Success)
                {
                    int month          = -1;
                    int index_of_date  = m.Index;
                    int length_of_date = m.Length;

                    switch (m.Groups["month"].Value)
                    {
                    case "Jan":
                        month = 1;
                        break;

                    case "Feb":
                        month = 2;
                        break;

                    case "Mar":
                        month = 3;
                        break;

                    case "Apr":
                        month = 4;
                        break;

                    case "May":
                        month = 5;
                        break;

                    case "Jun":
                        month = 6;
                        break;

                    case "Jul":
                        month = 7;
                        break;

                    case "Aug":
                        month = 8;
                        break;

                    case "Sep":
                        month = 9;
                        break;

                    case "Oct":
                        month = 10;
                        break;

                    case "Nov":
                        month = 11;
                        break;

                    case "Dec":
                        month = 12;
                        break;
                    }

                    int year;
                    if (!string.IsNullOrEmpty(m.Groups["year"].Value))
                    {
                        year = int.Parse(m.Groups["year"].Value);
                    }
                    else
                    {
                        year = DefaultDate.Year;
                    }

                    DateTime date;
                    if (!convert_to_date(year, month, int.Parse(m.Groups["day"].Value), out date))
                    {
                        return(false);
                    }
                    parsed_date = new ParsedDateTime(index_of_date, length_of_date, -1, -1, date);
                    return(true);
                }

                return(false);
            }
        }
Esempio n. 50
0
 public sqlite3( bool UTF16Encoding, DateTimeFormat dateTimeFormat, bool oldDateTimeFormat )
 {
     if( UTF16Encoding )
         _encoding = Encoding.Unicode;
     else
         _encoding = Encoding.UTF8;
     _oldDateTimeFormat = oldDateTimeFormat;
     _DateTimeFormat = dateTimeFormat;
 }
Esempio n. 51
0
 /// <summary>Converts the given DateTime value to a string using the given summary desired format</summary>
 /// <param name="dt">Specifies the DateTime value to convert</param>
 /// <param name="dtFormat">Specifies the desired format from the set of supported enum values.</param>
 /// <returns>The DateTime converted to a string based on the desired format.</returns>
 public static string CvtToString(this DateTime dt, DateTimeFormat dtFormat)
 {
     return(CvtToString(ref dt, dtFormat));
 }