示例#1
0
        public async Task <ActionResult> SaveFullEditChanges(EditCollaboratorViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = await UserManager.FindByEmailAsync(model.Email);

                bool error = false;

                if (!string.IsNullOrEmpty(model.NewPassword))
                {
                    var result = UserManager.ChangePassword(user.Id, model.Password, model.NewPassword);

                    if (!result.Succeeded)
                    {
                        ModelState["Password"].Errors.Add("Senha incorreta");
                        error = true;
                    }
                }

                if (!error)
                {
                    user = await UserManager.FindByEmailAsync(model.Email);

                    Collaborator collaborator = model.ToCollaborator(user.PasswordHash);

                    BusinessManager.Instance.Collaborators.Update(collaborator);

                    return(RedirectToAction("Index", "LocalAdmin"));
                }
            }

            return(View("FullEdit", model));
        }
示例#2
0
        public ActionResult RemoveLeave(int id)
        {
            //------------Background identity check-------------//
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return(Redirect("/Home/Index"));
            }

            Collaborator coll = dal.GetCollaborator(System.Web.HttpContext.Current.User.Identity.Name);
            //--------------------------------------------------//

            Leave currentLeave = dal.GetLeave(id);

            // Transfer the leave days into the collab's available days
            if (currentLeave.Type == LeaveType.RTT)
            {
                coll.NbRTT = currentLeave.ComputeLengthLeave();
            }
            else if (currentLeave.Type == LeaveType.PAID)
            {
                coll.NbPaid = currentLeave.ComputeLengthLeave();
            }


            // Remove the ER
            dal.GetLeave(id).Status = LeaveStatus.CANCELED;

            dal.SaveChanges();

            return(Redirect("/Leave/Index"));
        }
        public async Task 異常系_共同編集者以外が記事を更新()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);

            draft.Title = "共同編集テスト_共同編集者以外が記事を更新";
            draft.Body  = "共同編集テスト_共同編集者以外が記事を更新";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);

            var collaborator1 = new Collaborator(_collaborator1)
            {
                Role = RoleType.Owner
            };
            var collaborator2 = new Collaborator(_collaborator2)
            {
                Role = RoleType.Member
            };
            var collaborator3 = new Collaborator(_collaborator3)
            {
                Role = RoleType.Member
            };
            var collaborators = new[] { collaborator1, collaborator2 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            try
            {
                var newDraft = item.ToDraft(collaborator3);
            }
            catch (Exception exception)
            {
                Assert.AreEqual(exception.GetType(), typeof(NotEntitledToEditItemException));
            }
        }
        public ActionResult CreateAccount(Collaborator model /*, int collId*/)
        {
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return(Redirect("/Home/Index"));
            }

            // Check admin privilege
            Collaborator coll = dal.GetCollaborator(System.Web.HttpContext.Current.User.Identity.Name);

            if (!HelperModel.CheckAdmin(coll))
            {
                return(Redirect("/Home/Index"));
            }

            // Validation
            if (ModelState.IsValid && ValidationLogin(model))
            {
                dal.CreateCollaborator(model.FirstName, model.LastName, model.Login, dal.EncodeMD5(model.Password));
                return(Redirect("/Admin/Index"));
            }
            else
            {
                ModelState.AddModelError("", "Le champ nom de compte doit être unique !");
            }
            return(View(model));
        }
        public async Task 正常系_共同編集者のロールを変更()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);

            draft.Title = "共同編集テスト_共同編集者のロールを変更";
            draft.Body  = "共同編集テスト_共同編集者のロールを変更";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);

            var collaborator1 = new Collaborator(_collaborator1)
            {
                Role = RoleType.Member
            };
            var collaborator2 = new Collaborator(_collaborator2)
            {
                Role = RoleType.Member
            };
            var collaborator3 = new Collaborator(_collaborator3)
            {
                Role = RoleType.Member
            };
            var collaborators = new[] { collaborator1, collaborator2, collaborator3 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            collaborator1.Role = RoleType.Owner;
            await ItemDbCommand.SaveCollaboratorsAsync(item);

            var savedItem = await ItemDbCommand.FindAsync(item.Id);

            item.IsStructuralEqual(savedItem);

            savedItem.Collaborators.ToArray().IsStructuralEqual(new[] { collaborator1, collaborator2, collaborator3 });
        }
        public static CollaboratorDto Convert(Collaborator collaborator)
        {
            var posts = new List <PostDto>();

            if (collaborator.PostCollaborator != null)
            {
                foreach (var pc in collaborator.PostCollaborator)
                {
                    pc.Post.PostTag          = null;
                    pc.Post.PostCollaborator = null;
                    pc.Post.PostCategory     = null;
                    posts.Add(PostConverter.Convert(pc.Post));
                }
            }

            return(new CollaboratorDto
            {
                Id = collaborator.Id,
                Name = collaborator.Name,
                Date = collaborator.Date,
                Role = collaborator.Role,
                Description = collaborator.Description,
                Links = collaborator.Links,
                Posts = posts
            });
        }
