public void AddList_returns_list() { var list = new TodoList(); list.Name = "My First List"; var user = new User() {Email = "*****@*****.**", Name = "brian", Password = "******"}; var copied = user.AddList(list); Assert.AreSame(list, copied); }
public void Todoリストを初期化する() { todoList=new TodoList(); todo = new Todo("any_title", "any_detail"); todoList.Add(todo); }
public MainWindow() : base() { this.todoList = new TodoList(); this.Build(); this.edTask.Focus(); }
public void 空のTodoリストを作る() { todoList = new TodoList(); }
public static void Init() { // Get existing open window or if none, make a new one: _window = ( TodoList )EditorWindow.GetWindow (typeof ( TodoList )); _window.titleContent.text = "Todo List"; _window.autoRepaintOnSceneChange = false; }
public void IfIModifySeveralItemsTheWholeLotGetPersistedAtomically() { string userId = string.Empty; String listId = string.Empty; #region Saving the items and keeping the ids around using (var meh = NewSession()) { var user = new User() { DisplayName = "Rob Ashton", EmailAddress = "*****@*****.**", Name = "robashton" }; var list = new TodoList() { Name = "DDD9 todo list", Items = new List<TodoItem>() { new TodoItem(){ Title = "Item #1" } } }; meh.Store(user); meh.Store(list); meh.SaveChanges(); userId = user.Id; listId = list.Id; } #endregion using (var session = NewSession()) { User user = session.Load<User>(userId); TodoList list = session.Load<TodoList>(listId); user.DisplayName = "Doris"; list.Items.Add(new TodoItem() { Title = "Item #2" }); // This saves ALL changes atomically // (YES! A unit of work with a single request) session.SaveChanges(); } using (var session = NewSession()) { User user = session.Load<User>(userId); TodoList list = session.Load<TodoList>(listId); Assert.AreEqual("Doris", user.DisplayName); Assert.AreEqual(2, list.Items.Count); } }
public static void Init () { // Get existing open window or if none, make a new one: _window = ( TodoList )EditorWindow.GetWindow (typeof ( TodoList )); _window.title = "Todo List"; _window.autoRepaintOnSceneChange = false; //EditorStyles.textField.wordWrap = true; //EditorStyles.textArea.wordWrap = true; //EditorStyles.label.wordWrap = true; }
public HttpResponseMessage Post(TodoListInput list) { var entity = new TodoList() { Name = list.Name, Owner = LoadUser() }; _repo.Store(entity); return Request.CreateResponse(HttpStatusCode.OK, new TodoListDisplay() { Name = entity.Name, Id = entity.Id }); }
internal TodoList ToEntity() { var entity = new TodoList() { Id = this.Id, Title = this.Title, CreationDate = DateTime.Now, Todos = this.Todos.Select(todo => todo.ToEntity()).ToList() }; return entity; }
public ActionResult Index() { if (HttpContext.Request.Cookies["todolistapp"] == null) { // save the key of the list for later retrieval TodoList tl = new TodoList(); tl.Key = Helpers.Helpers.GetSHA512Id(); _db.TodoLists.Add(tl); _db.SaveChanges(); HttpCookie appCookie = new HttpCookie("todolistapp"); appCookie.Values["todos"] = tl.Key.ToString(); // appCookie.Expires = DateTime.Now.AddMinutes(5); appCookie.Values["timestamp"] = tl.Timestamp.ToString(); appCookie.Path = "/"; Response.Cookies.Add(appCookie); } return View(); }
private void loadTodoList() { //Dummy if (!(_todoServiceClient.List().Count > 0)) { var tid = _todoServiceClient.Add(new Service.Entity.Todo() { AddedBy = "Amit", Title = "First todo", Text = "this is first todo" }); } var lstTodos = _todoServiceClient.List(); if ((lstTodos != null) && (lstTodos.Count > 0)) { foreach (var item in lstTodos) { TodoList.Add(new TodoViewModel(item)); } } }
private async Task <TodoList> SetListTitleTest(int listId, string title) { // Act string url = "/api/TodoLists/setlisttitle?" + "listId=" + listId + "&title=" + title; var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, url); var response = await _client.SendAsync(request); // Assert response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); TodoList todoList = JsonConvert.DeserializeObject <TodoList>(responseString); Assert.NotNull(todoList); Assert.Equal(title, todoList.Title); return(todoList); }
/// <summary> /// Initiate a new todo list for new user /// </summary> /// <param name="userName"></param> private static void InitiateDatabaseForNewUser(string userName) { TodoItemContext db = new TodoItemContext(); TodoList todoList = new TodoList(); todoList.UserId = userName; todoList.Title = "My Todo List #1"; todoList.Todos = new List <TodoItem>(); db.TodoLists.Add(todoList); db.SaveChanges(); todoList.Todos.Add(new TodoItem() { Title = "Todo item #1", TodoListId = todoList.TodoListId, IsDone = false }); todoList.Todos.Add(new TodoItem() { Title = "Todo item #2", TodoListId = todoList.TodoListId, IsDone = false }); db.SaveChanges(); }
private TodoList GetList(string name) { // Try to pull out a list var list = _todoContext.TodoLists .Where(l => l.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); // If we don't have one yet create it if (list == null) { list = new TodoList { Name = name }; _todoContext.TodoLists.Add(list); _todoContext.SaveChanges(); } return(list); }
public void ShouldAddSingleItem() { var id = 0; TodoItem item = new TodoItem() { ItemType = TodoItemType.Single, Title = "Single item", Completed = false }; TodoList itemList = new TodoList(); itemList.Tasks.Add(item); TodoRepository repository = new TodoRepository(); repository.AddTodos(itemList); var output = repository.DisplayAllItems(); Assert.That(output, Is.EqualTo($"[ ] ({id}) {item.Title}\n")); }
public IHttpActionResult PostList(string title, string description, DateTime dueDate) { try { var newEntry = new TodoList(title, description, dueDate); todo.Add(newEntry); var AddSql = @"INSERT INTO [dbo].[TodoTable] (Title,Description,DueDate) VALUES (@Title,@Description,@DueDate)"; db.Database.ExecuteSqlCommand( AddSql, new SqlParameter("@Title", title), new SqlParameter("@Description", description), new SqlParameter("@DueDate", dueDate)); return(Json(new { newEntry })); } catch (Exception) { return(BadRequest()); } }
public void GetAllFolderByPath(string dirPath, ref List <TodoList> sourceList) { DirectoryInfo currentInfo = new DirectoryInfo(dirPath); DirectoryInfo[] childrenList = currentInfo.GetDirectories(); for (int i = 0; i < childrenList.Length; i++) { string folderName = childrenList[i].Name; bool exclude = false; if (_normalKeyWords == null) { exclude = true; } else { for (int j = 0; j < _normalKeyWords.Count; j++) { if (folderName.Contains(_normalKeyWords[j])) { exclude = true; break; } } } if (exclude) { TodoList temp = new TodoList(); temp.parentPath = dirPath; temp.name = folderName; //temp.extension = childrenList[i].Extension; //temp.path = temp.parentPath + "/" + temp.name + temp.extension; sourceList.Add(temp); } GetAllFolderByPath(childrenList[i].FullName, ref sourceList); } }
public async Task <IActionResult> SetListTitle(int listId, string title) { if (!ModelState.IsValid) { return(BadRequest("Error: Model state is not valid.")); } if (listId < 1) { return(BadRequest("Error: List id cannot be negative.")); } if (title == null || title.Length == 0) { return(BadRequest("Error: Title cannot be empty.")); } var userId = User.GetUserId(); User user = await _context.GetUserById(userId); if (user == null) { return(NotFound("Error: User with this id not found.")); } TodoList todoList = await _context .GetTodoListByListIdAndUserId(listId, userId); if (todoList == null) { return(NotFound("Error: Todo List with this id not found.")); } todoList.Title = title; _context.UpdateTodoList(todoList); return(Ok(todoList)); }
public IActionResult Index(int lid = 0, int tid = 0, string sortBy = "all") { List <TodoList> _list = _listRepository.GetListsByUserID(temp_uid); TodoList current = _list[0]; //sets the current list foreach (TodoList tdl in _list) { if (tdl.ListID == lid) { current = tdl; } } //sets the current task UserTask t; if (tid == 0) { t = new UserTask(); } else { t = _taskRepository.GetTaskByTaskID(tid); } if (sortBy.Equals("complete")) { current.Tasks.RemoveAll(task => task.Status == 1); } if (sortBy.Equals("active")) { current.Tasks.RemoveAll(task => task.Status == 0); } //model that contains all content needed on the dashboard DashboardContent dbc = new DashboardContent(_list, current, t, sortBy); return(View(dbc)); }
public static void PopulateContractDictionary( Dictionary <Type, DataContract> dataContracts) { // fill in dictionaries from pre-initialized data XmlDictionary xmlDict = new XmlDictionary(); TodoList knownContractsTodoList = new TodoList(); for (int i = 0; i < DataContractMap.Length; i++) { int encodedTableIndex = DataContractMap[i].TableIndex; Type type = Type.GetTypeFromHandle(DataContractMap[i].UserCodeType.RuntimeTypeHandle); DataContract decodedContract = DecodeContract(encodedTableIndex, xmlDict, knownContractsTodoList); if (!type.IsRemovedByDR()) { dataContracts.Add(type, decodedContract); } // Silly optimization to mimick previous implementation: If the next entry refers to the same data // contract, let's add that one to the map too without decoding a new DataContract instance. if (((i + 1) < DataContractMap.Length) && (DataContractMap[i + 1].TableIndex == encodedTableIndex)) { Type otherType = Type.GetTypeFromHandle(DataContractMap[i + 1].UserCodeType.RuntimeTypeHandle); if (!otherType.IsRemovedByDR()) { dataContracts.Add(otherType, decodedContract); } i++; } } foreach (KeyValuePair <DataContract, int> entry in knownContractsTodoList) { DataContract contract = entry.Key; int knownDataContractsListIndex = entry.Value; contract.KnownDataContracts = DecodeKnownContractsList(dataContracts, knownDataContractsListIndex); } }
public async Task <IActionResult> Post( [Bind("Name,Priority")] TodoList item) { try { if (ModelState.IsValid) { await _repo.Post(item); if (item == null) { throw new ArgumentNullException(nameof(item)); } } } catch (DbUpdateException ex) { ModelState.AddModelError("", "Unable to save changes. " + ex); } return(View(item)); }
public static void Load() { SetDefault(); #if DEBUG SetDebug(); #endif Tasks = new TodoList(); string fName = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Settings.xml"; if (!File.Exists(fName)) { return; } try { XmlDocument options = new XmlDocument(); AppLog.WriteEvent("Loading config " + fName); options.Load(fName); XmlElement root = options.DocumentElement; XmlElement timetable = root["timetable"]; if (!DateTime.TryParse(timetable.GetAttribute("start"), out startTime)) { AppLog.WriteEvent("Cannot parse " + timetable.GetAttribute("start")); startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 7, 30, 0); } if (!DateTime.TryParse(timetable.GetAttribute("end"), out endTime)) { AppLog.WriteEvent("Cannot parse " + timetable.GetAttribute("end")); endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 19, 0, 0); } AppLog.WriteEvent("End time " + endTime.ToShortTimeString()); } catch (Exception ex) { AppLog.WriteError("Config.Load", ex); } finally { TodayTime = new TimeTable(); } }
public void ChangeTodoList_ModifyTodoItemInTodoList() { TodoList todoList = new TodoList(m_TodoItems, false); int iTodoID = 3; //Find Todo Item by TodoID TodoItem item = todoList.GetItem(iTodoID); //Modify properties of the Todo Item item.Task = "Contact Touron International for Neuron Regeneration"; item.Deadline = new DateTime(2021, 12, 07); item.ItemStatus = TodoModelItemStatus.Modified; //Verify changes by requering Todo Item in mock TodoList repository. TodoItem itemTest = todoList.GetItem(iTodoID); Assert.IsNotNull(itemTest); Assert.AreEqual("Contact Touron International for Neuron Regeneration", itemTest.Task); Assert.AreEqual(new DateTime(2021, 12, 07), item.Deadline); Assert.IsTrue(itemTest.ItemStatus == TodoModelItemStatus.Modified); }
void DataItemDeleted(Guid pk, string type) { if (!Dispatcher.CheckAccess()) // CheckAccess returns true if you're on the dispatcher thread { Dispatcher.Invoke(new DataItemDeletedEventHandler(DataItemDeleted), pk, type); return; } if (type == typeof(Project).ToString()) { Project currentProject = null; foreach (Project project in ProjectList) { if (project.pId == pk) { currentProject = project; break; } } ProjectList.Remove(currentProject); todoViewSource.View.Refresh(); } else if (type == typeof(Todo).ToString()) { Todo currentTodo = null; foreach (Todo todo in TodoList) { if (todo.pId == pk) { currentTodo = todo; break; } } TodoList.Remove(currentTodo); todoViewSource.View.Refresh(); } else { } }
public IHttpActionResult Put(string id, [FromBody] TodoList todoList) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var idx = _todoLists.FindIndex(t => t.Id == id); if (idx == -1) { return(BadRequest("TodoList not found")); } var result = _todoLists.Find(t => t.Id == id); _todoLists.Remove(result); _todoLists.Insert(idx, todoList); return(Ok("Todolist updated")); }
public void GetTaskListTest_ReturnNotFoundList() { #region Arrange User user = new User(1, "Name1", "Email1", "Pass1"); TodoList todoList = null; int listID = 2; Extensions.Extensions.IsUnitTest = true; model = new Mock <IRepository>(); model.Setup(repo => repo.GetUserById(user.Id)).Returns(Task.FromResult(user)); model.Setup(repo => repo.GetTodoListByListIdAndUserId(listID, user.Id)) .Returns(Task.FromResult(todoList)); #endregion // Act controller = new TodoListsController(model.Object); var result = controller.GetTaskList(listID); // Assert var okObjectResult = Assert.IsType <NotFoundObjectResult>(result.Result); }
static async Task RunAsync() { client.BaseAddress = new Uri("http;//localhost:50508/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue("apllication/json")); var todoApi = "api/todo"; var lists = GetTodoListAsync(todoApi); var newList = new TodoList() { Name = "Lista creada desde cliente", Owner = "Mr. Johnson" }; var uri = await CreateTodoListAsync(newList, todoApi); Console.Write(uri); Console.ReadKey(); }
public static TodoListDetailViewmodel Create(TodoList todoList, bool?hideCompletedItems, string orderBy) { var filteredItems = todoList.Items.AsEnumerable(); if (hideCompletedItems == true) { filteredItems = filteredItems.Where(i => !i.IsDone); } if (orderBy == nameof(TodoItem.Rank)) { filteredItems = filteredItems.OrderBy(i => i.Rank ?? int.MaxValue); } else { filteredItems = filteredItems.OrderBy(i => i.Importance); } var items = filteredItems.Select(TodoItemSummaryViewmodelFactory.Create).ToList(); return(new TodoListDetailViewmodel(todoList.TodoListId, todoList.Title, items, hideCompletedItems, orderBy)); }
void Save() { mWaiting.SetActive(true); TodoList todolist = new TodoList(); todolist.Todo = mTodo; AsyncCallback <TodoList> callback = new AsyncCallback <TodoList>( savedTodoList => { mResultMessage = "Success\n\n\"" + savedTodoList.Todo + "\" saved."; mIsSaveFinish = true; }, fault => { mResultMessage = "Error\n\nCode = " + fault.FaultCode + "\nMessage = " + fault.Message; mIsSaveFinish = true; }); Backendless.Persistence.Of <TodoList>().Save(todolist, callback); }
private void DeleteItem_Click(object sender, RoutedEventArgs e) { try { using (TodoList context = new TodoList()) { var button = sender as Button; var myValue = int.Parse(button.Tag.ToString()); var task = context.Tasks.Where(x => x.Id == myValue).FirstOrDefault(); if (task != null) { task.IsDeleted = true; context.SaveChanges(); updateTasks(); } } } catch (Exception ex) { } }
private void ItemCompleted_Unchecked(object sender, RoutedEventArgs e) { try { var button = sender as CheckBox; var myValue = int.Parse(button.Tag.ToString()); using (TodoList context = new TodoList()) { var task = context.Tasks.Where(x => x.Id == myValue).FirstOrDefault(); if (task != null) { task.IsCompleted = false; context.SaveChanges(); updateTasks(); } } } catch (Exception ex) { } }
static void Main(string[] args) { TodoList tdl = new TodoList(); tdl.Add("Invite friends"); tdl.Add("Buy decorations"); tdl.Add("Party"); PasswordManager pm = new PasswordManager("iluvopie", false); tdl.Display(); pm.Display(); //pm.ChangePassword("iluvopie","pieloveme"); //pm.Display(); //tdl.Reset(); //pm.Reset(); //tdl.Display(); //pm.Display(); }
public string RegisterUser(string name, string surname, string username, string password) { try { if (ValidatePassword(password)) { Warning.Text = ""; using (TodoList context = new TodoList()) { if (context.Users.Where(x => x.Username == username).FirstOrDefault() == null) { var user = new User(); user.Name = name; user.Surname = surname; user.Password = Helpers.PasswordHash.Hash(password); user.Username = username; context.Users.Add(user); context.SaveChanges(); return("OK"); } else { return("Username is already occupied"); } } } else { return("Password should be 4 to 8 character & include upper and lower case letter and number"); } } catch (Exception ex) { return("Error occurred"); } }
public async Task AddListAndTaskTest() { var list = new TodoList { Id = Guid.NewGuid().ToString(), Name = "Test", Description = "Test" }; var response = await client.PostAsJsonAsync("api/Todo/lists", list); response.EnsureSuccessStatusCode(); var task = new TodoTask { Id = Guid.NewGuid().ToString(), Name = "Test task", Completed = false }; response = await client.PostAsJsonAsync($"api/Todo/list/{list.Id}/tasks", task); response.EnsureSuccessStatusCode(); response = await client.GetAsync($"api/Todo/list/{list.Id}"); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var addedList = JsonConvert.DeserializeObject <TodoList>(responseString); Assert.AreEqual(list.Id, addedList.Id); Assert.AreEqual(1, addedList.Tasks.Count); var addedTask = addedList.Tasks.First(); Assert.AreEqual(task.Id, addedTask.Id); Assert.AreEqual(task.Name, addedTask.Name); Assert.AreEqual(task.Completed, addedTask.Completed); }
public async Task <IActionResult> Create([Bind("Id,Name")] TodoList todoList) { IdentityUser currentUser = await _userManager.GetUserAsync(User); if (currentUser == null) { return(Challenge()); } if (!ModelState.IsValid) { return(RedirectToAction(nameof(Index))); } bool success = await _aspTodoService.AddListAsync(currentUser, todoList); if (!success) { return(BadRequest("Could not add todolist.")); } return(RedirectToAction("Index")); }
private async void OkButton_Click(object sender, EventArgs e) { TodoList todoList = new TodoList() { Title = TitleTextBox.Text, UserId = "unknown" }; HttpResult <TodoList> result; using (TodoClient todoClient = ClientFactory.CreateTodoClient()) { result = await todoClient.AddTodoListAsync(todoList); } if (result.Succeeded) { this.NavigationService.GoBack(); } else { ErrorDialog.ShowErrors(result.Errors); } }
static async Task RunAsync() { var client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:49959/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("http://localhost:49959/")); var todoApi = "api/todo"; var lists = GetTodoListsAsync(todoApi); var newlist = new TodoList() { Name = "Lista creada desde el cliente", Owner = "Ernesto" }; var uri = await CreateTodoListAsync(newlist, todoApi); Console.WriteLine(uri); Console.ReadKey(); }
public async void CanDeleteAList() { DbContextOptions <TodoDbContext> options = new DbContextOptionsBuilder <TodoDbContext>() .UseInMemoryDatabase("GetTodoListName") .Options; using (TodoDbContext context = new TodoDbContext(options)) { TodoList list = new TodoList(); list.ListTitle = "test"; context.TodoLists.Add(list); context.SaveChanges(); context.TodoLists.Remove(list); context.SaveChanges(); var listContents = await context.TodoLists.ToListAsync(); Assert.DoesNotContain(list, listContents); } }
private void DeleteTodo() { if (SelectedTodo == null) { MessageBox.Show("Please Select Todo for Delete to List!"); return; } using (UnitOfWork uow = new UnitOfWork()) { todoItems = uow.GetRepository <TodoItemModel>().GetAll(x => x.TaskId.Equals(selectedTodo.TaskId)).ToList(); if (todoItems.Count() == 0) { uow.GetRepository <TodoModel>().Delete(SelectedTodo); uow.SaveChanges(); todoList = uow.GetRepository <TodoModel>().GetAll().ToList(); TodoList.Remove(selectedTodo); } else { MessageBox.Show("Linked items not deleted", "Todo deleted", System.Windows.MessageBoxButton.OK, MessageBoxImage.Information); } } }
public async Task <ActionResult <TodoListModel> > Create(TodoListModel model) { try { var todoList = new TodoList { Name = model.Name, OwnerId = 1 // TODO: Set from current user }; await _todoListRepository.CreateAsync(todoList); _logger.LogInformation("Created todo list"); model = _mapper.Map <TodoListModel>(todoList); return(CreatedAtAction("GetList", new { id = model.Id }, model)); } catch (Exception ex) { _logger.LogError(ex, "Error creating todo list"); return(StatusCode(500)); } }
public App() { // The root page of your application MainPage = new TodoList(); }
void Remove(TodoList todolist) { AsyncCallback<long> callback = new AsyncCallback<long>( deletionTime => { mResultMessage = "Success\n\nremoved."; mIsRemoveFinish = true; }, fault => { mResultMessage = "Error\n\nCode = " + fault.FaultCode + "\nMessage = " + fault.Message; mIsRemoveFinish = true; }); Backendless.Persistence.Of<TodoList>().Remove(todolist, callback); }
void Save() { mWaiting.SetActive(true); TodoList todolist = new TodoList(); todolist.Todo = mTodo; AsyncCallback<TodoList> callback = new AsyncCallback<TodoList>( savedTodoList => { mResultMessage = "Success\n\n\"" + savedTodoList.Todo + "\" saved."; mIsSaveFinish = true; }, fault => { mResultMessage = "Error\n\nCode = " + fault.FaultCode + "\nMessage = " + fault.Message; mIsSaveFinish = true; }); Backendless.Persistence.Of<TodoList>().Save(todolist, callback); }
/// <summary> /// Initiate a new todo list for new user /// </summary> /// <param name="userName"></param> private static void InitiateDatabaseForNewUser(string userName) { TodoItemContext db = new TodoItemContext(); TodoList todoList = new TodoList(); todoList.UserId = userName; todoList.Title = "My Todo List #1"; todoList.Todos = new List<TodoItem>(); db.TodoLists.Add(todoList); db.SaveChanges(); todoList.Todos.Add(new TodoItem() { Title = "Todo item #1", TodoListId = todoList.TodoListId, IsDone = false }); todoList.Todos.Add(new TodoItem() { Title = "Todo item #2", TodoListId = todoList.TodoListId, IsDone = false }); db.SaveChanges(); }