Beispiel #1
0
		public TodoViewModel( Todo todo )
		{
			MessengerInstance.Register<TagAddedMessage>( this, OnTagAdded );
			MessengerInstance.Register<TagRemovedMessage>( this, OnTagRemoved );

			TodoRepo = new TodoRepository( App.Session );
			Model = todo;
			_Done = Model.Done;

			if( Model?.Project?.Tags != null )
			{
				AllTags = new ObservableCollection<TodoTagViewModel>( Model.Project.Tags.Select( t => new TodoTagViewModel( t )
				{
					IsSelected = Model.Tags.Contains( t )
				} ) );
			}
			else
			{
				AllTags = new ObservableCollection<TodoTagViewModel>();
			}

			foreach( var t in AllTags )
			{
				t.Selected += Tag_Selected;
				t.Deselected += Tag_Deselected;
			}

			Tags = new ObservableCollection<TodoTagViewModel>( AllTags.Where( t => t.IsSelected ) );
		}
Beispiel #2
0
 public void Setup()
 {
     //remove this call to setup once ReSharper
     //unit test runner supports NUnit 2.5
     setup();
     repository = new TodoRepository(session);
 }
Beispiel #3
0
 public TodoController(TodoRepository repository, BloggerGateway gateway, 
     ThoughtRepository thoughtRepository, TopicRepository topicRepository)
 {
     this.repository = repository;
     this.gateway = gateway;
     this.thoughtRepository = thoughtRepository;
     this.topicRepository = topicRepository;
 }
Beispiel #4
0
 public void setup()
 {
     mocks = new MockRepository();
     builder = new TestControllerBuilder();
     session = mocks.DynamicMock<ISession>();
     todoRepository = mocks.StrictMock<TodoRepository>(session);
     todoController = new TodoController(todoRepository);
     builder.InitializeController(todoController);
 }
