Example #1
0
        private void OnlineTemplate_OnLoaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string[] input = new string[]
                {
                    "-c", ClientId, "-s", ClientSecret, "-a", BimId,
                    "-h", AdminMail, "-f", " .\\sample", "-t", ",",
                    "-z", ",", "-e", "UTF-8", "-d", "yyyy-MM-dd"
                };
                AppOptions options = AppOptions.Parse(input);
                // options.AccountRegion = "EU";
                options.AdminRole = "Project Manager";

                ProjectWorkflow projectProcess = new ProjectWorkflow(options);

                List <BimProject> projects     = projectProcess.GetAllProjects();
                List <string>     templateList = new List <string>();
                foreach (var iter in projects)
                {
                    templateList.Add(iter.name);
                }

                ComboBoxTemplate.ItemsSource = templateList;
            }
            catch (Exception ex)
            {
                statusbar.Text = "Fail to Load Templates: " + ex.Message;
            }
        }
Example #2
0
        private void OnEnable()
        {
            WorkflowSettings.Load();
            string path = EditorPrefs.GetString(WorkflowSettings.PROJECT_WORKFLOW_DATA);

            workflow = AssetDatabase.LoadAssetAtPath(path, typeof(ProjectWorkflow)) as ProjectWorkflow;
        }
Example #3
0
        public ActionResult Create(string ticketTag)
        {
            if (string.IsNullOrWhiteSpace(ticketTag))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            List <TicketStatus> availStatuses      = null;
            Project             parentProj         = db.Projects.First(p => p.TicketTag == ticketTag);
            ProjectWorkflow     parentProjWorkflow = parentProj.ActiveWorkflow;

            if (parentProjWorkflow.InitialTicketStatusId == null)
            {
                availStatuses = new List <TicketStatus>();
                foreach (TicketStatus ts in db.TicketStatuses.Where(ts => ts.MustBeAssigned == false && ts.IsStarted == false).ToList())
                {
                    availStatuses.Add(ts);
                }
            }

            var viewModel = new CreateTicketViewModel()
            {
                ParentProject        = parentProj,
                Reporter             = db.Users.Find(User.Identity.GetUserId()),
                PrioritySelections   = db.TicketPriorityTypes.ToDictionary(tp => tp.Name, tp => tp.Id),
                AvailableStatuses    = availStatuses,
                AvailableTicketTypes = db.TicketTypes.ToList()
            };

            return(View(viewModel));
        }
Example #4
0
        static void Main(string[] args)
        {
            // Delete previous versions of log.txt
            System.IO.File.Delete("Log/logInfo.txt");
            System.IO.File.Delete("Log/logImportant.txt");

            AppOptions options = AppOptions.Parse(args);

            ProjectWorkflow     projectProcess     = new ProjectWorkflow(options);
            FolderWorkflow      folderProcess      = new FolderWorkflow(options);
            ProjectUserWorkflow projectUserProcess = new ProjectUserWorkflow(options);
            AccountWorkflow     accountProcess     = new AccountWorkflow(options);

            DataTable         csvData  = projectProcess.CustomGetDataFromCsv();
            List <BimProject> projects = projectProcess.GetAllProjects();

            List <BimCompany>   companies      = null;
            BimProject          currentProject = null;
            List <HqUser>       projectUsers   = null;
            List <NestedFolder> folders        = null;
            NestedFolder        currentFolder  = null;

            for (int row = 0; row < csvData.Rows.Count; row++)
            {
                string projectName = csvData.Rows[row]["project_name"].ToString();

                if (!string.IsNullOrEmpty(projectName))
                {
                    Util.LogImportant($"\nCurrent project: {projectName}");

                    currentProject = projects.Find(x => x.name == projectName);

                    if (currentProject == null)
                    {
                        projects = projectProcess.CustomCreateProject(csvData, row, projectName, projectProcess);

                        currentProject = projects.Find(x => x.name == projectName);
                        CheckProjectCreated(currentProject, projectName);
                    }

                    folders = folderProcess.CustomGetFolderStructure(currentProject);

                    companies = accountProcess.CustomUpdateCompanies(csvData, row, accountProcess);

                    projectUsers = projectUserProcess.CustomUpdateProjectUsers(csvData, row, companies, currentProject, projectUserProcess);
                }

                currentFolder = CreateFoldersAndAssignPermissions(csvData, row, projectUsers, folderProcess, folders, currentFolder, currentProject, projectUserProcess);

                UploadFilesFromFolder(csvData, row, folderProcess, currentFolder, currentProject.id, options.LocalFoldersPath);
            }
        }
Example #5
0
        public async Task AddHoursToProjectWorkflowAsync(string projectId, string userId, double reportedHours)
        {
            var model = new ProjectWorkflow {
                Id            = Guid.NewGuid().ToString(),
                ProjectId     = projectId,
                UserId        = userId,
                ReportedHours = reportedHours,
                Timestamp     = DateTime.Now
            };

            _context.ProjectWorkflows.Add(model);
            await _context.SaveChangesAsync();
        }
Example #6
0
        public ActionResult Show(string ticketIdentifier)
        {
            if (string.IsNullOrWhiteSpace(ticketIdentifier))
            {
                TempData.AddDangerToast("You must provide the ticket identifier to display. Please try again.");
                return(RedirectToAction("Index", "Tickets"));
            }
            Ticket ticket = db.Tickets.ToList().FirstOrDefault(t => t.GetTicketIdentifier() == ticketIdentifier);

            if (ticket == null)
            {
                TempData.AddDangerToast("We were unable to locate this ticket. Please try again.");
                return(RedirectToAction("Index", "Tickets"));
            }

            if (!_permissionsHelper.CanViewTicket(User, ticket.Id))
            {
                TempData.AddDangerToast("You are not allowed to view this resource.");
                return(RedirectToAction("Index", "Tickets"));
            }


            ProjectWorkflow        parentProjWorkflow = ticket.ParentProject.ActiveWorkflow;
            List <ApplicationUser> solvers            = null;

            if (User.Identity.GetUserId() == ticket.ParentProject.ProjectManagerId || User.IsInRole("ServerAdmin"))
            {
                solvers = ticket.ParentProject.GetSolverMembers();
            }
            List <TicketStatus> availStatuses = null;

            if (ticket.Permissions(User).CanUpdateTicketStatus)
            {
                availStatuses = parentProjWorkflow.GetAvailableStatuses(ticket.Id, User, db);
            }

            var viewModel = new EditTicketViewModel()
            {
                ParentProject        = ticket.ParentProject,
                Reporter             = ticket.Reporter,
                PrioritySelections   = db.TicketPriorityTypes.ToDictionary(tp => tp.Name, tp => tp.Id),
                AvailableTicketTypes = db.TicketTypes.ToList(),
                CurrentTicket        = ticket,
                AvailableSolvers     = solvers,
                AvailableStatuses    = availStatuses
            };

            return(View(viewModel));
        }
Example #7
0
        public ActionResult Edit(string ticketIdentifier)
        {
            if (string.IsNullOrWhiteSpace(ticketIdentifier))
            {
                TempData.AddDangerToast("We were unable to locate a ticket with this identifier.");
                return(RedirectToAction("Index", "Projects"));
            }
            Ticket ticket = db.Tickets.ToList().FirstOrDefault(t => t.GetTicketIdentifier() == ticketIdentifier);

            if (ticket == null)
            {
                TempData.AddDangerToast("We were unable to locate a ticket with this identifier.");
                return(RedirectToAction("Index", "Projects"));
            }
            if (!_permissionsHelper.CanEditTicket(User, ticket.Id))
            {
                TempData.AddDangerToast("You are not allowed to view this resource / perform this action.");
                return(RedirectToAction("Index", "Home"));
            }

            ProjectWorkflow        parentProjWorkflow = ticket.ParentProject.ActiveWorkflow;
            List <ApplicationUser> solvers            = null;

            if (_permissionsHelper.IsProjectManager(User, ticket.ParentProjectId) || User.IsInRole("ServerAdmin"))
            {
                solvers = ticket.ParentProject.GetSolverMembers();
            }

            List <TicketStatus> availStatuses = null;

            if ((_permissionsHelper.IsUserStaff(User) && parentProjWorkflow.CanStaffSetStatusOnInteract) ||
                (_permissionsHelper.IsTicketOwner(User, ticket.Id) && parentProjWorkflow.CanTicketOwnerSetStatusOnInteract))
            {
                availStatuses = parentProjWorkflow.GetAvailableStatuses(ticket.Id, User, db);
            }

            var viewModel = new EditTicketViewModel()
            {
                ParentProject        = ticket.ParentProject,
                Reporter             = db.Users.Find(User.Identity.GetUserId()),
                PrioritySelections   = db.TicketPriorityTypes.ToDictionary(tp => tp.Name, tp => tp.Id),
                AvailableTicketTypes = db.TicketTypes.ToList(),
                AvailableStatuses    = availStatuses,
                CurrentTicket        = ticket,
                AvailableSolvers     = solvers
            };

            return(View(viewModel));
        }