示例#7
0
        /// <summary></summary>
        /// <param name="item"></param>
        /// <param name="collaborator"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RemoveCollaboratorAsync(Item item, Collaborator collaborator, CancellationToken cancellationToken)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (collaborator == null)
            {
                throw new ArgumentNullException("collaborator");
            }
            if (!item.Collaborators.Contains(collaborator))
            {
                throw new InvalidOperationException("target user is not included in collaborators.");
            }

            const string delete = @"
DELETE FROM [dbo].[Collaborators]
WHERE
    [ItemId] = @ItemId
AND [UserId] = @UserId
";

            using (var cn = CreateConnection())
            {
                await cn.OpenAsync(cancellationToken).ConfigureAwait(false);

                await
                cn.ExecuteAsync(delete, new { ItemId = item.Id, UserId = collaborator.Id })
                .ConfigureAwait(false);
            }

            item.RemoveCollaborator(collaborator);
        }
示例#8
0
        private async void Button_OnClicked(object sender, EventArgs e)
        {
            var scannerPage = new ZXingScannerPage();
            await Navigation.PushAsync(scannerPage);

            scannerPage.OnScanResult += (result) =>
            {
                scannerPage.IsScanning = false;
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Navigation.PopAsync();

                    char[] splitChar          = { '/' };
                    split                     = result.Text.Split(splitChar);
                    Collaborator chosenCollab = FindCollaborator(await App.Database.GetCollaboratorAsync());

                    if (chosenCollab != null)
                    {
                        await Navigation.PushAsync(new ItemPage
                        {
                            BindingContext = chosenCollab as Collaborator
                        });
                    }
                    else
                    {
                        await DisplayAlert("Invalid QR Code", "Invalid QR Code - Please try again", "OK");
                    }
                });
            };
        }
示例#9
0
        private async void ScanningPage()
        {
            var scannerPage = new ZXingScannerPage();
            await Navigation.PushAsync(scannerPage);

            List <Collaborator> list = await App.Database.GetCollaboratorAsync();

            scannerPage.OnScanResult += (result) =>
            {
                scannerPage.IsScanning = false;
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Navigation.PopAsync();
                    //  await DisplayAlert("Scanned Detail", result.Text, "OK");
                    char[] splitChar          = { '/' };
                    split                     = result.Text.Split(splitChar);
                    Collaborator chosenCollab = FindCollaborator(list);

                    if (chosenCollab != null)
                    {
                        await Navigation.PushAsync(new ItemPage
                        {
                            BindingContext = chosenCollab as Collaborator
                        });
                    }
                    else
                    {
                        await DisplayAlert("Invalid QR Code", "Invalid QR Code - Please try again", "OK");
                    }
                });
            };
        }
        public void DeleteCollaborator(int Id)
        {
            Collaborator collaborator = GetCollaborator(Id);

            _context.Collaborators.Remove(collaborator);
            _context.SaveChanges();
        }
示例#11
0
        public async Task <Response> SignIn(CollaboratorViewModel model)
        {
            try
            {
                Collaborator _collaborator = null;
                if (!string.IsNullOrEmpty(model.Email))
                {
                    _collaborator = await this._repository.GetByEmail(model.Email);
                }

                if (_collaborator != null)
                {
                    bool authorized = Crypto.ComparePassword(model.Password, new Encoded(_collaborator.Password));

                    if (authorized)
                    {
                        var _model = this._mapper.Map <CollaboratorViewModel>(_collaborator);
                        var _auth  = new Auth <CollaboratorViewModel>(Jwt.CreateToken(model.Email), _model);
                        return(Ok(_auth, HttpMessage.Login_Authorized));
                    }
                    else
                    {
                        return(Unauthorized("A conta informada é inválida!"));
                    }
                }
                else
                {
                    return(Unauthorized("A conta informada é inválida!"));
                }
            }
            catch (Exception except)
            {
                return(await InternalServerError(except.Message));
            }
        }
示例#12
0
        public Task <IEnumerable <Notification> > GetNotifications()
        {
            int.TryParse(System.Web.HttpContext.Current.User.Identity.Name, out int collId);
            Collaborator loggedUser = _notificationsTicker.GetCollaborator(collId);

            return(Task.Run(() => _notificationsTicker.GetNotifications(loggedUser)));
        }
示例#13
0
        public async Task <Response> Update(CollaboratorViewModel model)
        {
            try
            {
                Encoded _encoded = !string.IsNullOrEmpty(model.Password) ? Crypto.EncryptPassword(model.Password) : null;
                var     _entity  = new Collaborator(model);
                _entity.SetActive(true);
                _entity.SetUpdatedAt(DateTime.UtcNow.AddHours(-3));

                if (_encoded != null)
                {
                    _entity.SetPassword(_encoded.Encrypted);
                }

                if (_entity.IsValid())
                {
                    return(Ok(await this._repository.Update(_entity), HttpMessage.Updated_Successfully));
                }
                else
                {
                    return(BadRequest(_entity.GetValidationResults()));
                }
            }
            catch (Exception except)
            {
                return(await InternalServerError(except.Message));
            }
        }
        public void Delete(int id)
        {
            Collaborator collaborator = GetCollaborator(id);

            _database.Remove(collaborator);
            _database.SaveChanges();
        }
