public IHttpActionResult PutScheduleTable(int id, ScheduleTable scheduleTable)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != scheduleTable.ScheduleCode)
            {
                return(BadRequest());
            }

            db.Entry(scheduleTable).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ScheduleTableExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemple #2
0
 private void UpdatePlanOnDelete(ScheduleTable schOld)
 {
     if (!UpdatePlan(schOld))
     {
         UpdatePlan(schOld, +2);
     }
 }
Exemple #3
0
        public void Edit(ScheduleTable sch)
        {
            var schOld = _ctx.ScheduleTables
                         .Include(x => x.StudGroup)
                         .SingleOrDefault(x => x.ScheduleTableId == sch.ScheduleTableId);

            if (schOld == null)
            {
                return;
            }


            schOld.Auditory   = sch.Auditory;
            schOld.LectorName = sch.LectorName;
            schOld.LessonType = sch.LessonType;
            schOld.GroupSub   = sch.GroupSub;

            if (schOld.SubjectName == sch.SubjectName)
            {
                this.UpdatePlan(schOld);
            }
            else
            {
                this.UpdatePlanOnDelete(schOld);
                this.UpdatePlan(sch, -2);
            }

            schOld.SubjectName = sch.SubjectName;

            this.UpdateSchCache(sch.StudGroup.FacultId);
        }
Exemple #4
0
    void Start()
    {
        int id = ScheduleDetail.ScheduleId;

        if (id == 0)
        {
            return;
        }
        Year.text = Calendar.SelectedDate.ToString("yyyy年");
        Date.text = Calendar.SelectedDate.ToString("M月d日");

        var result = ScheduleTable.FindById(id);

        if (result.Rows.Count == 0)
        {
            return;
        }

        var data = result.Rows[0];

        titleField.text = (string)data["title"];
        descField.text  = (string)data["detail"];

        backButton.onClick.AddListener(() => {
            SceneManager.LoadScene("ScheduleDetail");
        });
        updateButton.onClick.AddListener(UpdateSchedule);
    }
        private static ScheduleTable CreateScheduleTable(UiData uiData, ObjectId propertySetDefinitionId, ObjectId styleId, Transaction trans)
        {
            Database         db  = ScheduleSample.GetDatabase();
            BlockTableRecord btr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

            ScheduleTable scheduleTable = new ScheduleTable();

            scheduleTable.SetToStandard(db);
            scheduleTable.SetDatabaseDefaults(db);
            scheduleTable.StyleId = styleId;
            scheduleTable.SetDefaultLayer();

            btr.AppendEntity(scheduleTable);
            trans.AddNewlyCreatedDBObject(scheduleTable, true);

            ObjectIdCollection selectionSet = new ObjectIdCollection();

            foreach (List <ObjectId> idSetByObjectType in uiData.classObjectIdsMap.Values)
            {
                foreach (ObjectId id in idSetByObjectType)
                {
                    selectionSet.Add(id);
                }
            }

            scheduleTable.SetSelectionSet(selectionSet, new ObjectIdCollection());
            scheduleTable.AutomaticUpdate = true;

            return(scheduleTable);
        }