Example #8
0
        public ProjectWorkflowWrapper(ProjectWorkflow workflow,
                                      IUnitsOfWorkContainer unitsOfWork)
        {
            _workflow    = workflow;
            _unitsOfWork = unitsOfWork;

            //Entry Methods Binding
            BindEntryMethods();

            //Exit Methods Binding
            BindExitMethods();

            //Guard For Transitions
            BindGuardMethods();
        }
Example #9
0
        private void OnSetupConfigurationGUI()
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Workflow configuration");
            workflow = EditorGUILayout.ObjectField(workflow, typeof(ProjectWorkflow), false) as ProjectWorkflow;
            EditorGUILayout.EndHorizontal();

            if (GUILayout.Button("Create New Workflow Configuration"))
            {
                workflow = ScriptableObject.CreateInstance <ProjectWorkflow>();
                string path = AssetDatabase.GenerateUniqueAssetPath(WorkflowSettings.workflowDataDirectory + "/" + Application.productName + " Workflow.asset");
                AssetDatabase.CreateAsset(workflow, path);
                AssetDatabase.SaveAssets();
            }

            if (workflow != null)
            {
                EditorUtility.SetDirty(workflow);
            }
        }
        public bool Initialize()
        {
            bool result = false;

            try
            {
                folderProcess      = new FolderWorkflow(options);
                projectProcess     = new ProjectWorkflow(options);
                serviceProcess     = new ServiceWorkflow(options);
                accountProcess     = new AccountWorkflow(options);
                projectUserProcess = new ProjectUserWorkflow(options);

                result = true;
            }
            catch (Exception e)
            {
                result = false;
                Log.Error(e, "Error during intitialization");
            }
            return(result);
        }
 public async Task<ActionResult> ProcessDocumentsAsync(ProjectWorkflow prjWorkflow, DocumentToProjectLink link2doc, string comment, AppUser currentUser)
 {
     try
     {
         var dbDoc = await _dbContext.ProjectDocuments.FirstOrDefaultAsync(pd => pd.ProjectId == prjWorkflow.Id && pd.Link2StateId == link2doc.Id);
         if (dbDoc == null)
         {
             dbDoc = new ProjectDocument
             {
                 Body = System.Text.Encoding.UTF8.GetBytes(link2doc.DocName),
                 CreatedBy = currentUser,
                 CreatedOn = DateTime.UtcNow,
                 Link2StateId = link2doc.Id,
                 ProjectId = prjWorkflow.Id,
                 StateId = link2doc.StateId,
                 Comment = comment
             };
             _dbContext.ProjectDocuments.Add(dbDoc);
         }
         else
         {
             dbDoc.Body = System.Text.Encoding.UTF8.GetBytes(link2doc.DocName);
             dbDoc.CreatedBy = currentUser;
             dbDoc.CreatedOn = DateTime.UtcNow;
             dbDoc.Link2StateId = link2doc.Id;
             dbDoc.ProjectId = prjWorkflow.Id;
             dbDoc.StateId = link2doc.StateId;
             dbDoc.Comment = comment;
         }
         await _dbContext.SaveChangesAsync();
         return ActionResult.Success(dbDoc);
     }
     catch(Exception ex)
     {
         return ActionResult.Failed(ex);
     }
 }
Example #12
0
        /// <summary>
        /// runs the upload to the BIM360 environment
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Upload_OnClick(object sender, RoutedEventArgs e)
        {
            var progress = new updates_upload();

            progress.Show();
            // convert string to stream
            byte[]       byteArray = Encoding.UTF8.GetBytes(AccProjectConfig.ExportBim360Projects());
            MemoryStream dataset   = new MemoryStream(byteArray);

            //dataset.Position = 0;


            //Updates
            progress.pgb.Value             = 10;
            progress.ProgressLabel.Content = "Build Connection";
            // ProgressBar "refresh"
            CallDispatch(progress);

            //maybe change
            string[] input = new string[] { "-c", ClientId, "-s", ClientSecret, "-a", BimId,
                                            "-h", AdminMail, "-f", " .\\sample", "-t", ",",
                                            "-z", ",", "-e", "UTF-8", "-d", "yyyy-MM-dd" };


            // Delete previous versions of log.txt
            System.IO.File.Delete("Log/logInfo.txt");
            System.IO.File.Delete("Log/logImportant.txt");

            AppOptions options = AppOptions.Parse(input);

            // options.AccountRegion = "EU";
            options.AdminRole = "Project Manager";

            ProjectWorkflow projectProcess = new ProjectWorkflow(options);

            System.Threading.Thread.Sleep(1000);
            // load all existing projects from the BIM360 environment
            List <BimProject> projects = projectProcess.GetAllProjects();

            FolderWorkflow      folderProcess      = new FolderWorkflow(options);
            ProjectUserWorkflow projectUserProcess = new ProjectUserWorkflow(options);
            AccountWorkflow     accountProcess     = new AccountWorkflow(options);

            //Updates
            progress.pgb.Value             = 25;
            progress.ProgressLabel.Content = "Convert Data from GUI";
            // ProgressBar "refresh"
            CallDispatch(progress);

            // load data from custom CSV file. Filepath was set in constructor of projectProcess by pushing the options instance
            DataTable csvData = new DataTable();

            csvData = ProjectWorkflow.CustomGetDataFromCsv_stream(dataset);

            //Updates
            progress.pgb.Value             = 40;
            progress.ProgressLabel.Content = "Uploading";
            // ProgressBar "refresh"
            CallDispatch(progress);

            List <BimCompany>   companies      = null;
            BimProject          currentProject = null;
            List <HqUser>       projectUsers   = null;
            List <NestedFolder> folders        = null;
            NestedFolder        currentFolder  = null;

            //Uploading
            try
            {
                for (int row = 0; row < csvData.Rows.Count; row++)
                {
                    string projectName = csvData.Rows[row]["project_name"].ToString();

                    // check if the current row defines the start point for another project (project_name column must be set)
                    if (!string.IsNullOrEmpty(projectName))
                    {
                        Util.LogImportant($"\nCurrent project: {projectName}");

                        // check if the requested project name is already present inside BIM360
                        currentProject = projects.Find(x => x.name == projectName);

                        if (currentProject == null)
                        {
                            // create the project
                            projects = projectProcess.CustomCreateProject(csvData, row, projectName, projectProcess);

                            // set the current project variable to the recently created project
                            currentProject = projects.Find(x => x.name == projectName);

                            // verify the initialization of the new project
                            CheckProjectCreated(currentProject, projectName);
                        }



                        // create the folder structure
                        folders = folderProcess.CustomGetFolderStructure(currentProject);

                        // add the companies
                        companies = accountProcess.CustomUpdateCompanies(csvData, row, accountProcess);

                        // create or update the project users
                        projectUsers = projectUserProcess.CustomUpdateProjectUsers(csvData, row, companies,
                                                                                   currentProject, projectUserProcess);

                        //activate all services
                        ServiceWorkflow serviceProcess = new ServiceWorkflow(options);

                        //check what servers needs to be activated
                        if (ServiceTab.CheckBoxservices.IsChecked == true)
                        {
                            #region Add Services
                            var listname = new List <string>();
                            listname.Add("admin");
                            listname.Add("doc_manage");
                            if (ServiceTab.CheckBoxpm.IsChecked == true)
                            {
                                listname.Add("pm");
                            }
                            if (ServiceTab.CheckBoxfng.IsChecked == true)
                            {
                                listname.Add("fng");
                            }
                            if (ServiceTab.CheckBoxcollab.IsChecked == true)
                            {
                                listname.Add("collab");
                            }
                            if (ServiceTab.CheckBoxcost.IsChecked == true)
                            {
                                listname.Add("cost");
                            }
                            if (ServiceTab.CheckBoxgng.IsChecked == true)
                            {
                                listname.Add("gng");
                            }
                            if (ServiceTab.CheckBoxglue.IsChecked == true)
                            {
                                listname.Add("glue");
                            }
                            if (ServiceTab.CheckBoxplan.IsChecked == true)
                            {
                                listname.Add("plan");
                            }
                            if (ServiceTab.CheckBoxfield.IsChecked == true)
                            {
                                listname.Add("field");
                            }
                            if (ServiceTab.CheckBoxassete.IsChecked == true)
                            {
                                listname.Add("assets");
                            }
                            #endregion

                            var serviceList = new List <ServiceActivation>();
                            foreach (var iter in listname)
                            {
                                serviceList.Add(new ServiceActivation());
                                serviceList.Last().service_type = iter;
                                serviceList.Last().project_name = projectName;
                                //test hardcoded Test company name needs to be enter or find out
                                serviceList.Last().company = ServiceTab.Company.Text.Trim();
                                serviceList.Last().email   = AdminMail;
                            }

                            serviceProcess.ActivateServicesProcess(
                                new List <BimProject>(new BimProject[] { currentProject }), serviceList);
                        }
                    }

                    // assign permissions
                    currentFolder = CreateFoldersAndAssignPermissions(csvData, row, projectUsers, folderProcess,
                                                                      folders, currentFolder, currentProject, projectUserProcess);

                    // run the file upload if requested
                    UploadFilesFromFolder(csvData, row, folderProcess, currentFolder, currentProject.id,
                                          options.LocalFoldersPath);
                    //Updates
                    progress.pgb.Value             = 50 + (50 / csvData.Rows.Count * row);
                    progress.ProgressLabel.Content = "Uploading";
                    // ProgressBar "refresh"
                    CallDispatch(progress);
                }
            }
            catch (Exception ex)
            {
                //show the error
                statusbar.Text = ex.Message;
                progress.Close();
                return;
            }

            statusbar.Text = "Upload successful";
            progress.Close();
        }
