Ejemplo n.º 1
0
        private void SaveMessages(IPost message, int projectID)
        {
            var projectEngine = _engineFactory.ProjectEngine;
            var messageEngine = _engineFactory.MessageEngine;

            try
            {
                var newMessage = new Message
                {
                    Title       = ReplaceLineSeparator(message.Title),
                    Description = message.Body,
                    Project     = projectEngine.GetByID(FindProject(projectID)),
                    CreateOn    = message.PostedOn.ToUniversalTime(),
                    CreateBy    = FindUser(message.AuthorID)
                };

                newMessage = messageEngine.SaveOrUpdate(newMessage, true, new[] { newMessage.CreateBy }, null);
                _newMessagesID.Add(new MessageIDWrapper {
                    InBasecamp = message.ID, InProjects = newMessage.ID
                });
                SaveMessageComments(message.RecentComments, message.ID);
            }
            catch (Exception e)
            {
                StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveMessage, message.Title), e);
                LogError(string.Format("message '{0}' failed", message.Title), e);
                _newMessagesID.RemoveAll(x => x.InBasecamp == message.ID);
            }
        }
Ejemplo n.º 2
0
        private void SaveTasks(IToDoList todoList, int projectID)
        {
            var projectEngine = _engineFactory.ProjectEngine;
            var taskEngine    = _engineFactory.TaskEngine;

            foreach (var task in todoList.Items.Where(x => _withClosed || !x.Completed))
            {
                try
                {
                    var newTask = new Task
                    {
                        Title       = ReplaceLineSeparator(task.Content),
                        Status      = task.Completed ? TaskStatus.Closed : TaskStatus.Open,
                        Project     = projectEngine.GetByID(FindProject(projectID)),
                        CreateOn    = task.CreatedOn.ToUniversalTime(),
                        CreateBy    = FindUser(task.CreatorID),
                        Description = string.Empty,
                        Deadline    = task.Deadline
                    };

                    newTask.Deadline = DateTime.SpecifyKind(newTask.Deadline, DateTimeKind.Local);

                    if (task.ResponsibleID != -1)
                    {
                        var user = FindUser(task.ResponsibleID);
                        newTask.Responsibles.Add(user);
                    }

                    if (todoList.MilestoneID != -1)
                    {
                        var foundMilestone = FindMilestone(todoList.MilestoneID);
                        if (foundMilestone != -1)
                        {
                            newTask.Milestone = foundMilestone;
                        }
                    }

                    newTask = taskEngine.SaveOrUpdate(newTask, null, true, true);
                    _newTasksID.Add(new TaskIDWrapper {
                        InBasecamp = task.ID, InProjects = newTask.ID
                    });
                    SaveTaskComments(task.RecentComments, task.ID);
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveTask, task.Content), e);
                    LogError(string.Format("task '{0}' failed", task.Content), e);
                    _newTasksID.RemoveAll(x => x.InBasecamp == task.ID);
                }
            }
        }
Ejemplo n.º 3
0
        public void StartImport()
        {
            HttpContext.Current = null;
            try
            {
                LogStatus("started");

                CoreContext.TenantManager.SetCurrentTenant(Id);
                Thread.CurrentPrincipal = _principal;

                HttpContext.Current = new HttpContext(
                    new HttpRequest("fake", CommonLinkUtility.GetFullAbsolutePath("/"), string.Empty),
                    new HttpResponse(new StringWriter()));

                scope          = DIHelper.Resolve(_disableNotifications);
                _engineFactory = scope.Resolve <EngineFactory>();

                StatusState.SetStatusStarted();
                StatusState.StatusLogInfo(ImportResource.ImportStarted);
                var basecampManager = BaseCamp.GetInstance(_url, _userName, _password);

                LogStatus("import users");
                SaveUsers(basecampManager);

                LogStatus("import projects");

                SaveProjects(basecampManager);

                StatusState.SetStatusCompleted();

                StatusState.StatusLogInfo(ImportResource.ImportCompleted);
            }
            finally
            {
                if (HttpContext.Current != null)
                {
                    new DisposableHttpContext(HttpContext.Current).Dispose();
                    HttpContext.Current = null;
                }
                scope.Dispose();
            }
        }