Exemple #6
0
    void Start()
    {
        var result = ScheduleTable.FindById(ScheduleId);

        if (result.Rows.Count == 0)
        {
            return;
        }
        var data = result.Rows[0];

        var date = DateTime.Parse((string)data["date"]);
        var icon = (int)data["icon"];

        Year.text    = date.ToString("yyyy年");
        Date.text    = date.ToString("M月d日");
        Title.text   = (string)data["title"];
        Detail.text  = (string)data["detail"];
        Remind.text  = (string)data["time"];
        Image.sprite = iconList[icon];

        BackButton.onClick.AddListener(() => {
            SceneManager.LoadScene("ScheduleList");
        });
        EditButton.onClick.AddListener(() => {
            SceneManager.LoadScene("ScheduleEdit");
        });
        DeleteButton.onClick.AddListener(() => {
            ScheduleTable.DeleteById(ScheduleId);
            SceneManager.LoadScene("ScheduleList");
        });
    }
        /// <summary>
        /// Creates the whole property sets, schedule table style and schedule table in database.
        /// </summary>
        /// <param name="uiData">The data saved from the wizard.</param>
        /// <returns>Returns the object id of the property set definition, schedule table style and schedule table.</returns>
        public static ScheduleTableCreateResult CreateScheduleTable(UiData uiData)
        {
            ScheduleTableCreateResult result = new ScheduleTableCreateResult();
            Database             db          = ScheduleSample.GetDatabase();
            DBTransactionManager tm          = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                try
                {
                    PropertySetDefinition psd = CreatePropertySetDefinition(uiData, trans);
                    result.PropertySetDefinitionId = psd.Id;
                    if (result.PropertySetDefinitionId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create property set definition."));
                    }

                    ScheduleTableStyle style = CreateStyle(uiData, psd, trans);
                    result.StyleId = style.Id;
                    if (result.StyleId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create property style."));
                    }

                    AddPropertySetToObjects(uiData, result.PropertySetDefinitionId, trans);

                    ScheduleTable table = CreateScheduleTable(uiData, result.PropertySetDefinitionId, result.StyleId, trans);
                    result.ScheduleTableId = table.Id;
                    if (result.ScheduleTableId == ObjectId.Null)
                    {
                        throw (new System.Exception("Failed to create Schedule Table."));
                    }

                    Editor            editor       = ScheduleSample.GetEditor();
                    PromptPointResult editorResult = editor.GetPoint("Please pick a point to insert the schedule table:");
                    if (editorResult.Status == PromptStatus.OK)
                    {
                        table.Location = editorResult.Value;
                        table.Scale    = 10;
                        trans.Commit();
                    }
                    else
                    {
                        trans.Abort();
                    }
                }
                catch (System.Exception)
                {
                    trans.Abort();
                    return(null);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return(result);
        }
Exemple #8
0
 public override bool CalculateDelay(out int delay, ScheduleTable schedule, int iteration)
 {
     using (var scope = _serviceScopeFactory.CreateScope())
     {
         Console.WriteLine("in ScopedProcessor.CalculateDelay");
         return(CalculateDelayInScope(scope.ServiceProvider, out delay, schedule, iteration));
     }
 }
Exemple #9
0
        private DateTime GetSchDateTime(ScheduleTable table)
        {
            var schDate = new DateTime(table.Date.Year, table.Date.Month, table.Date.Day,
                                       table.Lesson.Time.Hour, table.Lesson.Time.Minute, table.Lesson.Time.Second);

            var weekdayForSch = NormalizationWeekday((int)schDate.DayOfWeek);
            var weekdayOffset = table.WeekdayId - weekdayForSch;
            var daysOffset    = (table.WeekdayId >= weekdayForSch) ? weekdayOffset : weekdayOffset + 7;

            schDate = schDate.AddDays(daysOffset);
            return(schDate);
        }
            /// <summary>
            /// Compute the days of the week that have been changed between
            /// the the two tables.
            /// </summary>
            /// <param name="scheduleTable">Schedule Table to diff</param>
            /// <param name="pendingChangesDifference">OldPendingChanges\NewPendingChanges + NewPendingChanges\OldPendingChanges</param>
            /// <returns></returns>
            public IEnumerable <DayOfWeek> ChangedDays(ScheduleTable scheduleTable, IEnumerable <Course> pendingChangesDifference)
            {
                var addedOrRemovedCourses = Courses.SymmetricDifference(scheduleTable.Courses).ToImmutableHashSet();

                return(pendingChangesDifference.Concat(addedOrRemovedCourses)
                       .Concat(scheduleTable.Courses.Union(Courses)
                               .Where(course => course.AllTutorials.SelectMany(it => it).Any(tutorial => addedOrRemovedCourses.Contains(tutorial)))
                               )
                       .SelectMany(course => course.RegularDates)
                       .Select(regularDate => regularDate.Key.From.DayOfWeek)
                       .Distinct());
            }
Exemple #11
0
        private bool UpdatePlan(ScheduleTable sch)
        {
            var df = DateTime.Now - GetSchDateTime(sch);
            var h  = (df.Days / 7 - 1) * 2;

            if (df.Hours < 2)
            {
                return(false);
            }

            UpdatePlan(sch, -1 * (h + 2));
            return(true);
        }
Exemple #12
0
    void UpdateSchedule()
    {
        string date   = Calendar.SelectedDate.ToString("yyyy-MM-dd");
        string title  = titleField.text;
        string detail = descField.text;
        int    icon   = iconManager.selectedId;
        int    remind = 0;
        string time   = timePicker.HourText.text + ":" + timePicker.MinuteText.text;

        ScheduleTable.Update(ScheduleDetail.ScheduleId, date, title, detail, icon, remind, time);

        SceneManager.LoadScene("ScheduleDetail");
    }
        public IHttpActionResult DeleteScheduleTable(int id)
        {
            ScheduleTable scheduleTable = db.ScheduleTable.Find(id);

            if (scheduleTable == null)
            {
                return(NotFound());
            }

            db.ScheduleTable.Remove(scheduleTable);
            db.SaveChanges();

            return(Ok(scheduleTable));
        }
Exemple #14
0
        public ScheduleTableCreate FormToTable(FormCollection scheduleRows, out bool isValid)
        {
            var result = new ScheduleTableCreate
            {
                IsWeekOdd         = bool.Parse(scheduleRows[2]),
                GroupId           = int.Parse(scheduleRows[1]),
                ScheduleTableRows = new List <ScheduleTable>()
            };

            isValid = true;

            for (var i = 3; i < scheduleRows.Count; i++)
            {
                //if (scheduleRows.GetKey(i).EndsWith("ScheduleTableId")) i++;
                var id = 0; // * 0 == id -> не существует *
                if (scheduleRows.GetKey(i).EndsWith("ScheduleTableId"))
                {
                    int.TryParse(scheduleRows[i++], out id);
                }

                var item = new ScheduleTable
                {
                    ScheduleTableId = id,

                    Date = DateTime.Now,

                    Auditory    = scheduleRows[i++].Trim(),
                    LectorName  = scheduleRows[i++].Trim(),
                    SubjectName = scheduleRows[i++].Trim(),
                    LessonType  = int.Parse(scheduleRows[i++]),
                    LessonId    = int.Parse(scheduleRows[i++]),
                    GroupId     = int.Parse(scheduleRows[i++]),
                    WeekdayId   = int.Parse(scheduleRows[i]),
                    IsWeekOdd   = result.IsWeekOdd
                };

                if (item.Auditory.Trim() == string.Empty || item.SubjectName.Trim() == string.Empty)
                {
                    isValid = false;
                }

                result.ScheduleTableRows.Add(item);
            }

            return(result);
        }
Exemple #15
0
    public void LoadSchedule()
    {
        Calendar.SelectedDate = current;
        YearText.text         = current.ToString("yyyy年");
        MonthText.text        = current.ToString("M月d日");

        foreach (var schedule in scheduleList)
        {
            Destroy(schedule);
        }

        var result = ScheduleTable.FindByDate(current.ToString("yyyy-MM-dd"));

        foreach (var data in result.Rows)
        {
            Add(data);
        }
    }
Exemple #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var key = System.Text.Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:token").Value);

            services.AddDbContext <DataContext>(x => x
                                                .UseSqlServer(Configuration.GetConnectionString("MCConnection"))
                                                // .UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
                                                .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
            services.AddMvc(config =>
            {
                config.RespectBrowserAcceptHeader = true;
                config.InputFormatters.Add(new XmlSerializerInputFormatter(config));
                config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            }
                            ).AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }
                                             ).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // services.AddTransient<Seed>();
            // services.BuildServiceProvider().GetService<DataContext>().Database.Migrate();
            services.AddCors();
            // services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
            services.AddAutoMapper();
            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddScoped <IMicroCreditRepository, MicroCreditRepository>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
            services.AddScoped <LogUserActivity>();
            // services.AddSingleton<IHostedService, Poller>();
            ScheduleTable.AddScopedServices(services);
            TemplateHttpClient.AddServices(services);
            ScheduleTable.AddScheduledServices(services);
        }
        public IHttpActionResult GetScheduleTable(int id)
        {
            ScheduleTable scheduleTable = db.ScheduleTable.Find(id);

            if (scheduleTable == null)
            {
                return(NotFound());
            }
            ScheduleModel temp = new ScheduleModel
            {
                ScheduleCode     = scheduleTable.ScheduleCode,
                ValidForm        = scheduleTable.ValidFrom,
                ValidTo          = scheduleTable.ValidTo,
                Uploader         = scheduleTable.Uploader,
                ScheduleFileName = scheduleTable.ScheduleFileName
            };

            return(Ok(temp));
        }
        public IHttpActionResult PostScheduleTable(ScheduleModel scheduleTable)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ScheduleTable temp = new ScheduleTable
            {
                ScheduleCode     = scheduleTable.ScheduleCode,
                ValidFrom        = scheduleTable.ValidForm,
                ValidTo          = scheduleTable.ValidTo,
                Uploader         = scheduleTable.Uploader,
                ScheduleFileName = scheduleTable.ScheduleFileName
            };

            db.ScheduleTable.Add(temp);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = scheduleTable.ScheduleCode }, scheduleTable));
        }