Example #13
0
        static void Main(string[] args)
        {
            // Delete previous versions of log.txt
            System.IO.File.Delete("Log/logInfo.txt");
            System.IO.File.Delete("Log/logImportant.txt");

            AppOptions options = AppOptions.Parse(args);
            // options.AccountRegion = "EU";

            ProjectWorkflow     projectProcess     = new ProjectWorkflow(options);
            FolderWorkflow      folderProcess      = new FolderWorkflow(options);
            ProjectUserWorkflow projectUserProcess = new ProjectUserWorkflow(options);
            AccountWorkflow     accountProcess     = new AccountWorkflow(options);

            // load data from custom CSV file. Filepath was set in constructor of projectProcess by pushing the options instance
            DataTable csvData = projectProcess.CustomGetDataFromCsv();

            // load all existing projects from the BIM360 environment
            List <BimProject> projects = projectProcess.GetAllProjects();

            List <BimCompany>   companies      = null;
            BimProject          currentProject = null;
            List <HqUser>       projectUsers   = null;
            List <NestedFolder> folders        = null;
            NestedFolder        currentFolder  = null;

            for (int row = 0; row < csvData.Rows.Count; row++)
            {
                string projectName = csvData.Rows[row]["project_name"].ToString();

                // check if the current row defines the start point for another project (project_name column must be set)
                if (!string.IsNullOrEmpty(projectName))
                {
                    Util.LogImportant($"\nCurrent project: {projectName}");

                    // check if the requested project name is already present inside BIM360
                    currentProject = projects.Find(x => x.name == projectName);

                    if (currentProject == null)
                    {
                        // create the project
                        projects = projectProcess.CustomCreateProject(csvData, row, projectName, projectProcess);

                        // set the current project variable to the recently created project
                        currentProject = projects.Find(x => x.name == projectName);

                        // verify the initialization of the new project
                        CheckProjectCreated(currentProject, projectName);
                    }

                    // create the folder structure
                    folders = folderProcess.CustomGetFolderStructure(currentProject);

                    // add the companies
                    companies = accountProcess.CustomUpdateCompanies(csvData, row, accountProcess);

                    // create or update the project users
                    projectUsers = projectUserProcess.CustomUpdateProjectUsers(csvData, row, companies, currentProject, projectUserProcess);
                }

                // assign permissions
                currentFolder = CreateFoldersAndAssignPermissions(csvData, row, projectUsers, folderProcess, folders, currentFolder, currentProject, projectUserProcess);

                // run the file upload if requested
                UploadFilesFromFolder(csvData, row, folderProcess, currentFolder, currentProject.id, options.LocalFoldersPath);
            }
        }
Example #14
0
        public async Task<ActionResult> UpdateProjectStateHistory()
        {
            string projectId = string.Empty;
            try
            {
                var history = _dbContext.ProjectHistory.Where(ph => ph.Type == EventType.ProjectStateChanged).Select(ph => ph.ProjectId).Distinct().ToList();
                var projects = await (from p in Query()
                                      where !p.IsDeleted &&
                                        history.Count(ph => ph == p.Id) == 0 &&
                                        p.ActiveStateId != null &&
                                        p.ActiveStateId != "-1-SEC-QuotationDatas"
                                      select p).ToListAsync();
                int cnt = 0;
                foreach (var p in projects)
                {
                    projectId = p.Id;
                    var projectWorkflow = new ProjectWorkflow(p, _workflowDefinition, new ProjectStoreWorkflowManager(_dbContext), _userManager);
                    var finishedStates = GetFinishedStates(p.Id, projectWorkflow.States.Cast<State>());
                    foreach(var fState in finishedStates)
                    {
                        _historyManager.LogInfo(p.Id, null,
                                            new
                                            {
                                                FromState = fState.FromState,
                                                ToState = fState.ToState,
                                                Model = fState.Model
                                            }, 
                                            EventType.ProjectStateChanged, 
                                            fState.Transition.CreatedBy,
                                            fState.Transition.CreatedOn);
                    }

                    cnt += 1;
                }
                return ActionResult.Success(new { Count = cnt });
            }
            catch (Exception ex)
            {
                return ActionResult.Failed(projectId + ex.Message);
            }
        }
Example #15
0
        public async Task<ActionResult> SetNextStateAsync(AppUser creator, ProjectViewModel currentState)
        {
            try
            {
                var entityProcessors = new BaseProcessor[] { new InvoiceProcessor(_invoiceManager), new InvoicesCollectionProcessor(_invoiceManager) };

                Company company = GetCompany(currentState.Company.Id);

                var project = currentState.Project != null ?
                    currentState.Project :
                    new Project
                    {
                        Id = Guid.NewGuid().ToString(),
                        CreatedBy = creator,
                        CreatedOn = DateTime.UtcNow,
                        Company = company,
                        CompanyId = company.Id,
                        AccountingYear = DateTime.Now.Year,
                        ActiveStateId = _workflowDefinition.GetWorkflowDefinition(company.Name).States.Values.First().Id
                    };

                var projectWorkflow = new ProjectWorkflow(project, _workflowDefinition, new ProjectStoreWorkflowManager(_dbContext), _userManager);
                projectWorkflow.ToBePaid = _invoiceManager.GetToBePaid(projectWorkflow.Id, projectWorkflow.GetStateModel<QuoteOfEntry>()?.AmountTTC);
                projectWorkflow.ToBeInvoiced = _invoiceManager.GetToBeInvoiced(projectWorkflow.Id, projectWorkflow.GetStateModel<QuoteOfEntry>()?.AmountTTC);
                projectWorkflow.InvoicesPaid = _invoiceManager.GetInvoicesPaid(projectWorkflow.Id);
                projectWorkflow.InvoicesToPay = _invoiceManager.GetInvoicesToPay(projectWorkflow.Id);
                projectWorkflow.InvoicesInLate = _invoiceManager.GetInvoicesInLate(projectWorkflow.Id);

                var nextState = projectWorkflow.NextStep(currentState.State, creator, async (parameters) =>
                {
                    foreach (var processor in entityProcessors)
                    {
                        if (processor.CanProcess(parameters.StateModel.GetType()))
                        {
                            await processor.ProcessAsync(parameters);
                        }
                    }
                }, async (alertsParameters) =>
                {
                    await _alertsManager.CreateOnSubmitAlertsAsync(alertsParameters.Project, alertsParameters.Transition, (State)alertsParameters.CurrentState, creator);
                    await _alertsManager.CreateOnEnterAlertsAsync(alertsParameters.Project, alertsParameters.Transition, (State)alertsParameters.NextState, creator);
                });

                if (nextState != null)
                {
                    var result = new ProjectViewModel
                    {
                        Company = company,
                        Project = projectWorkflow,
                        State = nextState,
                        ModelType = nextState.GetModel().GetType().FullName,
                        FinishedStates = GetFinishedStates(project.Id, projectWorkflow.States.Cast<State>()),
                    };

                    if (currentState != null && currentState.State != null)
                    {
                        _historyManager.LogInfo(projectWorkflow.Id,
                                                result.FinishedStates.LastOrDefault()?.Transition?.Id,
                                                new
                                                {
                                                    FromState = currentState.State,
                                                    ToState = nextState,
                                                    Model = (projectWorkflow.States.FirstOrDefault(s => s.Id == currentState.State.Id)?.Model as BaseStateModel)?.ToDictionary().Select(k => new Tuple<string, object>(k.Key, k.Value))
                                                },
                                                EventType.ProjectStateChanged,
                                                creator);
                    }

                    UpdateAggregatedList(project.Id);
                    return ActionResult<ProjectViewModel>.Success(result);
                }
                else if (projectWorkflow.States.Last().Id == currentState.State.Id)
                {
                    project = Query().First(p => p.Id == project.Id);
                    project.IsArchived = true;
                    _dbContext.SaveChanges();

                    var result = new ProjectViewModel
                    {
                        Project = new ProjectWorkflow(project, _workflowDefinition, new ProjectStoreWorkflowManager(_dbContext), _userManager),
                    };
                    UpdateAggregatedList(project.Id);
                    return ActionResult<ProjectViewModel>.Success(result);
                }
                throw new InvalidOperationException($"Cannot process state {currentState.State.Id}");
            }
            catch (Exception ex)
            {
                try
                {
                    ex.Data.Add("creator", JsonConvert.SerializeObject(creator));
                    ex.Data.Add("currentState", JsonConvert.SerializeObject(currentState));
                }
                catch { }
                return ActionResult.Failed(ex);
            }
        }
