Exemple #1
0
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.Branch model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update Branch set ");
            strSql.Append("BranchName=@BranchName,");
            strSql.Append("BranchAddress=@BranchAddress,");
            strSql.Append("BranchPhone=@BranchPhone,");
            strSql.Append("BranchDetail=@BranchDetail");
            strSql.Append(" where ID=@ID");
            SQLiteParameter[] parameters =
            {
                new SQLiteParameter("@BranchName",    DbType.String),
                new SQLiteParameter("@BranchAddress", DbType.String),
                new SQLiteParameter("@BranchPhone",   DbType.String),
                new SQLiteParameter("@BranchDetail",  DbType.String),
                new SQLiteParameter("@ID",            DbType.Int32, 8)
            };
            parameters[0].Value = model.BranchName;
            parameters[1].Value = model.BranchAddress;
            parameters[2].Value = model.BranchPhone;
            parameters[3].Value = model.BranchDetail;
            parameters[4].Value = model.ID;

            int rows = DbHelperSQLite.ExecuteSql(strSql.ToString(), parameters);

            if (rows > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #2
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Model.Branch model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("insert into Branch(");
            strSql.Append("BranchName,BranchAddress,BranchPhone,BranchDetail)");
            strSql.Append(" values (");
            strSql.Append("@BranchName,@BranchAddress,@BranchPhone,@BranchDetail)");
            strSql.Append(";select LAST_INSERT_ROWID()");
            SQLiteParameter[] parameters =
            {
                new SQLiteParameter("@BranchName",    DbType.String),
                new SQLiteParameter("@BranchAddress", DbType.String),
                new SQLiteParameter("@BranchPhone",   DbType.String),
                new SQLiteParameter("@BranchDetail",  DbType.String)
            };
            parameters[0].Value = model.BranchName;
            parameters[1].Value = model.BranchAddress;
            parameters[2].Value = model.BranchPhone;
            parameters[3].Value = model.BranchDetail;

            object obj = DbHelperSQLite.GetSingle(strSql.ToString(), parameters);

            if (obj == null)
            {
                return(0);
            }
            else
            {
                return(Convert.ToInt32(obj));
            }
        }
Exemple #3
0
 /// <summary>
 /// 得到一个对象实体
 /// </summary>
 public Model.Branch DataRowToModel(DataRow row)
 {
     Model.Branch model = new Model.Branch();
     if (row != null)
     {
         if (row["ID"] != null && row["ID"].ToString() != "")
         {
             model.ID = int.Parse(row["ID"].ToString());
         }
         if (row["BranchName"] != null)
         {
             model.BranchName = row["BranchName"].ToString();
         }
         if (row["BranchAddress"] != null)
         {
             model.BranchAddress = row["BranchAddress"].ToString();
         }
         if (row["BranchPhone"] != null)
         {
             model.BranchPhone = row["BranchPhone"].ToString();
         }
         if (row["BranchDetail"] != null)
         {
             model.BranchDetail = row["BranchDetail"].ToString();
         }
     }
     return(model);
 }
Exemple #4
0
        public BranchViewModel(Model.MapStory pMapStory, Model.Branch pBranch)
        {
            this.SelectedMapStory = pMapStory;
            this.CurrentBranch    = pBranch;
            var message = new Model.Message();

            this.MessageList = new ObservableCollection <Model.Message>();

            if (CurrentBranch.Messages == null)
            {
                CurrentBranch.Messages = new List <Model.Message>();
            }

            foreach (var m in CurrentBranch.Messages)
            {
                if (m.GetType() == typeof(Model.Message))
                {
                    message = m as Model.Message;
                    MessageList.Add(message);
                }

                else if (m.GetType() == typeof(Model.Question))
                {
                    message = m as Model.Question;
                    MessageList.Add(message);
                }
                else
                {
                    var dialog = new Windows.UI.Popups.MessageDialog("Error, unsupported Message type is tried to be added into the MessageList.");
                }
            }
        }
Exemple #5
0
 public void AddBranch()
 {
     Model.Branch newlyAddedBranch = new Model.Branch();
     newlyAddedBranch.Name     = this.NewBranchName;
     newlyAddedBranch.Messages = new List <Model.Message>();
     Branches.Add(newlyAddedBranch);
     this.SelectedInteractableObject.Branches.Add(newlyAddedBranch);
 }
Exemple #6
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Model.MapStory mapStory = new Model.MapStory();
            Model.Branch   branch   = new Model.Branch();
            base.OnNavigatedTo(e);

            if (e.Parameter.GetType() == typeof(object[]))
            {
                object[] parameter = e.Parameter as object[];
                mapStory = parameter[0] as Model.MapStory;
                branch   = parameter[1] as Model.Branch;
            }

            BVM = new ViewModel.BranchViewModel(mapStory, branch);
        }
