예제 #1
0
        public IActionResult Reservation(int id, [FromQuery] DateModel query)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            if (this.reservationsServices.RoomIsReserved(id, query.Date))
            {
                return(this.RedirectToAction("Reserved", new { id, query.Date }));
            }

            if (!this.periodsServices.RoomIsAvailable(id, query.Date) || query.Date < DateTime.Now.Date)
            {
                return(this.RedirectToAction("NotAvailable"));
            }

            var viewModel = new ReservationViewModel
            {
                Room  = this.roomsServices.GetRoomByRoomId(id),
                Hotel = this.hotelsService.GetHotelByRoomId(id),
                Date  = query.Date,
                Price = this.periodsServices.GetPriceByPeriod(query.Date)
            };

            return(this.View(viewModel));
        }
예제 #2
0
        public long SwapFreeTime(FreeTimeModel freetime)
        {
            long      id;
            DateModel datemodel = new DateModel();
            Date      date      = new Date();
            FreeTime  ftime     = new FreeTime();
            DateTime  datetime  = new DateTime(freetime.Day.Year, freetime.Day.Month, freetime.Day.Day, freetime.Time.Hour, freetime.Time.Minute, freetime.Time.Second);


            using (var db = new MainDb())
            {
                try
                {
                    datemodel = date.List("Get_id", datetime).Single();

                    id = datemodel.Id;
                }
                catch
                {
                    datemodel.Day  = freetime.Day;
                    datemodel.Time = freetime.Time;
                    id             = date.Add(datemodel);
                }
                Console.WriteLine(freetime.Id);
                ftime.Delete(freetime.Id);
                return(id);
            }
        }
예제 #3
0
        public long Add(DateModel model)
        {
            //TODO: валидация модели

            //Сохранение
            using (var db = new MainDb())
            {
                Date     date     = new Date();
                DateTime datetime = new DateTime(model.Day.Year, model.Day.Month, model.Day.Day, model.Time.Hour, model.Time.Minute, model.Time.Second);

                long id = 0;
                try
                {
                    id = date.List("Get_Id", datetime).Single().Id;
                }
                catch
                {
                    id = Convert.ToInt64(db.Date.InsertWithIdentity(() => new Kpo.Dal.MainDb.DateDataModel
                    {
                        Day  = model.Day,
                        Time = model.Time
                    }));
                }
                return(id);
            }
        }
예제 #4
0
        /// <summary>
        /// Получить элемент по заданным параметрам
        /// </summary>
        /// <returns></returns>

        public DateModel Get_Item(string field, string value, ConditionType type)
        {
            FilterCondition filter = new FilterCondition(field, value, type);

            using (var db = new MainDb())
            {
                var query = MakeSelect(db);
                if (filter != null)
                {
                    if (filter.Field.Equals("Id", StringComparison.CurrentCultureIgnoreCase) && filter.Value != null)
                    {
                        if (filter.Type == ConditionType.Equal)
                        {
                            query = query.Where(q => q.Id.Equals(filter.Value));
                        }
                    }
                }
                DateModel Result = new DateModel();
                try
                {
                    Result = query.Single();
                    return(Result);
                }
                catch
                {
                    DateModel NullResult = new DateModel();
                    NullResult.Id   = 0;
                    NullResult.Day  = DateTime.Parse("0000.00.00");
                    NullResult.Time = DateTime.Parse("00.00.00");
                    return(NullResult);
                }
            }
        }