Example #16
0
 private void CreateScheduledAlerts(IEnumerable<Alert> alerts, ProjectWorkflow project,
     StateTransition<string> transition, State state, AppUser currentUser)
 {
     foreach (var alert in alerts)
     {
         var item = new ProjectAlertScheduled
         {
             AlertLinkId = alert.Id,
             ProjectId = project.Id,
             StateId = state.Id,
             TransitionId = int.Parse(transition.Id)
         };
         _dbContext.ProjectAlertsScheduled.Add(item);
     }
     if (alerts.Any())
     {
         _dbContext.SaveChanges();
     }
 }
Example #17
0
        private async Task CreateAlertsAsync(IEnumerable<Alert> alerts, ProjectWorkflow project,
            StateTransition<string> transition, State state, AppUser currentUser)
        {
            dynamic model = project.GetComplexModel(state.Id);

            foreach (var alert in alerts)
            {
                var matchProperties = true;
                foreach (var condition in alert.ConditionQuery.Where(c => !string.IsNullOrEmpty(c)))
                {
                    if (!project.GetComplexModelDictionary(state.Id).AsQueryable().Where(condition).Any())
                    {
                        matchProperties = false;
                        break;
                    }
                }
                if (!matchProperties)
                {
                    continue;
                }

                var projectAlert = new ProjectAlert
                {
                    CreatedBy = currentUser,
                    CreatedById = currentUser.Id,
                    ProjectId = project.Id,
                    StartDate = alert.IsRecurrent ? (DateTime?)null : DateTime.UtcNow,
                    CreatedOn = DateTime.UtcNow,
                    StateId = state.Id,
                    //IsFired = isFired,
                    IsRecurrent = alert.IsRecurrent,
                    CommitActionName = alert.CommitActionName,
                    TransitionId = int.Parse(transition.Id),
                    AlertLinkId = alert.Id
                };
                _dbContext.ProjectAlerts.Add(projectAlert);

                if (!alert.IsRecurrent)
                {
                    var message = new AlertMessage
                    {
                        From = GetEmailsByRole(alert.Action.MessageTemplate.From),
                        To = GetEmailsByRole(alert.Action.MessageTemplate.To),
                        Subject = alert.Action.MessageTemplate.Subject ?? $"{project.Company.Name} alert",
                        Body = await GetMessageHtml(alert.Action.MessageTemplate.Body, model)
                    };
                    alert.Action.DoAction(message);

                    _dbContext.ProjectAlertActions.Add(new ProjectAlertAction
                    {
                        ProjectAlert = projectAlert,
                        ProjectAlertId = projectAlert.Id,
                        From = alert.Action.MessageTemplate.From,
                        To = alert.Action.MessageTemplate.To,
                        Subject = alert.Action.MessageTemplate.Subject,
                        Body = message.Body
                    });
                }

                _historyManager.LogInfo(projectAlert.ProjectId, projectAlert.TransitionId, projectAlert, EventType.FireAlert, currentUser);
            }
            //if (alerts.Any())
            {
                _dbContext.SaveChanges();
            }
        }
Example #18
0
        public async Task<ActionResult> CreateOnSubmitAlertsAsync(ProjectWorkflow project,
            StateTransition<string> transition, State state, AppUser currentUser)
        {
            try
            {
                if (state == null)
                {
                    return ActionResult.Failed("State not set");
                }
                var submitAlertsDef = project.WorkflowDefinition
                    .Alerts
                    .Where(a => a.State.Id == state.Id)
                    .SelectMany(a => a.OnSubmitAlerts).ToList();
                await CreateAlertsAsync(submitAlertsDef, project, transition, state, currentUser);

                var scheduledAlertsDef = project.WorkflowDefinition
                    .Alerts
                    .Where(a => a.State.Id == state.Id)
                    .SelectMany(a => a.ScheduledAlerts).ToList();
                CreateScheduledAlerts(scheduledAlertsDef, project, transition, state, currentUser);

                return ActionResult.Success();
            }
            catch (Exception ex)
            {
                return ActionResult.Failed(ex);
            }
        }
		private void Execute(Func<ProjectAlertScheduled, string[]> getConditionStrings, Func<ProjectAlertScheduled, ProjectWorkflow, string, int?, bool> checkCondition)
        {
            var scheduledAlerts = GetScheduledAlerts().ToList();
            var projectsCache = new Dictionary<string, ProjectWorkflow>();
            foreach (var alert in scheduledAlerts)
            {
                var conditionStrings = getConditionStrings(alert);

                if (!conditionStrings.Any())
                {
                    continue;
                }

                ProjectWorkflow project;
                if (!projectsCache.TryGetValue(alert.Project.Id, out project))
                {
                    project = new ProjectWorkflow(alert.Project, _workflowDefinition,
                            new ProjectStoreWorkflowManager(_dbContext));
                    projectsCache.Add(alert.Project.Id, project);
                }
                
                if (project.IsDeleted || project.IsArchived)
                {
                    _dbContext.ProjectAlertsScheduled.Remove(alert);
                    continue;
                }
                //if(_dbContext.ProjectAlerts.Any(pa => pa.ProjectId == project.Id && pa.AlertLinkId == alert.AlertLinkId && pa.CreatedOn.Date == DateTime.UtcNow.Date))
                //{
                //    continue;
                //}

                var matchProperties = true;
                foreach (var condition in conditionStrings.Where(c => !string.IsNullOrEmpty(c)))
                {
                    if (!checkCondition(alert, project, condition, alert.InvoiceId))
                    {
                        matchProperties = false;
                        break;
                    }
                }
                if (!matchProperties)
                {
                    continue;
                }

                var alertLink =
                        _dbContext.AlertToProjectLinks.Include(a => a.Conditions)
                            .FirstOrDefault(a => a.Id == int.Parse(alert.AlertLinkId));

                var projectAlert = new ProjectAlert
                {
                    CreatedBy = alert?.Transition?.CreatedBy,
                    CreatedById = alert?.Transition?.CreatedBy?.Id,
                    ProjectId = project.Id,
                    StartDate = DateTime.UtcNow,
                    CreatedOn = DateTime.UtcNow,
                    StateId = alert.StateId,
                    IsRecurrent = false,
                    CommitActionName = alertLink?.CommitActionName,
                    TransitionId = alert.TransitionId,
                    AlertLinkId = alert.AlertLinkId
                };
                _dbContext.ProjectAlerts.Add(projectAlert);

                var qNum = (project.States[0].Model as QuoteOfEntry)?.QuotationNumber;
                var body = Task.Run(() => GetMessageHtml(alertLink?.Body, project.GetComplexModel(alert.StateId))).Result.Result;

                if (!((string)body).Contains(qNum))
                {
                    throw new InvalidOperationException($"qNum: {qNum}, body: {body}");
                }

                if (alertLink.SendEmail)
                {
                    var subject = Task.Run(() => GetMessageHtml((alertLink?.Subject ?? $"{project.Company.Name} alert"), project.GetComplexModel(alert.StateId))).Result.Result;
                    var message = new AlertMessage
                    {
                        From = GetEmailsByRole(alertLink?.From),
                        To = GetEmailsByRole(alertLink?.To),
                        Subject = subject,
                        Body = body
                    };

                    var mailAction = new MailAlertAction();
                    mailAction.DoAction(message);
                }

                _dbContext.ProjectAlertActions.Add(new ProjectAlertAction
                {
                    ProjectAlert = projectAlert,                    
                    From = alertLink?.From,
                    To = alertLink?.To,
                    Subject = alertLink?.Subject,
                    Body = body
                });
				
				if (!alertLink.IsRecurrent)
                {
                    _dbContext.ProjectAlertsScheduled.Remove(alert);
                }

                _historyManager.LogInfo(projectAlert.ProjectId, projectAlert.TransitionId, projectAlert, EventType.FireAlert, null);
                _dbContext.SaveChanges();
            }
        }