示例#15
0
 /// <summary>
 /// Adds the collaborators to notes.
 /// </summary>
 /// <param name="collaborator">The collaborator.</param>
 /// <returns></returns>
 /// <exception cref="Exception"></exception>
 public CollbratorModel AddCollaboratorToNotes(CollbratorResponse collaborator, long UserId, long NoteId)
 {
     try
     {
         bool result = this.collbratorcontext.Notes.Any(option => option.UserId == UserId && option.NoteId == NoteId);
         if (result)
         {
             Collaborator addCollaborator = new Collaborator()
             {
                 CollaboratorEmail = collaborator.CollaboratorEmail,
             };
             this.collbratorcontext.Collaborators.Add(addCollaborator);
         }
         this.collbratorcontext.SaveChangesAsync();
         var             col         = collbratorcontext.Collaborators.FirstOrDefault(N => N.NoteId == NoteId && N.UserId == UserId);
         CollbratorModel collbrator1 = new CollbratorModel
         {
             CollaboratorId    = col.CollaboratorId,
             CollaboratorEmail = col.CollaboratorEmail,
             NoteId            = NoteId,
             UserId            = UserId,
         };
         return(collbrator1);
     }
     catch (Exception exception)
     {
         throw new Exception(exception.Message);
     }
 }
示例#16
0
        public IComandResult Handle(UpdateCollaboratorComand comand)
        {
            var name     = new Name(comand.FirstName, comand.LastName);
            var document = new Document(comand.Document);
            var email    = new Email(comand.Email);
            var address  = new Address(comand.Street, comand.Number, comand.District, comand.City, comand.Country, comand.ZipCode);
            var idAdd    = _collaboratorRepository.Get(comand.Id).IdAddress;

            address.Id = idAdd;
            var phone        = new Phone(comand.Phone);
            var collaborator = new Collaborator(name, document, email, phone, address, comand.Salary, comand.ProjectName, comand.BirthDate, comand.JobTitle)
            {
                Id = comand.Id
            };

            AddNotifications(collaborator);
            AddNotifications(name);
            AddNotifications(document);
            AddNotifications(email);
            AddNotifications(address);
            AddNotifications(phone);
            if (IsInvalid())
            {
                return(null);
            }

            _collaboratorRepository.Update(collaborator);

            return(new CreateCollaboratorCommandResult(collaborator.Id, name.ToString(), email.Address));
        }
示例#17
0
    public void UpdatePlayRound()
    {
        gameController.PrintField(PlayField);
        this.CheckLevelCompleted();

        // Methode aanroep staat hier, omdat deze methode elke keer wordt aangeroepen als er een zet gedaan is.
        // Vervolgens wordt Collaborator aangeroepen en deze gaat bereken of de medewerker slaapt, wakker is of wakker gemaakt moet worden
        if (CollaboratorActive)
        {
            if (Collaborator.CalculateAwake())
            {
                int rand = new Random().Next(1, 5);

                switch (rand)
                {
                case 1:
                    Collaborator.MoveDown(PlayField);
                    break;

                case 2:
                    Collaborator.MoveLeft(PlayField);
                    break;

                case 3:
                    Collaborator.MoveUp(PlayField);
                    break;

                case 4:
                    Collaborator.MoveRight(PlayField);
                    break;
                }
            }
        }
    }
示例#18
0
        public IComandResult Handle(CreateCollaboratorComand comand)
        {
            if (_collaboratorRepository.CheckDocument(comand.Document))
            {
                AddNotification("Document", "Esse documento já está cadastrado");
            }

            if (_collaboratorRepository.CheckEmail(comand.Email))
            {
                AddNotification("Email", "Esse email já está cadastrado");
            }

            var name         = new Name(comand.FirstName, comand.LastName);
            var document     = new Document(comand.Document);
            var email        = new Email(comand.Email);
            var address      = new Address(comand.Street, comand.Number, comand.District, comand.City, comand.Country, comand.ZipCode);
            var phone        = new Phone(comand.Phone);
            var collaborator = new Collaborator(name, document, email, phone, address, comand.Salary, comand.ProjectName, comand.BirthDate, comand.JobTitle);

            AddNotifications(collaborator);
            AddNotifications(name);
            AddNotifications(document);
            AddNotifications(email);
            AddNotifications(address);
            AddNotifications(phone);

            if (IsInvalid())
            {
                return(null);
            }

            _collaboratorRepository.Save(collaborator);

            return(new CreateCollaboratorCommandResult(collaborator.Id, name.ToString(), email.Address));
        }
        public async Task FindWithUserAndCollaboratorsAsyncTest_IsPublic_False(
            [ProjectDataSource] Project project,
            [UserDataSource] User user,
            [CollaboratorDataSource] Collaborator collaborator)
        {
            user.IsPublic = false;
            project.User  = user;
            project.Collaborators.Add(collaborator);
            // Seeding
            DbContext.Add(user);
            DbContext.Add(collaborator);
            DbContext.Add(project);

            await DbContext.SaveChangesAsync();

            // Testing
            Project retrieved = await Repository.FindWithUserAndCollaboratorsAsync(project.Id);

            Assert.AreEqual(project.Id, retrieved.Id);
            Assert.AreEqual(project.Name, retrieved.Name);
            Assert.AreEqual(project.ShortDescription, retrieved.ShortDescription);
            Assert.AreEqual(project.Description, retrieved.Description);
            Assert.AreEqual(project.Uri, retrieved.Uri);
            Assert.AreEqual(project.User.Name, retrieved.User.Name);
            Assert.AreEqual(project.User.Email, Defaults.Privacy.RedactedEmail);
            Assert.AreEqual(project.Collaborators[0].FullName, retrieved.Collaborators[0].FullName);
        }
