private bool MatchingDpOutcome(string learnRefNum, DateTime?endDate)
 {
     return(_learnerDpQueryService.GetDestinationAndProgressionForLearner(learnRefNum)?.DPOutcomes
            ?.Any(dp => ((dp.OutType.CaseInsensitiveEquals(OutTypeConstants.PaidEmployment) && _employedOutcomeCodes.Contains(dp.OutCode)) ||
                         (dp.OutType.CaseInsensitiveEquals(OutTypeConstants.Education) && _educationOutcomeCodes.Contains(dp.OutCode))) &&
                  dp.OutStartDate < (endDate?.AddMonths(6) ?? DateTime.MaxValue)) ?? false);
 }
Ejemplo n.º 2
0
        public static DateTime EndOfCurrentmonth(this DateTime value)
        {
            var retVal = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01);

            retVal = retVal.AddMonths(1).AddDays(-1);
            return new DateTime(retVal.Year, retVal.Month, retVal.Day);
        }
Ejemplo n.º 3
0
        public bool TryConvertToDateTimeRange(out DateTime?dateTimeStart, out DateTime?dateTimeEnd)
        {
            dateTimeStart = null;
            dateTimeEnd   = null;

            if (!ParseDateStrings(out int parsedYear, out int parsedMonth, out int parsedDay))
            {
                return(false);
            }

            try
            {
                dateTimeStart = new DateTime(parsedYear, parsedMonth, parsedDay);

                if (!string.IsNullOrEmpty(Day))
                {
                    dateTimeEnd = dateTimeStart?.AddDays(1);
                }
                else if (!string.IsNullOrEmpty(Month))
                {
                    dateTimeEnd = dateTimeStart?.AddMonths(1);
                }
                else
                {
                    dateTimeEnd = dateTimeStart?.AddYears(1);
                }
                return(true);
            }
            catch (ArgumentOutOfRangeException)
            {
                return(false);
            }
        }
Ejemplo n.º 4
0
            public static DateTime InstantToDateTime(double instant, DateTime start, TimeUnits units = TimeUnits.SECONDS)
            {
                DateTime instantAsDate = start;

                switch (units)
                {
                   case TimeUnits.YEARS:
                  instantAsDate = start.AddYears((int)instant);
                  break;
                   case TimeUnits.MONTHS:
                  instantAsDate = start.AddMonths((int)instant);
                  break;
                   case TimeUnits.DAYS:
                  instantAsDate = start.AddDays(instant);
                  break;
                   case TimeUnits.HOURS:
                  instantAsDate = start.AddHours(instant);
                  break;
                   case TimeUnits.MINUTES:
                  instantAsDate = start.AddMinutes(instant);
                  break;
                   case TimeUnits.SECONDS:
                  instantAsDate = start.AddSeconds(instant);
                  break;
                }

                return instantAsDate;
            }
Ejemplo n.º 5
0
        /// <summary>
        /// Returns true if the date is this month's date.
        /// </summary>
        public static bool IsThisMonth(this DateTime time)
        {
            DateTime now = DateTime.UtcNow;
             DateTime monthStart = new DateTime(now.Year, now.Month, 1);
             DateTime monthEnd = monthStart.AddMonths(1);

             return time > monthStart && time < monthEnd;
        }
Ejemplo n.º 6
0
        public void CanAddMonthsAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dt = new DateTime(2015, 2, 9, 0, 0, 0);
            var result = dt.AddMonths(1, tz);

            var expected = new DateTimeOffset(2015, 3, 9, 0, 0, 0, TimeSpan.FromHours(-7));
            Assert.Equal(expected, result);
            Assert.Equal(expected.Offset, result.Offset);
        }
        private void Add_Blackout_Dates(ref DatePicker dp_cal)
        {
            var      dates = new List <DateTime?>();
            DateTime?date  = dp_cal.DisplayDate;

            DateTime?startDate = date?.AddMonths(-10);
            DateTime?endDate   = date?.AddMonths(10);

            for (var dt = startDate; dt <= endDate; dt = dt?.AddDays(1))
            {
                if (dt?.DayOfWeek != DayOfWeek.Sunday)
                {
                    dates.Add(dt);
                }
            }
            foreach (DateTime d in dates)
            {
                dp_cal.BlackoutDates.Add(new CalendarDateRange(d, d));
            }
        }
Ejemplo n.º 8
0
        private static void UpdateGirlSeason()
        {
            if (girlSeason == null || girlSeasonStart?.AddMonths(1) < DateTime.Today)
            {
                girlSeasonStart = DateTime.Today;
                using (var db = new Database())
                {
                    var misc = db.Misc.FirstOrDefault();
                    if (misc != null)
                    {
                        if (misc.GirlSeasonStartDate.AddMonths(1) < DateTime.Today)
                        {
                            // rotate seasons
                            if (misc.GirlSeason > 0)
                            {
                                // submit seasonal ratings into the main ones
                                var table = db.Girls.Where(x => x.Season == misc.GirlSeason).ToArray();
                                foreach (var girl in table)
                                {
                                    girl.Rating += girl.SeasonRating;
                                }

                                db.Girls.UpdateRange(table);
                            }

                            misc.GirlSeason++;
                            misc.GirlSeasonStartDate = girlSeasonStart.Value;
                            db.Update(misc);
                        }
                        girlSeason = misc.GirlSeason;
                    }
                    else
                    {
                        db.Misc.Add(new Misc
                        {
                            GirlSeason          = 0,
                            GirlSeasonStartDate = girlSeasonStart.Value
                        });
                    }

                    db.SaveChanges();
                }
            }
        }
Ejemplo n.º 9
0
        public ActionResult Index(string slug = "", int year = 0, int month = 0, int page = 0)
        {
            ViewBag.CurrentLanguage = CurrentLanguage;
            if (!string.IsNullOrEmpty(slug))
            {
                var post = _nccPostService.GetBySlug(slug);
                if (post != null)
                {
                    post = _mediator.FirePostEvent(post, PostEvent.Show, null, _logger);
                    SetShortCodeContent(post);
                    return(View("Details", post));
                }
                TempData["Message"] = "Post not found";
            }
            DateTime?dateFrom = null;
            DateTime?dateTo   = null;

            if (year > 0 && month > 0)
            {
                dateFrom = new DateTime(year, month, 1);
                dateTo   = dateFrom?.AddMonths(1).AddMinutes(-1);
            }
            else if (year > 0)
            {
                dateFrom = new DateTime(year, 1, 1);
                dateTo   = dateFrom?.AddYears(1).AddMinutes(-1);
            }
            var postPerPage = GlobalContext.WebSite.WebSitePageSize;
            var totalPost   = _nccPostService.Count(true, true, true, true, dateFrom, dateTo);
            var allPost     = _nccPostService.Load(page, postPerPage, true, true, true, true, dateFrom, dateTo, 0, 0, 0, "", "PublishDate", "desc");

            for (int i = 0; i < allPost.Count; i++)
            {
                allPost[i] = _mediator.FirePostEvent(allPost[i], PostEvent.Show);
            }

            ViewBag.CurrentPage = page;
            ViewBag.PostPerPage = postPerPage;
            ViewBag.TotalPost   = totalPost;
            return(View(allPost));
        }