Example #20
0
 public ProjectWorkflowWrapper(ProjectWorkflow workflow)
 {
     _workflow = workflow;
 }
Example #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetTemplate_OnClick(object sender, RoutedEventArgs e)
        {
            var progress = new updates_upload();

            progress.Show();

            //Updates
            progress.pgb.Value             = 10;
            progress.ProgressLabel.Content = "Build Connection";
            // ProgressBar "refresh"
            CallDispatch(progress);

            string[] input = new string[] { "-c", ClientId, "-s", ClientSecret, "-a", BimId,
                                            "-h", AdminMail, "-f", " .\\sample", "-t", ",",
                                            "-z", ",", "-e", "UTF-8", "-d", "yyyy-MM-dd" };

            AppOptions options = AppOptions.Parse(input);

            // options.AccountRegion = "EU";
            options.AdminRole = "Project Manager";

            ProjectWorkflow projectProcess = new ProjectWorkflow(options);
            FolderWorkflow  folderProcess  = new FolderWorkflow(options);

            System.Threading.Thread.Sleep(1000);
            // load all existing projects from the BIM360 environment
            List <BimProject> projects = projectProcess.GetAllProjects();

            //Updates
            progress.pgb.Value             = 30;
            progress.ProgressLabel.Content = "Download Project";
            // ProgressBar "refresh"
            CallDispatch(progress);

            BimProject currentProject = null;

            // get project from bim360
            try
            {
                currentProject = projects.Find(x => x.name == TextBoxTemplate.Text.Trim());
            }
            catch (Exception)
            {
                statusbar.Text = "No Project with the name:" + TextBoxTemplate.Text.Trim() + " found!";
                return;
            }
            if (currentProject == null)
            {
                return;
            }

            var nestedfolders = folderProcess.CustomGetFolderStructure(currentProject);

            foreach (var iterfolder in nestedfolders)
            {
            }

            progress.pgb.Value             = 50;
            progress.ProgressLabel.Content = "Converte to local Project 0/2";
            // ProgressBar "refresh"
            CallDispatch(progress);


            var newproject = new Bim360Project(TextBoxTemplate.Text.Trim());

            newproject.ProjectType = Selection.SelectProjectType(currentProject.project_type);
            var roots = new List <Folder>();

            //hier rekursive alle ordner finden
            foreach (var iterfolder in nestedfolders)
            {
                roots.Add(getNestedFolder(iterfolder));
                progress.pgb.Value             = 70;
                progress.ProgressLabel.Content = "Converte to local Project 1/2";
                // ProgressBar "refresh"
                CallDispatch(progress);
            }
            //here hardcoded plan and projectfiles need to be changed in the furtuer if  ACC comes
            if (roots[0].Name == "Plans")
            {
                newproject.Plans        = roots[0];
                newproject.ProjectFiles = roots[1];
            }
            else
            {
                newproject.Plans        = roots[1];
                newproject.ProjectFiles = roots[0];
            }

            AccProjectConfig.ProjectsView.ItemsSource = AccProjectConfig.projects;
            AccProjectConfig.projects.Add(newproject);
            AccProjectConfig.ProjectsView.Items.Refresh();
            progress.Close();
            statusbar.Text = "Import successful";
        }
Example #22
0
        public async Task<ActionResult> UpdateStateAsync(AppUser creator, ProjectViewModel currentState = null)
        {
            try
            {
                Company company = GetCompany(currentState.Company.Id);

                if (currentState.Project == null)
                {
                    return ActionResult.Failed("Project was not created");
                }

                var entityProcessors = new BaseProcessor[] { new InvoiceProcessor(_invoiceManager), new InvoicesCollectionProcessor(_invoiceManager) };

                var projectWorkflow = new ProjectWorkflow(currentState.Project, _workflowDefinition, new ProjectStoreWorkflowManager(_dbContext), _userManager);
                projectWorkflow.UpdateState(currentState.State, creator, async (parameters) =>
                {
                    foreach (var processor in entityProcessors)
                    {
                        if (processor.CanProcess(parameters.StateModel.GetType()))
                        {
                            await processor.ProcessAsync(parameters);
                        }
                    }
                });

                var result = new ProjectViewModel
                {
                    Company = company,
                    Project = projectWorkflow,
                    State = projectWorkflow.States.OfType<State>().FirstOrDefault(s => s.Id == currentState.State.Id),
                    ModelType = _workflowDefinition.GetWorkflowDefinition(company.Name).States[currentState.State.Id].GetModel().GetType().FullName,
                    FinishedStates = currentState.FinishedStates,
                };
                UpdateAggregatedList(currentState.Project.Id);

                if (currentState != null && currentState.State != null) {
                    _historyManager.LogInfo(currentState.Project.Id, null,
                                        new
                                        {
                                            FromState = currentState.State,
                                            ToState = currentState.State,
                                            Model = (projectWorkflow.States.FirstOrDefault(s => s.Id == currentState.State.Id)?.Model as BaseStateModel)?.ToDictionary().Select(k => new Tuple<string, object>(k.Key, k.Value))
                                        }, (EventType)99, creator);
                }

                return ActionResult<ProjectViewModel>.Success(result);
            }
            catch (Exception ex)
            {
                return ActionResult.Failed(ex);
            }
        }
Example #23
0
        public async Task<ActionResult> SkipStateAsync(AppUser creator, ProjectViewModel currentState)
        {
            try
            {
                Company company = GetCompany(currentState.Company.Id);

                if (currentState.Project == null)
                {
                    return ActionResult.Failed("Project was not created");
                }

                var projectWorkflow = new ProjectWorkflow(currentState.Project, _workflowDefinition, new ProjectStoreWorkflowManager(_dbContext), _userManager);
                var nextState = projectWorkflow.SkipState(currentState.State, creator, _alertsManager);

                if (nextState != null)
                {
                    var result = new ProjectViewModel
                    {
                        Company = company,
                        Project = projectWorkflow,
                        State = nextState,
                        ModelType = nextState.GetModel().GetType().FullName,
                        FinishedStates = GetFinishedStates(currentState.Project.Id, projectWorkflow.States.Cast<State>()),
                    };
                    UpdateAggregatedList(currentState.Project.Id);
                    return ActionResult<ProjectViewModel>.Success(result);
                }
                throw new InvalidOperationException($"Cannot process state {currentState.State.Id}");
            }
            catch (Exception ex)
            {
                return ActionResult.Failed(ex);
            }
        }