示例#20
0
    private void DoMove(Dictionary <string, Square> PlayField, string newSquareID, string squareNextToNewSquareID)
    {
        Square toMoveSquare; // represents the square the player wants to stand on

        PlayField.TryGetValue(newSquareID, out toMoveSquare);
        Square nextSquare = null; // represent the next square from toMoveSquare, necessary for moving a movable

        if (!toMoveSquare.Available)
        {
            return; // return without moving
        }
        else if (toMoveSquare.MovableObject is Collaborator)
        {
            Collaborator c = (Collaborator)toMoveSquare.MovableObject;
            c.Touched = true;
            return; // return without moving
        }

        if (toMoveSquare.MovableObject != null) // if the square contains a movableObject / is available
        {
            // find out whether the next square the movable has to move to is available
            PlayField.TryGetValue(squareNextToNewSquareID, out nextSquare);
            if (!nextSquare.Available || nextSquare.MovableObject != null)
            {
                return; // return without moving
            }
            else // move movable
            {
                toMoveSquare.MovableObject.Replace(toMoveSquare, nextSquare); // move the movable
            }
        }
        this.Replace(this.Square, toMoveSquare); // move spike
    }
示例#21
0
        public async Task <IActionResult> Create([FromBody] Collaborator item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            var userId              = _userManager.GetUserId(HttpContext.User);
            var collaborator        = _collaboratorRepository.Find(item.ProjectID, item.UserID);
            var currentCollaborator = _collaboratorRepository.Find(item.ProjectID, userId);

            if (currentCollaborator == null || currentCollaborator.Permission != Permissions.Owner)
            {
                return(new UnauthorizedResult());
            }
            else if (collaborator != null)
            {
                return(CreatedAtRoute("GetCollaborator", new { id = collaborator.Id }, collaborator));
            }

            _collaboratorRepository.Add(item);
            // Broadcast new collaborator
            var project = _projectRepository.Find(item.ProjectID);
            await _projAndCollabHandler.Add(project.Id);

            var newCollaborator = _collaboratorRepository.Find(item.Id);

            return(CreatedAtAction("GetCollaborator", new { id = item.Id }, newCollaborator));
        }
示例#22
0
        public async Task <IActionResult> Update(long id, [FromBody] Collaborator item)
        {
            if (item == null || item.Id != id)
            {
                return(BadRequest());
            }

            var userId = _userManager.GetUserId(HttpContext.User);
            var currentCollaborator = _collaboratorRepository.Find(item.ProjectID, userId);

            if (currentCollaborator == null || currentCollaborator.Permission != Permissions.Owner)
            {
                return(Unauthorized());
            }

            if (!_projectRepository.UserHasAccess(item.ProjectID, userId))
            {
                return(Unauthorized());
            }

            var collaborator = _collaboratorRepository.Find(id);

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

            collaborator.Permission = item.Permission;
            _collaboratorRepository.Update(collaborator);
            // Broadcast new collaborator
            var project = _projectRepository.Find(collaborator.ProjectID);
            await _projAndCollabHandler.Add(project.Id);

            return(NoContent());
        }
示例#23
0
        // GET: Notification
        public ActionResult Index()
        {
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return(Redirect("/Home/Index"));
            }

            Collaborator            coll  = dal.GetCollaborator(System.Web.HttpContext.Current.User.Identity.Name);
            NotificationSelectionVM model = new NotificationSelectionVM();

            foreach (Notification n in dal.GetNotifications(coll))
            {
                SelectNotificationEditorVM notifVM = new SelectNotificationEditorVM()
                {
                    Id           = n.Id,
                    NotifType    = n.NotifType,
                    NotifStatus  = (n.NotifStatus == NotificationStatus.UNREAD ? "unread" : "read"),
                    NotifResult  = n.NotifResult.ToString(),
                    NotifContent = n.NotifContent,
                    Selected     = false
                };
                model.Notifications.Insert(0, notifVM);
            }

            return(View(model));
        }