Ejemplo n.º 10
0
 public void AddMonths(DateTime time, int months)
 {
     Assert.Equal(time.AddMonths(months), new KoreanCalendar().AddMonths(time, months));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Gets a DateTime representing the last day in the current month
 /// </summary>
 /// <param name="date">The current date</param>
 /// <returns>Last day of this month</returns>
 public static DateTime Last(this DateTime date)
 {
     return(date.AddMonths(1).AddDays(-date.Day));
 }
Ejemplo n.º 12
0
 public void AddMonths(DateTime time, int months)
 {
     Assert.Equal(time.AddMonths(months), new ThaiBuddhistCalendar().AddMonths(time, months));
 }
 private static DateTime?calculateMaturityDate(DateTime?abc_JoiningDate, int?abc_InvestmentPeriod)
 {
     return(abc_JoiningDate?.AddMonths((int)abc_InvestmentPeriod));
 }
Ejemplo n.º 14
0
        private void GenerateAppointments()
        {
            Random   ran   = new Random();
            DateTime today = DateTime.Now;

            if (today.Month == 12)
            {
                today = today.AddMonths(-1);
            }
            else if (today.Month == 1)
            {
                today = today.AddMonths(1);
            }
            int      day         = (int)today.DayOfWeek;
            DateTime currentWeek = DateTime.Now.AddDays(-day);
            var      datecoll    = new ObservableCollection <DateTime>();
            DateTime startMonth  = new DateTime(today.Year, today.Month - 1, 1, 0, 0, 0);

            for (int i = 1; i < 30; i += 2)
            {
                for (int j = -7; j < 14; j++)
                {
                    datecoll.Add(currentWeek.Date.AddDays(j).AddHours(ran.Next(9, 18)));
                }
            }

            ObservableCollection <SolidColorBrush> brush = new ObservableCollection <SolidColorBrush>();

            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0xA2, 0xC1, 0x39)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0xD8, 0x00, 0x73)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0x1B, 0xA1, 0xE2)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0xE6, 0x71, 0xB8)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0xF0, 0x96, 0x09)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0x33, 0x99, 0x33)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0xAB, 0xA9)));
            brush.Add(new SolidColorBrush(Color.FromArgb(0xFF, 0xE6, 0x71, 0xB8)));

            Appointments = new ScheduleAppointmentCollection();
            var tempcollection = new ScheduleAppointmentCollection();

            Appointments = tempcollection;
            int count = 0;

            for (int m = 0; m < 30; m++)
            {
                currentdate = datecoll[ran.Next(0, datecoll.Count)];
                DateTime nextdate = datecoll[ran.Next(0, datecoll.Count)];
                count++;
                ScheduleAppointment appointment1 = new ScheduleAppointment()
                {
                    StartTime = currentdate, EndTime = currentdate.AddHours(ran.Next(0, 2)), Subject = subject[count % subject.Length], Location = "Chennai", AppointmentBackground = brush[m % 3]
                };

                appointment1.ResourceCollection.Add(new Resource()
                {
                    TypeName = "Doctors", ResourceName = "Dr.Jacob"
                });
                count++;
                ScheduleAppointment appointment2 = new ScheduleAppointment()
                {
                    StartTime = nextdate, EndTime = nextdate.AddHours(ran.Next(0, 2)), Subject = subject[count % subject.Length], Location = "Chennai", AppointmentBackground = brush[(m + 2) % 3]
                };
                appointment2.ResourceCollection.Add(new Resource()
                {
                    TypeName = "Doctors", ResourceName = "Dr.Darsy"
                });
                if (m < 5)
                {
                    appointment1.IsRecursive    = true;
                    appointment2.IsRecursive    = true;
                    appointment1.RecurrenceRule = "FREQ=WEEKLY;BYDAY=TU,";
                    appointment2.RecurrenceRule = "FREQ=WEEKLY;BYDAY=MO,";
                }
                tempcollection.Add(appointment1);
                tempcollection.Add(appointment2);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 注册赠送模板
        /// </summary>
        /// <param name="accountModel"></param>
        public void AddFreeTemplate(Account accountModel)
        {
            string             typeids  = $"{(int)TmpType.小程序单页模板},{(int)TmpType.小程序企业模板},{(int)TmpType.小程序专业模板}";
            List <XcxTemplate> templist = XcxTemplateBLL.SingleModel.GetListByTypes(typeids);

            if (templist == null || templist.Count <= 0 || accountModel == null)
            {
                return;
            }

            XcxAppAccountRelation usertemplate = GetModelByaccound(accountModel.Id.ToString());

            if (usertemplate != null)
            {
                return;
            }

            TransactionModel tran    = new TransactionModel();
            DateTime         nowtime = DateTime.Now;
            int version = 0;
            int month   = 100 * 12;

            foreach (XcxTemplate item in templist)
            {
                version = 0;
                if (item.Type == (int)TmpType.小程序专业模板)
                {
                    version = 3;
                    month   = 3;
                }
                else
                {
                    month = 100 * 12;
                }
                tran.Add($@"insert into XcxAppAccountRelation(TId,AccountId,AddTime,Url,price,outtime,agentid,VersionId) 
            values({item.Id}, '{accountModel.Id}', '{nowtime}', '{item.Link}', {item.Price}, '{nowtime.AddMonths(month)}',0,{version})");

                AgentdepositLog pricemodellog = new AgentdepositLog();
                pricemodellog.addtime       = DateTime.Now;
                pricemodellog.afterDeposit  = 0;
                pricemodellog.agentid       = 0;
                pricemodellog.beforeDeposit = 0;
                pricemodellog.cost          = 0;
                pricemodellog.costdetail    = $"客户免费使用小程序模板:{(version == 3 ? "专业基础版" : item.TName)}";
                pricemodellog.type          = 0;
                pricemodellog.tid           = item.Id;

                tran.Add(AgentdepositLogBLL.SingleModel.BuildAddSql(pricemodellog));
            }

            if (!ExecuteTransactionDataCorect(tran.sqlArray, tran.ParameterArray))
            {
                log4net.LogHelper.WriteInfo(this.GetType(), "赠送免费版:失败," + Newtonsoft.Json.JsonConvert.SerializeObject(tran));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// F8 リボン 印刷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnF8Key(object sender, KeyEventArgs e)
        {
            PrinterDriver ret = AppCommon.GetPrinter(frmcfg.PrinterName);

            if (ret.Result == false)
            {
                this.ErrorMessage = "プリンタドライバーがインストールされていません!";
                return;
            }
            frmcfg.PrinterName = ret.PrinterName;

            if (!base.CheckAllValidation())
            {
                MessageBox.Show("入力内容に誤りがあります。");
                SetFocusToTopControl();
                return;
            }


            int i表示順序 = 表示順序_Cmb.SelectedIndex;


            if (作成年 == null || 作成月 == null)
            {
                this.ErrorMessage = "作成年月は入力必須項目です。";
                return;
            }
            int i年月;

            i年月 = Convert.ToInt32((作成年).ToString()) * 100 + Convert.ToInt32(作成月.ToString());

            //乗務員リスト作成
            int?[] i乗務員List = new int?[0];
            if (!string.IsNullOrEmpty(乗務員ピックアップ))
            {
                string[] 乗務員List = 乗務員ピックアップ.Split(',');
                i乗務員List = new int?[乗務員List.Length];

                for (int i = 0; i < 乗務員List.Length; i++)
                {
                    string str = 乗務員List[i];
                    int    code;
                    if (!int.TryParse(str, out code))
                    {
                        this.ErrorMessage = "乗務員指定の形式が不正です。";
                        return;
                    }
                    i乗務員List[i] = code;
                }
            }

            DateTime dDate = new DateTime(AppCommon.IntParse(作成年.ToString()), AppCommon.IntParse(作成月.ToString()), 1);

            開始年 = AppCommon.IntParse(作成年.ToString());
            開始月 = AppCommon.IntParse(作成月.ToString());
            項目1 = dDate.Month.ToString() + "月";
            int i開始年月 = dDate.Year * 100 + dDate.Month;

            dDate = dDate.AddMonths(1);
            項目2   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目3   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目4   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目5   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目6   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目7   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目8   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目9   = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目10  = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目11  = dDate.Month.ToString() + "月";
            dDate = dDate.AddMonths(1);
            項目12  = dDate.Month.ToString() + "月";
            int i終了年月 = dDate.Year * 100 + dDate.Month;

            終了年  = dDate.Year;
            終了月  = dDate.Month;
            項目13 = "年合計";
            項目14 = "平 均";
            項目15 = "対売上";


            //帳票出力用
            base.SendRequest(new CommunicationObject(MessageType.RequestDataWithBusy, SEARCH_JMI13010, new object[] { 乗務員From, 乗務員To, i乗務員List, 乗務員ピックアップ,
                                                                                                                      作成年, 作成月, }));
        }
Ejemplo n.º 17
0
        public static bool compareDate(DateTime a, int?year, int?month, int?day, string method)
        {
            try
            {
                bool result;
                switch (method)
                {
                case "=":
                    if (year != null && month != null && day != null)
                    {
                        result = a.Year.Equals(year) && a.Month.Equals(month) && a.Day.Equals(day);
                    }
                    else if (year != null && month != null)
                    {
                        result = a.Year.Equals(year) && a.Month.Equals(month);
                    }
                    else if (year != null)
                    {
                        result = a.Year.Equals(year);
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                case ">=":
                    if (year != null && month != null && day != null)
                    {
                        var b = new DateTime((int)year, (int)month, (int)day);
                        result = a >= b;
                    }
                    else if (year != null && month != null)
                    {
                        var b = new DateTime((int)year, (int)month, 1);

                        result = a >= b;
                    }
                    else if (year != null)
                    {
                        result = a.Year >= year;
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                case "<=":
                    if (year != null && month != null && day != null)
                    {
                        var b = new DateTime((int)year, (int)month, (int)day);
                        result = a <= b;
                    }
                    else if (year != null && month != null)
                    {
                        var b = new DateTime((int)year, (int)month, 1);
                        b      = b.AddMonths(1).AddDays(-1);
                        result = a <= b;
                    }
                    else if (year != null)
                    {
                        result = a.Year <= year;
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                case "!=":
                    if (year != null && month != null && day != null)
                    {
                        result = !(a.Year.Equals(year) && a.Month.Equals(month) && a.Day.Equals(day));
                    }
                    else if (year != null && month != null)
                    {
                        result = !(a.Year.Equals(year) && a.Month.Equals(month));
                    }
                    else if (year != null)
                    {
                        result = !(a.Year.Equals(year));
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                case ">":
                    if (year != null && month != null && day != null)
                    {
                        var b = new DateTime((int)year, (int)month, (int)day);
                        result = a > b;
                    }
                    else if (year != null && month != null)
                    {
                        var b = new DateTime((int)year, (int)month, 1);
                        b      = b.AddMonths(1).AddDays(-1);
                        result = a > b;
                    }
                    else if (year != null)
                    {
                        result = a.Year > year;
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                case "<":
                    if (year != null && month != null && day != null)
                    {
                        var b = new DateTime((int)year, (int)month, (int)day);
                        result = a < b;
                    }
                    else if (year != null && month != null)
                    {
                        var b = new DateTime((int)year, (int)month, 1);
                        result = a < b;
                    }
                    else if (year != null)
                    {
                        result = a.Year < year;
                    }
                    else
                    {
                        result = false;
                    }
                    break;

                default:
                    return(false);
                }
                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 季度第一天
 /// </summary>
 /// <param name="quarters">上季度-1 下季度+1</param>
 /// <returns></returns>
 public string GetFirstDayOfQuarter(int? quarters)
 {
     int quarter = quarters ?? 0;
     return dt.AddMonths(quarter * 3 - ((dt.Month - 1) % 3)).ToString("yyyy-MM-01");
 }
Ejemplo n.º 19
0
        private void button1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            object[] obj = new object[lista.Count];

            int    contador = 0;
            double sy       = 0;

            foreach (Dictionary <string, object> item in this.lista)
            {
                double folio = Convert.ToDouble(item["folio"]);


                string rfc             = Convert.ToString(item["rfc"]);
                string nombre          = Convert.ToString(item["nombre_em"]);
                string f_emischeq      = string.IsNullOrWhiteSpace(Convert.ToString(item["f_emischeq"]))?"": string.Format("{0:d}", item["f_emischeq"]);
                string ubicPagare      = Convert.ToString(item["ubic_pagare"]);
                string proyecto        = Convert.ToString(item["proyecto"]);
                string numdesc         = Convert.ToString(item["numdesc"]);
                string totdesc         = Convert.ToString(item["totdesc"]);
                double importe         = (string.IsNullOrWhiteSpace(Convert.ToString(item["importe"]))) ? 0 : (Convert.ToDouble(item["importe"]));
                double imp_unit        = (string.IsNullOrWhiteSpace(Convert.ToString(item["imp_unit"]))) ? 0 : (Convert.ToDouble(item["imp_unit"]));;
                double pagado          = (string.IsNullOrWhiteSpace(Convert.ToString(item["pagado"]))) ? 0 : (Convert.ToDouble(item["pagado"]));
                double saldo           = (string.IsNullOrWhiteSpace(Convert.ToString(item["saldo"]))) ? 0 : (Convert.ToDouble(item["saldo"]));
                string cta             = Convert.ToString(item["cuenta"]);
                string cta_descripcion = Convert.ToString(item["descripcion_cta"]);
                string fechaUltimo     = string.IsNullOrWhiteSpace(Convert.ToString(item["ultimop"])) ? "" : string.Format("{0:d}", item["ultimop"]);
                string resultadoFinal  = string.Empty;
                if (!string.IsNullOrWhiteSpace(f_emischeq))
                {
                    DateTime fec1 = DateTime.Parse(f_emischeq);
                    DateTime fec2 = DateTime.Parse(this.fecha);

                    string c1   = string.Format("{0}-{1}-{2}", fec1.Year, fec1.Month, fec1.Day);
                    string c2   = string.Format("{0}-{1}-{2}", fec2.Year, fec2.Month, fec2.Day);
                    double Q    = 0;
                    int    quin = 0;
                    int    concilia;


                    for (int A1 = fec1.Year; A1 <= fec2.Year; A1++)
                    {
                        for (int M1 = 1; M1 <= 12; M1++)
                        {
                            quin = (M1 * 2) - 1;
                            DateTime ftemp = new DateTime(A1, M1, 8);
                            if (ftemp >= fec1 && ftemp <= fec2)
                            {
                                Q++;
                            }

                            quin++;

                            ftemp = new DateTime(A1, M1, 23);

                            if (ftemp >= fec1 && ftemp <= fec2)
                            {
                                Q++;
                            }
                        }
                    }

                    Q = 0;
                    while (true)
                    {
                        DateTime aux1 = new DateTime(fec1.Year, fec1.Month, 8);
                        if (aux1 < fec2)
                        {
                            Q++;
                        }
                        else
                        {
                            break;
                        }

                        aux1 = new DateTime(fec1.Year, fec1.Month, 23);
                        if (aux1 < fec2)
                        {
                            Q++;
                        }
                        else
                        {
                            break;
                        }

                        fec1 = fec1.AddMonths(1);
                    }

                    int Qtotales = Convert.ToInt32(Q);
                    int AA       = Convert.ToInt32((Qtotales) / 24);
                    int QAux     = Qtotales - (AA * 24);
                    int AM       = Convert.ToInt32((QAux / 2));
                    int AQ       = QAux - (AM * 2);

                    int A  = AA;
                    int M  = AM;
                    int q1 = AQ;


                    resultadoFinal = string.Format("A:{0}-M:{1}", A, M);
                }
                sy += saldo;
                object[] aux = { folio, rfc, nombre, ubicPagare, proyecto, numdesc + "/" + totdesc, importe, imp_unit, pagado, saldo, cta, cta_descripcion, resultadoFinal };
                obj[contador] = aux;
                contador++;
            }
            string opcion1 = (opcion) ? "QUIROGRAFARIOS" : "HIPOTECARIOS";
            string fecha   = this.fecha;

            string logo = globales.getImagen(globales.imagenesSispe.logoreportes);

            object[][] parametros = new object[2][];
            object[]   headers    = { "p1", "p2", "fecha", "logo" };
            object[]   body       = { opcion1, string.Format("{0:d}", DateTime.Parse(fecha)), string.Format("{0:d}", DateTime.Now), logo };
            parametros[0] = headers;
            parametros[1] = body;


            if (listBox1.SelectedIndex == 0)
            {
                globales.reportes("reporteRsaldopSaldosPrestamo", "reporteSinSaldo", obj, "", false, parametros);
            }
            else if (listBox1.SelectedIndex == 1)
            {
                globales.reportes("reporteSaldopResumenCuenta", "reporteSinSaldo", obj, "", false, parametros);
            }
            else if (listBox1.SelectedIndex == 2)
            {
                globales.reportes("reporteRSaldoPAlfabetico", "reporteSinSaldo", obj, "", false, parametros);
            }
            else if (listBox1.SelectedIndex == 3)
            {
                globales.reportes("reporteRSaldoPAlfabeticoSinSaldordlc", "reporteSinSaldo", obj, "", false, parametros);
            }
            else if (listBox1.SelectedIndex == 4)
            {
                globales.reportes("reporteRSaldoPFolio", "reporteSinSaldo", obj, "", false, parametros);
            }
            else
            {
                SaveFileDialog dialogoGuardar = new SaveFileDialog();
                dialogoGuardar.AddExtension = true;
                dialogoGuardar.DefaultExt   = ".dbf";
                if (dialogoGuardar.ShowDialog() == DialogResult.OK)
                {
                    string ruta = dialogoGuardar.FileName;

                    Stream ops = File.Open(ruta, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                    DotNetDBF.DBFWriter escribir = new DotNetDBF.DBFWriter();
                    escribir.DataMemoLoc = ruta.Replace("dbf", "dbt");

                    DotNetDBF.DBFField c1  = new DotNetDBF.DBFField("FOLIO", DotNetDBF.NativeDbType.Numeric, 20, 2);
                    DotNetDBF.DBFField c2  = new DotNetDBF.DBFField("RFC", DotNetDBF.NativeDbType.Char, 100);
                    DotNetDBF.DBFField c3  = new DotNetDBF.DBFField("NOMBRE_EM", DotNetDBF.NativeDbType.Char, 100);
                    DotNetDBF.DBFField c4  = new DotNetDBF.DBFField("PROYECTO", DotNetDBF.NativeDbType.Char, 100);
                    DotNetDBF.DBFField c5  = new DotNetDBF.DBFField("IMP_UNIT", DotNetDBF.NativeDbType.Numeric, 10, 2);
                    DotNetDBF.DBFField c6  = new DotNetDBF.DBFField("F_PRIMDESC", DotNetDBF.NativeDbType.Char, 20);
                    DotNetDBF.DBFField c7  = new DotNetDBF.DBFField("IMPORTE", DotNetDBF.NativeDbType.Numeric, 10, 2);
                    DotNetDBF.DBFField c8  = new DotNetDBF.DBFField("UBIC_PAGAR", DotNetDBF.NativeDbType.Char, 80);
                    DotNetDBF.DBFField c9  = new DotNetDBF.DBFField("NUMDESC", DotNetDBF.NativeDbType.Numeric, 10, 2);
                    DotNetDBF.DBFField c10 = new DotNetDBF.DBFField("TOTDESC", DotNetDBF.NativeDbType.Numeric, 10, 2);
                    DotNetDBF.DBFField c11 = new DotNetDBF.DBFField("PAGADO", DotNetDBF.NativeDbType.Numeric, 10, 2);
                    DotNetDBF.DBFField c12 = new DotNetDBF.DBFField("FECHA", DotNetDBF.NativeDbType.Char, 20);
                    DotNetDBF.DBFField c13 = new DotNetDBF.DBFField("CTA", DotNetDBF.NativeDbType.Char, 20);
                    DotNetDBF.DBFField c14 = new DotNetDBF.DBFField("SALDO", DotNetDBF.NativeDbType.Numeric, 10, 2);

                    DotNetDBF.DBFField[] campos = new DotNetDBF.DBFField[] { c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14 };
                    escribir.Fields = campos;

                    foreach (Dictionary <string, object> item in this.lista)
                    {
                        List <object> record = new List <object> {
                            Convert.ToDouble(item["folio"]),
                            Convert.ToString(item["rfc"]),
                            Convert.ToString(item["nombre_em"]),
                            Convert.ToString(item["proyecto"]),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["imp_unit"])))?0:Convert.ToDouble(item["imp_unit"]),
                            Convert.ToString(item["f_primdesc"]).Replace(" 12:00:00 a. m.", ""),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["importe"])))?0:Convert.ToDouble(item["importe"]),
                            Convert.ToString(item["ubic_pagare"]),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["numdesc"])))?0:Convert.ToDouble(item["numdesc"]),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["totdesc"])))?0:Convert.ToDouble(item["totdesc"]),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["pagado"])))?0:Convert.ToDouble(item["pagado"]),
                            Convert.ToString(item["f_emischeq"]).Replace(" 12:00:00 a. m.", ""),
                            Convert.ToString(item["cuenta"]),
                            (string.IsNullOrWhiteSpace(Convert.ToString(item["saldo"])))?0:Convert.ToDouble(item["saldo"])
                        };

                        escribir.AddRecord(record.ToArray());
                    }

                    escribir.Write(ops);
                    escribir.Close();
                    ops.Close();

                    globales.MessageBoxSuccess("Archivo .DBF generado exitosamente", "Archivo generado", globales.menuPrincipal);
                }
            }

            this.Cursor = Cursors.Default;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the excel date.
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <param name="day">The day.</param>
        /// <param name="hour">The hour.</param>
        /// <param name="minute">The minute.</param>
        /// <param name="second">The second.</param>
        /// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param>
        /// <returns></returns>
        public static double GetExcelDate(int year, int month, int day, int hour, int minute, int second, bool use1904windowing)
        {
            if ((!use1904windowing && year < 1900) || //1900 date system must bigger than 1900
                (use1904windowing && year < 1904))      //1904 date system must bigger than 1904
            {
                return(BAD_DATE);
            }

            DateTime startdate;

            if (use1904windowing)
            {
                startdate = new DateTime(1904, 1, 1);
            }
            else
            {
                startdate = new DateTime(1900, 1, 1);
            }
            int nextyearmonth = 0;

            if (month > 12)
            {
                nextyearmonth = month - 12;
                month         = 12;
            }
            int nextmonthday = 0;

            if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12))
            {
                //big month
                if (day > 31)
                {
                    nextmonthday = day - 31;
                    day          = 31;
                }
            }
            else if ((month == 4 || month == 6 || month == 9 || month == 11))
            {
                //small month
                if (day > 30)
                {
                    nextmonthday = day - 30;
                    day          = 30;
                }
            }
            else if (DateTime.IsLeapYear(year))
            {
                //Feb. with leap year
                if (day > 29)
                {
                    nextmonthday = day - 29;
                    day          = 29;
                }
            }
            else
            {
                //Feb without leap year
                if (day > 28)
                {
                    nextmonthday = day - 28;
                    day          = 28;
                }
            }

            if (day <= 0)
            {
                nextmonthday = day - 1;
                day          = 1;
            }

            DateTime date = new DateTime(year, month, day, hour, minute, second);

            date = date.AddMonths(nextyearmonth);
            date = date.AddDays(nextmonthday);
            double value = (date - startdate).TotalDays + 1;

            if (!use1904windowing && value >= 60)
            {
                value++;
            }
            else if (use1904windowing)
            {
                value--;
            }
            return(value);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 帳票ファイル作成処理
        /// </summary>
        /// <param name="targetReport"></param>
        /// <param name="staffNo"></param>
        /// <param name="orderNo"></param>
        public void SaveFile()
        {
            bool       bNoDataFlag;
            double     dOutputTemp;
            ICellStyle cellStyleTemp;
            DateTime   dtTargetDay;

            DataTable        dtResultDetail;
            DateTime         dtTargetMonth       = DateTime.ParseExact(pstrTargetMonth + "01", "yyyyMMdd", null);
            SaveFileDialog   sfd                 = new SaveFileDialog();
            JapaneseCalendar clsJapaneseCalendar = new JapaneseCalendar();

            // 保存ダイアログのプロパティ設定
            SetSaveFileDialogProperties(ref sfd);

            //ダイアログを表示する
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // オブジェクト初期化
            InitializeObject();

            // Officeオブジェクトの初期化
            IWorkbook xlWorkbook = WorkbookFactory.Create(strFilePath);
            ISheet    xlSheet    = xlWorkbook.GetSheet("シート");

            // === Excelデータ入力 ===

            // 作成年月日
            WriteCellValue(xlSheet, COLUMN_CREATE_YEAR, ROW_CREATE_YEAR, double.Parse(clsJapaneseCalendar.GetYear(System.DateTime.Now).ToString()));
            WriteCellValue(xlSheet, COLUMN_CREATE_MONTH, ROW_CREATE_MONTH, double.Parse(DateTime.Now.ToString("MM")));
            WriteCellValue(xlSheet, COLUMN_CREATE_DAY, ROW_CREATE_DAY, double.Parse(DateTime.Now.ToString("dd")));

            // 区分
            WriteCellValue(xlSheet, COLUMN_KUBUN, ROW_KUBUN, drWardYoushiki9["kubun"].ToString());

            // 看護配置・看護補助配置人数
            WriteCellValue(xlSheet, COLUMN_NURSE_COUNT, ROW_NURSE_COUNT, double.Parse(drWardYoushiki9["nurse_count"].ToString()));
            WriteCellValue(xlSheet, COLUMN_CARE_COUNT, ROW_CARE_COUNT, double.Parse(drWardYoushiki9["care_count"].ToString()));

            // 届出の病棟数
            WriteCellValue(xlSheet, COLUMN_WARD_COUNT, ROW_WARD_COUNT, double.Parse(drWardYoushiki9["ward_count"].ToString()));

            // 届出の病床数
            WriteCellValue(xlSheet, COLUMN_BED_COUNT, ROW_BED_COUNT, double.Parse(drWardYoushiki9["bed_count"].ToString()));

            // 1日平均入院患者数
            WriteCellValue(xlSheet, COLUMN_AVERAGE_DAY, ROW_AVERAGE_DAY, double.Parse(drWardYoushiki9["average_day"].ToString()));

            // 1日平均入院患者数(算出期間)
            WriteCellValue(xlSheet, COLUMN_AVERAGE_DAY_START_YEAR, ROW_AVERAGE_DAY_START_YEAR, double.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth.AddMonths(-12)).ToString()));
            WriteCellValue(xlSheet, COLUMN_AVERAGE_DAY_START_MONTH, ROW_AVERAGE_DAY_START_MONTH, double.Parse(dtTargetMonth.AddMonths(-12).ToString("MM")));
            WriteCellValue(xlSheet, COLUMN_AVERAGE_DAY_END_YEAR, ROW_AVERAGE_DAY_END_YEAR, double.Parse(clsJapaneseCalendar.GetYear(System.DateTime.Now.AddMonths(-1)).ToString()));
            WriteCellValue(xlSheet, COLUMN_AVERAGE_DAY_END_MONTH, ROW_AVERAGE_DAY_END_MONTH, double.Parse(dtTargetMonth.AddMonths(-1).ToString("MM")));

            // 平均在院日数
            WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS, ROW_AVERAGE_YEARS, double.Parse(drWardYoushiki9["average_year"].ToString()));

            // 平均在院日数(算出期間)
            // Mod Start WataruT 2020.11.06 様式9の平均在院日数の算出期間修正
            //WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_START_YEAR, ROW_AVERAGE_YEARS_START_YEAR, double.Parse((int.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth.AddMonths(-3)).ToString()) - 1).ToString()));
            WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_START_YEAR, ROW_AVERAGE_YEARS_START_YEAR, double.Parse((int.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth.AddMonths(-3)).ToString())).ToString()));
            // Mod End   WataruT 2020.11.06 様式9の平均在院日数の算出期間修正
            WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_START_MONTH, ROW_AVERAGE_YEARS_START_MONTH, double.Parse(dtTargetMonth.AddMonths(-3).ToString("MM")));
            // Mod Start WataruT 2020.11.06 様式9の平均在院日数の算出期間修正
            //WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_END_YEAR, ROW_AVERAGE_YEARS_END_YEAR, double.Parse((int.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth.AddMonths(-1)).ToString()) - 1).ToString()));
            WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_END_YEAR, ROW_AVERAGE_YEARS_END_YEAR, double.Parse((int.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth.AddMonths(-1)).ToString())).ToString()));
            // Mod End   WataruT 2020.11.06 様式9の平均在院日数の算出期間修正
            WriteCellValue(xlSheet, COLUMN_AVERAGE_YEARS_END_MONTH, ROW_AVERAGE_YEARS_END_MONTH, double.Parse(dtTargetMonth.AddMonths(-1).ToString("MM")));

            // 対象年月
            WriteCellValue(xlSheet, COLUMN_TARGET_YEAR, ROW_TARGET_YEAR, double.Parse(clsJapaneseCalendar.GetYear(dtTargetMonth).ToString()));
            WriteCellValue(xlSheet, COLUMN_TARGET_MONTH, ROW_TARGET_MONTH, double.Parse(dtTargetMonth.ToString("MM")));

            // 稼働日数
            WriteCellValue(xlSheet, COLUMN_WORK_DAYS, ROW_WORK_DAYS, DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month));

            // << 看護職員表 >>

            // == 日付・曜日 ==
            for (int i = 0; i < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); i++)
            {
                // 日にち
                WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_DAY, (i + 1).ToString() + "日");

                // 曜日
                WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_DAY_OF_WEEK, dtTargetMonth.AddDays(double.Parse(i.ToString())).ToString("ddd") + "曜");
            }

            // == 職員氏名欄(種別、順番、病棟、氏名、雇用形態) ==
            for (int iStaff = 0; iStaff < astrScheduleStaffNurse.GetLength(0); iStaff++)
            {
                // 種別
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, astrScheduleStaffNurse[iStaff, 2]);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 順番
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 1, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, double.Parse((iStaff + 1).ToString()));
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 1, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 1, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 病棟
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 2, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, pstrWardName);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 2, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 2, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 氏名
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 3, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, astrScheduleStaffNurse[iStaff, 1]);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 3, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 3, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(常勤)
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 4, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, "常勤");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 4, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, 1);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 4, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(短時間)
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 5, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, "短時間");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 5, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 5, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(非常勤)
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 6, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, "非常勤");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 6, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 6, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(他部署兼務)
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 7, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, "他部署兼務");
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 7, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_NURSE_STAFF_START + 7, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");
            }

            // == 実績データ ==
            for (int iStaff = 0; iStaff < astrScheduleStaffNurse.GetLength(0); iStaff++)
            {
                // 対象職員の実績データ取得
                dtResultDetail = clsDatabaseControl.GetResultDetail_Ward_Staff_StaffKind_TargetMonth(pstrWard,
                                                                                                     astrScheduleStaffNurse[iStaff, 0], "01", pstrTargetMonth);

                // 1日から順に処理
                for (int iDay = 0; iDay < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); iDay++)
                {
                    // データなしフラグを初期化
                    bNoDataFlag = false;

                    // 実績データがある場合
                    if (dtResultDetail.Rows.Count != 0)
                    {
                        foreach (DataRow row in dtResultDetail.Rows)
                        {
                            if (DateTime.Parse(row["target_date"].ToString()).Day == iDay + 1)
                            {
                                if (double.TryParse(row["work_time_day"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, dOutputTemp);
                                }
                                if (double.TryParse(row["work_time_night"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, dOutputTemp);
                                }
                                if (double.TryParse(row["work_time_night_total"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, dOutputTemp);
                                }
                                bNoDataFlag = true;
                                break;
                            }
                        }
                    }

                    // 実績データがない場合
                    else if (bNoDataFlag == false)
                    {
                        WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, "");
                        WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                        WriteCellValue(xlSheet, COLUMN_NURSE_DAY_START + iDay, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, "");
                    }
                }
            }

            // == 休日の背景色変更 ==
            for (int i = 0; i < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); i++)
            {
                // 対象日付をセット
                dtTargetDay = DateTime.Parse(dtTargetMonth.ToString("yyyy/MM/") + String.Format("{0:D2}", i + 1));

                // 日曜または祝日判定
                if (clsDatabaseControl.GetHolidayDate_Check(dtTargetDay.ToString("yyyyMMdd")) || dtTargetDay.ToString("ddd") == "日")
                {
                    for (int iStaff = 0; iStaff < astrScheduleStaffNurse.GetLength(0); iStaff++)
                    {
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 3, cellStyleTemp);
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 2, cellStyleTemp);
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_NURSE_DAY_START + i, ROW_NURSE_STAFF_START + (iStaff + 1) * 3 - 1, cellStyleTemp);
                    }
                }
            }

            // << 看護補助職員表 >>

            // == 日付・曜日 ==
            for (int i = 0; i < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); i++)
            {
                // 日にち
                WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_DAY, (i + 1).ToString() + "日");

                // 曜日
                WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_DAY_OF_WEEK, dtTargetMonth.AddDays(double.Parse(i.ToString())).ToString("ddd") + "曜");
            }

            // == 職員氏名欄(種別、順番、病棟、氏名、雇用形態) ==
            for (int iStaff = 0; iStaff < astrScheduleStaffCare.GetLength(0); iStaff++)
            {
                // 順番
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, double.Parse((iStaff + 1).ToString()));
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 病棟
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 1, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, pstrWardName);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 1, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 1, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 氏名
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 2, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, astrScheduleStaffCare[iStaff, 1]);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 2, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 2, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(常勤)
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 3, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "常勤");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 3, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, 1);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 3, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(短時間)
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 4, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "短時間");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 4, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 4, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(非常勤)
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 5, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "非常勤");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 5, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 5, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                // 雇用形態(他部署兼務)
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 6, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "他部署兼務");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 6, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, 0);
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 6, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");

                //Add Start WataruT 2020.08.31 様式9に事務的業務の担当者フラグをセット
                // 事務的業務
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 7, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "事務的業務");
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 7, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, int.Parse(astrScheduleStaffCare[iStaff, 3]));
                WriteCellValue(xlSheet, COLUMN_CARE_STAFF_START + 7, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");
                //Add End   WataruT 2020.08.31 様式9に事務的業務の担当者フラグをセット
            }

            // == 実績データ ==
            for (int iStaff = 0; iStaff < astrScheduleStaffCare.GetLength(0); iStaff++)
            {
                // 対象職員の実績データ取得
                dtResultDetail = clsDatabaseControl.GetResultDetail_Ward_Staff_StaffKind_TargetMonth(pstrWard,
                                                                                                     astrScheduleStaffCare[iStaff, 0], "02", pstrTargetMonth);

                // 1日から順に処理
                for (int iDay = 0; iDay < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); iDay++)
                {
                    // データなしフラグを初期化
                    bNoDataFlag = false;

                    // 実績データがある場合
                    if (dtResultDetail.Rows.Count != 0)
                    {
                        foreach (DataRow row in dtResultDetail.Rows)
                        {
                            if (DateTime.Parse(row["target_date"].ToString()).Day == iDay + 1)
                            {
                                if (double.TryParse(row["work_time_day"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, dOutputTemp);
                                }
                                if (double.TryParse(row["work_time_night"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, dOutputTemp);
                                }
                                if (double.TryParse(row["work_time_night_total"].ToString(), out dOutputTemp))
                                {
                                    WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, dOutputTemp);
                                }
                                bNoDataFlag = true;
                                break;
                            }
                        }
                    }
                    // 実績データがない場合
                    else if (bNoDataFlag == false)
                    {
                        WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, "");
                        WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, "");
                        WriteCellValue(xlSheet, COLUMN_CARE_DAY_START + iDay, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, "");
                    }
                }
            }

            // == 休日の背景色変更 ==
            for (int i = 0; i < DateTime.DaysInMonth(dtTargetMonth.Year, dtTargetMonth.Month); i++)
            {
                // 対象日付をセット
                dtTargetDay = DateTime.Parse(dtTargetMonth.ToString("yyyy/MM/") + String.Format("{0:D2}", i + 1));

                // 日曜または祝日判定
                if (clsDatabaseControl.GetHolidayDate_Check(dtTargetDay.ToString("yyyyMMdd")) || dtTargetDay.ToString("ddd") == "日")
                {
                    for (int iStaff = 0; iStaff < astrScheduleStaffCare.GetLength(0); iStaff++)
                    {
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 3, cellStyleTemp);
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 2, cellStyleTemp);
                        cellStyleTemp = xlWorkbook.CreateCellStyle();
                        cellStyleTemp.CloneStyleFrom(GetCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1));
                        cellStyleTemp.FillPattern         = FillPattern.LessDots;
                        cellStyleTemp.FillForegroundColor = IndexedColors.Black.Index;
                        cellStyleTemp.FillBackgroundColor = IndexedColors.White.Index;
                        WriteCellStyle(xlSheet, COLUMN_CARE_DAY_START + i, ROW_CARE_STAFF_START + (iStaff + 1) * 3 - 1, cellStyleTemp);
                    }
                }
            }

            // 不要な行を非表示とする
            for (int i = ROW_NURSE_STAFF_START + (3 * astrScheduleStaffNurse.GetLength(0)); i <= ROW_NURSE_STAFF_END; i++)
            {
                xlSheet.GetRow(i).Height = 1;
            }
            for (int i = ROW_CARE_STAFF_START + (3 * astrScheduleStaffCare.GetLength(0)); i <= ROW_CARE_STAFF_END; i++)
            {
                xlSheet.GetRow(i).Height = 1;
            }

            // シート内の各関数の再計算
            XSSFFormulaEvaluator.EvaluateAllFormulaCells(xlWorkbook);

            // ファイル保存
            using (var fs = new FileStream(sfd.FileName, FileMode.Create))
            {
                xlWorkbook.Write(fs);
            }

            // 終了メッセージ
            MessageBox.Show("保存完了");
        }
        /* Función de controlador tipo GET que abre la vista principal del sistema del lado del
         * usuario, en esta vista se permite visualizar toda la información principal de la comisión.
         * Parámetros: Id de la comisión*/
        public ActionResult InformacionPrincipal(int id)
        {
            ComisionUserTableViewModel model = new ComisionUserTableViewModel();

            using (var db = new SaludOcupacionalEntities())
            {
                var oComision        = db.Comision.Find(id);
                var oCentroDeTrabajo = db.CentroDeTrabajo.Find(oComision.idCentroDeTrabajo);
                model.nombre           = oCentroDeTrabajo.nombreCentroDeTrabajo;
                model.contacto         = oComision.contacto;
                model.contactoCorreo   = oComision.contactoCorreo;
                model.contactoTelefono = oComision.contactoTelefono;
                model.jefatura         = oComision.jefatura;
                model.jefaturaCorreo   = oComision.jefaturaCorreo;
                model.jefaturaTelefono = oComision.jefaturaTelefono;
                model.idComision       = oComision.idComision;
                model.fechaDeRegistro  = oComision.fechaDeRegistro;
                model.numeroRegistro   = oComision.numeroDeRegistro;
                model.ultimoInforme    = oComision.ultimoInforme;
            }
            if (model.contacto == null || model.contactoCorreo == null || model.contactoTelefono == null || model.jefatura == null ||
                model.jefaturaCorreo == null || model.jefaturaTelefono == null || model.fechaDeRegistro == null || model.numeroRegistro == null)
            {
                return(Redirect(Url.Content("~/ComisionUser/LlenarInformacion/" + model.idComision)));
            }
            using (SaludOcupacionalEntities db = new SaludOcupacionalEntities())
            {
                model.representantes = (from d in db.Representante
                                        where d.idComision == id && d.estado == 1
                                        orderby d.idRepresentante
                                        select new RepresentanteTableViewModel
                {
                    idRepresentante = d.idRepresentante,
                    nombre = d.nombre,
                    correo = d.correo,
                    telefono = d.telefono,
                    idComision = d.idComision,
                    tipo = d.tipo == 0 ? "Patrono" : "Trabajador"
                }).ToList();
            }

            DateTime hoy          = DateTime.Today;
            DateTime?fechaInforme = model.ultimoInforme;

            // Comparación para alzar la notificación de entrega del informe anual.
            if (fechaInforme == null || fechaInforme?.Year < hoy.Year)
            {
                ViewBag.Mensaje = "Recuerde por favor entregar el informe Anual\n Ya lo ha entregado?";
            }

            DateTime?fechaRegistro        = model.fechaDeRegistro;
            DateTime?fechaVencimiento     = fechaRegistro?.AddYears(3);
            DateTime?fechaVencimientoTemp = fechaVencimiento?.AddMonths(-2);

            /* Comparación que actualiza el mensaje de vencimiento de comisión, dependiendo si
             * faltan 2 meses para su vencimiento, o bien está vencida. La renovación de comisión
             * es un proceso que se realiza por fuera entonces sólo corresponde recordar*/
            if (hoy < fechaVencimiento && hoy >= fechaVencimientoTemp)
            {
                var cantDias = (fechaVencimiento - hoy)?.TotalDays;
                ViewBag.Vencimiento = "Su comisión está a " + cantDias.ToString() + " días de vencerse. Por favor, renuévela.";
            }
            else if (hoy >= fechaVencimiento)
            {
                ViewBag.Vencimiento = "Su comisión está vencida desde el " + fechaVencimiento?.ToShortDateString() + ". Por favor, renuévela.";
            }

            int cantPatronos, cantTrabajadores;

            using (var db = new SaludOcupacionalEntities())
            {
                cantPatronos = (from d in db.Comision
                                join r in db.Representante on d.idComision equals r.idComision
                                where d.idComision == model.idComision && r.tipo == 0 && r.estado == 1
                                select d.idCentroDeTrabajo).Count();

                cantTrabajadores = (from d in db.Comision
                                    join r in db.Representante on d.idComision equals r.idComision
                                    where d.idComision == model.idComision && r.tipo == 1 && r.estado == 1
                                    select d.idCentroDeTrabajo).Count();
            }

            /* Comparación que actualiza el mensaje de recordatorio al usuario de comisión, para que tenga
             * ingresados al sistema una cantidad bipartita de patronos o trabajadores. Que esto se cumpla es
             * deber del usuario que utiliza el sistema.*/
            if (cantPatronos != cantTrabajadores)
            {
                ViewBag.RepresentantesWarning = "Su comisión no tiene cantidades iguales de Patronos y Trabajadores, por favor asegúrese de que esto se cumpla.";
            }

            return(View(model));
        }