Example #24
0
        protected override void Seed(Semplicita.Models.ApplicationDbContext context)
        {
            bool seedDemo = false;


            RoleManager <IdentityRole> roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            try {
                #region Roles Generation

                if (!context.Roles.Any(r => r.Name == "ServerAdmin"))
                {
                    roleManager.Create(new IdentityRole {
                        Name = "ServerAdmin"
                    });
                }
                if (!context.Roles.Any(r => r.Name == "ProjectAdmin"))
                {
                    roleManager.Create(new IdentityRole {
                        Name = "ProjectAdmin"
                    });
                }
                if (!context.Roles.Any(r => r.Name == "SuperSolver"))
                {
                    roleManager.Create(new IdentityRole {
                        Name = "SuperSolver"
                    });
                }
                if (!context.Roles.Any(r => r.Name == "Solver"))
                {
                    roleManager.Create(new IdentityRole {
                        Name = "Solver"
                    });
                }
                if (!context.Roles.Any(r => r.Name == "Reporter"))
                {
                    roleManager.Create(new IdentityRole {
                        Name = "Reporter"
                    });
                }

                #endregion Roles Generation

                #region User Creation

                //stores
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new UserManager <ApplicationUser>(userStore);

                //Matthew
                if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                {
                    var user = new ApplicationUser {
                        UserName        = "******",
                        Email           = "*****@*****.**",
                        FirstName       = "Matthew",
                        LastName        = "Wendel",
                        AvatarImagePath = "/img/avatars/matthew.png"
                    };
                    userManager.Create(user, "Abcd3FG#");
                    userManager.AddToRole(user.Id, "ServerAdmin");
                }

                //Jason
                if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                {
                    var user = new ApplicationUser {
                        UserName        = "******",
                        Email           = "*****@*****.**",
                        FirstName       = "Jason",
                        LastName        = "Twichell",
                        AvatarImagePath = "/img/avatars/jason.png"
                    };
                    userManager.Create(user, "Abc&123!");
                    userManager.AddToRole(user.Id, "ProjectAdmin");
                }

                //Drew
                if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                {
                    var user = new ApplicationUser {
                        UserName        = "******",
                        Email           = "*****@*****.**",
                        FirstName       = "Andrew",
                        LastName        = "Russell",
                        AvatarImagePath = "/img/avatars/andrew.png"
                    };
                    userManager.Create(user, "Abc&123!");
                    userManager.AddToRole(user.Id, "SuperSolver");
                }


                //Shelby (Reporter)
                if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                {
                    var user = new ApplicationUser {
                        UserName        = "******",
                        Email           = "*****@*****.**",
                        FirstName       = "Shelby",
                        LastName        = "Holtzclaw",
                        AvatarImagePath = "/img/avatars/shelby.png"
                    };
                    userManager.Create(user, "ShelbyH!");
                    userManager.AddToRole(user.Id, "Reporter");
                }


                #endregion User Creation

                #region TicketType Creation

                if (!context.TicketTypes.Any(tt => tt.Name == "Missing/Broken Dependancy"))
                {
                    context.TicketTypes.Add(new TicketType()
                    {
                        Name = "Missing/Broken Dependancy", Description = "The issue is suspected of originating from a missing, corrupt, or outdated package/module."
                    });
                }
                if (!context.TicketTypes.Any(tt => tt.Name == "Bug"))
                {
                    context.TicketTypes.Add(new TicketType()
                    {
                        Name = "Bug", Description = "Normal functionality is breaking when the user is operating in particular conditions."
                    });
                }
                if (!context.TicketTypes.Any(tt => tt.Name == "Not as Intended"))
                {
                    context.TicketTypes.Add(new TicketType()
                    {
                        Name = "Not as Intended", Description = "A feature is not working within proper specification, or is not generating proper results."
                    });
                }
                if (!context.TicketTypes.Any(tt => tt.Name == "Aesthetic Correction"))
                {
                    context.TicketTypes.Add(new TicketType()
                    {
                        Name = "Aesthetic Correction", Description = "A request for spelling correction, grammar validation, paragraph structure, or layout changes. This issue should not be impactful to functionality."
                    });
                }
                if (!context.TicketTypes.Any(tt => tt.Name == "Feature Request"))
                {
                    context.TicketTypes.Add(new TicketType()
                    {
                        Name = "Feature Request", Description = "Features that the reporter desires are missing, and this request is for consideration to add the requested feature."
                    });
                }

                context.SaveChanges();

                #endregion TicketType Creation

                #region TicketPriority Creation

                if (!context.TicketPriorityTypes.Any(tpt => tpt.Name == "Low"))
                {
                    var priority = new TicketPriority()
                    {
                        Name = "Low",
                        Rank = 100
                    };

                    context.TicketPriorityTypes.Add(priority);
                }
                if (!context.TicketPriorityTypes.Any(tpt => tpt.Name == "Medium"))
                {
                    var priority = new TicketPriority()
                    {
                        Name = "Medium",
                        Rank = 50
                    };

                    context.TicketPriorityTypes.Add(priority);
                }
                if (!context.TicketPriorityTypes.Any(tpt => tpt.Name == "High"))
                {
                    var priority = new TicketPriority()
                    {
                        Name = "High",
                        Rank = 1
                    };

                    context.TicketPriorityTypes.Add(priority);
                }

                context.SaveChanges();

                #endregion TicketPriority Creation

                #region TicketStatus Creation

                if (!context.TicketStatuses.Any(tst => tst.Name == "New-Unassigned"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "New-Unassigned",
                        Display          = "New (Unassigned)",
                        DisplayForeColor = "#000000",
                        DisplayBackColor = "#EC860F",
                        Description      = "The issue has just been created, and has not been assigned to a solver yet.",
                        IsStarted        = false,
                        MustBeAssigned   = false,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = true,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "New-Assigned"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "New-Assigned",
                        Display          = "New",
                        DisplayForeColor = "#000000",
                        DisplayBackColor = "#DDE31E",
                        Description      = "The issue has been created, and has been assigned to a solver pending first contact.",
                        IsStarted        = false,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = false,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = true
                    };
                    context.TicketStatuses.Add(status);
                }

                if (!context.TicketStatuses.Any(tst => tst.Name == "Investigation"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Investigation",
                        Display          = "Investigation",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#509D8D",
                        Description      = "The solver has started looking into potential solutions for the reporter's inquiry.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = true,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = true,
                        ShouldWorkflowContinueStaff    = true
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "Reviewing"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Reviewing",
                        Display          = "Under Review",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#509D8D",
                        Description      = "The solver needs time to review findings before working on implementing a solution.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = true,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "InProgress"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "InProgress",
                        Display          = "Solution In Progress",
                        DisplayForeColor = "#000",
                        DisplayBackColor = "#32E89F",
                        Description      = "The solver is in the middle of implimenting a potential solution discovered.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = true,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "ReporterWaiting"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "ReporterWaiting",
                        Display          = "Reporter Waiting",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#96389C",
                        Description      = "The reporter has added additional information, and is waiting for confirmation from the solver.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = true,
                        IsForStaff       = false,
                        ShouldWorkflowContinueReporter = true,
                        ShouldWorkflowContinueStaff    = true,
                    };
                    context.TicketStatuses.Add(status);
                }

                if (!context.TicketStatuses.Any(tst => tst.Name == "Solved"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Solved",
                        Display          = "Solved!",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#428A3B",
                        Description      = "The reporter's issue has been resolved, and resulted in a resolution that alligns with the intended outcome of their inquiry.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = true,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }


                if (!context.TicketStatuses.Any(tst => tst.Name == "NeedInfo"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "NeedInfo",
                        Display          = "More Information Required",
                        DisplayForeColor = "#000",
                        DisplayBackColor = "#C8687B",
                        Description      = "This issue cannot be worked on with the information redialy available. More information is required from the reporter before work can continue.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = true,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = true,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "Pending"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Pending",
                        Display          = "Pending/Blocked",
                        DisplayForeColor = "#000",
                        DisplayBackColor = "#4C60BB",
                        Description      = "This issue cannot be worked on at the moment due to other pending issues, or because a potential solution has not yet been found.",
                        IsStarted        = true,
                        MustBeAssigned   = true,
                        IsInProgress     = false,
                        IsPausedPending  = true,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = false,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "CantSolve"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "CantSolve",
                        Display          = "Can't Solve",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#D74242",

                        Description     = "The reporter's issue was not able to be solved due to a block or obstruction that would result from available potential solutions.",
                        IsStarted       = true,
                        MustBeAssigned  = true,
                        IsInProgress    = false,
                        IsPausedPending = false,
                        IsResolved      = false,
                        IsClosed        = false,
                        IsCanceled      = true,
                        IsForReporter   = false,
                        IsForStaff      = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "WontSolve"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "WontSolve",
                        Display          = "Refused/Won't Solve",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#933030",
                        Description      = "The reporter's issue will not be solved, because the reporter is inquiring about intended functionality or a procedure that is actually working as intended.",
                        IsStarted        = true,
                        MustBeAssigned   = false,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = false,
                        IsCanceled       = true,
                        IsForReporter    = false,
                        IsForStaff       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }

                if (!context.TicketStatuses.Any(tst => tst.Name == "Closed"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Closed",
                        Display          = "Closed",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#7D7D7D",
                        Description      = "The reporter's issue has been resolved and has been confirmed as satisfactory with the reporter.",
                        IsStarted        = true,
                        MustBeAssigned   = false,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = true,
                        IsClosed         = true,
                        IsCanceled       = false,
                        IsArchived       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "ApprovedAnswer"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "ApprovedAnswer",
                        Display          = "ApprovedAnswer",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#7D7D7D",
                        Description      = "The answer to this question is sealed as a credible solution.",
                        IsStarted        = true,
                        MustBeAssigned   = false,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = true,
                        IsClosed         = true,
                        IsCanceled       = false,
                        IsArchived       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }
                if (!context.TicketStatuses.Any(tst => tst.Name == "Disposed"))
                {
                    var status = new TicketStatus()
                    {
                        Name             = "Disposed",
                        Display          = "Disposed",
                        DisplayForeColor = "#FFF",
                        DisplayBackColor = "#4F4F4F",
                        Description      = "The reporter's issue was canceled, and has been archived.",
                        IsStarted        = true,
                        MustBeAssigned   = false,
                        IsInProgress     = false,
                        IsPausedPending  = false,
                        IsResolved       = false,
                        IsClosed         = true,
                        IsCanceled       = true,
                        IsArchived       = true,
                        ShouldWorkflowContinueReporter = false,
                        ShouldWorkflowContinueStaff    = false,
                    };
                    context.TicketStatuses.Add(status);
                }

                context.SaveChanges();

                #endregion TicketStatus Creation

                #region Project Workflow Creation

                if (!context.ProjectWorkflows.Any(pwf => pwf.Name == "Blank Workflow"))
                {
                    var workflow = new ProjectWorkflow()
                    {
                        Name        = "Blank Workflow",
                        Description = "As named, this allows tickets to flow through projects, with all statuses being set manually.",
                        CreatedAt   = DateTime.Now,

                        AutoTicketAssignBehavior = ProjectWorkflow.AutoTicketAssignBehaviorType.LeaveUnassigned,


                        ArchivedNotResolvedStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Disposed").Id,
                        ArchivedResolvedStatusId    = context.TicketStatuses.ToList().First(ts => ts.Name == "Closed").Id,


                        CanStaffSetStatusOnInteract       = true,
                        CanTicketOwnerSetStatusOnInteract = true
                    };

                    context.ProjectWorkflows.Add(workflow);
                }
                if (!context.ProjectWorkflows.Any(pwf => pwf.Name == "Default Workflow"))
                {
                    var workflow = new ProjectWorkflow()
                    {
                        Name        = "Default Workflow",
                        Description = "An example workflow that takes tickets into standard statuses upon normal interactions.",
                        CreatedAt   = DateTime.Now,

                        AutoTicketAssignBehavior = ProjectWorkflow.AutoTicketAssignBehaviorType.EvenSteven,

                        InitialTicketStatusId          = context.TicketStatuses.ToList().First(ts => ts.Name == "New-Unassigned").Id,
                        TicketUnassignedStatusId       = context.TicketStatuses.ToList().First(ts => ts.Name == "New-Unassigned").Id,
                        TicketAssignedStatusId         = context.TicketStatuses.ToList().First(ts => ts.Name == "New-Assigned").Id,
                        ReporterInteractionStatusId    = context.TicketStatuses.ToList().First(ts => ts.Name == "ReporterWaiting").Id,
                        SolverInteractionStatusId      = context.TicketStatuses.ToList().First(ts => ts.Name == "Investigation").Id,
                        SuperSolverInteractionStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Investigation").Id,
                        ProjMgrInteractionStatusId     = context.TicketStatuses.ToList().First(ts => ts.Name == "Investigation").Id,
                        ServerAdminInteractionStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Investigation").Id,

                        ArchivedNotResolvedStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Disposed").Id,
                        ArchivedResolvedStatusId    = context.TicketStatuses.ToList().First(ts => ts.Name == "Closed").Id,

                        CanStaffSetStatusOnInteract       = true,
                        CanTicketOwnerSetStatusOnInteract = false
                    };

                    context.ProjectWorkflows.Add(workflow);
                }
                if (!context.ProjectWorkflows.Any(pwf => pwf.Name == "Q&A Workflow"))
                {
                    var workflow = new ProjectWorkflow()
                    {
                        Name        = "Q&A Workflow",
                        Description = "This workflow is used in projects where the reporter creates a ticket with an epic/question, and a response is provided by a staff member to reach resolution. If the answer is accepted by the reporter, the response is finalized.",
                        CreatedAt   = DateTime.Now,

                        AutoTicketAssignBehavior = ProjectWorkflow.AutoTicketAssignBehaviorType.RoundRobin,

                        InitialTicketStatusId          = context.TicketStatuses.ToList().First(ts => ts.Name == "ReporterWaiting").Id,
                        TicketUnassignedStatusId       = context.TicketStatuses.ToList().First(ts => ts.Name == "ReporterWaiting").Id,
                        TicketAssignedStatusId         = context.TicketStatuses.ToList().First(ts => ts.Name == "ReporterWaiting").Id,
                        ReporterInteractionStatusId    = context.TicketStatuses.ToList().First(ts => ts.Name == "ReporterWaiting").Id,
                        SolverInteractionStatusId      = context.TicketStatuses.ToList().First(ts => ts.Name == "Solved").Id,
                        SuperSolverInteractionStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Solved").Id,
                        ProjMgrInteractionStatusId     = context.TicketStatuses.ToList().First(ts => ts.Name == "Solved").Id,
                        ServerAdminInteractionStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Solved").Id,

                        ArchivedNotResolvedStatusId = context.TicketStatuses.ToList().First(ts => ts.Name == "Disposed").Id,
                        ArchivedResolvedStatusId    = context.TicketStatuses.ToList().First(ts => ts.Name == "Closed").Id,

                        CanStaffSetStatusOnInteract       = true,
                        CanTicketOwnerSetStatusOnInteract = false
                    };

                    context.ProjectWorkflows.Add(workflow);
                }

                context.SaveChanges();

                #endregion Project Workflow Creation

                #region Project Creation

                if (!context.Projects.Any(p => p.Name == "Default Project"))
                {
                    var project = new Project()
                    {
                        Name             = "Default Project",
                        Description      = "The default project that issues get placed into.",
                        TicketTag        = "DEF",
                        CreatedAt        = DateTime.Now,
                        ProjectManagerId = context.Users.First(u => u.Email == "*****@*****.**").Id,
                        IsActiveProject  = true,

                        Members = new List <ApplicationUser>()
                        {
                            context.Users.ToList().First(u => u.Email == "*****@*****.**"),
                            context.Users.ToList().First(u => u.Email == "*****@*****.**"),
                            context.Users.ToList().First(u => u.Email == "*****@*****.**")
                        },

                        ActiveWorkflowId = context.ProjectWorkflows.ToList().FirstOrDefault(pwf => pwf.Name == "Default Workflow").Id
                    };
                    context.Projects.Add(project);
                }

                context.SaveChanges();
                #endregion Project Creation

                if (seedDemo)
                {
                    #region Demo Components
                    //Demo Users
                    if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                    {
                        var user = new ApplicationUser {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            FirstName      = "Demo:",
                            LastName       = "Server Admin",
                            EmailConfirmed = true,
                            IsDemoUser     = true
                        };
                        userManager.Create(user, Util.GetSetting("demo:Password"));
                        userManager.AddToRole(user.Id, "ServerAdmin");
                    }
                    if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                    {
                        var user = new ApplicationUser {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            FirstName      = "Demo:",
                            LastName       = "Project Admin",
                            EmailConfirmed = true,
                            IsDemoUser     = true
                        };
                        userManager.Create(user, Util.GetSetting("demo:Password"));
                        userManager.AddToRole(user.Id, "ProjectAdmin");
                    }
                    if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                    {
                        var user = new ApplicationUser {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            FirstName      = "Demo:",
                            LastName       = "Super Solver",
                            EmailConfirmed = true,
                            IsDemoUser     = true
                        };
                        userManager.Create(user, Util.GetSetting("demo:Password"));
                        userManager.AddToRole(user.Id, "SuperSolver");
                    }
                    if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                    {
                        var user = new ApplicationUser {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            FirstName      = "Demo:",
                            LastName       = "Solver",
                            EmailConfirmed = true,
                            IsDemoUser     = true
                        };
                        userManager.Create(user, Util.GetSetting("demo:Password"));
                        userManager.AddToRole(user.Id, "Solver");
                    }
                    if (!context.Users.Any(u => u.Email == "*****@*****.**"))
                    {
                        var user = new ApplicationUser {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            FirstName      = "Demo:",
                            LastName       = "Reporter",
                            EmailConfirmed = true,
                            IsDemoUser     = true
                        };
                        userManager.Create(user, Util.GetSetting("demo:Password"));
                        userManager.AddToRole(user.Id, "Reporter");
                    }
                    #endregion
                }
            } catch (DbEntityValidationException e) {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw e;
            }
        }
Example #25
0
        /// <summary>
        /// runs the upload to the BIM360 environment
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Upload_OnClick(object sender, RoutedEventArgs e)
        {
            var progress = new updates_upload();

            progress.Show();
            //main window closing prevention
            try
            {
                // convert string to stream
                byte[]       byteArray = Encoding.UTF8.GetBytes(AccProjectConfig.ExportBim360Projects());
                MemoryStream dataset   = new MemoryStream(byteArray);
                //dataset.Position = 0;


                //Updates
                progress.pgb.Value             = 10;
                progress.ProgressLabel.Content = "Build Connection";
                // ProgressBar "refresh"
                CallDispatch(progress);

                //input for upload
                string[] input = new string[]
                {
                    "-c", ClientId, "-s", ClientSecret, "-a", BimId,
                    "-h", AdminMail, "-f", " .\\sample", "-t", ",",
                    "-z", ",", "-e", "UTF-8", "-d", "yyyy-MM-dd"
                };

                // specify a folder in the %APPDATA% to store the logging files
                var loggingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                // Delete previous versions of log.txt
                try
                {
                    System.IO.File.Delete(Path.Combine(loggingFolder, "Bim360Interface/logInfo.txt"));
                    System.IO.File.Delete(Path.Combine(loggingFolder, "Bim360Interface/logInfo_important.txt"));
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    // throw;
                }

                AppOptions options = AppOptions.Parse(input);
                // options.AccountRegion = "EU";
                options.AdminRole = "Project Manager";

                ProjectWorkflow projectProcess = new ProjectWorkflow(options);
                System.Threading.Thread.Sleep(1000);
                // load all existing projects from the BIM360 environment
                List <BimProject> projects = projectProcess.GetAllProjects();

                FolderWorkflow      folderProcess      = new FolderWorkflow(options);
                ProjectUserWorkflow projectUserProcess = new ProjectUserWorkflow(options);
                AccountWorkflow     accountProcess     = new AccountWorkflow(options);

                // this is the admin mail to activate the projects
                var adminMail = AdminMail;
                //Get defaut company name
                string defaultcomp;
                try
                {
                    defaultcomp = folderProcess.CustomDefaultCompanyName(adminMail);
                }
                catch (NullReferenceException)
                {
                    defaultcomp = "DefaultCompany";
                }

                //Updates
                progress.pgb.Value             = 25;
                progress.ProgressLabel.Content = "Convert Data from GUI";
                // ProgressBar "refresh"
                CallDispatch(progress);

                // load data from custom CSV file. Filepath was set in constructor of projectProcess by pushing the options instance
                DataTable csvData = new DataTable();
                csvData = ProjectWorkflow.CustomGetDataFromCsv_stream(dataset);

                //Updates
                progress.pgb.Value             = 40;
                progress.ProgressLabel.Content = "Uploading";
                // ProgressBar "refresh"
                CallDispatch(progress);

                List <BimCompany>   companies      = null;
                BimProject          currentProject = null;
                List <HqUser>       projectUsers   = null;
                List <NestedFolder> folders        = null;
                NestedFolder        currentFolder  = null;

                //Uploading
                try
                {
                    for (int row = 0; row < csvData.Rows.Count; row++)
                    {
                        string projectName = csvData.Rows[row]["project_name"].ToString();

                        // check if the current row defines the start point for another project (project_name column must be set)
                        if (!string.IsNullOrEmpty(projectName))
                        {
                            Util.LogImportant($"\nCurrent project: {projectName}");

                            // check if the requested project name is already present inside BIM360
                            currentProject = projects.Find(x => x.name == projectName);

                            if (currentProject == null)
                            {
                                // create the project
                                projects = projectProcess.CustomCreateProject(csvData, row, projectName,
                                                                              projectProcess);

                                // set the current project variable to the recently created project
                                currentProject = projects.Find(x => x.name == projectName);

                                // verify the initialization of the new project
                                CheckProjectCreated(currentProject, projectName);
                            }



                            // create the folder structure
                            folders = folderProcess.CustomGetFolderStructure(currentProject, adminMail);



                            // add the companies
                            companies = accountProcess.CustomUpdateCompanies(csvData, row, accountProcess);

                            // create or update the project users
                            projectUsers = projectUserProcess.CustomUpdateProjectUsers(csvData, row, companies,
                                                                                       currentProject, projectUserProcess);


                            //activate services
                            ServiceWorkflow serviceProcess = new ServiceWorkflow(options);

                            #region Add Services

                            // admin and doc_manage should be always activated
                            var serviceShortcuts = new List <string> {
                                "admin", "doc_manage"
                            };

                            // check which service should be activated in addition to admin and doc_manage
                            if (ServiceTab.CheckBoxProjectManagement.IsChecked == true)
                            {
                                serviceShortcuts.Add("pm");
                            }

                            if (ServiceTab.CheckBoxFieldManagement.IsChecked == true)
                            {
                                serviceShortcuts.Add("fng");
                            }

                            if (ServiceTab.CheckBoxDesignCollab.IsChecked == true)
                            {
                                serviceShortcuts.Add("collab");
                            }

                            if (ServiceTab.CheckBoxCostManagement.IsChecked == true)
                            {
                                serviceShortcuts.Add("cost");
                            }

                            if (ServiceTab.CheckBoxgng.IsChecked == true)
                            {
                                serviceShortcuts.Add("gng");
                            }

                            if (ServiceTab.CheckBoxglue.IsChecked == true)
                            {
                                serviceShortcuts.Add("glue");
                            }

                            if (ServiceTab.CheckBoxPlan.IsChecked == true)
                            {
                                serviceShortcuts.Add("plan");
                            }

                            if (ServiceTab.CheckBoxField.IsChecked == true)
                            {
                                serviceShortcuts.Add("field");
                            }

                            if (ServiceTab.CheckBoxAssets.IsChecked == true)
                            {
                                serviceShortcuts.Add("assets");
                            }

                            #endregion

                            var serviceList = new List <ServiceActivation>();

                            foreach (var serviceShortcut in serviceShortcuts)
                            {
                                //ToDo: this part needs revision

                                serviceList.Add(new ServiceActivation()
                                {
                                    email        = AdminMail,
                                    service_type = serviceShortcut,
                                    project_name = projectName,
                                    company      = defaultcomp
                                });
                            }

                            // take the current project and activate all services that were checked
                            serviceProcess.ActivateServicesProcess(
                                new List <BimProject>(new BimProject[] { currentProject }), serviceList);
                        }

                        // assign permissions
                        currentFolder = CreateFoldersAndAssignPermissions(csvData, row, projectUsers, folderProcess,
                                                                          folders, currentFolder, currentProject, projectUserProcess);

                        // run the file upload if requested
                        UploadFilesFromFolder(csvData, row, folderProcess, currentFolder, currentProject.id,
                                              options.LocalFoldersPath);
                        //Updates
                        progress.pgb.Value             = 50 + (50 / csvData.Rows.Count * row);
                        progress.ProgressLabel.Content = "Uploading";
                        // ProgressBar "refresh"
                        CallDispatch(progress);
                    }
                }
                catch (Exception ex)
                {
                    //show the error
                    statusbar.Text = ex.Message;
                    progress.Close();
                    return;
                }

                statusbar.Text = "Upload successful";
                progress.Close();
            }
            catch (Exception ex)
            {
                this.statusbar.Text = "Error on upload:" + ex.Message;
                progress.Close();
            }
        }