示例#24
0
        public ActionResult MarkAsRead(NotificationSelectionVM model)
        {
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return(Redirect("/Home/Index"));
            }

            // get the ids of the items selected:
            var selectedIds = model.GetSelectedIds();

            // Use the ids to retrieve the records for the selected notification
            // from the database:
            Collaborator coll = dal.GetCollaborator(System.Web.HttpContext.Current.User.Identity.Name);
            var          selectedNotification = from x in dal.GetNotifications(coll)
                                                where selectedIds.Contains(x.Id)
                                                select x;

            // Process
            foreach (Notification notif in selectedNotification)
            {
                notif.NotifStatus = NotificationStatus.READ;
            }

            dal.SaveChanges();

            // Redirect the results:
            return(RedirectToAction("Index"));
        }
示例#25
0
 public IActionResult AddCollaborator([FromBody] Collaborator collaboratorModel)
 {
     try
     {
         var AccountId = Convert.ToInt32(HttpContext.Items["userId"]);
         collaboratorModel.SenderEmail = Convert.ToString(HttpContext.Items["email"]);
         Collaborator collaborator = _collaboratorService.AddCollaborator(AccountId, collaboratorModel.SenderEmail, collaboratorModel);
         if (collaborator == null)
         {
             return(NotFound(new ServiceResponse <Collaborator> {
                 StatusCode = (int)HttpStatusCode.NotFound, Message = "Internal Server Error", Data = null
             }));
         }
         _msmq.AddToQueue(collaboratorModel.RecieverEmail + " " + "Collaborated Successfully by" + collaboratorModel.SenderEmail + "  " + System.DateTime.Now.ToString());
         return(Ok(new ServiceResponse <Collaborator> {
             StatusCode = (int)HttpStatusCode.OK, Message = "Added Successfully", Data = collaborator
         }));
     }
     catch (Exception)
     {
         return(BadRequest(new ServiceResponse <Collaborator> {
             StatusCode = (int)HttpStatusCode.BadRequest, Message = "Page Not Found", Data = null
         }));
     }
 }
示例#26
0
        public Leave(LeaveStatus status, LeaveType type, Collaborator collaborator, DateTime startDate, DateTime endDate, string Start, string End)
        {
            Description             = collaborator.FirstName + " " + collaborator.LastName + " (" + collaborator.Service.Name + ")"; //generer un nom du type "NomPrenom (Service) - nbDemiJournées"
            Status                  = status;
            Type                    = type;
            Collaborator            = collaborator;
            StartDate               = startDate;
            EndDate                 = endDate;
            StartMorningOrAfternoon = Start;
            EndMorningOrAfternoon   = End;

            Treatment = HelperModel.ComputeTreatmentLeave(Collaborator);

            if (status == LeaveStatus.APPROVED)
            {
                this.Color = "#256cbf";
            }
            else if (status == LeaveStatus.PENDING_APPROVAL_1)
            {
                this.Color = "#c69b00";
            }
            else if (status == LeaveStatus.PENDING_APPROVAL_2)
            {
                this.Color = "#c68b90";
            }
            else
            {
                this.Color = "#bf4425";
            }
        }
示例#27
0
        public Collaborator AddCollaborator(int AccountId, string EmailId, Collaborator collaboratorModel)
        {
            var result = _context.Collaborator.Add(collaboratorModel);

            _context.SaveChanges();
            return(result.Entity);
        }
 public void Update(Collaborator collaborator)
 {
     _context.Entry <Address>(collaborator.Address).State = EntityState.Modified;
     _context.SaveChanges();
     _context.Entry <Collaborator>(collaborator).State = EntityState.Modified;
     _context.SaveChanges();
 }
示例#29
0
        public async Task <CollaboratorResponseDto> AddCollaborator(string email, int userId, CollaboratorRequestDto collaborator)
        {
            try
            {
                Collaborator modelCollaborator = _mapper.Map <Collaborator>(collaborator);
                if (email == modelCollaborator.email)
                {
                    throw new FundooException(ExceptionMessages.SELF_COLLABORATE);
                }
                Collaborator collaboratorWithSameUser = await _collaboratorRepository.GetCollaboratorByEmail(modelCollaborator.email, modelCollaborator.NoteId);

                if (collaboratorWithSameUser != null)
                {
                    throw new FundooException(ExceptionMessages.ALREADY_COLLABORATER);
                }
                Note note = await _noteRepository.GetNote(modelCollaborator.NoteId, userId);

                if (note == null)
                {
                    throw new FundooException(ExceptionMessages.NO_SUCH_NOTE);
                }
                Message message = new EmailService.Message(new string[] { modelCollaborator.email },
                                                           "Added as collaborator",
                                                           $"<h2>You have been added as collaborated by <p style='color:red'>" + email + "</p> To note <p style='color:green'>" + note.Title + "</p><h2>");
                _mqServices.AddToQueue(message);
                return(_mapper.Map <CollaboratorResponseDto>(await _collaboratorRepository.AddCollaborator(email, modelCollaborator)));
            }
            catch (Microsoft.EntityFrameworkCore.DbUpdateException)
            {
                throw new FundooException(ExceptionMessages.NO_SUCH_USER);
            }
        }