Beispiel #5
0
        public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, IOptions<AntiforgeryOptions> options, TodoRepository repository)
        {
            app.Use(next => context =>
            {
                if (
                    string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
                {
                    // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
                }

                return next(context);
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.Map("/api/items", a => a.Run(async context =>
            {
                if (string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    var items = repository.GetItems();
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(items));
                }
                else if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    // This will throw if the token is invalid.
                    await antiforgery.ValidateRequestAsync(context);

                    var serializer = new JsonSerializer();
                    using (var reader = new JsonTextReader(new StreamReader(context.Request.Body)))
                    {
                        var item = serializer.Deserialize<TodoItem>(reader);
                        repository.Add(item);
                    }

                    context.Response.StatusCode = 204;
                }
            }));
        }
Beispiel #6
0
 public TodoDeleteHandler(TodoRepository repo)
 {
     this.repo = repo;
 }
 public TodoesController(TodoRepository todoRepository)
 {
     this.todoRepository = todoRepository;
 }
Beispiel #8
0
 public TodoAppSrv(TodoRepository todorep, AssigneeRepository assigneerep)
 {
     this.todorep     = todorep;
     this.assigneerep = assigneerep;
 }
        public static void CreateItem(GameObject itemPrefab, TodoItem item, Transform parent, TodoRepository repository)
        {
            var go = Instantiate(itemPrefab, parent).GetComponent <TodoItemController>();

            go.removeButton.onClick.AddListener(() =>
            {
                repository.RemoveItem(item.Id);
                Destroy(go.gameObject);
            });
            go.textTitle.text = item.Text;
        }
Beispiel #10
0
 public TodoServices(TodoRepository todoRepository)
 {
     _todoRepository = todoRepository;
 }
 public TodoController()
 {
     _repository = new TodoRepository(User);
 }
Beispiel #12
0
 public TomorrowController(ILogger <TomorrowController> logger, TodoDbContext context)
 {
     _logger = logger;
     filter  = new Filter(context);
     db      = new TodoRepository(context);
 }
 public TodoService(TodoRepository todorepository, AssigneeRepository assigneeRepository)
 {
     this.todorepository     = todorepository;
     this.assigneeRepository = assigneeRepository;
 }
Beispiel #14
0
 public TodoController()
 {
     _repository = new TodoRepository(User);
 }
Beispiel #15
0
 public TodoController(TodoRepository todoRepository)
 {
     TodoRepository = todoRepository;
 }
        private ITodoRepository GetRepository(TodoRepoType dbType)
        {
            ITodoRepository db = null;

            switch (dbType) {
                case TodoRepoType.SQL:
                    db = new TodoRepository(@"Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-ITI_Todo-20120914092713;Integrated Security=SSPI");
                    break;
                case TodoRepoType.XML:
                    db = new TodoRepository_XML("Data/Todos.xml");
                    break;
            }

            return db;
        }
        public void AddingNullToDatabaseThrowsException()
        {
            ITodoRepository repository = new TodoRepository();

            repository.Add(null);
        }
        public void UpdatingWithNullArgThrowsException()
        {
            ITodoRepository repository = new TodoRepository();

            repository.Update(null);
        }
        public async Task Can_Create_Update_And_Delete_Todo_Items()
        {
            // Arrange
            var now   = new DateTimeOffset(2018, 08, 12, 10, 41, 0, TimeSpan.Zero);
            var clock = new FakeClock(Instant.FromDateTimeOffset(now));

            var loggerFactory = new LoggerFactory();
            var options       = new SqlLocalDbOptions()
            {
                AutomaticallyDeleteInstanceFiles = true,
                StopOptions = StopInstanceOptions.NoWait,
                StopTimeout = TimeSpan.FromSeconds(1),
            };

            using (var localDB = new SqlLocalDbApi(options, loggerFactory))
            {
                using (TemporarySqlLocalDbInstance instance = localDB.CreateTemporaryInstance(deleteFiles: true))
                {
                    var builder = new DbContextOptionsBuilder <TodoContext>()
                                  .UseSqlServer(instance.ConnectionString);

                    using (var context = new TodoContext(builder.Options))
                    {
                        context.Database.EnsureCreated();
                        context.Database.Migrate();

                        var target = new TodoRepository(clock, context);

                        // Act - Verify the repository is empty
                        IList <TodoItem> items = await target.GetItemsAsync();

                        // Assert
                        Assert.NotNull(items);
                        Assert.Empty(items);

                        // Arrange - Add a new item
                        string text = "Buy cheese";

                        // Act
                        TodoItem item = await target.AddItemAsync(text);

                        // Assert
                        Assert.NotNull(item);
                        Assert.NotEmpty(item.Id);
                        Assert.Equal(text, item.Text);
                        Assert.Equal(now, item.CreatedAt);
                        Assert.Null(item.CompletedAt);

                        // Arrange - Mark the item as completed
                        string id = item.Id;

                        // Act
                        bool?completeResult = await target.CompleteItemAsync(id);

                        // Assert
                        Assert.True(completeResult);

                        // Act - Verify the repository has one item that is completed
                        items = await target.GetItemsAsync();

                        // Assert
                        Assert.NotNull(items);
                        Assert.NotEmpty(items);
                        Assert.Equal(1, items.Count);

                        item = items[0];
                        Assert.NotNull(item);
                        Assert.NotEmpty(item.Id);
                        Assert.Equal(text, item.Text);
                        Assert.Equal(now, item.CreatedAt);
                        Assert.Equal(now, item.CompletedAt);

                        // Act - Delete the item
                        bool deleteResult = await target.DeleteItemAsync(id);

                        // Assert
                        Assert.True(deleteResult);

                        // Act - Verify the repository is empty again
                        items = await target.GetItemsAsync();

                        // Assert
                        Assert.NotNull(items);
                        Assert.Empty(items);
                    }
                }
            }
        }
Beispiel #20
0
 public TodoController(TodoRepository repository)
 {
     this.repository = repository;
 }
 public TodoController(TodoRepository repository)
 {
     _repository = repository;
 }
 public TodoService(TodoRepository todoRepository)
 {
     TodoRepository = todoRepository;
 }
Beispiel #23
0
 public void TestInitialize()
 {
     _todosRepository = new TodoRepository();
 }
        public async Task <IActionResult> PostDayoff([FromBody] LearnerDayoffViewModel inputObj)
        {
            var              result = new Result <object>();
            List <Lesson>    lessons;
            List <Amendment> amendments = new List <Amendment>();
            List <Amendment> exsitsAmendment;
            Learner          learner;
            dynamic          courseSchedules;
            List <Holiday>   holidays;

            try
            {
                lessons = await _ablemusicContext.Lesson.Where(l => l.LearnerId == inputObj.LearnerId && l.IsCanceled != 1 && l.CourseInstanceId.HasValue && inputObj.InstanceIds.Contains(l.CourseInstanceId.Value) &&
                                                               l.BeginTime.Value.Date >= inputObj.BeginDate.Date && l.BeginTime.Value.Date <= inputObj.EndDate.Date).OrderBy(l => l.CourseInstanceId).ToListAsync();

                courseSchedules = await(from i in _ablemusicContext.One2oneCourseInstance
                                        join cs in _ablemusicContext.CourseSchedule on i.CourseInstanceId equals cs.CourseInstanceId
                                        join l in _ablemusicContext.Learner on i.LearnerId equals l.LearnerId
                                        join t in _ablemusicContext.Teacher on i.TeacherId equals t.TeacherId
                                        join c in _ablemusicContext.Course on i.CourseId equals c.CourseId
                                        join o in _ablemusicContext.Org on i.OrgId equals o.OrgId
                                        join r in _ablemusicContext.Room on i.RoomId equals r.RoomId
                                        where inputObj.InstanceIds.Contains(cs.CourseInstanceId.Value)
                                        select new
                {
                    cs.CourseScheduleId,
                    cs.CourseInstanceId,
                    i.OrgId,
                    o.OrgName,
                    i.RoomId,
                    r.RoomName,
                    i.CourseId,
                    c.CourseName,
                    i.TeacherId,
                    TeacherFirstName = t.FirstName,
                    TeacherLastName  = t.LastName,
                    TeacherEmail     = t.Email,
                    cs.DayOfWeek,
                    i.LearnerId,
                    LearnerFirstName = l.FirstName,
                    LearnerLastName  = l.LastName,
                    LearnerEmail     = l.Email,
                }).ToListAsync();
                learner = await _ablemusicContext.Learner.Where(l => l.LearnerId == inputObj.LearnerId).FirstOrDefaultAsync();

                holidays = await _ablemusicContext.Holiday.ToListAsync();

                exsitsAmendment = await _ablemusicContext.Amendment.Where(a => a.LearnerId == inputObj.LearnerId && a.AmendType == 1 &&
                                                                          a.CourseInstanceId.HasValue && inputObj.InstanceIds.Contains(a.CourseInstanceId.Value) &&
                                                                          ((inputObj.BeginDate >= a.BeginDate && inputObj.BeginDate <= a.EndDate) ||
                                                                           (inputObj.EndDate >= a.BeginDate && inputObj.EndDate <= a.EndDate) ||
                                                                           (inputObj.BeginDate <= a.BeginDate && inputObj.EndDate >= a.EndDate))).ToListAsync();
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.ToString();
                return(BadRequest(result));
            }
            if (courseSchedules.Count < 1)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "Course schedule not found";
                return(BadRequest(result));
            }
            if (learner == null)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "Learner not found";
                return(BadRequest(result));
            }
            if (exsitsAmendment.Count > 0)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "There is a conflict of date on your previous dayoff";
                return(BadRequest(result));
            }
            Dictionary <string, int> invoiceNumsMapLessonQuantity = new Dictionary <string, int>();

            foreach (var lesson in lessons)
            {
                if (inputObj.IsInvoiceChange && lesson.InvoiceNum != null)
                {
                    if (!invoiceNumsMapLessonQuantity.ContainsKey(lesson.InvoiceNum))
                    {
                        invoiceNumsMapLessonQuantity.Add(lesson.InvoiceNum, 1);
                    }
                    else
                    {
                        invoiceNumsMapLessonQuantity[lesson.InvoiceNum]++;
                    }
                }
                lesson.IsCanceled = 1;
                lesson.Reason     = inputObj.Reason;
            }

            var invoices = new List <Invoice>();
            var invoiceWaitingConfirms   = new List <InvoiceWaitingConfirm>();
            var invoiceNumMapCoursePrice = new Dictionary <string, decimal>();
            var awaitMakeUpLessons       = new List <AwaitMakeUpLesson>();

            if (inputObj.IsInvoiceChange)
            {
                try
                {
                    invoices = await _ablemusicContext.Invoice.Where(i => i.IsActive == 1 && invoiceNumsMapLessonQuantity.Keys.Contains(i.InvoiceNum)).ToListAsync();

                    invoiceWaitingConfirms = await _ablemusicContext.InvoiceWaitingConfirm.Where(iw => iw.IsActivate == 1 && invoiceNumsMapLessonQuantity.Keys.Contains(iw.InvoiceNum)).ToListAsync();

                    foreach (var i in invoiceWaitingConfirms)
                    {
                        var coursePrice = (await _ablemusicContext.One2oneCourseInstance.Where(oto => oto.CourseInstanceId == i.CourseInstanceId).Include(oto => oto.Course).FirstOrDefaultAsync()).Course.Price;
                        invoiceNumMapCoursePrice.Add(i.InvoiceNum, coursePrice.Value);
                    }
                }
                catch (Exception ex)
                {
                    result.IsSuccess    = false;
                    result.ErrorMessage = ex.Message;
                    return(BadRequest(result));
                }
                if (invoiceWaitingConfirms.Count <= 0 || invoiceWaitingConfirms.Count < invoiceNumsMapLessonQuantity.Count)
                {
                    result.IsSuccess    = false;
                    result.ErrorMessage = "Invoce not found, try to request without apply to invoce";
                    return(BadRequest(result));
                }
                foreach (var i in invoices)
                {
                    if (i.PaidFee > 0)
                    {
                        result.IsSuccess    = false;
                        result.ErrorMessage = "Paid invoce found, try to request without apply to invoce";
                        result.Data         = new List <object>
                        {
                            i
                        };
                        return(BadRequest(result));
                    }
                    else
                    {
                        var fee = invoiceNumMapCoursePrice[i.InvoiceNum] * invoiceNumsMapLessonQuantity[i.InvoiceNum];
                        i.LessonFee      -= fee;
                        i.TotalFee       -= fee;
                        i.OwingFee       -= fee;
                        i.LessonQuantity += invoiceNumsMapLessonQuantity[i.InvoiceNum];
                    }
                }
                foreach (var iw in invoiceWaitingConfirms)
                {
                    if (iw.PaidFee > 0)
                    {
                        result.IsSuccess    = false;
                        result.ErrorMessage = "Paid invoce found, try to request without apply to invoce";
                        result.Data         = new List <object>
                        {
                            iw
                        };
                        return(BadRequest(result));
                    }
                    else
                    {
                        var fee = invoiceNumMapCoursePrice[iw.InvoiceNum] * invoiceNumsMapLessonQuantity[iw.InvoiceNum];
                        iw.LessonFee      -= fee;
                        iw.TotalFee       -= fee;
                        iw.OwingFee       -= fee;
                        iw.LessonQuantity -= invoiceNumsMapLessonQuantity[iw.InvoiceNum];
                    }
                }
            }
            else
            {
                foreach (var l in lessons)
                {
                    awaitMakeUpLessons.Add(new AwaitMakeUpLesson()
                    {
                        CreateAt              = DateTime.UtcNow.ToNZTimezone(),
                        SchduledAt            = null,
                        ExpiredDate           = l.BeginTime.Value.AddMonths(3).Date,
                        MissedLessonId        = l.LessonId,
                        NewLessonId           = null,
                        IsActive              = 1,
                        LearnerId             = l.LearnerId,
                        CourseInstanceId      = l.CourseInstanceId,
                        GroupCourseInstanceId = null,
                    });
                }
            }

            foreach (var cs in courseSchedules)
            {
                if (cs.LearnerId != inputObj.LearnerId)
                {
                    result.IsSuccess    = false;
                    result.ErrorMessage = "InstanceId not match learnerId";
                    return(BadRequest(result));
                }
                Amendment amendment = new Amendment
                {
                    CourseInstanceId = cs.CourseInstanceId,
                    OrgId            = cs.OrgId,
                    DayOfWeek        = cs.DayOfWeek,
                    BeginTime        = null,
                    EndTime          = null,
                    LearnerId        = cs.LearnerId,
                    RoomId           = cs.RoomId,
                    BeginDate        = inputObj.BeginDate,
                    EndDate          = inputObj.EndDate,
                    CreatedAt        = toNZTimezone(DateTime.UtcNow),
                    Reason           = inputObj.Reason,
                    IsTemporary      = null,
                    AmendType        = 1,
                    CourseScheduleId = cs.CourseScheduleId
                };
                amendments.Add(amendment);
            }

            DateTime todoDate = inputObj.EndDate;

            foreach (var holiday in holidays)
            {
                if (holiday.HolidayDate.Date == todoDate.Date)
                {
                    todoDate = todoDate.AddDays(-1);
                }
            }

            DateTime remindScheduledDate = todoDate;

            var teacherIdMapTodoContent    = new Dictionary <short, string>();
            var teacherMapRemindLogContent = new Dictionary <Teacher, string>();

            foreach (var cs in courseSchedules)
            {
                if (!teacherIdMapTodoContent.ContainsKey(cs.TeacherId))
                {
                    teacherIdMapTodoContent.Add(cs.TeacherId, TodoListContentGenerator.DayOffForTeacher(cs, inputObj.EndDate.ToString()));
                }

                teacherMapRemindLogContent.Add(new Teacher
                {
                    TeacherId = cs.TeacherId,
                    Email     = cs.TeacherEmail
                }, RemindLogContentGenerator.DayOffForTeacher(cs, inputObj.EndDate.ToString()));
            }

            using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
            {
                TodoRepository todoRepository = new TodoRepository(_ablemusicContext);
                todoRepository.AddSingleTodoList("Period Dayoff Remind", TodoListContentGenerator.DayOffForLearner(courseSchedules[0],
                                                                                                                   inputObj.EndDate.ToString()), inputObj.UserId, todoDate, null, courseSchedules[0].LearnerId, null);
                todoRepository.AddMutipleTodoLists("Period Dayoff Remind", teacherIdMapTodoContent, inputObj.UserId, todoDate, null, null);
                var saveTodoResult = await todoRepository.SaveTodoListsAsync();

                if (!saveTodoResult.IsSuccess)
                {
                    return(BadRequest(saveTodoResult));
                }

                RemindLogRepository remindLogRepository = new RemindLogRepository(_ablemusicContext);
                remindLogRepository.AddSingleRemindLog(courseSchedules[0].LearnerId, courseSchedules[0].LearnerEmail,
                                                       RemindLogContentGenerator.DayOffForLearner(courseSchedules[0], inputObj.EndDate.ToString()), null, "Period Dayoff Remind", null, remindScheduledDate);
                remindLogRepository.AddMultipleRemindLogs(teacherMapRemindLogContent, null, "Period Dayoff Remind", null, remindScheduledDate);
                var saveRemindLogResult = await remindLogRepository.SaveRemindLogAsync();

                if (!saveRemindLogResult.IsSuccess)
                {
                    return(BadRequest(saveRemindLogResult));
                }

                try
                {
                    foreach (var amendment in amendments)
                    {
                        await _ablemusicContext.Amendment.AddAsync(amendment);
                    }
                    if (!inputObj.IsInvoiceChange)
                    {
                        foreach (var makeUpLesson in awaitMakeUpLessons)
                        {
                            await _ablemusicContext.AwaitMakeUpLesson.AddAsync(makeUpLesson);
                        }
                    }
                    await _ablemusicContext.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    result.IsSuccess    = false;
                    result.ErrorMessage = ex.ToString();
                    return(BadRequest(result));
                }

                string userConfirmUrlPrefix = _configuration.GetSection("UrlPrefix").Value;
                //sending Email
                //List<NotificationEventArgs> notifications = new List<NotificationEventArgs>();
                foreach (var todo in saveTodoResult.Data)
                {
                    var     remind                = saveRemindLogResult.Data.Find(r => r.LearnerId == todo.LearnerId && r.TeacherId == todo.TeacherId);
                    string  currentPersonName     = "";
                    dynamic currentCourseSchedule = null;
                    if (todo.TeacherId == null)
                    {
                        foreach (var cs in courseSchedules)
                        {
                            if (todo.LearnerId == cs.LearnerId)
                            {
                                currentPersonName     = cs.LearnerFirstName + " " + cs.LearnerLastName;
                                currentCourseSchedule = cs;
                            }
                        }
                    }
                    else
                    {
                        foreach (var cs in courseSchedules)
                        {
                            if (todo.TeacherId == cs.TeacherId)
                            {
                                currentPersonName     = cs.TeacherFirstName + " " + cs.TeacherLastName;
                                currentCourseSchedule = cs;
                            }
                        }
                    }
                    string confirmURL  = userConfirmUrlPrefix + todo.ListId + "/" + remind.RemindId;
                    string mailContent = EmailContentGenerator.Dayoff(currentPersonName, currentCourseSchedule, inputObj, confirmURL);
                    remindLogRepository.UpdateContent(remind.RemindId, mailContent);
                    //notifications.Add(new NotificationEventArgs(remind.Email, "Dayoff is expired", mailContent, remind.RemindId));
                }
                var remindLogUpdateContentResult = await remindLogRepository.SaveUpdatedContentAsync();

                if (!remindLogUpdateContentResult.IsSuccess)
                {
                    result.IsSuccess    = false;
                    result.ErrorMessage = remindLogUpdateContentResult.ErrorMessage;
                    return(BadRequest(result));
                }
                //foreach (var mail in notifications)
                //{
                //    _notificationObservable.send(mail);
                //}
                dbContextTransaction.Commit();
            }

            foreach (var amendment in amendments)
            {
                amendment.Learner = null;
            }
            result.Data = new
            {
                EffectedAmendmentCount             = amendments.Count,
                EffectedLessonsCount               = lessons.Count,
                EffectedAwaitMakeUpLessonCount     = awaitMakeUpLessons.Count,
                EffectedInvoiceWaitingConfirmCount = invoiceWaitingConfirms.Count,
                EffectedInvoiceCount               = invoices.Count,
                EffectedAmendments            = amendments,
                EffectedLessons               = lessons,
                EffectedAwaitMakeUpLessons    = awaitMakeUpLessons,
                EffectedInvoiceWaitingConfirm = invoiceWaitingConfirms,
                EffectedInvoices              = invoices,
            };
            return(Ok(result));
        }