Exemple #7
0
        //public static List<string> AutoComplBranch(string prefixText, int count, string flagfilter)
        //{
        //    List<string> lBranchs = new List<string>();

        //    List<SqlParameter> sp = new List<SqlParameter>()
        //    {
        //         new SqlParameter() {ParameterName = "@SearchText", SqlDbType = SqlDbType.NVarChar, Value = prefixText +'%'}
        //    };

        //    //if (flagfilter == "BranchID")
        //    //{
        //    DataTable dtEmployee = Manager.DataFacade.DTSQLCommand("SELECT BranchID FROM Branch where BranchID like @SearchText", sp);
        //    foreach (DataRow drEmployee in dtEmployee.Rows)
        //    {
        //        lBranchs.Add(drEmployee["BranchID"].ToString());
        //    }
        //    //}
        //    //else
        //    //{
        //    //    DataTable dtEmployee = Manager.DataFacade.DTSQLCommand("SELECT * FROM Employee where EmployeeID like @SearchText", sp);
        //    //    foreach (DataRow drEmployee in dtEmployee.Rows)
        //    //    {
        //    //        lEmployees.Add(drEmployee["EmployeeID"].ToString());
        //    //    }
        //    //}


        //    return lBranchs;
        //}

        //001 Penambahan Try catch
        public static string InsertBranch(string lBranchID, string lBranchName, string lBranchDescription, string lCompanyID)
        {
            try
            {
                Model.Branch mdlBranch = new Model.Branch();
                mdlBranch.BranchID          = lBranchID;
                mdlBranch.BranchName        = lBranchName;
                mdlBranch.BranchDescription = lBranchDescription;
                mdlBranch.CompanyID         = lCompanyID;
                DataContext.Branches.InsertOnSubmit(mdlBranch);
                DataContext.SubmitChanges();
                return("SQLSuccess");
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Exemple #8
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.Branch GetModel(int ID)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select ID,BranchName,BranchAddress,BranchPhone,BranchDetail from Branch ");
            strSql.Append(" where ID=@ID");
            SQLiteParameter[] parameters =
            {
                new SQLiteParameter("@ID", DbType.Int32, 4)
            };
            parameters[0].Value = ID;

            Model.Branch model = new Model.Branch();
            DataSet      ds    = DbHelperSQLite.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                return(DataRowToModel(ds.Tables[0].Rows[0]));
            }
            else
            {
                return(null);
            }
        }
        public async Task InsertAsync(int siteId, string initialAuthorizationCode, int userId = -1)
        {
            //_config[ConfigurationKey.InitialAuthorizationCode]
            // this is the data required for a user to register
            var system = new Model.System
            {
                SiteId = siteId,
                Name   = "Library District"
            };

            system = await _systemRepository.AddSaveAsync(userId, system);

            var branch = new Model.Branch
            {
                SystemId = system.Id,
                Name     = "Main Library",
            };

            branch = await _branchRepository.AddSaveAsync(userId, branch);

            var pointTranslation = new Model.PointTranslation
            {
                ActivityAmount            = 1,
                ActivityDescription       = "minute",
                ActivityDescriptionPlural = "minutes",
                IsSingleEvent             = false,
                PointsEarned    = 1,
                SiteId          = siteId,
                TranslationName = "One minute, one point",
                TranslationDescriptionPastTense    = "read {0}",
                TranslationDescriptionPresentTense = "reading {0}"
            };

            pointTranslation = await _pointTranslationRepository.AddSaveAsync(userId,
                                                                              pointTranslation);

            int programCount = 0;
            var program      = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Prereaders (ages 4 and below)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = false,
                AskSchool          = false,
                AgeMaximum         = 4,
                PointTranslationId = pointTranslation.Id
            };

            program = await _programRepository.AddSaveAsync(userId, program);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Kids (ages 5 to 11)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = true,
                AskSchool          = true,
                AgeMaximum         = 11,
                AgeMinimum         = 5,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Teens (ages 12 to 17)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = false,
                AskSchool          = true,
                AgeMaximum         = 17,
                AgeMinimum         = 12,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Adults (ages 18 and up)",
                Position           = programCount,
                AgeRequired        = false,
                AskAge             = false,
                SchoolRequired     = false,
                AskSchool          = false,
                AgeMinimum         = 18,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            // required for a user to be an administrator
            var adminRole = await _roleRepository.AddSaveAsync(userId, new Model.Role
            {
                Name = "System Administrator"
            });

            // add code to make first user system administrator
            await _authorizationCodeRepository.AddSaveAsync(userId, new Model.AuthorizationCode
            {
                Code        = initialAuthorizationCode.Trim().ToLower(),
                Description = "Initial code to grant system administrator status.",
                IsSingleUse = true,
                RoleId      = adminRole.Id,
                SiteId      = siteId
            });

            // system permissions
            foreach (var value in Enum.GetValues(typeof(Model.Permission)))
            {
                await _roleRepository.AddPermissionAsync(userId, value.ToString());
            }
            await _roleRepository.SaveAsync();

            // add permissions to the admin role
            foreach (var value in Enum.GetValues(typeof(Model.Permission)))
            {
                await _roleRepository.AddPermissionToRoleAsync(userId,
                                                               adminRole.Id,
                                                               value.ToString());
            }
            await _roleRepository.SaveAsync();

            foreach (var value in Enum.GetValues(typeof(Model.ChallengeTaskType)))
            {
                await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                         value.ToString());
            }
            await _challengeTaskRepository.SaveAsync();
        }
        public async Task InsertAsync(int siteId, string initialAuthorizationCode)
        {
            int userId = Defaults.InitialInsertUserId;

            //_config[ConfigurationKey.InitialAuthorizationCode]
            // this is the data required for a user to register
            var system = new Model.System
            {
                SiteId = siteId,
                Name   = "Library District"
            };

            system = await _systemRepository.AddSaveAsync(userId, system);

            var branch = new Model.Branch
            {
                SystemId = system.Id,
                Name     = "Main Library",
                Address  = "The Geographic Center, Lebanon, KS 66952"
            };

            branch = await _branchRepository.AddSaveAsync(userId, branch);

            var pointTranslation = new Model.PointTranslation
            {
                ActivityAmount            = 1,
                ActivityDescription       = "minute",
                ActivityDescriptionPlural = "minutes",
                IsSingleEvent             = false,
                PointsEarned    = 1,
                SiteId          = siteId,
                TranslationName = "One minute, one point",
                TranslationDescriptionPastTense    = "read {0}",
                TranslationDescriptionPresentTense = "reading {0}"
            };

            pointTranslation = await _pointTranslationRepository.AddSaveAsync(userId,
                                                                              pointTranslation);

            var programIds   = new List <int>();
            int programCount = 0;
            var program      = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Prereaders (ages 4 and below)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = false,
                AskSchool          = false,
                AgeMaximum         = 4,
                PointTranslationId = pointTranslation.Id
            };

            program = await _programRepository.AddSaveAsync(userId, program);

            programIds.Add(program.Id);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Kids (ages 5 to 11)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = true,
                AskSchool          = true,
                AgeMaximum         = 11,
                AgeMinimum         = 5,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            programIds.Add(program.Id);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Teens (ages 12 to 17)",
                Position           = programCount++,
                AgeRequired        = true,
                AskAge             = true,
                SchoolRequired     = false,
                AskSchool          = true,
                AgeMaximum         = 17,
                AgeMinimum         = 12,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            programIds.Add(program.Id);

            program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 1000,
                Name               = "Adults (ages 18 and up)",
                Position           = programCount,
                AgeRequired        = false,
                AskAge             = false,
                SchoolRequired     = false,
                AskSchool          = false,
                AgeMinimum         = 18,
                PointTranslationId = pointTranslation.Id
            };
            program = await _programRepository.AddSaveAsync(userId, program);

            programIds.Add(program.Id);

            // insert system user
            userId = await _userRepository.GetSystemUserId();

            await _systemRepository.UpdateCreatedByAsync(userId, system.Id);

            await _branchRepository.UpdateCreatedByAsync(userId, branch.Id);

            await _pointTranslationRepository.UpdateCreatedByAsync(userId, pointTranslation.Id);

            await _programRepository.UpdateCreatedByAsync(userId, programIds.ToArray());

            // required for a user to be an administrator
            var adminRole = await _roleRepository.AddSaveAsync(userId, new Model.Role
            {
                Name    = "System Administrator",
                IsAdmin = true
            });

            // add code to make first user system administrator
            await _authorizationCodeRepository.AddSaveAsync(userId, new Model.AuthorizationCode
            {
                Code        = initialAuthorizationCode.Trim().ToLower(),
                Description = "Initial code to grant system administrator status.",
                IsSingleUse = false,
                RoleId      = adminRole.Id,
                SiteId      = siteId
            });

            // set up system permissions and add to the admin role
            var permissionList = Enum.GetValues(typeof(Model.Permission))
                                 .Cast <Model.Permission>()
                                 .Select(_ => _.ToString());
            await _roleRepository.AddPermissionListAsync(userId, permissionList);

            await _roleRepository.SaveAsync();

            foreach (var value in Enum.GetValues(typeof(Model.ChallengeTaskType)))
            {
                await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                         value.ToString());
            }
            await _challengeTaskRepository.SaveAsync();
        }