예제 #5
0
        public async Task <IActionResult> AddDate([FromBody] DateModel date)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string id = _userManager.GetUserId(HttpContext.User);

            var findAssistant = _db.Assistants.FirstOrDefault(a => a.as_user_id == id);

            var newDate = new Date
            {
                date_dateTime = date.date_dateTime,
                date_dr_id    = date.date_dr_id,
                date_pat_id   = date.date_pat_id
            };

            var addDate = await _db.Dates.AddAsync(newDate);

            if (addDate != null)
            {
                await _db.SaveChangesAsync();

                return(Ok(new { DateId = newDate.date_id, Doctorid = newDate.date_dr_id, Patientid = newDate.date_pat_id, status = 1, message = "Registration of date Succeded on " + newDate.date_dateTime }));
            }
            return(BadRequest(new JsonResult("Can't add this date")));
        }
        public void Month_SetToInvalidValue_ShouldNotBeValid(int?month)
        {
            var dt = new DateModel();

            dt.Month = month;
            Assert.IsFalse(dt.IsValid);
        }
예제 #7
0
        public List <AttendanceRecord> GetFutureAttendance(DateModel selDate)
        {
            try
            {
                string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                var    attendanceRecords = new List <AttendanceRecord>();
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("GetFutureAttendance", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@SelectedDate",
                        Value         = selDate.date
                    });
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        AttendanceRecord record = new AttendanceRecord();
                        record.ResourceId     = Convert.ToInt32(rdr["ResourceId"]);
                        record.ResourceName   = rdr["ResourceName"].ToString();
                        record.AvailableHours = Convert.ToInt32(rdr["AvailableHours"]);
                        attendanceRecords.Add(record);
                    }

                    return(attendanceRecords);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void DateNullValuesIsValid()
        {
            var date  = DateTime.Now;
            var model = new DateModel();

            Assert.True(model.IsValid("Value2"));
        }
예제 #9
0
        public void CreateNewBookList(ApplicationDbContext context, DateModel date)
        {
            ApplicationDbContext _context  = context;
            IDataAccessAction    dataAcces = new DataAccsessAction(_context);

            BookingListModel[] BooklistM1tmp = new BookingListModel[15];

            var machines = dataAcces.Machines.GetAllMachines();

            foreach (var machine in machines)
            {
                for (int i = 8; i < 23; i++)
                {
                    int    t    = i - 8;
                    string time = i.ToString() + "-" + (i + 1).ToString();
                    BooklistM1tmp[t] = new BookingListModel()
                    {
                        DateModel = date,
                        Date      = date.DateData,
                        Status    = true,
                        Machine   = machine,
                        Time      = time
                    };
                    dataAcces.BookingList.Add(BooklistM1tmp[t]);
                }
            }

            dataAcces.Complete();
        }
예제 #10
0
        //double [][] Signature = new double[5][];

        public Analysis1(DateModel dateModel, string name)
        {
            this.Name       = name;
            this.DateModel  = dateModel;
            PerAnalysis     = 4;
            AnalysisResults = new AnalysisResult(name);
        }
        public void Year_SetToInvalidValue_ShouldNotBeValid(int?year)
        {
            var dt = new DateModel();

            dt.Year = year;
            Assert.IsFalse(dt.IsValid);
        }
        /// <summary>
        /// Returns the number of returning volunteers who were present on a given day
        /// </summary>
        public int GetNumReturningVolunteers(DateModel date)
        {
            DataTable dt = new DataTable();

            using (NpgsqlConnection con = new NpgsqlConnection(connString))
            {
                string sql = @"SELECT COUNT(volunteerid)
                               FROM Volunteer_Attendance va
                               WHERE attended = true
                               AND dayattended = @date
                               AND 0 <> 
	                               (SELECT COUNT(*) FROM Volunteer_Attendance 
	                                WHERE volunteerid = va.volunteerid 
	                                AND dayattended <> va.dayattended
	                                AND attended = true)"    ;

                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
                {
                    NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
                    cmd.Parameters.Add($"@date", NpgsqlTypes.NpgsqlDbType.Date).Value = date.Date;
                    con.Open();
                    da.Fill(dt);
                    con.Close();
                }
            }

            return((int)(long)dt.Rows[0]["count"]);
        }