示例#30
0
        public async Task <IActionResult> PutCollaborator(long id, Collaborator collaborator)
        {
            if (id != collaborator.TodosListId)
            {
                return(BadRequest());
            }

            _context.Entry(collaborator).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CollaboratorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#31
0
 /// <summary></summary>
 /// <param name="item"></param>
 /// <param name="collaborator"></param>
 /// <returns></returns>
 public Task RemoveCollaboratorAsync(Item item, Collaborator collaborator)
 {
     return RemoveCollaboratorAsync(item, collaborator, CancellationToken.None);
 }
 public static string GetTarget_AccountID(Collaborator collaborator)
 {
     return collaborator.AccountID;
 }
示例#33
0
        /// <summary>記事の共同編集者を更新します。</summary>
        /// <param name="item">共同編集者を更新する記事</param>
        /// <param name="collaborators">共同編集者</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>        
        public async Task SaveCollaboratorsAsync(Item item, Collaborator[] collaborators, CancellationToken cancellationToken)
        {
            if (item == null) throw new ArgumentNullException("item");
            if (collaborators == null) throw new ArgumentNullException("collaborators");

            const string delete = @"
DELETE FROM [dbo].[Collaborators]
WHERE [ItemId] = @ItemId
";

            const string insert = @"
INSERT INTO [dbo].[Collaborators] (
    [ItemId],
    [UserId],
    [RoleType]
) VALUES (
    @ItemId,
    @UserId,
    @RoleType
)
";
            using (var cn = CreateConnection())
            {
                await cn.OpenAsync(cancellationToken).ConfigureAwait(false);

                using (var tr = cn.BeginTransaction())
                {
                    try
                    {
                        await cn.ExecuteAsync(delete, new {ItemId = item.Id}, tr).ConfigureAwait(false);

                        foreach (var collaborator in collaborators)
                        {
                            await
                                cn.ExecuteAsync(insert, new { ItemId = item.Id, UserId = collaborator.Id, RoleType = collaborator.Role }, tr)
                                    .ConfigureAwait(false);
                        }

                        tr.Commit();

                        item.ClearAllCollaborators();
                        foreach (var collaborator in collaborators)
                        {
                            item.AddCollaborator(collaborator);
                        }
                    }
                    catch
                    {
                        tr.Rollback();
                        throw;
                    }
                }
            }
        }
示例#34
0
        /// <summary></summary>
        /// <param name="item"></param>
        /// <param name="collaborator"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RemoveCollaboratorAsync(Item item, Collaborator collaborator, CancellationToken cancellationToken)
        {
            if (item == null) throw new ArgumentNullException("item");
            if (collaborator == null) throw new ArgumentNullException("collaborator");
            if (!item.Collaborators.Contains(collaborator)) throw new InvalidOperationException("target user is not included in collaborators.");

            const string delete = @"
DELETE FROM [dbo].[Collaborators]
WHERE
    [ItemId] = @ItemId
AND [UserId] = @UserId
";
            using (var cn = CreateConnection())
            {
                await cn.OpenAsync(cancellationToken).ConfigureAwait(false);

                await
                    cn.ExecuteAsync(delete, new { ItemId = item.Id, UserId = collaborator.Id })
                        .ConfigureAwait(false);
            }

            item.RemoveCollaborator(collaborator);
        }
示例#35
0
        static void Main()
        {
            try
            {
                //Request Bearer Access Token
                Console.Write("\nEnter Smartsheet API access token\n");
                string token = Console.ReadLine();
                string baseURL = "https://api.smartsheet.com/1.1/sheet";

                //Create GET web request that will list available sheets
                WebRequest getRequest = WebRequest.Create(baseURL + "s");
                getRequest.ContentType = "application/json; charset=utf-8";
                getRequest.Method = "GET";
                getRequest.Headers.Add("Authorization: Bearer " + token);

                //Capture json web response using StreamReader
                Stream dataStream = getRequest.GetResponse().GetResponseStream();
                StreamReader objReader = new StreamReader(dataStream);

                //Deserialize data stream to dynamic object so we can work with the data
                JavaScriptSerializer js = new JavaScriptSerializer();
                var sheetList = js.Deserialize<dynamic>(objReader.ReadToEnd());
                Console.Write("\nFetching your list of sheets...\n");

                //If the dynamic object is empty, the user doesn't have any sheets
                //They can either close the program or try again.
                if (sheetList.Length == 0)
                {
                    Console.Write("\nYou don't have any sheets.\nPress Esc to close or Enter to restart.");
                    HelloSmartsheet.exitRestart();
                }

                //If the user has sheets, iterate through and display the first 5 available sheets
                else
                {
                    Console.WriteLine("\nTotal sheets: " + sheetList.Length + "\nShowing the first five sheets:\n");
                    for (int i=0; i<sheetList.Length&i<5;i++)
                    {
                        Console.Write((i + 1).ToString() + ": " + sheetList[i]["name"] + "\n");
                    }
                    Console.Write("\nEnter the number of the sheet you want to share:\n");
                }

                //Grab sheet ID based on user selection
                int id = int.Parse(Console.ReadLine()) - 1;

                //User inputs email address and access level of collaborator
                Console.Write("\nEnter an email address to share " + sheetList[id]["name"] + " to:\n");
                string email = Console.ReadLine();

                Console.Write("\nChoose an access level (ADMIN, EDITOR, EDITOR_SHARE or VIEWER) for " + email + "\n");
                string accessLevel = Console.ReadLine();

                Console.Write("\nSharing " + sheetList[id]["name"] + " to " + email + " as " + accessLevel + "...\n");

                //Create Collaborator object based on user input, convert to JSON string
                Collaborator collab = new Collaborator { email = email, accessLevel = accessLevel };
                string json = js.Serialize(collab);

                //Create POST webrequest that shares sheet
                WebRequest postRequest = WebRequest.Create(baseURL + "/" + sheetList[id]["id"].ToString() + "/shares?sendemail=false");
                postRequest.ContentType = "application/json; charset=utf-8";
                postRequest.Method = "POST";
                postRequest.Headers.Add("Authorization: Bearer " + token);

                using (var streamWriter = new StreamWriter(postRequest.GetRequestStream()))
                {
                    streamWriter.Write(json);
                }

                //Get response, display confirmation and share ID to user
                Stream responseStream = postRequest.GetResponse().GetResponseStream();
                StreamReader readStream = new StreamReader(responseStream);
                var jsonResponse = js.Deserialize<dynamic>(readStream.ReadToEnd());
                Console.Write("\nSheet shared successfully! Share ID " + jsonResponse["result"]["id"] + "\nPress Esc to close or Enter to restart\n");
                HelloSmartsheet.exitRestart();
            }

            //Displays error message in console if request is not successful
            catch (Exception e)
            {
                Console.Write("\n" + e.Message + "\n" + "Press Esc to close or Enter to resart\n");
                HelloSmartsheet.exitRestart();
            }
        }
示例#36
0
        /// <summary></summary>
        /// <param name="item"></param>
        /// <param name="collaborator"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task AddCollaboratorAsync(Item item, Collaborator collaborator, CancellationToken cancellationToken)
        {
            if (item == null) throw new ArgumentNullException("item");
            if (collaborator == null) throw new ArgumentNullException("collaborator");
            if (item.Collaborators.Contains(collaborator)) throw new InvalidOperationException("target user is already included in collaborators.");

            const string insert = @"
INSERT INTO [dbo].[Collaborators] (
    [ItemId],
    [UserId],
    [RoleType]
) VALUES (
    @ItemId,
    @UserId,
    @RoleType
)
";
            using (var cn = CreateConnection())
            {
                await cn.OpenAsync(cancellationToken).ConfigureAwait(false);

                await
                    cn.ExecuteAsync(insert, new { ItemId = item.Id, UserId = collaborator.Id, RoleType = collaborator.Role })
                        .ConfigureAwait(false);
            }

            item.AddCollaborator(collaborator);
        }
        public async Task 異常系_共同編集者以外が記事を更新()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);
            draft.Title = "共同編集テスト_共同編集者以外が記事を更新";
            draft.Body = "共同編集テスト_共同編集者以外が記事を更新";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);
            var collaborator1 = new Collaborator(_collaborator1) { Role = RoleType.Owner };
            var collaborator2 = new Collaborator(_collaborator2) { Role = RoleType.Member };
            var collaborator3 = new Collaborator(_collaborator3) { Role = RoleType.Member };
            var collaborators = new[] { collaborator1, collaborator2 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            try
            {
                var newDraft = item.ToDraft(collaborator3);
            }
            catch (Exception exception)
            {
                Assert.AreEqual(exception.GetType(), typeof(NotEntitledToEditItemException));
            }
        }