Exemple #19
0
        private void UpdatePlan(ScheduleTable sch, int h)
        {
            if (sch.LessonType > 3)
            {
                return;
            }

            sch.Date = DateTime.Now;

            var plan =
                _ctx.Plans.Include(x => x.Subject)
                .SingleOrDefault(x => x.GroupId == sch.GroupId && x.Subject.Title == sch.SubjectName);

            if (plan == null || (plan.LabH == 0 && plan.LectionH == 0 && plan.PracticeH == 0))
            {
                return;
            }

            UpdatePlanTime(plan, sch.LessonType, h);
        }
Exemple #20
0
    void Start()
    {
        animator       = GetComponent <Animator>();
        nameFrame.text = PlayerPrefs.GetString("CHARACTER_NAME", "そばこ");

        textDict = new Dictionary <string, string>();
        textDict.Add("どうかしましたか?", "疑問");
        textDict.Add("なんですか?", "疑問");
        textDict.Add("わっ!びっくりしました……", "驚く");
        textDict.Add("っ!な、なにも隠してないですよー", "目そらし");
        textDict.Add("あ、あんまり見られると照れちゃいます……", "照れ困");
        textDict.Add("実は食べ物の中で一番そばが好きなんです!", "笑顔2");
        textDict.Add("マスターは動物好きですか?いつかモフモフのワンちゃんに触ってみたいなぁ", "笑顔3");
        textDict.Add("今日は髪型がうまくまとまらなくて……もしかしていつもと同じだと思ってませんか?", "しょぼん");
        textDict.Add("いつでも笑顔!を心がけてるんですよ♪", "笑顔1");
        textDict.Add("えへへ♪マスターとたくさんお話できてうれしいです!", "笑顔2");
        textDict.Add("今日もたくさんいい事があるといいですね!", "笑顔3");
        textDict.Add("音楽を聴くとつい踊りたくなっちゃいます♪", "ルンルン");
        textDict.Add("明日はなにをしようかな~?", "ルンルン");

        foreach (var data in TodoTable.FindAll().Rows)
        {
            if ((int)data["status"] == 0)
            {
                textDict.Add($"『{(string)data["title"]}』はもう終わりましたか?", "笑顔1");
            }
        }

        var date = DateTime.Now;

        foreach (var data in ScheduleTable.FindByDate(date.ToString("yyyy-MM-dd")).Rows)
        {
            textDict.Add($"今日は『{(string)data["title"]}』の予定がありますよ!", "笑顔1");
        }
        date.AddDays(1);
        foreach (var data in ScheduleTable.FindByDate(date.ToString("yyyy-MM-dd")).Rows)
        {
            textDict.Add($"明日は『{(string)data["title"]}』の予定がありますよ!", "笑顔1");
        }
        StartCoroutine(Test());
    }
        public List <ScheduleTable> Calculate(ClassGroup groupRoot)
        {
            int countTotal = 0;

            foreach (ClassGroup i in groupRoot.Children)
            {
                countTotal += i.SelectCount;
            }
            groupRoot.SelectCount = countTotal;

            var root = PreProcess(groupRoot); // 했어 ㅠㅠ



            var groups = CreateGroupClasses(root); // 했어 ㅠㅠ


            getCombinationCurrent = new List <ScheduleMid>();
            getCombinationResult  = new List <List <ScheduleMid> >();
            GetCombinations(groups); // 갔다고

            List <ScheduleTable> ret = new List <ScheduleTable>();

            foreach (var i in getCombinationResult)
            {
                var tmp = new ScheduleTable();
                foreach (var j in i)
                {
                    foreach (var k in j.infos)
                    {
                        tmp.ClassAddList(k);
                    }
                }
                ret.Add(tmp);
            }

            return(ret);
        }