예제 #13
0
        /// <summary>
        /// Método para atualizar a data de um work
        /// </summary>
        /// <param name="workId">Id do work</param>
        /// <param name="date">Objeto DateModel com a data</param>
        /// <returns>Retorna true se a data for atualizada,
        /// false caso contrário </returns>
        public bool updateDate(int workId, DateModel date)
        {
            try{
                bool updated = false;

                using (SqlCommand cmd = _connection.Fetch().CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;

                    cmd.CommandText = "UPDATE dbo.[Job] " +
                                      "SET Date=@date " +
                                      "WHERE Id=@id";

                    cmd.Parameters.Add("@date", SqlDbType.Date).Value = date.Date;
                    cmd.Parameters.Add("@id", SqlDbType.Int).Value    = workId;

                    if (cmd.ExecuteNonQuery() > 0)
                    {
                        updated = true;
                    }
                }

                return(updated);
            }catch (Exception e) {
                throw new Exception(e.Message);
            }
        }
예제 #14
0
        public void DateModelCreateTest()
        {
            DateModel model = GetDateModel();

            RequestParameters testParameters = RequestParameters.CreateFromModel(model);

            ParametersDictionary expectedParameters = new ParametersDictionary()
            {
                new KeyValuePair <string, string>(
                    $"{nameof(model.StartDate)}",
                    $"{model.StartDate}"),
            };

            if (model.EndDate.HasValue)
            {
                expectedParameters.Add(
                    new KeyValuePair <string, string>(
                        $"{nameof(model.EndDate)}",
                        $"{model.EndDate}"));
            }

            RequestParameters expectedCollection = new RequestParameters(expectedParameters);

            Assert.AreEqual(testParameters.ToString(), expectedCollection.ToString());
        }
예제 #15
0
        private async Task <RemindBackupModel> EditRemindBackup(string content, string title, string week, int indexBefore, RemindListModel remind)
        {
            var user = GetCredential.getCredential("ZSCY");
            RemindBackupModel remindBackup = new RemindBackupModel();

            remindBackup.Content = remind.Remind.Content = content;
            remindBackup.Title   = remind.Remind.Title = title;
            remindBackup.Id      = remind.Id;
            remindBackup.Time    = remind.Remind.Time = null;
            if (indexBefore != 0)
            {
                remindBackup.Time = remind.Remind.Time = Convert.ToInt32(App.addRemindViewModel.RemindModel.BeforeTime[indexBefore].BeforeTime.TotalMinutes);
            }
            remindBackup.DateItems = new List <DateModel>();
            remind.Remind.DateItems.Clear();
            foreach (var item in App.SelCoursList)
            {
                var temp = new DateModel()
                {
                    Week  = week,
                    Class = item.ClassNum.ToString(),
                    Day   = item.DayNum.ToString()
                };
                remindBackup.DateItems.Add(temp);
                remind.Remind.DateItems.Add(temp);
            }
            remindBackup.StuNum  = user.UserName;
            remindBackup.IdNum   = user.Password;
            remind.Remind.StuNum = null;
            remind.Remind.IdNum  = null;
            await RemindWebRequest.getHttpWebRequest(Api.EditRemindApi, RemindWebRequest.editRemind(remindBackup), 0, true);

            return(remind.Remind);
        }
예제 #16
0
    /// <summary>
    /// 根据传入的时间,计算工作日天数
    /// </summary>
    /// <param name="date">带计算的时间</param>
    /// <param name="isContainToday">当天是否算工作日(默认:true)</param>
    /// <returns></returns>
    public int GetWorkDayNum2Today(DateTime date, bool isContainToday = true)
    {
        var currDate = DateTime.Now;

        int workDayNum = 0;
        int addDay     = date.Date > currDate.Date ? 1 : -1;

        if (isContainToday)
        {
            currDate = currDate.AddDays(-addDay);
        }

        DateModel thisYearData = GetConfigDataByYear(currDate.Year);

        if (thisYearData.Year > 0)
        {
            bool isEnd = false;
            do
            {
                currDate = currDate.AddDays(addDay);
                if (IsWorkDay(currDate, thisYearData))
                {
                    workDayNum += addDay;
                }
                isEnd = addDay > 0 ? (date.Date > currDate.Date) : (date.Date < currDate.Date);
            } while (isEnd);
        }
        return(workDayNum);
    }