Ejemplo n.º 23
0
        public static IEnumerable <DateTime> GetRecurrenceDateCollection(string RRule, DateTime RecStartDate, string RecException, int NeverCount)
        {
            List <DateTime> RecDateCollection = new List <DateTime>();
            DateTime        startDate         = RecStartDate;
            var             ruleSeperator     = new[] { '=', ';', ',' };
            var             weeklySeperator   = new[] { ';' };

            string[] ruleArray = RRule.Split(ruleSeperator);
            FindKeyIndex(ruleArray, RecStartDate);
            string[] weeklyRule = RRule.Split(weeklySeperator);
            FindWeeklyRule(weeklyRule);

            if (!RRule.Contains("INTERVAL"))
            {
                INTERVAL      = "INTERVAL";
                INTERVALCOUNT = "1";
            }

            if (RecException != null)
            {
                FindExdateList(RecException);
            }
            if (ruleArray.Length != 0 && RRule != "")
            {
                DateTime addDate = startDate;
                int      recCount;
                int.TryParse(RECCOUNT, out recCount);

                #region DAILY
                if (DAILY == "DAILY")
                {
                    if ((ruleArray.Length > 4 && INTERVAL == "INTERVAL") || ruleArray.Length == 4)
                    {
                        int DyDayGap = ruleArray.Length == 4 ? 1 : int.Parse(INTERVALCOUNT);
                        if (recCount == 0 && UNTIL == null)
                        {
                            recCount = NeverCount;
                        }
                        if (recCount > 0)
                        {
                            for (int i = 0; i < recCount; i++)
                            {
                                RecDateCollection.Add(addDate.Date);
                                addDate = addDate.AddDays(DyDayGap);
                            }
                        }
                        else if (UNTIL != null)
                        {
                            bool IsUntilDateReached = false;
                            while (!IsUntilDateReached)
                            {
                                RecDateCollection.Add(addDate.Date);
                                addDate = addDate.AddDays(DyDayGap);
                                int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                if (statusValue != -1)
                                {
                                    RecDateCollection.Add(addDate.Date);
                                    IsUntilDateReached = true;
                                }
                            }
                        }
                    }
                }
                #endregion

                #region WEEKLY
                else if (WEEKLY == "WEEKLY")
                {
                    int  WyWeekGap        = ruleArray.Length > 4 && INTERVAL == "INTERVAL" ? int.Parse(INTERVALCOUNT) : 1;
                    bool isweeklyselected = weeklyRule[WEEKLYBYDAYPOS].Length > 6;
                    if (recCount == 0 && UNTIL == null)
                    {
                        recCount = NeverCount;
                    }
                    if (recCount > 0)
                    {
                        while (RecDateCollection.Count < recCount && isweeklyselected)
                        {
                            GetWeeklyDateCollection(addDate, weeklyRule, RecDateCollection);
                            addDate = addDate.DayOfWeek == DayOfWeek.Saturday ? addDate.AddDays(((WyWeekGap - 1) * 7) + 1) : addDate.AddDays(1);
                        }
                    }
                    else if (UNTIL != null)
                    {
                        bool IsUntilDateReached = false;
                        while (!IsUntilDateReached && isweeklyselected)
                        {
                            GetWeeklyDateCollection(addDate, weeklyRule, RecDateCollection);
                            addDate = addDate.DayOfWeek == DayOfWeek.Saturday ? addDate.AddDays(((WyWeekGap - 1) * 7) + 1) : addDate.AddDays(1);
                            int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                            if (statusValue != -1)
                            {
                                IsUntilDateReached = true;
                            }
                        }
                    }
                }
                #endregion

                #region MONTHLY
                else if (MONTHLY == "MONTHLY")
                {
                    int MyMonthGap = ruleArray.Length > 4 && INTERVAL == "INTERVAL" ? int.Parse(INTERVALCOUNT) : 1;
                    int position   = ruleArray.Length > 4 && INTERVAL == "INTERVAL" ? 6 : BYMONTHDAYPOSITION;
                    if (BYMONTHDAY == "BYMONTHDAY")
                    {
                        int monthDate = int.Parse(BYMONTHDAYCOUNT);
                        if (monthDate <= 30)
                        {
                            int currDate = int.Parse(startDate.Day.ToString());
                            var temp     = new DateTime(addDate.Year, addDate.Month, monthDate);
                            addDate = monthDate < currDate?temp.AddMonths(1) : temp;

                            if (recCount == 0 && UNTIL == null)
                            {
                                recCount = NeverCount;
                            }
                            if (recCount > 0)
                            {
                                for (int i = 0; i < recCount; i++)
                                {
                                    addDate = GetByMonthDayDateCollection(addDate, RecDateCollection, monthDate, MyMonthGap);
                                }
                            }
                            else if (UNTIL != null)
                            {
                                bool IsUntilDateReached = false;
                                while (!IsUntilDateReached)
                                {
                                    addDate = GetByMonthDayDateCollection(addDate, RecDateCollection, monthDate, MyMonthGap);
                                    int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                    if (statusValue != -1)
                                    {
                                        IsUntilDateReached = true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (recCount == 0 && UNTIL == null)
                            {
                                recCount = NeverCount;
                            }
                            if (recCount > 0)
                            {
                                for (int i = 0; i < recCount; i++)
                                {
                                    if (addDate.Day == startDate.Day)
                                    {
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    else
                                    {
                                        i = i - 1;
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                    addDate = new DateTime(addDate.Year, addDate.Month, DateTime.DaysInMonth(addDate.Year, addDate.Month));
                                }
                            }
                            else if (UNTIL != null)
                            {
                                bool IsUntilDateReached = false;
                                while (!IsUntilDateReached)
                                {
                                    if (addDate.Day == startDate.Day)
                                    {
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                    addDate = new DateTime(addDate.Year, addDate.Month, DateTime.DaysInMonth(addDate.Year, addDate.Month));
                                    int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                    if (statusValue != -1)
                                    {
                                        IsUntilDateReached = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (BYDAY == "BYDAY")
                    {
                        if (recCount == 0 && UNTIL == null)
                        {
                            recCount = NeverCount;
                        }
                        if (recCount > 0)
                        {
                            while (RecDateCollection.Count < recCount)
                            {
                                var      weekCount         = MondaysInMonth(addDate);
                                var      monthStart        = new DateTime(addDate.Year, addDate.Month, 1);
                                DateTime weekStartDate     = monthStart.AddDays(-(int)(monthStart.DayOfWeek));
                                var      monthStartWeekday = (int)(monthStart.DayOfWeek);
                                int      nthweekDay        = GetWeekDay(BYDAYVALUE) - 1;
                                int      nthWeek;
                                int      bySetPos = 0;
                                int      setPosCount;
                                int.TryParse(BYSETPOSCOUNT, out setPosCount);
                                if (monthStartWeekday <= nthweekDay)
                                {
                                    if (setPosCount < 1)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    if (setPosCount < 0)
                                    {
                                        nthWeek = bySetPos;
                                    }
                                    else
                                    {
                                        nthWeek = bySetPos - 1;
                                    }
                                }
                                else
                                {
                                    if (setPosCount < 0)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    nthWeek = bySetPos;
                                }
                                addDate = weekStartDate.AddDays((nthWeek) * 7);
                                addDate = addDate.AddDays(nthweekDay);
                                if (addDate.CompareTo(startDate.Date) < 0)
                                {
                                    addDate = addDate.AddMonths(1);
                                    continue;
                                }
                                if (weekCount == 6 && addDate.Day == 23)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.Month == 2)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                                else if (weekCount == 6 && addDate.Day == 24)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.AddDays(7).Day != days)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                                else if (!(addDate.Day <= 23 && int.Parse(BYSETPOSCOUNT) == -1))
                                {
                                    RecDateCollection.Add(addDate.Date);
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                            }
                        }
                        else if (UNTIL != null)
                        {
                            bool IsUntilDateReached = false;
                            while (!IsUntilDateReached)
                            {
                                var      weekCount         = MondaysInMonth(addDate);
                                var      monthStart        = new DateTime(addDate.Year, addDate.Month, 1);
                                DateTime weekStartDate     = monthStart.AddDays(-(int)(monthStart.DayOfWeek));
                                var      monthStartWeekday = (int)(monthStart.DayOfWeek);
                                int      nthweekDay        = GetWeekDay(BYDAYVALUE) - 1;
                                int      nthWeek;
                                int      bySetPos = 0;
                                int      setPosCount;
                                int.TryParse(BYSETPOSCOUNT, out setPosCount);
                                if (monthStartWeekday <= nthweekDay)
                                {
                                    if (setPosCount < 1)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    if (setPosCount < 0)
                                    {
                                        nthWeek = bySetPos;
                                    }
                                    else
                                    {
                                        nthWeek = bySetPos - 1;
                                    }
                                }
                                else
                                {
                                    if (setPosCount < 0)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    nthWeek = bySetPos;
                                }
                                addDate = weekStartDate.AddDays((nthWeek) * 7);
                                addDate = addDate.AddDays(nthweekDay);
                                if (addDate.CompareTo(startDate.Date) < 0)
                                {
                                    addDate = addDate.AddMonths(1);
                                    continue;
                                }
                                if (weekCount == 6 && addDate.Day == 23)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.Month == 2)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                                else if (weekCount == 6 && addDate.Day == 24)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.AddDays(7).Day != days)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                                else if (!(addDate.Day <= 23 && int.Parse(BYSETPOSCOUNT) == -1))
                                {
                                    RecDateCollection.Add(addDate.Date);
                                    addDate = addDate.AddMonths(MyMonthGap);
                                }
                                int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                if (statusValue != -1)
                                {
                                    IsUntilDateReached = true;
                                }
                            }
                        }
                    }
                }
                #endregion

                #region YEARLY
                else if (YEARLY == "YEARLY")
                {
                    int YyYearGap = ruleArray.Length > 4 && INTERVAL == "INTERVAL" ? int.Parse(INTERVALCOUNT) : 1;
                    int position  = ruleArray.Length > 4 && INTERVAL == "INTERVAL" ? 6 : BYMONTHDAYPOSITION;
                    if (BYMONTHDAY == "BYMONTHDAY")
                    {
                        int monthIndex = int.Parse(BYMONTHCOUNT);
                        int dayIndex   = int.Parse(BYMONTHDAYCOUNT);
                        if (monthIndex > 0 && monthIndex <= 12)
                        {
                            int bound = DateTime.DaysInMonth(addDate.Year, monthIndex);
                            if (bound >= dayIndex)
                            {
                                var specificDate = new DateTime(addDate.Year, monthIndex, dayIndex);
                                if (specificDate.Date < addDate.Date)
                                {
                                    addDate = specificDate;
                                    addDate = addDate.AddYears(1);
                                }
                                else
                                {
                                    addDate = specificDate;
                                }
                                if (recCount == 0 && UNTIL == null)
                                {
                                    recCount = NeverCount;
                                }
                                if (recCount > 0)
                                {
                                    for (int i = 0; i < recCount; i++)
                                    {
                                        RecDateCollection.Add(addDate.Date);
                                        addDate = addDate.AddYears(YyYearGap);
                                    }
                                }
                                else if (UNTIL != null)
                                {
                                    bool IsUntilDateReached = false;
                                    while (!IsUntilDateReached)
                                    {
                                        RecDateCollection.Add(addDate.Date);
                                        addDate = addDate.AddYears(YyYearGap);
                                        int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                        if (statusValue != -1)
                                        {
                                            IsUntilDateReached = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (BYDAY == "BYDAY")
                    {
                        int monthIndex = int.Parse(BYMONTHCOUNT);
                        if (recCount == 0 && UNTIL == null)
                        {
                            recCount = NeverCount;
                        }
                        if (recCount > 0)
                        {
                            while (RecDateCollection.Count < recCount)
                            {
                                var      weekCount         = MondaysInMonth(addDate);
                                var      monthStart        = new DateTime(addDate.Year, monthIndex, 1);
                                DateTime weekStartDate     = monthStart.AddDays(-(int)(monthStart.DayOfWeek));
                                var      monthStartWeekday = (int)(monthStart.DayOfWeek);
                                int      nthweekDay        = GetWeekDay(BYDAYVALUE) - 1;
                                int      nthWeek;
                                int      bySetPos = 0;
                                int      setPosCount;
                                int.TryParse(BYSETPOSCOUNT, out setPosCount);
                                if (monthStartWeekday <= nthweekDay)
                                {
                                    if (setPosCount < 1)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    if (setPosCount < 0)
                                    {
                                        nthWeek = bySetPos;
                                    }
                                    else
                                    {
                                        nthWeek = bySetPos - 1;
                                    }
                                }
                                else
                                {
                                    if (setPosCount < 0)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    nthWeek = bySetPos;
                                }
                                addDate = weekStartDate.AddDays((nthWeek) * 7);
                                addDate = addDate.AddDays(nthweekDay);
                                if (addDate.CompareTo(startDate.Date) < 0)
                                {
                                    addDate = addDate.AddYears(1);
                                    continue;
                                }
                                if (weekCount == 6 && addDate.Day == 23)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.Month == 2)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                                else if (weekCount == 6 && addDate.Day == 24)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.AddDays(7).Day != days)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                                else if (!(addDate.Day <= 23 && int.Parse(BYSETPOSCOUNT) == -1))
                                {
                                    RecDateCollection.Add(addDate.Date);
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                            }
                        }
                        else if (UNTIL != null)
                        {
                            bool IsUntilDateReached = false;
                            while (!IsUntilDateReached)
                            {
                                var      weekCount         = MondaysInMonth(addDate);
                                var      monthStart        = new DateTime(addDate.Year, monthIndex, 1);
                                DateTime weekStartDate     = monthStart.AddDays(-(int)(monthStart.DayOfWeek));
                                var      monthStartWeekday = (int)(monthStart.DayOfWeek);
                                int      nthweekDay        = GetWeekDay(BYDAYVALUE) - 1;
                                int      nthWeek;
                                int      bySetPos = 0;
                                int      setPosCount;
                                int.TryParse(BYSETPOSCOUNT, out setPosCount);
                                if (monthStartWeekday <= nthweekDay)
                                {
                                    if (setPosCount < 1)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    if (setPosCount < 0)
                                    {
                                        nthWeek = bySetPos;
                                    }
                                    else
                                    {
                                        nthWeek = bySetPos - 1;
                                    }
                                }
                                else
                                {
                                    if (setPosCount < 0)
                                    {
                                        bySetPos = weekCount + setPosCount;
                                    }
                                    else
                                    {
                                        bySetPos = setPosCount;
                                    }
                                    nthWeek = bySetPos;
                                }
                                addDate = weekStartDate.AddDays((nthWeek) * 7);
                                addDate = addDate.AddDays(nthweekDay);
                                if (addDate.CompareTo(startDate.Date) < 0)
                                {
                                    addDate = addDate.AddYears(1);
                                    continue;
                                }
                                if (weekCount == 6 && addDate.Day == 23)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.Month == 2)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                                else if (weekCount == 6 && addDate.Day == 24)
                                {
                                    int  days = DateTime.DaysInMonth(addDate.Year, addDate.Month);
                                    bool flag = true;
                                    if (addDate.AddDays(7).Day != days)
                                    {
                                        flag = false;
                                    }
                                    if (flag)
                                    {
                                        addDate = addDate.AddDays(7);
                                        RecDateCollection.Add(addDate.Date);
                                    }
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                                else if (!(addDate.Day <= 23 && int.Parse(BYSETPOSCOUNT) == -1))
                                {
                                    RecDateCollection.Add(addDate.Date);
                                    addDate = addDate.AddYears(YyYearGap);
                                }
                                int statusValue = DateTime.Compare(addDate.Date, Convert.ToDateTime(UNTIL));
                                if (statusValue != -1)
                                {
                                    IsUntilDateReached = true;
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            var filteredDates = RecDateCollection.Except(exDateList).ToList();
            return(filteredDates);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 获取检测数据
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public DataSet GetMonitorData(DataTable dtQuery, DataSet combine = null)
        {
            DataTable tb_combine = new DataTable("combine")
            {
                Columns = { { "mt_code", typeof(string) } }
            };

            if (combine != null && combine.Tables.Contains("combine"))
            {
                tb_combine = combine.Tables["combine"];
            }

            DataRow dr       = dtQuery.Rows[0];
            int     NowPage  = dr.GetDataRowIntValue("now_page", 1);
            int     PageSize = dr.GetDataRowIntValue("page_size");
            string  userID   = dr["user_id"].ToString();
            string  mt_code  = dr["mt_code"].ToString();
            string  mt_time  = dr["mt_time"].ToString();

            if (mt_code == "99")
            {
                if (tb_combine.Rows.Count == 0)
                {
                    mt_code = "100";
                    tb_combine.Rows.Add(tb_combine.NewRow());
                    tb_combine.Rows[0]["mt_code"] = "101";
                }
                else
                {
                    mt_code = tb_combine.Rows[0]["mt_code"].ToString();
                    tb_combine.Rows.RemoveAt(0);
                }
            }

            string wherestr = " and a.mt_code='" + mt_code + "' ";
            string sql      = "select  MAX(mt_time) as max_time from tmo_monitor where user_id='" + userID + "' and mt_code='" + mt_code + "'";

            if (mt_time != string.Empty && mt_time != "0")
            {
                DateTime maxTime = DateTime.Now;
                object   ot      = MySQLHelper.QuerySingle(sql);
                if (ot != null)
                {
                    maxTime = Convert.ToDateTime(ot);
                }

                string time = "";
                if (mt_time == "1")
                {
                    time = maxTime.AddDays(-3).ToString();
                }
                if (mt_time == "2")
                {
                    time = maxTime.AddMonths(-1).ToString();
                }
                if (mt_time == "3")
                {
                    time = maxTime.AddMonths(-3).ToString();
                }
                if (mt_time == "4")
                {
                    time = maxTime.AddYears(-1).ToString();
                }
                if (time != "")
                {
                    wherestr += "and  a.mt_time>='" + time + "' ";
                }
            }

            StringBuilder strSql   = new StringBuilder();
            StringBuilder strWhere = new StringBuilder();
            StringBuilder groupStr = new StringBuilder();

            strSql.Append(
                "select id,a.mt_code,user_id,mt_valueint,mt_normalrange, mt_valuefloat,mt_valuetext,mt_isnormal,mt_time, mt_timestamp,a.input_time,mt_unit from");
            strWhere.Append(" tmo_monitor as a LEFT JOIN tmo_dicmonitor as b on  a.mt_code=b.mt_code  where user_id='" + userID + "'" + wherestr);
            groupStr.Append(" order by mt_time desc ");
            DataSet dsSel = tmoCommonDal.GetPagingData(strSql, strWhere, groupStr.ToString(), PageSize, NowPage);

            if (dsSel != null && combine != null)
            {
                if (combine.Tables.Contains("dt"))
                {
                    foreach (DataRow row in combine.Tables["dt"].Rows)
                    {
                        dsSel.Tables["dt"].Rows.Add(row.ItemArray);
                    }
                }

                if (combine.Tables.Contains("Count"))
                {
                    dsSel.Tables["Count"].Rows[0]["totalRowCount"] = dsSel.Tables["Count"].Rows[0].GetDataRowIntValue("totalRowCount") +
                                                                     combine.Tables["Count"].Rows[0].GetDataRowIntValue("totalRowCount");
                }
            }

            if (tb_combine.Rows.Count > 0)
            {
                if (dsSel == null)
                {
                    dsSel = new DataSet("tmodata");
                }
                dsSel.Tables.Add(tb_combine);
                dsSel = GetMonitorData(dtQuery, dsSel);
            }

            return(dsSel);
        }
Ejemplo n.º 25
0
        public void DisplayDateRangeEnd()
        {
            Calendar calendar = new Calendar();
            DateTime value = new DateTime(2000, 1, 30);
            calendar.DisplayDate = value;
            calendar.DisplayDateEnd = value;
            calendar.DisplayDateStart = value;
            Assert.IsTrue(CompareDates(calendar.DisplayDateStart.Value, value));
            Assert.IsTrue(CompareDates(calendar.DisplayDateEnd.Value, value));

            value = value.AddMonths(2);
            calendar.DisplayDateStart = value;

            Assert.IsTrue(CompareDates(calendar.DisplayDateStart.Value, value));
            Assert.IsTrue(CompareDates(calendar.DisplayDateEnd.Value, value));
            Assert.IsTrue(CompareDates(calendar.DisplayDate, value));
        }
Ejemplo n.º 26
0
        }// end of Page_Load

        protected void odswiez()
        {
            try
            {
                DateTime dTime = DateTime.Now;
                dTime = dTime.AddMonths(-1);
                if (Date1.Text.Length == 0)
                {
                    Date1.Text = dTime.Year.ToString() + "-" + dTime.Month.ToString("D2") + "-01";
                }
                if (Date2.Text.Length == 0)
                {
                    Date2.Text = dTime.Year.ToString() + "-" + dTime.Month.ToString("D2") + "-" + DateTime.DaysInMonth(dTime.Year, dTime.Month).ToString("D2");
                }

                Session["data_1"] = Date1.Text.Trim();
                Session["data_2"] = Date2.Text.Trim();
            }
            catch
            { }
            string id_dzialu = (string)Session["id_dzialu"];

            // string txt = string.Empty; //
            try
            {
                DataTable tabelka01 = dr.generuj_dane_do_tabeli_wierszy2018(Date1.Date, Date2.Date, (string)Session["id_dzialu"], 1, 1, 12, tenPlik);
                Session["tabelka002"] = tabelka01;
                //row 1
                tab_01_w01_c01.Text = tabelka01.Rows[0][1].ToString();
                tab_01_w01_c02.Text = tabelka01.Rows[0][2].ToString();
                tab_01_w01_c03.Text = tabelka01.Rows[0][3].ToString();
                tab_01_w01_c04.Text = tabelka01.Rows[0][4].ToString();
                tab_01_w01_c05.Text = tabelka01.Rows[0][5].ToString();
                tab_01_w01_c06.Text = tabelka01.Rows[0][6].ToString();

                tab_01_w01_c07.Text = tabelka01.Rows[0][7].ToString();
                tab_01_w01_c08.Text = tabelka01.Rows[0][8].ToString();
                tab_01_w01_c09.Text = tabelka01.Rows[0][9].ToString();
                tab_01_w01_c10.Text = tabelka01.Rows[0][10].ToString();
                tab_01_w01_c11.Text = tabelka01.Rows[0][11].ToString();
                tab_01_w01_c12.Text = tabelka01.Rows[0][12].ToString();
            }
            catch (Exception ex)
            {
                cm.log.Error(tenPlik + " " + ex);
            }

            try
            {
                DataTable tabelka01 = dr.generuj_dane_do_tabeli_wierszy2018(Date1.Date, Date2.Date, (string)Session["id_dzialu"], 2, 1, 12, tenPlik);
                Session["tabelka001"] = tabelka01;
                //row 1
                tab_02_w01_c01.Text = tabelka01.Rows[0][1].ToString();
                tab_02_w01_c02.Text = tabelka01.Rows[0][2].ToString();
                tab_02_w01_c03.Text = tabelka01.Rows[0][3].ToString();
                tab_02_w01_c04.Text = tabelka01.Rows[0][4].ToString();
                tab_02_w01_c05.Text = tabelka01.Rows[0][5].ToString();
                tab_02_w01_c06.Text = tabelka01.Rows[0][6].ToString();

                tab_02_w01_c07.Text = tabelka01.Rows[0][7].ToString();
                tab_02_w01_c08.Text = tabelka01.Rows[0][8].ToString();
                tab_02_w01_c09.Text = tabelka01.Rows[0][9].ToString();
                tab_02_w01_c10.Text = tabelka01.Rows[0][10].ToString();
                tab_02_w01_c11.Text = tabelka01.Rows[0][11].ToString();
                tab_02_w01_c12.Text = tabelka01.Rows[0][12].ToString();
                tab_02_w01_c13.Text = tabelka01.Rows[0][13].ToString();
                tab_02_w01_c14.Text = tabelka01.Rows[0][14].ToString();
            }
            catch (Exception ex)
            {
                cm.log.Error(tenPlik + " " + ex);
            }

            try
            {
                DataTable tabelka01 = dr.generuj_dane_do_tabeli_wierszy2018(Date1.Date, Date2.Date, (string)Session["id_dzialu"], 3, 1, 12, tenPlik);
                Session["tabelka003"] = tabelka01;
                //row 1
                tab_03_w01_c01.Text = tabelka01.Rows[0][1].ToString();
                tab_03_w01_c02.Text = tabelka01.Rows[0][2].ToString();
                tab_03_w01_c03.Text = tabelka01.Rows[0][3].ToString();
                tab_03_w01_c04.Text = tabelka01.Rows[0][4].ToString();
                tab_03_w01_c05.Text = tabelka01.Rows[0][5].ToString();
                tab_03_w01_c06.Text = tabelka01.Rows[0][6].ToString();
                tab_03_w01_c07.Text = tabelka01.Rows[0][7].ToString();
                tab_03_w01_c08.Text = tabelka01.Rows[0][8].ToString();
            }
            catch (Exception ex)
            {
                cm.log.Error(tenPlik + " " + ex);
            }


            try
            {
                DataTable tabelka01 = dr.generuj_dane_do_tabeli_wierszy2018(Date1.Date, Date2.Date, (string)Session["id_dzialu"], 4, 4, 13, tenPlik);
                Session["tabelka004"] = tabelka01;
                pisz("tab_4_", 4, 13, tabelka01);
            }
            catch (Exception ex)
            {
                cm.log.Error(tenPlik + " " + ex);
            }

            try
            {
                DataTable tabelka01 = dr.generuj_dane_do_tabeli_wierszy2018(Date1.Date, Date2.Date, (string)Session["id_dzialu"], 5, 3, 3, tenPlik);
                Session["tabelka005"] = tabelka01;
                pisz("tab_5_", 3, 3, tabelka01);
            }
            catch (Exception ex)
            {
                cm.log.Error(tenPlik + " " + ex);
            }

            // dopasowanie opisów
            makeLabels();
            Label11.Visible = false;
            try
            {
                Label11.Visible = cl.debug(int.Parse(id_dzialu));
            }
            catch
            {}

            //   Label11.Text = txt;
            Label3.Text = cl.nazwaSadu((string)Session["id_dzialu"]);
        }
Ejemplo n.º 27
0
        public ActionResult Mes(string Fecha)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("es-CO");
            // C# (use instead of DateTime.Now)
            DateTime Fecha00 = DateTime.UtcNow;

            Fecha00        = Fecha00.AddHours(-5).Date;
            ViewBag.fechaC = Fecha;

            var tem3 = from s in db.Temas
                       select s;

            if (!String.IsNullOrEmpty(Fecha))
            {
                Fecha00 = DateTime.Parse(Fecha).Date;
            }

            var int0 = 0;
            var int1 = 0;
            var int2 = 0;
            var int3 = 0;
            var int4 = 0;
            var int5 = 0;
            var int6 = 0;

            switch ((int)Fecha00.DayOfWeek)
            {
            case 1:
                int0 = 0;
                int1 = 1;
                int2 = 2;
                int3 = 3;
                int4 = 4;
                int5 = 5;
                int6 = 8;
                break;

            case 2:
                int0 = -1;
                int1 = 0;
                int2 = 1;
                int3 = 2;
                int4 = 3;
                int5 = 4;
                int6 = 5;
                break;

            case 3:
                int0 = -2;
                int1 = -1;
                int2 = 0;
                int3 = 1;
                int4 = 2;
                int5 = 3;
                int6 = 4;
                break;

            case 4:
                int0 = -3;
                int1 = -2;
                int2 = -1;
                int3 = 0;
                int4 = 1;
                int5 = 2;
                int6 = 3;
                break;

            case 5:
                int0 = -4;
                int1 = -3;
                int2 = -2;
                int3 = -1;
                int4 = 0;
                int5 = 1;
                int6 = 2;
                break;

            case 6:
                int0 = -5;
                int1 = -4;
                int2 = -3;
                int3 = -2;
                int4 = -1;
                int5 = 0;
                int6 = 1;
                break;

            case 0:
                int0 = -6;
                int1 = -5;
                int2 = -4;
                int3 = -3;
                int4 = -2;
                int5 = -1;
                int6 = 0;
                break;
            }
            switch (Fecha00.Month)
            {
            case 1:
                ViewBag.Mes = "Enero";
                break;

            case 2:
                ViewBag.Mes = "Febrero";
                break;

            case 3:
                ViewBag.Mes = "Marzo";
                break;

            case 4:
                ViewBag.Mes = "Abril";
                break;

            case 5:
                ViewBag.Mes = "Mayo";
                break;

            case 6:
                ViewBag.Mes = "Junio";
                break;

            case 7:
                ViewBag.Mes = "Julio";
                break;

            case 8:
                ViewBag.Mes = "Agosto";
                break;

            case 9:
                ViewBag.Mes = "Septiembre";
                break;

            case 10:
                ViewBag.Mes = "Octubre";
                break;

            case 11:
                ViewBag.Mes = "Noviembre";
                break;

            case 12:
                ViewBag.Mes = "Diciembre";
                break;
            }
            Fecha00 = DateTime.Parse(Fecha00.Year.ToString() + "-" + Fecha00.Month.ToString() + "-01");
            var Fecha01        = Fecha00.AddMonths(-1);
            var Fecha02        = Fecha00.AddMonths(1);
            var strweek        = (int)Fecha00.DayOfWeek;
            var currentCulture = CultureInfo.CurrentCulture;
            var weekNo         = currentCulture.Calendar.GetWeekOfYear(Fecha00, currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek);

            ViewBag.Mes     = ViewBag.Mes.ToString() + " Semana " + weekNo.ToString() + " Día:" + strweek.ToString();
            ViewBag.intweek = strweek;
            tem3            = tem3.Where(s => s.FechaHora > Fecha01 && s.FechaHora < Fecha02);
            ViewBag.fecha1  = Fecha01;
            ViewBag.fecha2  = Fecha02;
            ViewBag.fecha   = Fecha00.Date.ToLongDateString();
            var Intdaysmenos = strweek;

            //ViewBag.FechaI = Fecha00.AddDays(Intdaysmenos);
            ViewBag.FechaI = Fecha00;


            var Fecha1 = Fecha01.Date.ToLongDateString();
            var Fecha2 = Fecha02.Date.ToLongDateString();

            ViewBag.dia1 = Fecha1.ToString().Split(',');
            ViewBag.dia2 = Fecha2.ToString().Split(',');

            // Se saca la parte


            var IdUser = "";

            if (User.Identity.IsAuthenticated)
            {
                string currentUserId = User.Identity.GetUserId();
                IdUser = currentUserId;
            }
            //if (IdUser != null && !User.IsInRole("Admin"))
            //{
            tem3 = tem3.Where(s => s.UserId.Equals(IdUser));
            tem3 = tem3.OrderBy(s => s.FechaHora).ThenBy(s => s.Prioridad.Orden);
            //}


            //ViewBag.Semana = "Semana 48";

            return(View(tem3));
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Increases Month
 /// </summary>
 /// <param name="sender">Source menu item</param>
 public static void IncMonth(MenuItem sender)
 {
     _setDateTime = _setDateTime.AddMonths(1);
     RefreshSetDateTimeMenu();
 }
Ejemplo n.º 29
0
        private DateTime GetEndDate(DateTime now, TimeInterval interval, int numberOfCandleSticks)
        {
            switch (interval)
            {
            case TimeInterval.Minutes_1:
                return(now.AddDays(-5));

                break;

            case TimeInterval.Minutes_3:
                return(now.AddDays(-5));

                break;

            case TimeInterval.Minutes_5:
                return(now.AddDays(-5));

                break;

            case TimeInterval.Minutes_15:
                return(now.AddDays(-5));

                break;

            case TimeInterval.Minutes_30:
                return(now.AddDays(-5));

                break;

            case TimeInterval.Hours_1:
                return(now.AddDays(-10));

                break;

            case TimeInterval.Hours_2:
                return(now.AddDays(-10));

                break;

            case TimeInterval.Hours_4:
                return(now.AddDays(-50));

                break;

            case TimeInterval.Hours_6:
                return(now.AddDays(-50));

                break;

            case TimeInterval.Hours_8:
                return(now.AddDays(-50));

                break;

            case TimeInterval.Hours_12:
                return(now.AddDays(-50));

                break;

            case TimeInterval.Days_1:
                return(now.AddDays(-100));

                break;

            case TimeInterval.Days_3:
                return(now.AddDays(-300));

                break;

            case TimeInterval.Weeks_1:
                return(now.AddDays(-700));

                break;

            case TimeInterval.Months_1:
                return(now.AddMonths(-100));

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(interval), interval, null);
            }
        }
Ejemplo n.º 30
0
		// draws one day in the calendar grid
		private void DrawMonthCalendarDate (Graphics dc, Rectangle rectangle, MonthCalendar mc,	DateTime date, DateTime month, int row, int col) {
			Color date_color = mc.ForeColor;
			Rectangle interior = new Rectangle (rectangle.X, rectangle.Y, Math.Max(rectangle.Width - 1, 0), Math.Max(rectangle.Height - 1, 0));

			// find out if we are the lead of the first calendar or the trail of the last calendar						
			if (date.Year != month.Year || date.Month != month.Month) {
				DateTime check_date = month.AddMonths (-1);
				// check if it's the month before 
				if (check_date.Year == date.Year && check_date.Month == date.Month && row == 0 && col == 0) {
					date_color = mc.TrailingForeColor;
				} else {
					// check if it's the month after
					check_date = month.AddMonths (1);
					if (check_date.Year == date.Year && check_date.Month == date.Month && row == mc.CalendarDimensions.Height-1 && col == mc.CalendarDimensions.Width-1) {
						date_color = mc.TrailingForeColor;
					} else {
						return;
					}
				}
			} else {
				date_color = mc.ForeColor;
			}

			const int inflate = -1;

			if (date == mc.SelectionStart.Date && date == mc.SelectionEnd.Date) {
				// see if the date is in the start of selection
				date_color = mc.BackColor;
				// draw the left hand of the back ground
				Rectangle selection_rect = Rectangle.Inflate (rectangle, inflate, inflate);				
				dc.FillPie (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect, 0, 360);
			} else if (date == mc.SelectionStart.Date) {
				// see if the date is in the start of selection
				date_color = mc.BackColor;
				// draw the left hand of the back ground
				Rectangle selection_rect = Rectangle.Inflate (rectangle, inflate, inflate);				
				dc.FillPie (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect, 90, 180);
				// fill the other side as a straight rect
				if (date < mc.SelectionEnd.Date) 
				{
					// use rectangle instead of rectangle to go all the way to edge of rect
					selection_rect.X = (int) Math.Floor((double)(rectangle.X + rectangle.Width / 2));
					selection_rect.Width = Math.Max(rectangle.Right - selection_rect.X, 0);
					dc.FillRectangle (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect);
				}
			} else if (date == mc.SelectionEnd.Date) {
				// see if it is the end of selection
				date_color = mc.BackColor;
				// draw the left hand of the back ground
				Rectangle selection_rect = Rectangle.Inflate (rectangle, inflate, inflate);
				dc.FillPie (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect, 270, 180);
				// fill the other side as a straight rect
				if (date > mc.SelectionStart.Date) {
					selection_rect.X = rectangle.X;
					selection_rect.Width = rectangle.Width - (rectangle.Width / 2);
					dc.FillRectangle (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect);
				}
			} else if (date > mc.SelectionStart.Date && date < mc.SelectionEnd.Date) {
				// now see if it's in the middle
				date_color = mc.BackColor;
				// draw the left hand of the back ground
				Rectangle selection_rect = Rectangle.Inflate (rectangle, 0, inflate);
				dc.FillRectangle (ResPool.GetSolidBrush (mc.TitleBackColor), selection_rect);
			}

			// establish if it's a bolded font
			Font font = mc.IsBoldedDate (date) ? mc.bold_font : mc.Font;

			// just draw the date now
			dc.DrawString (date.Day.ToString(), font, ResPool.GetSolidBrush (date_color), rectangle, mc.centered_format);

			// today circle if needed
			if (mc.ShowTodayCircle && date == DateTime.Now.Date) {
				DrawTodayCircle (dc, interior);
			}

			// draw the selection grid
			if (mc.is_date_clicked && mc.clicked_date == date) {
				Pen pen = ResPool.GetDashPen (Color.Black, DashStyle.Dot);
				dc.DrawRectangle (pen, interior);
			}
		}
Ejemplo n.º 31
0
        public virtual string ReturnAxisValueHeader(int element)
        {
            DateTime workdate = _start.AddMonths(element);

            return(workdate.Month + "/" + workdate.Year);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets the post archive for the category with the given id.
        /// </summary>
        /// <param name="id">The unique category id</param>
        /// <param name="page">The optional page</param>
        /// <param name="year">The optional year</param>
        /// <param name="month">The optional month</param>
        /// <returns>The archive model</returns>
        public T GetById <T>(Guid id, int?page = 1, int?year = null, int?month = null) where T : Models.PostArchive
        {
            // Get the requested category
            var category = db.Categories
                           .FirstOrDefault(c => c.Id == id);

            if (category != null)
            {
                // Set basic fields
                var model = Activator.CreateInstance <T>();

                model.Id              = id;
                model.Title           = category.ArchiveTitle ?? category.Title;
                model.Slug            = category.Slug;
                model.MetaDescription = category.ArchiveDescription ?? category.Description;
                model.Route           = !String.IsNullOrEmpty(category.ArchiveRoute) ? category.ArchiveRoute : "/archive";
                model.Year            = year;
                model.Month           = month;
                model.Page            = Math.Max(1, page.HasValue ? page.Value : 1);

                // Build the query.
                var now   = DateTime.Now;
                var query = db.Posts
                            //.Include(p => p.Author)
                            .Include(p => p.Category)
                            .Where(p => p.CategoryId == id && p.Published <= now);

                if (year.HasValue)
                {
                    DateTime from;
                    DateTime to;

                    if (month.HasValue)
                    {
                        from = new DateTime(year.Value, month.Value, 1);
                        to   = from.AddMonths(1);
                    }
                    else
                    {
                        from = new DateTime(year.Value, 1, 1);
                        to   = from.AddYears(1);
                    }
                    query = query.Where(p => p.Published >= from && p.Published < to);
                }

                // Get the total page count for the archive
                model.TotalPages = Math.Max(Convert.ToInt32(Math.Ceiling((double)query.Count() / ArchivePageSize)), 1);
                model.Page       = Math.Min(model.Page, model.TotalPages);

                // Get the posts
                var posts = query
                            .OrderBy(p => p.Published)
                            .Skip((model.Page - 1) * ArchivePageSize)
                            .Take(ArchivePageSize)
                            .ToList();

                // Map & add the posts within the requested page
                var mapper = Module.Mapper;
                foreach (var post in posts)
                {
                    // Map fields
                    var postModel = mapper.Map <Post, Models.Post>(post);
                    postModel.Category = mapper.Map <Category, Models.CategoryItem>(post.Category);
                    //post.Permalink = $"~/{category.Slug}/{post.Slug}";

                    // Add to model
                    model.Posts.Add(postModel);
                }
                return(model);
            }
            return(null);
        }
Ejemplo n.º 33
0
        static DateAndTimeOfDayModelContext()
        {
            DateTime dt = new DateTime(2014, 12, 31);

            _dateTimes = Enumerable.Range(1, 5).Select(i =>
                new DateAndTimeOfDayModel
                {
                    Id = i,
                    Birthday = dt.AddYears(i),
                    PublishDay = i % 2 == 0 ? (DateTime?)null : dt.AddMonths(i),
                    CreatedTime = new TimeSpan(0, i, 4, 5, 198),
                    EdmTime = i % 3 == 0 ? (TimeSpan?)null : new TimeSpan(0, 8, i, 5, 198),
                    ResumeTime = new TimeSpan(0, i, 4, 5, 198)
                }).ToList();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Альтернатива PAckDocuments на стороне БД ОРЦ (т.е контрольные данные=> приходят поздже).
        /// Т.к EF6  не поддерживает работу Join с двумя котестами (таблицы находяться на разных серверах)=>
        /// Возможные варианты (выбран 3)
        /// 1)Создание view для таблиц из другого сервера
        /// 2)ковыряние в edmx (необходимо также работа c synonem в  SQL)
        /// 3)Написание SQL прямых заросов и разметка сущностей (теряем обстракцию, т.к необходимо указывать явные имена linkid servers)
        /// </summary>
        /// <param name="reportPeriod"></param>
        /// <param name="preview"></param>
        /// <param name="shiftPage"></param>
        /// <returns></returns>
        public bool PackDocSql(DateTime reportPeriod, IList <ShippingInfoLineDTO> preview, byte shiftPage = 3)
        {
            var startDate = reportPeriod.AddDays(-shiftPage).Date;
            var endDate   = reportPeriod.AddMonths(1).AddDays(shiftPage).Date;

            foreach (var dispatch in preview)
            {
                var temp = dispatch;

                using (this._engage.Uow = new UnitOfWork()) {
                    //для динамического соединения
                    var sapodConn = "[" + this._engage.Uow.GetRepository <v_otpr>().ActiveDbContext.Database.Connection.DataSource + @"].[" + this._engage.Uow.GetRepository <v_otpr>().ActiveDbContext.Database.Connection.Database + @"]";
                    var orcConn   = "[" + this._engage.Uow.GetRepository <krt_Guild18>().ActiveDbContext.Database.Connection.DataSource + @"].[" + this._engage.Uow.GetRepository <krt_Guild18>().ActiveDbContext.Database.Connection.Database + @"]";
                    var carriages = (temp.WagonsNumbers.Any()) ? string.Join(",", temp.WagonsNumbers.Select(x => $"'{x.n_vag}'")) : string.Empty;

                    //Для mapping требуется точное совпадение имен и типов столбцов
                    //Выбираем с какой стороны работать (сервер) по сущности
                    var result = this._engage.Uow.GetRepository <krt_Guild18>().ActiveDbContext.Database.SqlQuery <krt_Guild18>(@"
                    WITH SubResutl AS (
                        /*Doc from Invoices*/
                        SELECT @reportPeriod AS [reportPeriod],     vn.[Id] AS [idSapod],     null AS [idScroll], null AS [scrollColl],
                            CASE vn.[cod_sbor] WHEN '125' THEN NULL ELSE @warehouse END AS [warehouse],   CASE vn.[cod_sbor] WHEN '125' THEN NULL ELSE @id_otpr END AS [idDeliviryNote],
                            CONVERT(tinyint,vn.type_doc) AS [type_doc],@id_otpr AS [idSrcDocument],
                            CONVERT(BIT,CASE WHEN CONVERT(int,left(vn.cod_sbor,3)) IN (166,173,300,301,344) THEN 0 ELSE 1 END) AS [codeType],
                            CONVERT(int,left(vn.[cod_sbor],3)) AS [code], vn.[summa] + vn.[nds] as [sum],
                            NULL AS [parseTextm],
                            CONVERT(decimal(18,2),vn.[nds]/vn.[summa]) as [rateVAT], vn.[id_kart] AS [idCard]
                        FROM " + sapodConn + @".[dbo].[v_nach] AS vn
                        WHERE (vn.[id_otpr] = (@id_otpr) OR vn.[cod_sbor] IN ('125')) AND vn.[type_doc] IN (1,4) AND (vn.[date_raskr] BETWEEN @stDate AND @endDate) AND vn.[cod_kl] IN ('3494','349402')

                        UNION ALL

                        /*Doc from Scrolls*/
                        SELECT DISTINCT @reportPeriod AS [reportPeriod], vn.[Id] AS [idSapod], null AS [idScroll], null AS [scrollColl], @warehouse AS [warehouse],
                            @id_otpr AS [idDeliviryNote], CONVERT(tinyint,vn.[type_doc]) AS [type_doc],
                            CASE vn.[type_doc] when 2 then vp.[id_ved] ELSE vn.[id_kart] END AS [idSrcDocument],
                            CONVERT(BIT,CASE WHEN CONVERT(int,left(vn.[cod_sbor],3)) IN (166,173,300,301,344) THEN 0 ELSE 1 END) AS [codeType],
                            CONVERT(int,left(vn.[cod_sbor],3)) AS [code], vn.[summa] + vn.[nds] as [sum],
                            CASE CONVERT(int,left(vn.[cod_sbor],3)) WHEN 65 THEN ISNULL(REPLACE(SUBSTRING(REPLACE(RTRIM(LTRIM(CONVERT(VARCHAR(max),vn.[textm]))),' ',''),CHARINDEX(',',REPLACE(RTRIM(LTRIM(CAST(vn.[textm] AS VARCHAR(max)))),' ',''),6),4),',',''),0) ELSE NULL END AS [parseTextm],
                            CONVERT(decimal(18,2),vn.[nds]/vn.[summa]) as [rateVAT], vn.[id_kart] AS [idCard]
                        FROM " + sapodConn + @".[dbo].[v_pam] as vp INNER JOIN " + sapodConn + @".[dbo].[v_pam_vag] AS vpv
                            ON vpv.[id_ved] = vp.[id_ved] INNER JOIN " + sapodConn + @".[dbo].[v_nach] AS vn
                                ON ((vn.[id_kart] = vp.[id_kart] AND vn.[type_doc] = 2) AND vp.[kodkl] IN ('3494','349402')) OR
                           (vn.[date_raskr] IN (convert(date,vpv.[d_pod]),convert(date,vpv.[d_ub])) AND vn.[cod_sbor] = '065' AND vn.[type_doc] = 4)
                        WHERE vpv.[nomvag] IN (" + carriages + @") AND vn.[cod_kl] IN ('3494','349402') AND [state] = 32 AND (vp.[dved] BETWEEN @stDate AND @endDate)

                        UNION ALL

                        /*Doc from Act*/
                        SELECT @reportPeriod AS [reportPeriod], vn.Id AS [idSapod], null AS [idScroll], null AS [scrollColl], @warehouse AS [warehouse],
                            @id_otpr AS [idDeliviryNote], CONVERT(tinyint,vn.type_doc) AS [type_doc], va.Id AS [idSrcDocument],
                            CONVERT(BIT,CASE WHEN CONVERT(int,left(vn.cod_sbor,3)) IN (166,173,300,301,344) THEN 0 ELSE 1 END) AS [codeType],
                            CONVERT(int,left(vn.cod_sbor,3)) AS [code], vn.summa + vn.nds as [sum],
                            NULL AS [parseTextm],
                            CONVERT(decimal(18,2),vn.nds/vn.summa) as [rateVAT], vn.id_kart AS [idCard]
                        FROM " + sapodConn + @".[dbo].v_akt as va INNER JOIN " + sapodConn + @".[dbo].[v_nach] AS vn
                                ON vn.id_kart = va.id_kart AND vn.type_doc = 3 AND va.kodkl IN ('3494','349402') AND vn.cod_kl IN ('3494','349402') AND [state] = 32
                        WHERE Exists (SELECT * from " + sapodConn + @".[dbo].v_akt_vag as vav where vav.nomvag IN (" + carriages + @") and va.Id = vav.id_akt) AND (va.dakt BETWEEN @stDate AND @endDate)
                    )

                        SELECT 0 as [Id], sr.reportPeriod,sr.idSapod, knos.keykrt AS [idScroll],knos.keysbor AS [scrollColl], sr.warehouse, sr.idDeliviryNote,sr.type_doc, sr.idSrcDocument,
                        CONVERT(BIT,CASE WHEN CONVERT(int,sr.codeType) IN (166,173,300,301,344) THEN 0 ELSE 1 END) AS [codeType],
                        sr.code, CASE sr.code
							WHEN 65 THEN
								ROUND(ISNULL(ISNULL(knos.sm,sr.[sum]) / cast('' as xml).value('sql:column("                                 + @"""" + "parseTextm" + @"""" + @") cast as xs:integer ?', 'int') * @countCarriages,0),4)
                            ELSE ISNULL(knos.sm, sr.[sum])
                        END AS[sum], sr.[rateVat],sr.idCard
                        FROM SubResutl AS sr LEFT JOIN " + orcConn + @".[dbo].[krt_Naftan_orc_sapod] AS knos
	                        ON knos.Id = sr.idSapod AND knos.tdoc = sr.type_doc

                        UNION ALL

                        SELECT 0 as [Id], @reportPeriod AS [reportPeriod], knos.Id AS [idSapod],
                            kn.keykrt AS [idScroll],knos.keysbor AS [scrollColl],@warehouse AS [warehouse], NULL AS [idDeliviryNote], tdoc as [type_doc],
                            CASE tdoc when 4 THEN knos.id_kart else NULL END AS [idSrcDocument],
                            CONVERT(BIT,1) AS [codeType], vidsbr AS [code], sm as [sum],
                            CONVERT(decimal(18,2),knos.stnds/100) as [rateVAT],knos.id_kart AS [idCard]
                        FROM " + orcConn + @".[dbo].krt_naftan AS kn INNER JOIN " + orcConn + @".[dbo].krt_Naftan_orc_sapod AS knos
	                        ON knos.keykrt = kn.keykrt AND KN.U_KOD = 2
                        WHERE knos.dt BETWEEN @stDate AND @endDate;",
                                                                                                                                new SqlParameter("@reportPeriod", reportPeriod),
                                                                                                                                new SqlParameter("@warehouse", temp.Warehouse),
                                                                                                                                new SqlParameter("@id_otpr", (temp.Shipping == null) ? 0 : temp.Shipping.id),
                                                                                                                                new SqlParameter("@stDate", startDate),
                                                                                                                                new SqlParameter("@endDate", endDate),
                                                                                                                                new SqlParameter("@countCarriages", temp.WagonsNumbers.Count)).ToList();

                    try {
                        //Add or Delete
                        foreach (var entity in result)
                        {
                            var e    = entity;
                            var item = this._engage.Uow.GetRepository <krt_Guild18>().Get(x => x.reportPeriod == reportPeriod && x.idSapod == e.idSapod && x.scrollColl == e.scrollColl && x.idScroll == e.idScroll && x.idDeliviryNote == e.idDeliviryNote);

                            entity.id = (item == null) ? 0 : item.id;
                            this._engage.Uow.GetRepository <krt_Guild18>().Merge(entity);
                        }

                        this._engage.Uow.Save();
                    } catch (Exception ex) {
                        this._engage.Log.DebugFormat("Exception: {0}", ex.Message);
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 35
0
        protected void ASPxCallbackPanel1_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
        {
            if (!ASPxCallbackPanel1.IsCallback)
            {
                return;
            }

            string[] parameters = e.Parameter.Split(';');
            if (parameters.Length < 1)
            {
                return;
            }

            string commandName = parameters[0];

            if (commandName == "DeleteAppointmentCommand")
            {
                int value = Convert.ToInt32(parameters[1]);
                ASPxScheduler1.Storage.Appointments.Remove(ASPxScheduler1.Storage.Appointments.GetAppointmentById(value));
                ASPxScheduler1.DataBind();
                AgendaViewControl1.ReloadData();
            }
            else if (commandName == "SwitchViewToAgendaView")
            {
                DateTime selectedIntervalStart = ASPxScheduler1.ActiveView.GetVisibleIntervals().Start;
                DateTime intervalStart         = new DateTime(selectedIntervalStart.Year, selectedIntervalStart.Month, 1);
                AgendaViewControl1.SelectedInterval = new TimeInterval(intervalStart, intervalStart.AddMonths(1));
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 与指定的时间计算时间差(date-theDate)
        /// </summary>
        /// <param name="theTime">被计算日期</param>
        /// <param name="date">计算日期</param>
        /// <param name="calcTime">是事计算时间部分,默认true</param>
        /// <param name="calcHour">是否计算小时,默认true</param>
        /// <param name="calcMinute">是否计算分,默认true</param>
        /// <param name="calcSecond">是否计算秒,默认true</param>
        /// <returns></returns>
        public static TimeInfo GetTimeDiff(this DateTime theTime, DateTime date,
                                           bool calcTime = true, bool calcHour = true, bool calcMinute = true, bool calcSecond = true)
        {
            var timeinfo = new TimeInfo();

            timeinfo.Source = theTime;
            timeinfo.Now    = date;
            DateTime?temp = null;

            if (date < theTime)
            {
                temp    = theTime;
                theTime = date;
                date    = temp.Value;
            }

            #region 计算秒
            if (calcSecond && calcTime)
            {
                timeinfo.Second = date.Second - theTime.Second;
                if (timeinfo.Second < 0)
                {
                    timeinfo.Second += 60;
                    timeinfo.Minute -= 1;
                }
            }
            #endregion

            #region 计算分
            if (calcSecond && calcTime)
            {
                timeinfo.Minute += date.Minute - theTime.Minute;
                if (timeinfo.Minute < 0)
                {
                    timeinfo.Minute += 60;
                    timeinfo.Hour   -= 1;
                }
            }
            #endregion

            #region 计算时
            if (calcHour && calcTime)
            {
                timeinfo.Hour += date.Hour - theTime.Hour;
                if (timeinfo.Hour < 0)
                {
                    timeinfo.Hour += 24;
                    timeinfo.Day  -= 1;
                }
            }
            #endregion

            #region 计算天
            var theMonthDays = DateTime.DaysInMonth(theTime.Year, theTime.Month);
            // 判断出生日期和计算日期是不是都是月份的最后一天
            // 出生月总天数大于当前月总天数的月底做满月处理,
            // 如: 2000-03-31 到 2000-04-30 做为满月,5月份则要31号才做为满月,不计算天数
            if (!(theTime.Day + timeinfo.Day == theMonthDays && date.Day == DateTime.DaysInMonth(date.Year, date.Month)))
            {
                timeinfo.Day += date.Day - theTime.Day;
            }
            if (timeinfo.Day < 0)
            {
                var nowPrevMonth  = date.AddMonths(-1); // 当前日期上月日期
                var prevMonthDays = DateTime.DaysInMonth(nowPrevMonth.Year, nowPrevMonth.Month);
                // 如果借过来的月的总天数小于被减月份的总天数,则以被减月份的总天数为准
                // 如:  2013-01-20 到 2013-03-10 , 此时借的是2月份, 小于出生月1月份的总天数,则天数为 10-20+31=21天
                timeinfo.Day   += Math.Max(prevMonthDays, theMonthDays);
                timeinfo.Month -= 1;
            }
            #endregion

            #region 计算月
            timeinfo.Month += date.Month - theTime.Month;
            if (timeinfo.Month < 0) // 月数不足借年
            {
                timeinfo.Month += 12;
                timeinfo.Year  -= 1;
            }
            #endregion

            #region 计算年
            timeinfo.Year += date.Year - theTime.Year;
            #endregion

            if (temp.HasValue)
            {
                timeinfo.Second *= -1;
                timeinfo.Minute *= -1;
                timeinfo.Hour   *= -1;
                timeinfo.Day    *= -1;
                timeinfo.Month  *= -1;
                timeinfo.Year   *= -1;
            }
            return(timeinfo);
        }
Ejemplo n.º 37
0
 public override DateTime DataZakonczeniaGwarancji(DateTime dataZakupu)
 {
     return(dataZakupu.AddMonths(OkresGwarancji + RozszerzenieGwarancji));
 }
        public void Render(DateTime start, DateTime end)
        {
            CtlPresenter.Clear();

            byte alpha = 100;

            var winterColor = Draw.GetBrush(Draw.GetColor(alpha, Colors.White));
            var springColor = Draw.GetBrush(Draw.GetColor(alpha, Colors.Blue));
            var summerColor = Draw.GetBrush(Draw.GetColor(alpha, Colors.Green));
            var autumColor  = Draw.GetBrush(Draw.GetColor(alpha, Colors.Yellow));

            var year0Color = Draw.GetBrush(Draw.GetColor(255, Colors.WhiteSmoke));
            var year1Color = Draw.GetBrush(Draw.GetColor(255, Colors.DarkGray));

            var dictMonth = new Dictionary <int, Brush>()
            {
                { 1, winterColor },
                { 2, winterColor },
                { 3, springColor },
                { 4, springColor },
                { 5, springColor },
                { 6, summerColor },
                { 7, summerColor },
                { 8, summerColor },
                { 9, autumColor },
                { 10, autumColor },
                { 11, autumColor },
                { 12, winterColor }
            };

            var dictYear = new Dictionary <int, Brush>()
            {
                { 0, year0Color },
                { 1, year1Color }
            };

            var width  = CtlPresenter.ActualWidth;
            var height = CtlPresenter.ActualHeight;

            const double yearHeight = 5;

            // grid
            for (DateTime day = start; day <= end; day = day.AddMonths(1))
            {
                double x  = GetX(start.Ticks, end.Ticks, day.Ticks);
                double x2 = GetX(start.Ticks, end.Ticks, day.AddMonths(1).Ticks);

                CtlPresenter.DrawRectangle(dictMonth[day.Month], penGrid, Rects.Get(x, 0, x2 - x, height - yearHeight));

                if (day.Month == 1)
                {
                    CtlPresenter.DrawLine(penGridYear, Points.Get(x, 0), Points.Get(x, height - yearHeight));
                }

                var fmt = new FormattedText(day.Date.ToString("MMM") + "\r\n" + (day.Date.Year - 2000), Culture.Current, FlowDirection.LeftToRight, Font, 9, Brushes.Black, Tools.Render.PixelsPerDip);
                CtlPresenter.DrawText(fmt, Points.Get(x + (x2 - x - fmt.Width) / 2, (height - fmt.Height) / 2 - 3));

                CtlPresenter.DrawRectangle(dictYear[day.Year % 2], null, Rects.Get(x, height - yearHeight, x2 - x, yearHeight));
            }
            CtlPresenter.DrawLine(penGrid, Points.Get(0, 0), Points.Get(width, 0));
            //
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Получение данных со стороны  БД САПОД (используется для предварительного просмотра текущей документации по накладным)
        /// </summary>
        /// <param name="reportPeriod"></param>
        /// <param name="preview"></param>
        /// <param name="shiftPage"></param>
        /// <returns></returns>
        public bool PackDocuments(DateTime reportPeriod, IList <ShippingInfoLineDTO> preview, byte shiftPage = 3)
        {
            var startDate = reportPeriod.AddDays(-shiftPage);
            var endDate   = reportPeriod.AddMonths(1).AddDays(shiftPage);

            try {
                //type_doc 1 => one transaction (one request per one dbcontext)
                List <krt_Guild18> result = (from item in preview join vn in this._engage.GetTable <v_nach, int>(PredicateBuilder.New <v_nach>().DefaultExpression
                                                                                                                 .And(x => x.type_doc == 1 && new[] { "3494", "349402" }.Contains(x.cod_kl))
                                                                                                                 .And(PredicateExtensions.InnerContainsPredicate <v_nach, int?>("id_otpr", preview.Select(x => (int?)x.Shipping.id))).Expand())
                                             on item.Shipping.id equals vn.id_otpr
                                             select new krt_Guild18()
                {
                    reportPeriod = reportPeriod,
                    warehouse = item.Warehouse,
                    idDeliviryNote = item.Shipping.id,
                    type_doc = 1, idSrcDocument = item.Shipping.id,
                    code = Convert.ToInt32(vn.cod_sbor.Split(new[] { '.', ',' })[0]),
                    sum = (decimal)(vn.summa + vn.nds),
                    rateVAT = Math.Round((decimal)(vn.nds / vn.summa), 2),
                    codeType = new[] { 166, 173, 300, 301, 344 }.Contains(Convert.ToInt32(vn.cod_sbor.Split(new[] { '.', ',' })[0])),
                    idCard = vn.id_kart,
                    idScroll = this._engage.GetGroup <krt_Naftan_orc_sapod, long>(x => x.keykrt, x => x.id_kart == vn.id_kart).Select(y => y.First().keykrt).FirstOrDefault()
                }).ToList();

                foreach (var dispatch in preview)
                {
                    var shNumbers = dispatch.WagonsNumbers.Select(x => x.n_vag).ToList();
                    //type_doc 2 =>one transaction (one request per one dbcontext) (type 2 and type_doc 4 (065))
                    //in memory because not all method support entity to sql => more easy do it in memory
                    using (this._engage.Uow = new UnitOfWork()) {
                        result.AddRange((from vpv in this._engage.Uow.GetRepository <v_pam_vag>().GetAll(x => shNumbers.Contains(x.nomvag), false)
                                         join vp in this._engage.Uow.GetRepository <v_pam>().GetAll(x => x.state == 32 && new[] { "3494", "349402" }.Contains(x.kodkl) && x.dved > startDate && x.dved < endDate, false) on vpv.id_ved equals vp.id_ved
                                         join vn in this._engage.Uow.GetRepository <v_nach>().GetAll(x => x.type_doc == 2 && new[] { "3494", "349402" }.Contains(x.cod_kl), false)
                                         on vp.id_kart equals vn.id_kart
                                         select new { vp.id_ved, vn.cod_sbor, vn.summa, vn.nds, vn.id_kart }).Distinct().ToList()
                                        .Select(x => new krt_Guild18 {
                            reportPeriod   = reportPeriod,
                            warehouse      = dispatch.Warehouse,
                            idDeliviryNote = dispatch.Shipping.id,
                            type_doc       = 2, idSrcDocument = x.id_ved,
                            code           = Convert.ToInt32(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            sum            = (decimal)(x.summa + x.nds),
                            idCard         = x.id_kart, rateVAT = Math.Round((decimal)(x.nds / x.summa), 2),
                            codeType       = new[] { "166", "173", "300", "301", "344" }.Contains(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            idScroll       = this._engage.GetGroup <krt_Naftan_orc_sapod, long>(y => y.keykrt, z => z.id_kart == x.id_kart).Select(y => y.First().keykrt).FirstOrDefault()
                        }));
                    }
                    //065
                    using (this._engage.Uow = new UnitOfWork()) {
                        result.AddRange((from vpv in this._engage.Uow.GetRepository <v_pam_vag>().GetAll(x => shNumbers.Contains(x.nomvag), false) join vn in this._engage.Uow.GetRepository <v_nach>()
                                         .GetAll(x => x.type_doc == 4 && x.cod_sbor == "065" && new[] { "3494", "349402" }.Contains(x.cod_kl) && x.date_raskr > startDate && x.date_raskr < endDate, false) on
                                         new { p1 = vpv.d_pod, p2 = vpv.d_ub } equals new { p1 = vn.date_raskr, p2 = vn.date_raskr }
                                         select new { vpv.id_ved, vn.cod_sbor, vn.summa, vn.nds, vn.id_kart }).Distinct().ToList()
                                        .Select(x =>
                                                new krt_Guild18 {
                            reportPeriod   = reportPeriod,
                            warehouse      = dispatch.Warehouse,
                            idDeliviryNote = dispatch.Shipping.id,
                            type_doc       = 4, idSrcDocument = x.id_kart,
                            code           = Convert.ToInt32(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            sum            = (decimal)(x.summa + x.nds),
                            idCard         = x.id_kart, rateVAT = Math.Round((decimal)(x.nds / x.summa), 2),
                            codeType       = new[] { "166", "173", "300", "301", "344" }.Contains(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            idScroll       = this._engage.GetGroup <krt_Naftan_orc_sapod, long>(y => y.keykrt, z => z.id_kart == x.id_kart).Select(y => y.First().keykrt).FirstOrDefault()
                        }));
                    }
                    ////type_doc 3 =>one transaction (one request per one dbcontext)
                    using (this._engage.Uow = new UnitOfWork()) {
                        result.AddRange((from vav in this._engage.Uow.GetRepository <v_akt_vag>().GetAll(x => shNumbers.Contains(x.nomvag), false)
                                         join va in this._engage.Uow.GetRepository <v_akt>().GetAll(x => x.state == 32 && new[] { "3494", "349402" }.Contains(x.kodkl) && x.dakt > startDate && x.dakt < endDate, false) on vav.id_akt equals va.id
                                         join vn in this._engage.Uow.GetRepository <v_nach>().GetAll(x => x.type_doc == 3 && new[] { "3494", "349402" }.Contains(x.cod_kl), false)
                                         on va.id_kart equals vn.id_kart
                                         select new { va.id, vn.cod_sbor, vn.summa, vn.nds, vn.id_kart }).Distinct().ToList()
                                        .Select(x =>
                                                new krt_Guild18 {
                            reportPeriod   = reportPeriod,
                            warehouse      = dispatch.Warehouse,
                            idDeliviryNote = dispatch.Shipping.id,
                            type_doc       = 3, idSrcDocument = x.id,
                            code           = Convert.ToInt32(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            sum            = (decimal)(x.summa + x.nds),
                            idCard         = x.id_kart,
                            rateVAT        = Math.Round((decimal)(x.nds / x.summa), 2),
                            codeType       = new[] { "166", "173", "300", "301", "344" }.Contains(x.cod_sbor.Split(new[] { '.', ',' })[0]),
                            idScroll       = this._engage.GetGroup <krt_Naftan_orc_sapod, long>(y => y.keykrt, z => z.id_kart == x.id_kart).Select(y => y.First().keykrt).FirstOrDefault()
                        }));
                    }
                    //luggage (type_doc 0 or 4)
                    result.AddRange(this._engage.GetTable <krt_Naftan_orc_sapod, long>(x => new[] { 611, 629, 125 }.Contains(x.vidsbr) && x.dt.Month == reportPeriod.Month && x.dt.Year == reportPeriod.Year).ToList()
                                    .Select(x => new krt_Guild18 {
                        reportPeriod  = reportPeriod,
                        type_doc      = x.tdoc,
                        idSrcDocument = (int)x.id_kart, code = x.vidsbr,
                        sum           = x.sm, rateVAT = Math.Round((decimal)(x.nds / x.sm_no_nds), 2),
                        codeType      = new[] { 166, 173, 300, 301, 344 }.Contains(x.vidsbr),
                        idCard        = (int)x.id_kart, idScroll = x.keykrt
                    }));
                }
            } catch (Exception) {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 40
0
        static DateTimeModelContext()
        {
            DateTime dt = new DateTime(2014, 12, 31, 20, 12, 30, DateTimeKind.Utc);

            _dateTimes = Enumerable.Range(1, 5).Select(i =>
                new DateTimeModel
                {
                    Id = i,
                    BirthdayA = dt.AddYears(i),
                    BirthdayB = dt.AddMonths(i),
                    BirthdayC = new List<DateTime> { dt.AddYears(i), dt.AddMonths(i), dt.AddDays(i) },
                    BirthdayD = new List<DateTime?>
                    {
                        dt.AddYears(2 * i), null, dt.AddMonths(2 * i)
                    }
                }).ToList();
        }