示例#38
0
 /// <summary>記事の共同編集者を更新します。</summary>
 /// <param name="item">共同編集者を更新する記事</param>
 /// <param name="collaborators">共同編集者</param>
 /// <returns></returns>
 public Task SaveCollaboratorsAsync(Item item, Collaborator[] collaborators)
 {
     return SaveCollaboratorsAsync(item, collaborators, CancellationToken.None);
 }
        public async Task 正常系_共同編集者が記事を更新()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);
            draft.Title = "共同編集テスト_共同編集者が記事を更新";
            draft.Body = "共同編集テスト_共同編集者が記事を更新";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);
            var collaborator1 = new Collaborator(_collaborator1) { Role = RoleType.Owner };
            var collaborator2 = new Collaborator(_collaborator2) { Role = RoleType.Member };
            var collaborators = new[] { collaborator1, collaborator2 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            var newDraft = item.ToDraft(_collaborator1);

            newDraft.Title = "共同編集テスト_共同編集者が記事を更新した";
            newDraft.Body = "共同編集テスト_共同編集者が記事を更新した";

            var newItem = newDraft.ToItem(true);

            await ItemDbCommand.SaveAsync(newItem);

            newItem.Author.Is(_author);
            newItem.Editor.Is(_collaborator1);

            var savedItem = await ItemDbCommand.FindAsync(newItem.Id);

            savedItem.IsStructuralEqual(newItem);
        }