예제 #17
0
        public async ValueTask <List <OrderInfo> > GetInfoAboutOrdersByDate(DateModel dateModel)
        {
            var orderDictionary = new Dictionary <int, OrderInfo>();

            var result = await connection.QueryAsync <OrderInfo, City, Store, Product_Order, OrderInfo>(
                SpName.GetInfoAboutOrdersByDate,
                (orderInfo, city, store, po) =>
            {
                if (!orderDictionary.TryGetValue((int)orderInfo.OrderId, out OrderInfo newOrderInfo))
                {
                    newOrderInfo            = orderInfo;
                    newOrderInfo.Store      = store;
                    newOrderInfo.Store.City = city;
                    newOrderInfo.Products   = new List <Product_Order>();
                    orderDictionary.Add((int)orderInfo.OrderId, newOrderInfo);
                }

                if (po != null)
                {
                    newOrderInfo.Products.Add(po);
                }

                return(newOrderInfo);
            },
                new
            {
                dateModel.startDate,
                dateModel.endDate
            },
                commandType : CommandType.StoredProcedure,
                splitOn : "Id");

            return(result.Distinct().ToList());
        }
예제 #18
0
    /// <summary>
    /// 根据传入的日期和工作日天数,获得计算后的日期,可传负数
    /// </summary>
    /// <param name="day">天数</param>
    /// <param name="isContainToday">当天是否算工作日(默认:true)</param>
    /// <returns></returns>
    public DateTime GetReckonDate(DateTime date, int day, bool isContainToday = true)
    {
        if (date == new DateTime(2019, 10, 24))
        {
        }
        DateTime currDate = date;
        int      addDay   = day >= 0 ? 1 : -1;

        if (isContainToday)
        {
            currDate = currDate.AddDays(-addDay);
        }

        DateModel thisYearData = GetConfigDataByYear(currDate.Year);

        if (thisYearData.Year > 0)
        {
            int sumDay     = Math.Abs(day);
            int workDayNum = 0;
            while (workDayNum < sumDay)
            {
                currDate = currDate.AddDays(addDay);
                if (IsWorkDay(currDate, thisYearData))
                {
                    workDayNum++;
                }
            }
        }
        return(currDate);
    }
예제 #19
0
    /// <summary>
    /// 判断是否为工作日
    /// </summary>
    /// <param name="currDate">要判断的时间</param>
    /// <param name="thisYearData">当前的数据</param>
    /// <returns></returns>
    private bool IsWorkDay(DateTime currDate, DateModel thisYearData)
    {
        if (currDate.Year != thisYearData.Year)//跨年重新读取数据
        {
            thisYearData = GetConfigDataByYear(currDate.Year);
        }
        if (thisYearData.Year > 0)
        {
            string date = currDate.ToString("MMdd");
            int    week = (int)currDate.DayOfWeek;

            if (thisYearData.Work.IndexOf(date) >= 0)
            {
                return(true);
            }

            if (thisYearData.Holiday.IndexOf(date) >= 0)
            {
                return(false);
            }

            if (week != 0 && week != 6)
            {
                return(true);
            }
        }
        return(false);
    }