Ejemplo n.º 4
0
        public ImportFromBasecamp(string url, string userName, string password, Guid initiatorId, bool withClosed, bool disableNotifications, bool importUsersAsCollaborators, IEnumerable <int> projects)
        {
            _newUsersID      = new List <UserIDWrapper>();
            _newProjectsID   = new List <ProjectIDWrapper>();
            _newMilestonesID = new List <MilestoneIDWrapper>();
            _newMessagesID   = new List <MessageIDWrapper>();
            _newTasksID      = new List <TaskIDWrapper>();
            _newFilesID      = new List <FileIDWrapper>();

            _url                        = (PrepUrl(url).ToString().TrimEnd('/') + "/api/v1");
            _userName                   = userName;
            _password                   = password;
            _initiatorId                = initiatorId;
            _withClosed                 = withClosed;
            _disableNotifications       = disableNotifications;
            _importUsersAsCollaborators = importUsersAsCollaborators;
            StatusState.SetStatus(new ImportStatus(_url));
            Id         = TenantProvider.CurrentTenantID;
            _log       = LogManager.GetLogger("ASC.Project.BasecampImport");
            _principal = Thread.CurrentPrincipal;
            _projects  = projects;
        }
Ejemplo n.º 5
0
        private void SaveTaskComments(IEnumerable <IComment> comments, int taskid)
        {
            var commentEngine = _engineFactory.CommentEngine;

            foreach (var comment in comments)
            {
                try
                {
                    var newComment = new Comment
                    {
                        CreateBy     = FindUser(comment.AuthorID),
                        Content      = comment.Body,
                        CreateOn     = comment.CreatedAt.ToUniversalTime(),
                        TargetUniqID = ProjectEntity.BuildUniqId <Task>(FindTask(taskid))
                    };
                    commentEngine.SaveOrUpdate(newComment);
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveComment, comment.ID), e);
                    LogError(string.Format("comment '{0}' failed", comment.ID), e);
                }
            }
        }