Exemple #11
0
        public async Task InsertAsync(int siteId, string initialAuthorizationCode, int userId = -1)
        {
            //_config[ConfigurationKey.InitialAuthorizationCode]
            // this is the data required for a user to register
            var system = new Model.System
            {
                SiteId = siteId,
                Name   = "Library District"
            };

            system = await _systemRepository.AddSaveAsync(userId, system);

            var branch = new Model.Branch
            {
                SiteId   = siteId,
                SystemId = system.Id,
                Name     = "Main Library",
            };

            branch = await _branchRepository.AddSaveAsync(userId, branch);

            var program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 100,
                Name = "Reading Program",
            };

            program = await _programRepository.AddSaveAsync(userId, program);

            var pointTranslation = new Model.PointTranslation
            {
                ActivityAmount            = 1,
                ActivityDescription       = "book",
                ActivityDescriptionPlural = "books",
                IsSingleEvent             = true,
                PointsEarned    = 10,
                ProgramId       = program.Id,
                TranslationName = "One book, ten points",
                TranslationDescriptionPastTense    = "read {0}",
                TranslationDescriptionPresentTense = "reading {0}"
            };

            pointTranslation = await _pointTranslationRepository.AddSaveAsync(userId,
                                                                              pointTranslation);

            // required for a user to be an administrator
            var adminRole = await _roleRepository.AddSaveAsync(userId, new Model.Role
            {
                Name = "System Administrator"
            });

            // add code to make first user system administrator
            await _authorizationCodeRepository.AddSaveAsync(userId, new Model.AuthorizationCode
            {
                Code        = initialAuthorizationCode.Trim().ToLower(),
                Description = "Initial code to grant system administrator status.",
                IsSingleUse = true,
                RoleId      = adminRole.Id,
                SiteId      = siteId
            });

            // system permissions
            foreach (var value in Enum.GetValues(typeof(Model.Permission)))
            {
                await _roleRepository.AddPermissionAsync(userId, value.ToString());
            }
            await _roleRepository.SaveAsync();

            // add permissions to the admin role
            foreach (var value in Enum.GetValues(typeof(Model.Permission)))
            {
                await _roleRepository.AddPermissionToRoleAsync(userId,
                                                               adminRole.Id,
                                                               value.ToString());
            }
            await _roleRepository.SaveAsync();

            foreach (var value in Enum.GetValues(typeof(Model.ChallengeTaskType)))
            {
                if ((Model.ChallengeTaskType)value == Model.ChallengeTaskType.Book)
                {
                    await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                             value.ToString(),
                                                                             1,
                                                                             pointTranslation.Id);
                }
                else
                {
                    await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                             value.ToString());
                }
            }
            await _challengeTaskRepository.SaveAsync();
        }
        public async Task <JobStatus> RunImportJobAsync(int jobId,
                                                        CancellationToken token,
                                                        IProgress <JobStatus> progress = null)
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();

            var job = await _jobRepository.GetByIdAsync(jobId);

            var jobDetails
                = JsonConvert.DeserializeObject <JobBranchImport>(job.SerializedParameters);

            _logger.LogInformation("Job {JobId}: {JobType} to import {Filename}",
                                   job.Id,
                                   job.JobType,
                                   jobDetails.Filename);

            ICollection <Branch> importBranches = null;
            ICollection <string> importSystems  = null;

            token.Register(() =>
            {
                _logger.LogWarning("Job {JobId}: {ImportType} of {Filename} was cancelled after {Elapsed} ms.",
                                   job.Id,
                                   jobDetails.DoImport ? "Import" : "Test run",
                                   jobDetails.Filename,
                                   sw?.Elapsed.TotalMilliseconds);
            });

            string fullPath = _pathResolver.ResolvePrivateTempFilePath(jobDetails.Filename);

            if (!System.IO.File.Exists(fullPath))
            {
                _logger.LogError("Could not find {Filename}", fullPath);
                return(new JobStatus
                {
                    PercentComplete = 0,
                    Status = "Could not find the import file.",
                    Error = true,
                    Complete = true
                });
            }

            int importedCount  = 0;
            int processedCount = 0;

            int systemAdd  = 0;
            int systemEdit = 0;
            int branchAdd  = 0;
            int branchEdit = 0;

            int geocodingIssues = 0;

            var createdAt = _dateTimeProvider.Now;

            try
            {
                _logger.LogInformation("Job {JobId}: {ImportType} reading in CSV file: {Filename}",
                                       job.Id,
                                       jobDetails.DoImport ? "Import" : "Test run",
                                       jobDetails.Filename);

                progress?.Report(new JobStatus
                {
                    Status = "Reading in CSV file..."
                });

                try
                {
                    importBranches = await ReadBranchesAsync(fullPath);
                }
                catch (System.IO.IOException ioex)
                {
                    _logger.LogError(ioex,
                                     "Job {JobId}: Error reading CSV file {Filename}: {ErrorMessage}",
                                     job.Id,
                                     jobDetails.Filename,
                                     ioex.Message);
                    return(new JobStatus
                    {
                        Error = true,
                        Complete = true,
                        Status = $"Error reading records from the CSV file: {ioex.Message}"
                    });
                }

                if (importBranches?.Count == 0)
                {
                    return(new JobStatus
                    {
                        Error = true,
                        Complete = true,
                        Status = "No records found in the CSV file."
                    });
                }

                importSystems = importBranches.Select(_ => _.SystemName)
                                .OrderBy(_ => _)
                                .Distinct()
                                .ToList();

                _logger.LogInformation("Job {JobId}: {ImportType} found {SystemCount} systems, {BranchCount} branches",
                                       job.Id,
                                       jobDetails.DoImport ? "Import" : "Test run",
                                       importSystems?.Count,
                                       importBranches?.Count);

                await _jobRepository.UpdateStatusAsync(jobId,
                                                       $"Found {importSystems?.Count} systems and {importBranches?.Count} branches in the CSV file");

                progress?.Report(new JobStatus
                {
                    Status = $"Found {importSystems?.Count} systems and {importBranches?.Count} branches in the uploaded file..."
                });
                var lastUpdate = sw.Elapsed.TotalSeconds;

                var totalRecords = importSystems?.Count + importBranches?.Count;

                var softwareSystems = await _siteService.GetSystemList();

                var systemIndex = softwareSystems.ToDictionary(k => k.Id, v => v.Name);

                if (importSystems?.Count > 0)
                {
                    foreach (var importSystem in importSystems)
                    {
                        processedCount++;
                        var alreadyPresent = softwareSystems
                                             .FirstOrDefault(_ => _.Name == importSystem);

                        if (alreadyPresent != null)
                        {
                            _logger.LogInformation("Job {JobId}: Not creating system {SystemName}, already present as id {SystemId}",
                                                   job.Id,
                                                   importSystem,
                                                   alreadyPresent.Id);
                        }
                        else
                        {
                            Model.System existingSystem = null;
                            if (systemAdd + systemEdit == 0)
                            {
                                existingSystem = softwareSystems.SingleOrDefault();
                            }
                            if (existingSystem == null)
                            {
                                // add
                                systemAdd++;
                                if (jobDetails.DoImport)
                                {
                                    var addedSystem
                                        = await _siteService.AddSystemAsync(new Model.System
                                    {
                                        CreatedAt = createdAt,
                                        CreatedBy = jobDetails.UserId,
                                        Name      = importSystem,
                                        SiteId    = job.SiteId
                                    });

                                    systemIndex.Add(addedSystem.Id, importSystem);
                                    importedCount++;
                                }
                                else
                                {
                                    var fauxKey = systemAdd;
                                    while (systemIndex.ContainsKey(fauxKey))
                                    {
                                        fauxKey++;
                                    }
                                    systemIndex.Add(fauxKey, importSystem);
                                }
                            }
                            else
                            {
                                // edit
                                systemEdit++;
                                systemIndex[existingSystem.Id] = importSystem;
                                if (jobDetails.DoImport)
                                {
                                    _logger.LogInformation("Job {JobId}: Repurposing system {OldSystemName} as {NewSystemName}",
                                                           job.Id,
                                                           existingSystem.Name,
                                                           importSystem);
                                    existingSystem.CreatedAt = createdAt;
                                    existingSystem.CreatedBy = jobDetails.UserId;
                                    existingSystem.Name      = importSystem;
                                    await _siteService.UpdateSystemAsync(existingSystem);

                                    importedCount++;
                                }
                            }
                        }

                        if (sw.Elapsed.TotalSeconds > lastUpdate + 5)
                        {
                            progress?.Report(new JobStatus
                            {
                                PercentComplete = processedCount * 100 / totalRecords,
                                Status          = $"Processed {processedCount}, imported {importedCount} records; on system: {importSystem}"
                            });
                            lastUpdate = sw.Elapsed.TotalSeconds;
                        }
                    }
                }

                var status = new JobStatus
                {
                    Status = $"Processed {processedCount}, imported {importedCount} records; now importing branches..."
                };

                if (totalRecords > 0)
                {
                    status.PercentComplete = processedCount * 100 / totalRecords;
                }

                progress?.Report(status);
                lastUpdate = sw.Elapsed.TotalSeconds;

                if (importBranches?.Count > 0)
                {
                    var softwareBranches = await _siteService.GetAllBranches();

                    foreach (var branch in importBranches)
                    {
                        processedCount++;
                        var alreadyPresent = softwareBranches
                                             .FirstOrDefault(_ => _.Name == branch.Name &&
                                                             _.SystemName == branch.SystemName);

                        if (alreadyPresent != null)
                        {
                            _logger.LogInformation("Job {JobId}: Not creating branch {BranchName}, already present as id {BranchId}",
                                                   job.Id,
                                                   branch.Name,
                                                   alreadyPresent.Id);
                        }
                        else
                        {
                            Model.Branch existingBranch = null;
                            int?         systemId       = null;

                            if (systemIndex.ContainsValue(branch.SystemName))
                            {
                                systemId = systemIndex
                                           .Single(_ => _.Value == branch.SystemName)
                                           .Key;
                            }

                            if (systemId == null)
                            {
                                _logger.LogInformation("Job {JobId}: Couldn't find system named {SystemName} for branch {BranchName} in the database.",
                                                       job.Id,
                                                       branch.SystemName,
                                                       branch.Name);
                                return(new JobStatus
                                {
                                    Error = true,
                                    Complete = true,
                                    Status = $"Could not find system {branch.SystemName} for branch {branch.Name}."
                                });
                            }
                            if (branchAdd + branchEdit == 0)
                            {
                                existingBranch = softwareBranches.SingleOrDefault();
                            }

                            //geolocation
                            string geocode = null;
                            if (!string.IsNullOrEmpty(branch.Address))
                            {
                                geocode = await GeocodeAsync(job.SiteId, branch.Address);

                                if (string.IsNullOrEmpty(geocode))
                                {
                                    geocodingIssues++;
                                }
                            }

                            if (existingBranch == null)
                            {
                                // add
                                branchAdd++;
                                if (jobDetails.DoImport)
                                {
                                    await _siteService.AddBranchAsync(new Model.Branch
                                    {
                                        Address     = branch.Address,
                                        CreatedAt   = createdAt,
                                        CreatedBy   = jobDetails.UserId,
                                        Geolocation = geocode,
                                        Name        = branch.Name,
                                        SystemId    = (int)systemId,
                                        Telephone   = branch.Telephone,
                                        Url         = branch.Url
                                    });

                                    importedCount++;
                                }
                            }
                            else
                            {
                                // edit
                                branchEdit++;
                                if (jobDetails.DoImport)
                                {
                                    _logger.LogInformation("Job {JobId}: Repurposing branch {OldBranchName} as {NewBranchName}",
                                                           job.Id,
                                                           existingBranch.Name,
                                                           branch.Name);
                                    existingBranch.Address     = branch.Address;
                                    existingBranch.CreatedAt   = createdAt;
                                    existingBranch.CreatedBy   = jobDetails.UserId;
                                    existingBranch.Geolocation = geocode;
                                    existingBranch.Name        = branch.Name;
                                    existingBranch.SystemId    = (int)systemId;
                                    existingBranch.Telephone   = branch.Telephone;
                                    existingBranch.Url         = branch.Url;
                                    await _siteService.UpdateBranchAsync(existingBranch);

                                    importedCount++;
                                }
                            }
                        }

                        if (sw.Elapsed.TotalSeconds > lastUpdate + 5)
                        {
                            progress?.Report(new JobStatus
                            {
                                PercentComplete = processedCount * 100 / totalRecords,
                                Status          = $"Processed {processedCount}, imported {importedCount} records; on branch: {branch.Name}"
                            });
                            lastUpdate = sw.Elapsed.TotalSeconds;
                        }
                    }
                }
            }
            finally
            {
                System.IO.File.Delete(fullPath);
            }
            sw.Stop();

            // get result, return new JobStatus (percent = 100, complete = tru, status = whatever, error = true/false
            if (token.IsCancellationRequested)
            {
                _logger.LogWarning("Job {JobId}: Cancelled after importing {ImportedCount} records and {Elapsed} ms",
                                   job.Id,
                                   importedCount,
                                   sw.ElapsedMilliseconds);

                return(new JobStatus
                {
                    Complete = true,
                    Status = $"Import cancelled after {importedCount} records and {sw.Elapsed:c} seconds."
                });
            }

            await _jobRepository.UpdateStatusAsync(jobId,
                                                   $"Imported {systemAdd + systemEdit} systems and {branchAdd + branchEdit} branches.");

            _logger.LogInformation("Job {JobId}: {ImportType} added {SystemsAdded}, edited {SystemsEdited} systems; added {BranchesAdded}, edited {BranchesEdited} branches; {GeocodingIssues} geocoding issues",
                                   job.Id,
                                   jobDetails.DoImport ? "Import" : "Test run",
                                   systemAdd,
                                   systemEdit,
                                   branchAdd,
                                   branchEdit,
                                   geocodingIssues);

            var importType = jobDetails.DoImport ? "Imported" : "Test run imported";

            _logger.LogInformation("Job {JobId}: {ImportType} {importedCount} records in {Elapsed} ms",
                                   job.Id,
                                   importType,
                                   importedCount,
                                   sw.ElapsedMilliseconds);

            return(new JobStatus
            {
                PercentComplete = 100,
                Complete = true,
                Status = $"{importType} {importedCount} records (systems: {systemAdd} added, {systemEdit} updated; branches: {branchAdd} added, {branchEdit} updated) with {geocodingIssues} geocoding issues in {sw.Elapsed:c} seconds."
            });
        }
        private async Task <Model.MapStory> JSONtoModels(Windows.Storage.StorageFile file)
        {
            Model.Story storyModel = new Model.Story();
            Model.Map   mapModel   = new Model.Map();

            var dialog = new MessageDialog("");

            if (file != null)
            {
                string data = await Windows.Storage.FileIO.ReadTextAsync(file);

                JsonObject jsonObj = new JsonObject();
                jsonObj = JsonObject.Parse(data);

                MapStory.Story.Title       = jsonObj.GetNamedString("title");
                MapStory.Story.Description = jsonObj.GetNamedString("description");
                MapStory.Story.Author      = jsonObj.GetNamedString("author");

                //JsonObject, to access Json Api for Interactable Object.
                JsonObject interactableObjects = new JsonObject();

                interactableObjects = jsonObj.GetNamedObject("interactableobjects");
                //Multiple Interactable Objects usually. Has to dismantle and save them all into objects of the major Model: MapStory Model.
                foreach (var obj in interactableObjects)
                {
                    Model.InteractableObject interactableObjectModel = new Model.InteractableObject();

                    //Interactable Object (characters, enemies, bosses, friends, talking chair, etc)
                    interactableObjectModel.Name = obj.Key;
                    JsonObject jsonInteracatbleObject = new JsonObject();
                    jsonInteracatbleObject = JsonObject.Parse(obj.Value.ToString());
                    // Each interactable Objects has multiple branches, options, states, feelings etc...
                    foreach (var branch in jsonInteracatbleObject)
                    {
                        //Branch has a name.
                        Model.Branch branchModel = new Model.Branch();
                        branchModel.Messages = new List <Model.Message>();
                        branchModel.Name     = branch.Key;
                        JsonObject jsonObjBranch = new JsonObject();
                        jsonObjBranch = JsonObject.Parse(branch.Value.ToString());



                        //BranchModel added into the InteractableObjectModel. This process will repeatedly for the other branches.
                        interactableObjectModel.Branches.Add(branchModel);
                        //var dialogJson is not really a true JsonObject, it has only 2 properties (Key and Value).
                        //Those values have to be converted to Strings from a so called: "KeyValuePair".
                        foreach (var dialogJson in jsonObjBranch)
                        {
                            JsonObject dialogJsonObject = JsonObject.Parse(dialogJson.Value.ToString());

                            if (dialogJsonObject.ContainsKey("question"))
                            {
                                Model.Question questionModel = new Model.Question();
                                questionModel.Choices = new List <Model.Choice>();
                                questionModel.Name    = dialogJsonObject.GetNamedValue("name").ToString();
                                questionModel.Text    = dialogJsonObject.GetNamedValue("question").ToString();
                                if (dialogJsonObject.ContainsKey("emote"))
                                {
                                    questionModel.Emote = dialogJsonObject.GetNamedValue("emote").ToString();
                                }
                                JsonObject jsonObjChoices = new JsonObject();

                                if (JsonObject.TryParse(dialogJsonObject.GetNamedValue("choices").ToString(), out jsonObjChoices))
                                {
                                    foreach (var choiceJson in jsonObjChoices)
                                    {
                                        JsonObject   jsonObjectChoice = JsonObject.Parse(choiceJson.Value.ToString());
                                        Model.Choice choiceModel      = new Model.Choice();
                                        choiceModel.Name = jsonObjectChoice.GetNamedValue("name").ToString();

                                        //Recommend to have this... if it's empty, make a notification in the GUI.
                                        if (jsonObjChoices.ContainsKey("description"))
                                        {
                                            choiceModel.Description = jsonObjectChoice.GetNamedValue("description").ToString();
                                        }
                                        //Target is optional.
                                        if (jsonObjectChoice.ContainsKey("target"))
                                        {
                                            choiceModel.Function = jsonObjectChoice.GetNamedValue("target").ToString();
                                        }
                                        //Branch is optional... what's the real difference tho?
                                        if (jsonObjectChoice.ContainsKey("branch"))
                                        {
                                            choiceModel.Branch = jsonObjectChoice.GetNamedValue("branch").ToString();
                                        }
                                        questionModel.Choices.Add(choiceModel);
                                    }
                                    branchModel.Messages.Add(questionModel);
                                }
                                else
                                {
                                    MessageDialog msgbox = new MessageDialog("Error! There should be Choices jsonObject in the question JsonObject.");
                                    await msgbox.ShowAsync();
                                }
                            }

                            else
                            {
                                Model.Message message = new Model.Message();
                                if (dialogJsonObject.ContainsKey("name"))
                                {
                                    message.Name = dialogJsonObject.GetNamedValue("name").ToString();
                                }
                                else
                                {
                                    message.Name = "No name found?!";
                                }

                                if (dialogJsonObject.ContainsKey("message"))
                                {
                                    message.Text = dialogJsonObject.GetNamedValue("message").ToString();
                                }
                                else
                                {
                                    message.Text = "";
                                }
                                if (dialogJsonObject.ContainsKey("emote"))
                                {
                                    message.Emote = dialogJsonObject.GetNamedValue("emote").ToString();
                                }
                                branchModel.Messages.Add(message);
                            }

                            if (int.TryParse(dialogJson.Key, out int dialognumber))
                            {
                            }

                            else
                            {
                            }
                        }
                        //has chain of messages that the player has to go through.
                        //continue here ->
                        //extra info: go through another foreach. This time for the real dialogs.
                    }

                    //Interactable Object is filled... now it gets added into the MapStory.
                    this.MapStory.Story.InteractableObjects.Add(interactableObjectModel);
                }
            }



            else
            {
                dialog = new MessageDialog("Error, file is null!");
                await dialog.ShowAsync();
            }



            if (MapStory != null)
            {
                return(this.MapStory);
            }
            else
            {
                dialog = new MessageDialog("Error, MapStory is null!");
                await dialog.ShowAsync();

                MapStory = new Model.MapStory();
                return(MapStory);
            }
        }