예제 #20
0
        //Adds Book to the Database.
        public void AddBook(BookInputModel model)
        {
            var book = new BookEntityModel()
            {
                Title              = model.Title,
                Author             = model.Author,
                ISBN10             = model.ISBN10,
                ISBN13             = model.ISBN13,
                Description        = model.Description,
                Price              = model.Price,
                Genre              = model.Genre,
                NumberOfPages      = model.NumberOfPages,
                NumberOfCopiesSold = 0,
                Publisher          = model.Publisher,
                Rating             = 0,
                NumberOfRatings    = 0,
                InStock            = model.InStock,
                Image              = model.Image,
            };

            var datePublished = new DateModel()
            {
                Day   = model.DayPublished,
                Month = model.MonthPublished,
                Year  = model.YearPublished,
            };

            book.DatePublished = datePublished;
            _db.Books.Add(book);
            _db.SaveChanges();
        }
        public async Task <IActionResult> ChildrenByBusForDay([FromQuery] DateModel Date)
        {
            var user = await userManager.GetUserAsync(User);

            if (user == null ||
                !(await userManager.IsInRoleAsync(user, UserHelpers.UserRoles.Staff.ToString())) ||
                await userManager.IsInRoleAsync(user, UserHelpers.UserRoles.BusDriver.ToString()))
            {
                return(Utilities.ErrorJson("Not authorized."));
            }

            try
            {
                AnalyticsRepository repo = new AnalyticsRepository(configModel.ConnectionString);
                return(new JsonResult(new
                {
                    ChildrenByBus = repo.GetChildrenByBusForDay(Date)
                }));
            }

            catch (Exception exc)
            {
                return(new JsonResult(new
                {
                    Error = exc.Message,
                }));
            }
        }
예제 #22
0
        public InsuredDeceaseClaimModel()
        {
            InsurancePolicies = Enumerable.Repeat <Func <InsurancePolicyModel> >(() => new InsurancePolicyModel(), 4)
                                .Select(x => x())
                                .ToList();

            AdresseAssure = new AddressModel();
            AdresseAssure.PhoneNumberShownAndRequired = false;

            DateNaissanceAssure  = DateModel.CreateBirthDateModel();
            DateDecesAssure      = DateModel.CreatePastDateModel();
            DateUnionFait        = DateModel.CreatePastDateModel();
            DateJugementDivorce  = DateModel.CreatePastDateModel();
            DateSeparationFait   = DateModel.CreatePastDateModel();
            DateSeparationLegale = DateModel.CreatePastDateModel();

            AnneePremiersSymptomes    = new YearModel();
            AnneePremiereConsultation = new YearModel();
            MedicalConsultations1     = new List <MedicalConsultationModel> {
                new MedicalConsultationModel(true)
            };
            MedicalConsultations2 = new List <MedicalConsultationModel> {
                new MedicalConsultationModel(true)
            };
        }
        public async Task <IActionResult> VolunteersBlueShirt([FromQuery] DateModel model)
        {
            var user = await userManager.GetUserAsync(User);

            if (user == null ||
                !(await userManager.IsInRoleAsync(user, UserHelpers.UserRoles.Staff.ToString())))
            {
                return(Utilities.ErrorJson("Not authorized."));
            }

            if (model.Date == DateTime.MinValue)
            {
                return(Utilities.GenerateMissingInputMessage("date"));
            }

            try
            {
                AnalyticsRepository repo = new AnalyticsRepository(configModel.ConnectionString);

                return(new JsonResult(new
                {
                    Count = repo.GetNumBlueShirtVolunteers(model)
                }));
            }

            catch (Exception exc)
            {
                return(new JsonResult(new
                {
                    Error = exc.Message,
                }));
            }
        }