示例#40
0
        public async Task<ActionResult> AddCollaborator(string id, string userId)
        {
            var item = await _itemDbCommand.FindAsync(id);
            if (item == null) return HttpNotFound();
            if (!LogonUser.IsEntitledToEditItemCollaborators(item)) return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);

            var targetUser = await _userDbCommand.FindAsync(userId);
            if (targetUser == null) return HttpNotFound();

            if (item.Collaborators.Contains(targetUser)) throw new InvalidOperationException();

            var newCollaborator = new Collaborator(targetUser) { Role = RoleType.Member };

            await _itemDbCommand.AddCollaboratorAsync(item, newCollaborator);

            var model = Mapper.Map<CollaboratorEditModel>(newCollaborator);

            return PartialView("_CollaboratorEdit", model);
        }
        public async Task 正常系_共同編集者のロールを変更()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);
            draft.Title = "共同編集テスト_共同編集者のロールを変更";
            draft.Body = "共同編集テスト_共同編集者のロールを変更";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);

            var collaborator1 = new Collaborator(_collaborator1) { Role = RoleType.Member };
            var collaborator2 = new Collaborator(_collaborator2) { Role = RoleType.Member };
            var collaborator3 = new Collaborator(_collaborator3) { Role = RoleType.Member };
            var collaborators = new[] { collaborator1, collaborator2, collaborator3 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            collaborator1.Role = RoleType.Owner;
            await ItemDbCommand.SaveCollaboratorsAsync(item);

            var savedItem = await ItemDbCommand.FindAsync(item.Id);

            item.IsStructuralEqual(savedItem);

            savedItem.Collaborators.ToArray().IsStructuralEqual(new[] { collaborator1, collaborator2, collaborator3 });
        }
        public async Task 正常系_他の人が編集中の下書きを別の人が呼び出して記事を更新()
        {
            var draft = Draft.NewDraft(_author, ItemType.Article);
            draft.Title = "共同編集テスト_他の人が編集中の下書きを別の人が呼び出して記事を更新";
            draft.Body = "共同編集テスト_他の人が編集中の下書きを別の人が呼び出して記事を更新";

            var item = draft.ToItem(true);
            await ItemDbCommand.SaveAsync(item);
            var collaborator1 = new Collaborator(_collaborator1) { Role = RoleType.Owner };
            var collaborator2 = new Collaborator(_collaborator2) { Role = RoleType.Member };
            var collaborator3 = new Collaborator(_collaborator3) { Role = RoleType.Member };
            var collaborators = new[] { collaborator1, collaborator2, collaborator3 };
            await ItemDbCommand.SaveCollaboratorsAsync(item, collaborators);

            var collaborator1Draft = item.ToDraft(_collaborator1);

            collaborator1Draft.Title = "共同編集テスト_共同編集者①が記事を編集中";
            collaborator1Draft.Body = "共同編集テスト_共同編集者①が記事を編集中";

            await DraftDbCommand.SaveAsync(collaborator1Draft);

            // 共同編集者②が下書きを呼び出して下書きを更新
            var collaborator2Draft = await DraftDbCommand.FindAsync(item.Id, _collaborator2);
            collaborator2Draft.IsNull();
            collaborator2Draft = item.ToDraft(_collaborator2);
            collaborator2Draft.Title = "共同編集テスト_共同編集者②が記事を編集中";
            collaborator2Draft.Body = "共同編集テスト_共同編集者②が記事を編集中";

            await DraftDbCommand.SaveAsync(collaborator2Draft);

            var savedCollaborator2Draft = await DraftDbCommand.FindAsync(item.Id, _collaborator2);
            savedCollaborator2Draft.IsStructuralEqual(collaborator2Draft);

            // 共同編集者③が下書きを呼び出して下書きを更新
            var collaborator3Draft = await DraftDbCommand.FindAsync(item.Id, _collaborator3);
            collaborator3Draft.IsNull();

            collaborator3Draft = item.ToDraft(_collaborator3);
            collaborator3Draft.Title = "共同編集テスト_共同編集者③が記事を編集";
            collaborator3Draft.Body = "共同編集テスト_共同編集者③が記事を編集";

            var collaborator3Item = collaborator3Draft.ToItem();

            await ItemDbCommand.SaveAsync(collaborator3Item);

            var savedCollaborator3Item = await ItemDbCommand.FindAsync(item.Id);

            savedCollaborator3Item.Author.Is(_author);
            savedCollaborator3Item.Editor.Is(_collaborator3);
            savedCollaborator3Item.IsStructuralEqual(collaborator3Item);
        }