Exemple #22
0
        public async Task <IActionResult> CreateMutation(int userId, int accountId, [FromBody] MutationForCreationDto mutationForCreationDto)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != userId)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            mutationForCreationDto.UserId    = userId;
            mutationForCreationDto.AccountId = accountId;

            var account = await _repo.GetAccount(accountId);

            if (account == null || account.UserId != userId)
            {
                return(Unauthorized());
            }
            var user = await _repo.GetUser(userId);

            // eens kijken of de mapper zo slim is dat ie de sender informatie ook invult in messageToReturn
            // zelfs bij de sender info die nu ietsanders heet.
            var mutation = _map.Map <Mutation>(mutationForCreationDto);

            var lastMutation = await _repo.GetMutation(account.LastMutationCreated, userId, accountId);

            if (lastMutation == null)
            {
                mutation.Balance = mutation.Amount;
                mutation.PrevId  = -account.Id;
            }
            else
            {
                mutation.PrevId  = lastMutation.Id;
                mutation.Balance = lastMutation.Balance + mutation.Amount;
                var diffdays = (mutation.InterestDate - lastMutation.InterestDate).TotalDays;
                int nrdays   = (int)diffdays;
                if (lastMutation.InterestDate.AddDays(diffdays).DayOfYear != mutation.InterestDate.DayOfYear)
                {
                    nrdays += 1;
                }
                // zoek eerst nog de gemiddelde rente op dus alle percentages af totdat
                var interest = (nrdays / 365) * account.Percentage;
                account.CalculatedInterest += interest;
            }
            if (mutation.Percentage != 0.0)
            {
                account.Percentage = mutation.Percentage;
            }
            else
            {
                mutation.Percentage = account.Percentage;
            }
            account.Balance             = mutation.Balance;
            account.LastMutationCreated = mutation.Created;
            account.LastMutation        = mutation;

            _repo.Add(mutation);
            if (await _repo.SaveAll())
            {
                var mutationToReturn = _map.Map <MutationForDetailedDto>(mutation);
                ScheduleTable.StartProcess(schedulePollerProcess, 5000);
                return(CreatedAtRoute("GetMutation", new { id = mutation.Id }, mutationToReturn));
            }
            throw new Exception("Creating the mutation failed on save");
        }