예제 #24
0
        private void AddAnalyse_Click_1(object sender, EventArgs e)
        {
            AnalyseModel addmodel  = new AnalyseModel();
            DateModel    datemodel = new DateModel();

            datemodel.Day   = Program.Current_Date.Date;
            datemodel.Time += Program.Current_Date.TimeOfDay;

            addmodel.Date_Id = date.Add(datemodel);
            try
            {
                int selected = ListView.SelectedIndices[0];
                addmodel.Type_Id   = Analyse_Type.SelectedIndex + 1;
                addmodel.Client_Id = long.Parse(ListView.Items[selected].SubItems[0].Text);
                addmodel.Result    = long.Parse(ResultText.Text);
                addmodel.Coment    = Coment.Text;
                analyse.Add(addmodel);
                Coment.Clear();
                ResultText.Clear();
                MessageBox.Show("Данные внесены");
            }
            catch
            {
                MessageBox.Show("Некоторые поля не выбраны");
            }
        }
        /// <summary>
        /// Returns the number of children that attended OCC on a given date, grouped by class
        /// </summary>
        public List <DataModel> GetChildrenByClassForDay(DateModel date)
        {
            DataTable dt = new DataTable();

            using (NpgsqlConnection con = new NpgsqlConnection(connString))
            {
                string sql = @"SELECT c.classid, COUNT(*)
                              FROM Child c
                              INNER JOIN Child_Attendance ca
                              ON c.id = ca.childid
                              WHERE ca.dayattended = @date
                              GROUP BY c.classid";
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
                {
                    NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
                    cmd.Parameters.Add($"@date", NpgsqlTypes.NpgsqlDbType.Date).Value = date.Date;
                    con.Open();
                    da.Fill(dt);
                    con.Close();
                }
            }

            List <DataModel> numChildrenPerBus = new List <DataModel>();

            foreach (DataRow dr in dt.Rows)
            {
                numChildrenPerBus.Add(new DataModel(DBNull.Value.Equals(dr["classid"]) ? "Unknown" : ((int)dr["classid"]).ToString(), (int)(long)dr["count"]));
            }

            return(numChildrenPerBus);
        }
        public void Day_SetToInvalidValue_ShouldNotBeValid(int?day)
        {
            var dt = new DateModel();

            dt.Day = day;
            Assert.IsFalse(dt.IsValid);
        }
        /// <summary>
        /// Returns the number of "blue shirt" volunteers who were present on a given day
        /// </summary>
        public int GetNumBlueShirtVolunteers(DateModel date)
        {
            DataTable dt = new DataTable();

            using (NpgsqlConnection con = new NpgsqlConnection(connString))
            {
                string sql = @"SELECT COUNT(va.volunteerid)
                               FROM Volunteer_Attendance va
                               LEFT JOIN Volunteers v
                               ON va.volunteerid = v.id
                               WHERE v.blueshirt
                               AND dayattended = @date";

                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
                {
                    NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
                    cmd.Parameters.Add($"@date", NpgsqlTypes.NpgsqlDbType.Date).Value = date.Date;
                    con.Open();
                    da.Fill(dt);
                    con.Close();
                }
            }

            return((int)(long)dt.Rows[0]["count"]);
        }