Exemple #14
0
 public void RemoveBranch(Model.Branch rmBranch)
 {
     this.SelectedInteractableObject.Branches.Remove(rmBranch);
     this.Branches.Remove(rmBranch);
 }
Exemple #15
0
        public async Task InsertAsync(int siteId, string initialAuthorizationCode)
        {
            int userId = Defaults.InitialInsertUserId;
            //_config[ConfigurationKey.InitialAuthorizationCode]
            // this is the data required for a user to register

            var system = new Model.System
            {
                SiteId = siteId,
                Name   = "Library District"
            };

            system = await _systemRepository.AddSaveAsync(userId, system);

            var branch = new Model.Branch
            {
                SystemId = system.Id,
                Name     = "Main Library",
                Address  = "The Geographic Center, Lebanon, KS 66952"
            };

            branch = await _branchRepository.AddSaveAsync(userId, branch);

            var pointTranslation = new Model.PointTranslation
            {
                ActivityAmount            = 1,
                ActivityDescription       = "book",
                ActivityDescriptionPlural = "books",
                IsSingleEvent             = true,
                PointsEarned    = 10,
                SiteId          = siteId,
                TranslationName = "One book, ten points",
                TranslationDescriptionPastTense    = "read {0}",
                TranslationDescriptionPresentTense = "reading {0}"
            };

            pointTranslation = await _pointTranslationRepository.AddSaveAsync(userId,
                                                                              pointTranslation);

            var program = new Model.Program
            {
                SiteId = siteId,
                AchieverPointAmount = 100,
                Name = "Reading Program",
                PointTranslationId = pointTranslation.Id
            };

            program = await _programRepository.AddSaveAsync(userId, program);

            // insert system user
            userId = await _userRepository.GetSystemUserId();

            await _systemRepository.UpdateCreatedByAsync(userId, system.Id);

            await _branchRepository.UpdateCreatedByAsync(userId, branch.Id);

            await _pointTranslationRepository.UpdateCreatedByAsync(userId, pointTranslation.Id);

            await _programRepository.UpdateCreatedByAsync(userId, new int[] { program.Id });

            // required for a user to be an administrator
            var adminRole = await _roleRepository.AddSaveAsync(userId, new Model.Role
            {
                Name    = "System Administrator",
                IsAdmin = true
            });

            // add code to make first user system administrator
            await _authorizationCodeRepository.AddSaveAsync(userId, new Model.AuthorizationCode
            {
                Code        = initialAuthorizationCode.Trim().ToLower(),
                Description = "Initial code to grant system administrator status.",
                IsSingleUse = false,
                RoleId      = adminRole.Id,
                SiteId      = siteId
            });

            // set up system permissions and add to the admin role
            var permissionList = Enum.GetValues(typeof(Model.Permission))
                                 .Cast <Model.Permission>()
                                 .Select(_ => _.ToString());
            await _roleRepository.AddPermissionListAsync(userId, permissionList);

            await _roleRepository.SaveAsync();

            foreach (var value in Enum.GetValues(typeof(Model.ChallengeTaskType)))
            {
                if ((Model.ChallengeTaskType)value == Model.ChallengeTaskType.Book)
                {
                    await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                             value.ToString(),
                                                                             1,
                                                                             pointTranslation.Id);
                }
                else
                {
                    await _challengeTaskRepository.AddChallengeTaskTypeAsync(userId,
                                                                             value.ToString());
                }
            }
            await _challengeTaskRepository.SaveAsync();
        }