Exemple #23
0
 public MutationsController(IMicroCreditRepository repo, IMapper map)
 {
     _repo = repo;
     _map  = map;
     schedulePollerProcess = ScheduleTable.GetScheduleForProcess <PollerProcess>();
 }
Exemple #24
0
 protected abstract bool CalculateDelayInScope(IServiceProvider serviceProvider, out int delay, ScheduleTable schedule, int iteration);
        /// <summary>
        /// Find all actually overlapping dates, not simply the ones
        /// appearing in the same half hour slot. Each item
        /// of the collection is a group of colliding dates.
        /// </summary>
        /// <param name="scheduleTable">The precomputed ScheduleTable</param>
        private static Dictionary <Date, ISet <Date> > FindOverlappingDates(ScheduleTable scheduleTable)
        {
            var result = new Dictionary <Date, ISet <Date> >();
            // Key = Day at midnight in ms
            var perHourPerDayTable = new Dictionary <long, IList <ISet <Date> > >();

            foreach (var dayOfWeek in DaysOfWeek)
            {
                for (var halfHour = 0; halfHour < scheduleTable.DatesByHalfHourByDay[dayOfWeek].Count; halfHour++)
                {
                    if (scheduleTable.DatesByHalfHourByDay[dayOfWeek][halfHour].Count < 2)
                    {
                        // Skip half hours without overlaps
                        continue;
                    }

                    // hourData contains courses which may overlap
                    // so iterate over each pair of them and count the number of overlapping
                    // dates
                    foreach (var dateInHalfHour in scheduleTable.DatesByHalfHourByDay[dayOfWeek][halfHour])
                    {
                        foreach (var date in dateInHalfHour.Course.RegularDates.Find(group => group.Key.StructuralEquals(dateInHalfHour)))
                        {
                            var key           = date.From.AtMidnight().Ticks;
                            var startHalfHour = (date.From.FloorHalfHour().Hour * 60 + date.From.FloorHalfHour().Minute) / 30;
                            if (!perHourPerDayTable.ContainsKey(key))
                            {
                                perHourPerDayTable[key] = Enumerable.Repeat <ISet <Date> >(null, 48).ToList();
                            }
                            var dayTable = perHourPerDayTable[key];
                            var length   = date.LengthInHalfHours();
                            for (var h = startHalfHour; h < startHalfHour + length; h++)
                            {
                                if (dayTable[h] == null)
                                {
                                    dayTable[h] = new HashSet <Date>();
                                }
                                dayTable[h].Add(date);
                            }
                        }
                    }
                }
            }

            foreach (var dayTable in perHourPerDayTable.Values)
            {
                foreach (var halfHourData in dayTable.Where(it => it != null))
                {
                    foreach (var date in halfHourData)
                    {
                        if (!result.ContainsKey(date))
                        {
                            result[date] = new HashSet <Date>();
                        }
                        result[date].UnionWith(halfHourData.Except(new[] { date }));
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Update this ViewModel to match the data in the schedule.
        /// </summary>
        /// <param name="schedule"></param>
        public void UpdateFrom(Schedule schedule)
        {
            var selectedCoursesByCourses = schedule.SelectedCourses.ToDictionary(selectedCourse => selectedCourse.Course);
            var allPendingTutorials      = _pendingTutorials.SelectMany(it => it).ToImmutableHashSet();
            var newScheduleTable         = ComputeDatesByHalfHourByDay(schedule);
            List <DayOfWeek> changedDaysOfWeek;

            lock (_changedPendingTutorialsAndCourseUsers)
            {
                var newUsersByCourses = schedule.SelectedCourses.ToDictionary(it => it.Course, it => it.Users.Select(user => user.User.Id).ToList());
                _changedPendingTutorialsAndCourseUsers.AddRange(
                    newUsersByCourses.Where(
                        newUsersByCourse => !_usersByCourses.ContainsKey(newUsersByCourse.Key) ||
                        _usersByCourses[newUsersByCourse.Key].SymmetricDifference(newUsersByCourse.Value).Any()
                        )
                    .Select(newUserByCourse => newUserByCourse.Key)
                    );
                _usersByCourses = newUsersByCourses;

                changedDaysOfWeek = _scheduleTable != null
                    ? newScheduleTable.ChangedDays(_scheduleTable, _changedPendingTutorialsAndCourseUsers).ToList()
                    : DaysOfWeek;

                _changedPendingTutorialsAndCourseUsers.Clear();
            }
            _scheduleTable = newScheduleTable;

            EarliestHalfHour = newScheduleTable.EarliestStartHalfHour;
            LatestHalfHour   = newScheduleTable.LatestEndHalfHour;
            var datesByHalfHourByDay = newScheduleTable.DatesByHalfHourByDay;

            OverlappingDates = FindOverlappingDates(newScheduleTable);

            // Recreate course view models
            var columnsForDates = ComputeColumnsForDates(datesByHalfHourByDay);

            var weekdaysTmp = Weekdays.Count == 0 ? new ObservableCollectionEx <Weekday>(Enumerable.Repeat <Weekday>(null, DaysOfWeek.Count)) : Weekdays;

            foreach (var dayOfWeek in changedDaysOfWeek)
            {
                var isDayEmpty = true;

                // Init
                var courseViewModelsByHour = new List <ISet <CourseViewModel> >();
                for (var halfHour = 0; halfHour < 48; halfHour++)
                {
                    courseViewModelsByHour.Add(new HashSet <CourseViewModel>());
                }


                var datesByHalfHour = datesByHalfHourByDay[dayOfWeek];

                foreach (var date in datesByHalfHour
                         .SelectMany(dates => dates)
                         .Distinct()
                         .OrderByDescending(DateLengthSelector))
                {
                    isDayEmpty = false;

                    var flooredFrom       = date.From.FloorHalfHour();
                    var halfHourComputed  = (flooredFrom.Hour * 60 + flooredFrom.Minute) / 30;
                    var lengthInHalfHours = (int)(date.To.CeilHalfHour() - date.From.FloorHalfHour()).TotalMinutes / 30;

                    var maxOverlappingDates = Enumerable.Range(halfHourComputed, lengthInHalfHours).Max(halfHour2 => datesByHalfHour[halfHour2].Count - 1);
                    //for (var halfHour2 = halfHourComputed; halfHour2 < halfHourComputed + lengthInHalfHours; halfHour2++)
                    //{
                    //    maxOverlappingDates = Math.Max(maxOverlappingDates, datesByHalfHour[halfHour2].Count - 1);
                    //}

                    var course = date.Course;
                    var users  = selectedCoursesByCourses.ContainsKey(course) ?
                                 selectedCoursesByCourses[course].Users.Select(user => user.User.Name) :
                                 Enumerable.Empty <string>();
                    var datesInInterval        = course.RegularDates.First(x => Equals(x.Key, date)).ToList();
                    var isPending              = allPendingTutorials.Contains(course);
                    var overlapsWithNonPending = OverlapsWithNonPending(OverlappingDates, date, allPendingTutorials);
                    var discourageSelection    = course.IsTutorial && isPending && overlapsWithNonPending > 0;
                    var showDisplayTutorials   = !course.IsTutorial &&
                                                 course.AllTutorials.Count > 0 &&
                                                 course.AllTutorials.SelectMany(it => it).Any(tutorial => tutorial.RegularDates.Count > 0) &&
                                                 !course.AllTutorials.All(tutorialGroup =>
                                                                          tutorialGroup.Any(tutorial => allPendingTutorials.Contains(tutorial) || selectedCoursesByCourses.ContainsKey(tutorial))
                                                                          );
                    var tutorialParentCourse     = course.FindParent(_scheduleTable.Courses);
                    var parentTutorials          = tutorialParentCourse?.Tutorials ?? Enumerable.Empty <Course>();
                    var showAlternativeTutorials = course.IsTutorial && parentTutorials.Count() > 1;
                    var internalCourseId         = course.IsTutorial
                        ? tutorialParentCourse.InternalCourseID
                        : course.InternalCourseID;

                    var courseViewModel = new CourseViewModel(
                        course, date, users, lengthInHalfHours, maxOverlappingDates, halfHourComputed,
                        columnsForDates[date], datesInInterval, isPending, discourageSelection,
                        overlapsWithNonPending / (double)datesInInterval.Count,
                        showDisplayTutorials, showAlternativeTutorials, internalCourseId);

                    courseViewModelsByHour[halfHourComputed].Add(courseViewModel);
                }

                var index = dayOfWeek.Position();
                while (index-- > weekdaysTmp.Count)
                {
                    // Day we want to insert is probably a Sunday, but Saturday was removed earlier because it's empty
                    weekdaysTmp.Add(new Weekday(DaysOfWeek[weekdaysTmp.Count], Enumerable.Empty <ISet <CourseViewModel> >().ToList(), true));
                }

                var weekday = new Weekday(dayOfWeek, courseViewModelsByHour, isDayEmpty);
                if (dayOfWeek.Position() == weekdaysTmp.Count)
                {
                    // We inserted everything up to including Saturday, but Sunday is not yet present,
                    // so we need to append it to the list
                    weekdaysTmp.Add(weekday);
                }
                else
                {
                    weekdaysTmp[dayOfWeek.Position()] = weekday;
                }
            }

            if (weekdaysTmp.Count == 7 && weekdaysTmp[6].IsDayEmpty)
            {
                weekdaysTmp.RemoveAt(6);

                if (weekdaysTmp[5].IsDayEmpty)
                {
                    weekdaysTmp.RemoveAt(5);
                }
            }

            if (Weekdays.Count == 0)
            {
                // We're running this method for the first time
                Weekdays.AddRange(weekdaysTmp);
            }
        }
Exemple #27
0
 public void Add(ScheduleTable sch)
 {
     this._ctx.ScheduleTables.Add(sch);
     this.UpdateSchCache(sch.StudGroup.FacultId);
     this.UpdatePlan(sch, -2);
 }
Exemple #28
0
    private void SetCalendar()
    {
        yearText.text  = current.Year + "年";
        monthText.text = current.Month + "月";

        var prev = current.AddMonths(-1);
        var next = current.AddMonths(1);

        int dayOffset   = (int)new DateTime(current.Year, current.Month, 1).DayOfWeek - 1;
        int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);

        int day          = 1;
        int prevMonthDay = DateTime.DaysInMonth(prev.Year, prev.Month) - dayOffset;
        int nextMonthDay = 1;

        for (int i = 0; i < 42; i++)
        {
            var panel = panelList[i];

            float alpha = 1f;
            // 今月の1日より前
            if (i <= dayOffset)
            {
                panel.Date      = new DateTime(prev.Year, prev.Month, prevMonthDay);
                panel.Text.text = prevMonthDay.ToString();
                alpha           = 0.3f;
                prevMonthDay++;
            }
            // 今月の最終日より後ろ
            else if (day > daysInMonth)
            {
                panel.Date      = new DateTime(next.Year, next.Month, nextMonthDay);
                panel.Text.text = nextMonthDay.ToString();
                alpha           = 0.3f;
                nextMonthDay++;
            }
            // 今月の日付
            else
            {
                panel.Date      = new DateTime(current.Year, current.Month, day);
                panel.Text.text = day.ToString();
                day++;
            }

            var col = panel.Text.color;
            panel.Text.color   = new Color(col.r, col.g, col.b, alpha);
            panel.Image.sprite = null;

            var countPanel = panel.CountPanel;
            countPanel.SetActive(false);

            // DBから予定を取得
            var schedules = ScheduleTable.FindByDate(panel.Date.ToString("yyyy-MM-dd"));
            var count     = schedules.Rows.Count;
            if (0 < count)
            {
                int icon = (int)schedules.Rows[0]["icon"];
                panel.Image.sprite = iconList[icon];
                panel.Image.color  = new Color(1f, 1f, 1f, alpha);

                if (1 < count)
                {
                    countPanel.SetActive(true);
                    var text = countPanel.transform.Find("Text").GetComponent <Text>();
                    text.text = count.ToString();
                    if (9 < count)
                    {
                        text.text = "9+";
                    }
                }
            }
        }
    }
Exemple #29
0
        public void InitLocalMySQL()
        {
            if (this.Database.CreateIfNotExists())
            {
                EntityGenerator <Address> generatorAddress = new EntityGenerator <Address>();
                for (int i = 0; i < 10; i++)
                {
                    AddressTable.Add(generatorAddress.GenerateItem());
                }

                EntityGenerator <StreetNumber> generatorStreetNumber = new EntityGenerator <StreetNumber>();
                for (int i = 0; i < 20; i++)
                {
                    StreetNumberTable.Add(generatorStreetNumber.GenerateItem());
                }

                EntityGenerator <Employee> generatorEmployee = new EntityGenerator <Employee>();
                for (int i = 0; i < 10; i++)
                {
                    EmployeeTable.Add(generatorEmployee.GenerateItem());
                }

                EntityGenerator <Animal> generatorAnimal = new EntityGenerator <Animal>();
                for (int i = 0; i < 10; i++)
                {
                    AnimalTable.Add(generatorAnimal.GenerateItem());
                }

                EntityGenerator <Job> generatorJob = new EntityGenerator <Job>();
                for (int i = 0; i < 10; i++)
                {
                    JobTable.Add(generatorJob.GenerateItem());
                }

                EntityGenerator <Schedule> generatorSchedule = new EntityGenerator <Schedule>();
                for (int i = 0; i < 10; i++)
                {
                    ScheduleTable.Add(generatorSchedule.GenerateItem());
                }


                EntityGenerator <Structure> generatorStructure = new EntityGenerator <Structure>();
                for (int i = 0; i < 10; i++)
                {
                    StructureTable.Add(generatorStructure.GenerateItem());
                }

                EntityGenerator <Zoo> generatorZoo = new EntityGenerator <Zoo>();
                for (int i = 0; i < 10; i++)

                {
                    ZooTable.Add(generatorZoo.GenerateItem());
                }

                this.SaveChangesAsync();


                AddressTable.Find(1).StreetNumber = StreetNumberTable.Find(1);
                this.SaveChangesAsync();
            }
        }