예제 #28
0
        } // New Date Method

        public IHttpActionResult Put(int id, DateModel date)
        {
            try
            {
                if (date == null)
                {
                    return(BadRequest("Could not read date from body"));
                }

                var originalDate = _ctx.Dates.Find(id);

                if (originalDate == null || originalDate.ID != id)
                {
                    return(BadRequest("date is not found"));
                }
                else
                {
                    date.ID = id;
                }
                _ctx.Entry(originalDate).CurrentValues.SetValues(date);
                _ctx.SaveChanges();
                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        } // Update Date Method
예제 #29
0
        private void LoadDatabase()
        {
            //set visibility of all ranges
            Database.GetDataRangeCommand.Parameters.Clear();
            for (int i = 0; i < 16; i++)
            {
                Series[i].Values.Clear();
                ((GLineSeries)Series[i]).Visibility = (Visibility)Convert.ToInt32(!_deviceSelected[i]);
            }

            //add start/end time parameters
            Database.GetDataRangeCommand.Parameters.Add(new SQLiteParameter("Start", ((DateTime)SelectedStartTime).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss.fff")));
            Database.GetDataRangeCommand.Parameters.Add(new SQLiteParameter("End", ((DateTime)SelectedEndTime).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss.fff")));

            if (Database.Connection != null)
            {
                try
                {
                    Database.Connection.Open();
                    SQLiteDataReader reader = Database.GetDataRangeCommand.ExecuteReader();

                    int      i;
                    object[] _data = new object[17];
                    //load all data from database
                    while (reader.Read())
                    {
                        reader.GetValues(_data);
                        DateTime  time = DateTime.ParseExact((string)reader[0], "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
                        DateModel value;
                        for (i = 1; i < _data.Length; i++)
                        {
                            //only add to series if series is enabled
                            if (DeviceSelected[i - 1] && _data[i] != DBNull.Value)
                            {
                                //add new datemodel
                                value = new DateModel()
                                {
                                    Time  = time,
                                    Value = (double)_data[i]
                                };
                                Series[i - 1].Values.Add(value);
                            }
                            else if (_data[i] == DBNull.Value)
                            {
                                value = new DateModel()
                                {
                                    Time = time
                                };
                                Series[i - 1].Values.Add(value);
                            }
                        }
                    }
                    reader.Close();
                    Database.Connection.Close();
                }
                catch (SQLiteException sqlex)
                {
                }
            }
        }
예제 #30
0
        public IHttpActionResult Post(DateModel date)
        {
            try
            {
                var oldDate = _ctx.Dates.Find(date.ID);
                if (oldDate != null)
                {
                    return(Put(oldDate.ID, date));
                }
                if (!ModelState.IsValid || date == null)
                {
                    return(BadRequest(ModelState));
                }
                var newDate = _ctx.Dates.Add(date);
                _ctx.SaveChanges();

                if (newDate == null)
                {
                    return(BadRequest(ModelState));
                }

                return(Ok());
            }

            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        } // New Date Method
        public void DateWithNullsIsValid()
        {
            var model = new DateModel() { };

            var ctx = new ValidationContext(model, null, null);
            var results = new List<ValidationResult>();

            bool actual = Validator.TryValidateObject(model, ctx, results, true);
            var expected = true;
            Assert.AreEqual(actual, expected);
        }
        public void DateWithValue2NullIsNotValid()
        {
            var model = new DateModel() { Value1 = DateTime.Now };

            var ctx = new ValidationContext(model, null, null);
            var results = new List<ValidationResult>();

            bool actual = Validator.TryValidateObject(model, ctx, results, true);
            var expected = false;
            Assert.AreEqual(actual, expected);
        }
        public void DateIsValid()
        {
            var model = new DateModel() { Value1 = DateTime.Now, Value2 = DateTime.Now.AddDays(1) };

            var ctx = new ValidationContext(model, null, null);
            var results = new List<ValidationResult>();

            bool actual = Validator.TryValidateObject(model, ctx, results, true);
            var expected = true;
            Assert.AreEqual(actual, expected);
        }
        public void ShouldSerializeDateTimeInCorrectStringFormat(string dateTimeStr)
        {
            //Arrange
            var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters };
            var model = new DateModel
            {
                DateTime = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal),
                DateTimeNullable = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal)
            };

            //Act
            var actual = serializer.Serialize(model);

            //Assert
            var expected =
                "{\r\n  \"DateTime\": \"" + dateTimeStr + "\",\r\n  \"DateTimeNullable\": \"" + dateTimeStr + "\"\r\n}";
            Assert.AreEqual(expected, actual);
        }
예제 #35
0
 public DefaultReportModel()
 {
     Date = new DateModel();
     Houses = new List<HouseViewModel>();
 }
        public void ShouldSerializeDateTimeOffsetInCorrectStringFormat()
        {
            //Arrange
            var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters };
            var model = new DateModel
                {
                    DateTime = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00"),
                    DateTimeNullable = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00")
                };

            //Act
            var actual = serializer.Serialize(model);

            //Assert
            const string expected =
                "{\r\n  \"DateTime\": \"2012-08-31T00:11:00.3642578+10:00\",\r\n  \"DateTimeNullable\": \"2012-08-31T00:11:00.3642578+10:00\"\r\n}";
            Assert.AreEqual(expected, actual);
        }