Ejemplo n.º 6
0
        private void SaveFiles(IBaseCamp basecampManeger, IEnumerable <IAttachment> attachments, int projectID)
        {
            var step = 100.0 / attachments.Count();

            StatusState.StatusLogInfo(string.Format(ImportResource.ImportFileStarted, attachments.Count()));

            //select last version
            foreach (var attachment in attachments)
            {
                StatusState.StatusFileProgress(step);

                try
                {
                    var httpWReq = basecampManeger.Service.GetRequest(attachment.DownloadUrl);
                    using (var httpWResp = (HttpWebResponse)httpWReq.GetResponse())
                    {
                        if (attachment.ByteSize > SetupInfo.MaxUploadSize)
                        {
                            StatusState.StatusLogError(string.Format(ImportResource.FailedSaveFileMaxSizeExided, attachment.Name), new Exception());
                            continue;
                        }

                        var file = new ASC.Files.Core.File
                        {
                            FolderID      = _engineFactory.FileEngine.GetRoot(FindProject(projectID)),
                            Title         = attachment.Name,
                            ContentLength = attachment.ByteSize,
                            CreateBy      = FindUser(attachment.AuthorID),
                            CreateOn      = attachment.CreatedOn.ToUniversalTime(),
                            Comment       = ImportResource.CommentImport,
                        };
                        if (file.Title.LastIndexOf('\\') != -1)
                        {
                            file.Title = file.Title.Substring(file.Title.LastIndexOf('\\') + 1);
                        }

                        file = _engineFactory.FileEngine.SaveFile(file, httpWResp.GetResponseStream());

                        if ("Message".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var messageId = FindMessage(attachment.OwnerID);
                                _engineFactory.MessageEngine.AttachFile(new Message {
                                    ID = messageId
                                }, file.ID, false);                                                                    //It's not critical
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        if ("Todo".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var taskId = FindTask(attachment.OwnerID);
                                _engineFactory.TaskEngine.AttachFile(new Task {
                                    ID = taskId
                                }, file.ID, false);                                                           //It's not critical
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        _newFilesID.Add(new FileIDWrapper
                        {
                            InBasecamp = attachment.ID,
                            InProjects = file.ID
                        });
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveFile, attachment.Name), e);
                        LogError(string.Format("file '{0}' failed", attachment.Name), e);
                        _newFilesID.RemoveAll(x => x.InBasecamp == attachment.ID);
                    }
                    catch (Exception ex)
                    {
                        LogError(string.Format("file remove after error failed"), ex);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private void SaveProjects(IBaseCamp basecampManager)
        {
            var projects          = basecampManager.Projects;
            var step              = 50.0 / projects.Count();
            var projectEngine     = _engineFactory.ProjectEngine;
            var participantEngine = _engineFactory.ParticipantEngine;

            if (_projects.Any())
            {
                projects = projects.Where(r => _projects.Any(pr => pr == r.ID)).ToArray();
            }

            foreach (var project in projects)
            {
                try
                {
                    StatusState.StatusLogInfo(string.Format(ImportResource.ImportProjectStarted, project.Name));
                    StatusState.StatusProjectProgress(step);
                    var newProject = new Project
                    {
                        Status      = !project.IsClosed ? ProjectStatus.Open : ProjectStatus.Closed,
                        Title       = ReplaceLineSeparator(project.Name),
                        Description = project.Description,
                        Responsible = _initiatorId,
                        Private     = true
                    };

                    projectEngine.SaveOrUpdate(newProject, true);
                    var prt = participantEngine.GetByID(newProject.Responsible);
                    projectEngine.AddToTeam(newProject, prt, true);

                    foreach (var wrapper in
                             project.People.SelectMany(user => _newUsersID.Where(wrapper => user.ID == wrapper.InBasecamp)))
                    {
                        prt = participantEngine.GetByID(wrapper.InProjects);
                        projectEngine.AddToTeam(newProject, prt, true);

                        //check permission
                        var user = project.People.ToList().Find(p => p.ID == wrapper.InBasecamp);
                        if (user != null)
                        {
                        }
                    }
                    _newProjectsID.Add(new ProjectIDWrapper {
                        InBasecamp = project.ID, InProjects = newProject.ID
                    });
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveProject, project.Name), e);
                    LogError(string.Format("project '{0}' failed", project.Name), e);
                    _newProjectsID.RemoveAll(x => x.InBasecamp == project.ID);
                }
            }

            //Select only suceeded projects
            var projectsToProcess = projects.Where(x => _newProjectsID.Count(y => y.InBasecamp == x.ID) > 0).ToList();

            step = 50.0 / projectsToProcess.Count;
            foreach (var project in projectsToProcess)
            {
                StatusState.StatusLogInfo(string.Format(ImportResource.ImportProjectDataStarted, project.Name));

                StatusState.StatusProjectProgress(step);

                var messages = project.RecentMessages;
                foreach (var message in messages)
                {
                    SaveMessages(message, project.ID);
                }

                var todoLists = project.ToDoLists;
                foreach (var todoList in todoLists)
                {
                    SaveTasks(todoList, project.ID);
                }
                LogStatus("import files");
                SaveFiles(basecampManager, project.Attachments, project.ID);
            }
        }
Ejemplo n.º 8
0
        private void SaveUsers(IBaseCamp basecampManager)
        {
            var employees = basecampManager.People;
            var step      = 100.0 / employees.Count();

            foreach (var person in employees)
            {
                try
                {
                    if (TenantExtra.GetRemainingCountUsers() <= 0)
                    {
                        _importUsersOverLimitAsCollaborators = true;
                    }

                    StatusState.StatusUserProgress(step);
                    var userID = FindUserByEmail(person.EmailAddress);

                    if (userID.Equals(Guid.Empty))
                    {
                        var userName = Regex.Replace(person.UserName, @"[!|@|#|$|%|'|+]", "");
                        var name     = userName.Split(' ');
                        var userInfo = new UserInfo
                        {
                            Email     = person.EmailAddress,
                            FirstName = name.First(),
                            LastName  = name.Count() > 1 ? name.Last() : "",
                            UserName  = userName,
                            Status    = EmployeeStatus.Active,
                        };
                        var collaboratorFlag = _importUsersOverLimitAsCollaborators || _importUsersAsCollaborators;

                        if (!UserManagerWrapper.ValidateEmail(userInfo.Email))
                        {
                            throw new Exception("Invalid email");
                        }

                        var newUserInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, !_disableNotifications, collaboratorFlag);
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = newUserInfo.ID
                        });

                        //save user avatar
                        const string emptyAvatar = "http://asset0.37img.com/global/default_avatar_v1_4/avatar.gif?r=3";
                        if (person.AvatarUrl != emptyAvatar)
                        {
                            UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, StreamFile(person.AvatarUrl));
                        }
                    }
                    else
                    {
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = userID
                        });
                    }
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveUser, person.EmailAddress), e);
                    LogError(string.Format("user '{0}' failed", person.EmailAddress), e);
                    _newUsersID.RemoveAll(x => x.InBasecamp == person.ID);
                }
            }
        }
Ejemplo n.º 9
0
 public void ImportComplete()
 {
     StatusState.StatusCompletedAt(DateTime.Now);
 }
Ejemplo n.º 10
0
 public void ImportError(Exception e)
 {
     StatusState.StatusLogError(ImportResource.ImportFailed, e);
     StatusState.StatusError(e);
     LogError("generic error", e);
 }
Ejemplo n.º 11
0
 public static ImportStatus GetStatus()
 {
     return(StatusState.GetStatus());
 }