public void DeleteUserFromProjectsShare(Project project, ApplicationUser user)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                var projectsShare = unitOfWork.ProjectsShares.GetAll()
                        .FirstOrDefault(c => c.ProjectId.Equals(project.ProjectID) && c.UserId.Equals(user.Id));

                if (projectsShare != null)
                {
                    unitOfWork.ProjectsShares.Delete(projectsShare);

                    unitOfWork.Save();
                }

            }
        }
        public ActionResult AcceptInvite(int id)
        {
            _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
            var projectForShared = _serviceProject.GetProject(id);
            _serviceProjectsShareService.AddUserToProjectsShare(projectForShared, _currentUser, UserRoleProjectsShareConstants.Shared);

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
                return Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.ToString());

            return RedirectToAction("List", "Workflow");
        }
        public void AddUserToProjectsShare(Project project, ApplicationUser user, int userRole, ApplicationUser fromUser = null)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (userRole < UserRoleProjectsShareConstants.Invited && userRole > UserRoleProjectsShareConstants.Owner)
            {
                throw new ArgumentNullException(nameof(userRole));
            }

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                var projectsShare = unitOfWork.ProjectsShares.GetAll().FirstOrDefault(c => c.ProjectId.Equals(project.ProjectID)
                                            && c.UserId.Equals(user.Id));

                if (projectsShare != null)
                {
                    if (projectsShare.UserRole > UserRoleProjectsShareConstants.Invited)
                    {
                        throw new ArgumentException("User exists in projects share.");
                    }

                    projectsShare.UserRole = userRole;
                    unitOfWork.ProjectsShares.Update(projectsShare);
                }
                else
                {
                    var newprojectsShare = new ProjectsShare
                    {
                        ProjectId = project.ProjectID,
                        UserId = user.Id,
                        UserRole = userRole
                    };

                    if (fromUser != null)
                    {
                        newprojectsShare.FromUserId = fromUser.Id;
                    }

                    unitOfWork.ProjectsShares.Create(newprojectsShare);
                }

                unitOfWork.Save();
            }
        }
        public void CreateUser(ApplicationUser user)
        {
            //if (user == null)
            //{
            //    throw new ArgumentNullException(nameof(user));
            //}

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                unitOfWork.Users.Create(user);
                unitOfWork.Save();
            }
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    //await SmtpMailer.Instance(ConfigurationManagerConstant.WebConfiguration).SendAsyncRegisterNotification(user.Email);
                    SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).SendRegisterNotification(user.Email);

                    return RedirectToAction("List", "Workflow");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult ListProjectPartial()
        {
            _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
            var projects = _serviceProjectsShareService.GetUserProjects(_currentUser);
            var projectsViewModel = Mapper.Map<IEnumerable<Project>, IEnumerable<ProjectsListViewModel>>(projects).ToList();
            var countInvited = 0;
            foreach (var project in projectsViewModel)
            {
                project.UserRole = _serviceProjectsShareService.GetUserRole(_currentUser, project.ProjectID);
                if (project.UserRole == 0)
                {
                    countInvited++;
                }
            }

            ViewBag.CountInvited = countInvited;
            _projectModel.Projects = projectsViewModel;

            return PartialView("ListProjectPartial", _projectModel);
        }
        public ActionResult List(string id="0")
        {
            if (User.Identity.IsAuthenticated)
            {
                _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
                var projects = _serviceProjectsShareService.GetUserProjects(_currentUser);
                var projectsViewModel = Mapper.Map<IEnumerable<Project>, IEnumerable<ProjectsListViewModel>>(projects).ToList();
                var countInvited = 0;
                foreach (var project in projectsViewModel)
                {
                    project.UserRole = _serviceProjectsShareService.GetUserRole(_currentUser, project.ProjectID);
                    project.CountUsersForShared = _serviceProjectsShareService.GetUsersForSharedProject(_serviceProject.GetProject(project.ProjectID)).Count();
                    if (project.UserRole == 0)
                    {
                        countInvited++;
                    }
                }

                ViewBag.CountInvited = countInvited;
                _projectModel.Projects = projectsViewModel;
                _projectModel.IdCurrentProject = Convert.ToInt32(id);
                if (id != "0")
                {
                    var connectionsCurrentProject = _serviceConnection.GetConnectionDBs(_projectModel.IdCurrentProject);
                    _projectModel.ConnectionDbs = Mapper.Map<IEnumerable<ConnectionDB>, IEnumerable<ConnectionsListViewModel>>(connectionsCurrentProject).ToList();

                    var currentProject = _serviceProject.GetProject(_projectModel.IdCurrentProject);
                    if (currentProject != null)
                    {
                        ViewBag.name = currentProject.ProjectName;
                        ViewBag.desk = currentProject.ProjectDescription;
                    }
                    ViewBag.Count = _projectModel.ConnectionDbs.Count();

                    if (ViewBag.Count == 0)
                    {
                        ViewBag.ConnectionName = "ConnectionName";
                        ViewBag.DatabaseName = "connections.DatabaseName";
                        ViewBag.ServerName = "ServerName";
                    }

                }
                else
                {
                    ViewBag.name = "choose project";
                    ViewBag.desk = "No description";
                    ViewBag.ConnectionName = "ConnectionName";
                    ViewBag.DatabaseName = "DatabaseName";
                    ViewBag.ServerName = "ServerName";
                }

            }
            else
            {
                var proj = new List<ProjectsListViewModel>
                {
                    new ProjectsListViewModel
                    {
                        ProjectID = 1,
                        ProjectName = "Example",
                        ProjectDescription = "This project for demonstration service",
                        UserRole = UserRoleProjectsShareConstants.Owner,
                     }

                };
                var connect = new List<ConnectionsListViewModel>
                {
                    new ConnectionsListViewModel
                    {
                        ConnectionID = -1,
                        ConnectionName = "Example",
                        ConnectionOwner = 1,
                        DatabaseName = "Northwind",
                        LoginDB = "MyLogin",
                        ServerName = "MSSQL"
                    }
                };
                _projectModel.ConnectionDbs = connect;
                //ViewBag.ConnectionName = "ConnectionName";
                //ViewBag.DatabaseName = "DatabaseName";
                //ViewBag.ServerName = "ServerName";
                _projectModel.IdCurrentProject = proj[0].ProjectID;
                _projectModel.Name = proj[0].ProjectName;
                _projectModel.Description = proj[0].ProjectDescription;
                _projectModel.Projects = proj;

            }

            return View(_projectModel);
        }
        public ActionResult InviteUserToProjectPartial(UserViewModel user)
        {
            if (ModelState.IsValid)
            {
                var userForShared = _serviceUser.GetUserByID(user.UserId);

                var projectForShared = _serviceProject.GetProject(user.ProjectId);

                _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
                _serviceProjectsShareService.AddUserToProjectsShare(projectForShared, userForShared, UserRoleProjectsShareConstants.Invited, _currentUser);

                var bodyMail = _currentUser.UserName + " invited you to a project!";
                SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).SendMail(userForShared.Email, "Invitation to project", bodyMail);

                ViewBag.PreviousPage = System.Web.HttpContext.Current.Request.UrlReferrer;
                return PartialView("Success");
            }
            var users = _serviceProjectsShareService.GetUsersForSharedProject(_serviceProject.GetProject(user.ProjectId));

            user.Users = Mapper.Map<IEnumerable<ApplicationUser>, IEnumerable<UsersListViewModel>>(users);

            return PartialView("_InviteUserToProjectPartial", user);
        }
        public ActionResult DeleteProjectPartial(ProjectViewModel project)
        {
            _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
            var projects = _serviceProjectsShareService.GetUserProjects(_currentUser);
            var projectsViewModel = Mapper.Map<IEnumerable<Project>, IEnumerable<ProjectsListViewModel>>(projects).ToList();
            var deleteProject = projectsViewModel.FirstOrDefault(x => x.ProjectID == project.IdCurrentProject);
            if (deleteProject != null)
            {
                deleteProject.UserRole = _serviceProjectsShareService.GetUserRole(_currentUser, project.IdCurrentProject);
                if (deleteProject.UserRole == UserRoleProjectsShareConstants.Shared)
                {
                    _serviceProjectsShareService.DeleteUserFromProjectsShare(_serviceProject.GetProject(deleteProject.ProjectID), _currentUser);
                }

                if (deleteProject.UserRole == UserRoleProjectsShareConstants.Owner)
                {
                    var newproject = Mapper.Map<ProjectViewModel, Project>(project);
                    newproject.Delflag = DelflagConstants.UnactiveSet;
                    _serviceProject.SaveProject(newproject);

                    _serviceConnection.DeleteProjectConnections(deleteProject.ProjectID);
                }
            }

            ViewBag.PreviousPage = System.Web.HttpContext.Current.Request.UrlReferrer;
            return PartialView("Success");
        }
        public ActionResult DeleteInvite(int id)
        {
            _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());

            _serviceProjectsShareService.DeleteUserFromProjectsShare(_serviceProject.GetProject(id), _currentUser);

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
                return Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.ToString());

            return RedirectToAction("List", "Workflow");
        }
        public ActionResult CreateProjectPartial(ProjectViewModel projectModel)
        {
            _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
            if (ModelState.IsValid)
            {
                var newProject = Mapper.Map<ProjectViewModel, Project>(projectModel);
                _serviceProject.SaveProject(newProject);

                _serviceProjectsShareService.AddUserToProjectsShare(newProject, _currentUser, UserRoleProjectsShareConstants.Owner);

                ViewBag.PreviousPage = System.Web.HttpContext.Current.Request.UrlReferrer;
                return PartialView("Success");
            }
            return PartialView("CreateProjectPartial");
        }
        public int GetUserRole(ApplicationUser user, int projectId)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (projectId == 0)
            {
                throw new ArgumentNullException(nameof(projectId));
            }

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                return unitOfWork.ProjectsShares.GetMany(p => (p.UserId == user.Id && p.ProjectId == projectId))
                                                        .First().UserRole;

            }
        }
        public IEnumerable<Project> GetUserProjects(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                return unitOfWork.ProjectsShares.GetMany(p => (p.UserId == user.Id && p.User.Delflag == DelflagConstants.ActiveSet && p.Project.Delflag == DelflagConstants.ActiveSet))
                                .Select(f => f.Project).ToList().OrderByDescending(g => g.CreatedDate);
            }
        }