Exemplo n.º 1
0
        // When selecting program fill teacher
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            List <Employee> TeacherList = new List <Employee>();

            Model.Program program = comboBox1.SelectedItem as Model.Program;
            if (formLoaded && comboBox1.SelectedIndex != -1)
            {
                using (var db = new AcademyDB())
                {
                    foreach (Employee employee in db.Employee.ToList())
                    {
                        // get only Free Teachers from employers
                        Group grup = db.Group.FirstOrDefault(gr => gr.TeacherID == employee.id);
                        if (grup == null && employee.SpecialityID == program.id)
                        {
                            TeacherList.Add(employee);
                        }
                    }
                    comboBox2.DataSource    = null;
                    comboBox2.DataSource    = TeacherList;
                    comboBox2.DisplayMember = "Name";
                    comboBox2.ValueMember   = "id";
                }
            }
            comboBox2.Enabled = true;
        }
        // Updating Program from datagridView
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (formLoaded && e.RowIndex != dataGridView1.Rows.Count - 1)
            {
                int progID = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;

                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                using (var db = new AcademyDB())
                {
                    if (CheckRow(e.RowIndex)) // checking cells validation
                    {
                        Model.Program prog = db.Program.FirstOrDefault(c => c.id == progID);

                        prog.Name   = row.Cells[1].Value.ToString();
                        prog.Price  = Convert.ToInt32(row.Cells[2].Value);
                        prog.Period = Convert.ToInt32(row.Cells[3].Value);

                        if (db.SaveChanges() != 0)
                        {
                            fillGrid(db.Program.ToList());
                            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.FromArgb(224, 255, 224);
                        }
                        else
                        {
                            MessageBox.Show("Warning: Program did not updated!");
                        }
                    }
                }
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// 更新程序设计
 /// </summary>
 /// <param name="program">程序设计实体</param>
 public int Update(Model.Program program)
 {
     using (var db = new DataContext())
     {
         db.Update(program);
         return(db.SaveChanges());
     }
 }
Exemplo n.º 4
0
        public ActionResult OnPost()
        {
            if (ModelState.IsValid)
            {
                Controller.BCS RequestDirector = new Controller.BCS();

                activeProgram = RequestDirector.FindProgram(programCode);
            }
            return(Page());
        }
Exemplo n.º 5
0
        public void AddTask(Model.Program program)
        {
            if (set.Contains(program.ProgramName))
            {
                return;
            }

            set.Add(program.ProgramName);
            this.StartThread(program);
        }
Exemplo n.º 6
0
 // Sort groups by Program
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     Model.Program program = comboBox1.SelectedItem as Model.Program;
     if (formLoaded && comboBox1.SelectedIndex != -1)
     {
         using (var db = new AcademyDB())
         {
             fillGrid(db.Group.Where(g => g.ProgramID == program.id).ToList());
         }
     }
 }
        // Save employee
        private void button1_Click(object sender, EventArgs e)
        {
            using (var db = new AcademyDB())
            {
                if (isValid())
                {
                    Position position = comboBox2.SelectedItem as Position;
                    int?     SpecID   = null;

                    if (comboBox3.SelectedIndex != -1)
                    {
                        Model.Program program = comboBox3.SelectedItem as Model.Program;
                        SpecID = program.id;
                    }

                    string   email   = textBox3.Text.Trim();
                    Employee exitEmp = db.Employee.FirstOrDefault(em => em.Deleted == false && em.Email == email);

                    if (exitEmp == null)
                    {
                        Employee emp = new Employee()
                        {
                            Name         = textBox1.Text,
                            Surname      = textBox2.Text,
                            Email        = textBox3.Text,
                            Phone        = textBox4.Text,
                            PositionID   = position.id,
                            Salary       = Convert.ToDouble(textBox6.Text),
                            StartTime    = dateTimePicker2.Value,
                            Deleted      = false,
                            Photo        = selectedImage,
                            SpecialityID = SpecID
                        };

                        db.Employee.Add(emp);

                        if (db.SaveChanges() != 0)
                        {
                            MessageBox.Show("Employee added");
                            ClearInputs();
                        }
                        else
                        {
                            MessageBox.Show("Error: Employee did not added");
                        }
                    }
                    else
                    {
                        MessageBox.Show("This email is alredy registered as " + exitEmp.Name + " " + exitEmp.Surname);
                    }
                }
            }
        }
Exemplo n.º 8
0
        private void StartThread(Model.Program program)
        {
            DownloadBW thread = new DownloadBW(program);

            thread.WorkerReportsProgress      = true;
            thread.WorkerSupportsCancellation = true;
            thread.DoWork             += new DoWorkEventHandler(doWork);
            thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completeWork);
            thread.ProgressChanged    += new ProgressChangedEventHandler(progressChanged);

            thread.RunWorkerAsync(thread.program.ProgramName);
        }
Exemplo n.º 9
0
        // Search Teachers by Speciality
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Model.Program program = comboBox2.SelectedItem as Model.Program;

            using (var db = new AcademyDB())
            {
                if (comboBox2.Focused)
                {
                    SearchList = db.Employee.Where(emp => emp.SpecialityID == program.id).ToList();
                    fillGrid(SearchList);
                }
            }
        }
        // Delete button
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            // if column is Delete button column
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0 && e.RowIndex != dataGridView1.Rows.Count - 1)
            {
                DataGridViewRow row    = dataGridView1.Rows[e.RowIndex];
                DialogResult    result = MessageBox.Show(row.Cells[1].Value.ToString(), "Are you sure to delete?", MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    using (var db = new AcademyDB())
                    {
                        int           progID = (int)row.Cells[0].Value;
                        Model.Program prog   = db.Program.FirstOrDefault(c => c.id == progID);

                        string groups   = string.Join(" , ", db.Group.Where(gr => gr.ProgramID == progID && gr.Deleted == false).Select(g => g.Name));
                        int    empCount = db.Employee.Where(em => em.SpecialityID == progID && em.Deleted == false).Count();
                        if (groups.Length > 0 || empCount > 0)
                        {
                            DialogResult res = MessageBox.Show("The " + prog.Name + " contains groups: " + groups + " and " + empCount + " teachers if you will delete this program all groups and students will be invisible in list", "Are you sure to delete?", MessageBoxButtons.OKCancel);

                            if (res == DialogResult.OK)
                            {
                                prog.Deleted = true;
                            }
                        }
                        else
                        {
                            prog.Deleted = true;
                        }

                        if (db.SaveChanges() != 0)
                        {
                            refreshForm();
                        }
                        else
                        {
                            MessageBox.Show("Classroom did not deleted");
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        // get statistics
        public void getStatistic()
        {
            int stFee = 0;

            using (var db = new AcademyDB())
            {
                foreach (Student st in db.Student)
                {
                    Model.Program prog = db.Program.FirstOrDefault(p => p.Deleted == false && p.Price > st.Fee);
                    if (prog != null)
                    {
                        stFee++;
                    }
                }

                lblStudentCount.Text = db.Student.Where(st => st.Deleted == false).Count().ToString();
                lblDeptorCount.Text  = stFee.ToString();
            }
        }
Exemplo n.º 12
0
        public void PlayProgram()
        {
            if (LED.VirtualID == -1)
            {
                LED = LEDManager.GetModel(LED.ID);
                if (LED.VirtualID == -1)
                {
                    txtMessage.Text = "关闭中";
                }
            }
            else
            {
                if (LED.CurrentProgram == null)
                {
                    txtMessage.Text = "没有节目";
                }
                else
                {
                    if (_lastProgram != null)
                    {
                        if (LED.CurrentProgram.ID == _lastProgram.ID)
                        {
                            _lastIndex++;

                            if(_lastIndex >= LED.CurrentProgram.Messages.Count)
                            {
                                _lastIndex -= LED.CurrentProgram.Messages.Count;
                            }
                            txtMessage.Text = LED.CurrentProgram.Messages[_lastIndex].Content;
                            txtUpdateTime.Text = LED.LastUpdateTime.HasValue ? LED.LastUpdateTime.Value.ToString() : string.Empty;
                        }
                    }
                    else
                    {
                        _lastProgram = LED.CurrentProgram;
                        _lastIndex = 0;
                        txtMessage.Text = LED.CurrentProgram.Messages[_lastIndex].Content;
                    }
                }
            }
        }
        // Add program
        private void button1_Click(object sender, EventArgs e)
        {
            string progName = textBox1.Text.ToLower();

            using (var db = new AcademyDB())
            {
                Model.Program exitProg = db.Program.FirstOrDefault(c => c.Deleted == false && c.Name.ToLower() == progName);


                if (isValid())
                {
                    if (exitProg == null)
                    {
                        Model.Program newProgram = new Model.Program()
                        {
                            Name   = textBox1.Text,
                            Price  = Convert.ToInt32(textBox2.Text),
                            Period = Convert.ToInt32(textBox3.Text)
                        };

                        db.Program.Add(newProgram);

                        if (db.SaveChanges() == 0)
                        {
                            MessageBox.Show("Error: Classroom did not added");
                        }
                        else
                        {
                            ClearInputs();
                            refreshForm();
                        }
                    }
                    else
                    {
                        MessageBox.Show("The program width this name is alredy exist");
                    }
                }
            }
        }
Exemplo n.º 14
0
        /**
         *
         *
         */
        private void doJob()
        {
            //ObservableCollection<Program> temp = Helper.GetAppsInstalledInSystem();
            //foreach (Program p in temp)
            //{
            //    //var uiContext = SynchronizationContext.Current;
            //    //uiContext.Send(x => changeData(p), null);
            //    App.Current.Dispatcher.Invoke(new Action(() => {
            //        changeData(p);
            //    }));
            //}

            var lstDownHis = log.GetListDownHis();
            IEnumerable <System.IO.FileInfo> files = iup.queryInstallFiles();
            int test = 1;

            foreach (System.IO.FileInfo field in files)
            {
                var           found   = lstDownHis.Where(o => o.DriverName == field.Name).FirstOrDefault();
                Model.Program program = new Model.Program(field.Name, "");
                program.Position  = test;
                program.Progress  = found != null ? found.Progress : 0;
                program.TotalSize = found != null ? found.TotalSize : 1000;
                program.Status    = found != null?int.Parse(found.Status) : Program.DOWNLOADING;

                program.ClickCommand = new RelayCommand <object>(p => { return(true); }, p => {
                    var item = programList[(int)p - 1] as Model.Program;
                    if (item.ButtonText == "download")
                    {
                        item.Status     = Program.DOWNLOADING;
                        item.ButtonText = "pause";
                    }
                    else if (item.ButtonText == "pause")
                    {
                        item.Status     = Program.PAUSE;
                        item.ButtonText = "download";
                    }
                    download.AddTask(item);
                });
                program.InstallCommand = new RelayCommand <object>((p) => { return(true); }, (p) =>
                {
                    Console.Out.WriteLine("InstallCommand called");
                    var programRunning = programList[(int)p - 1] as Model.Program;
                    try
                    {
                        // Call to install app.
                        Console.Out.WriteLine("Installing...");
                        iup.Install(String.Format(@"D:\Files\{0}", program.ProgramName));
                        Console.Out.WriteLine("Completed");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Install Exception: '{0}'", e.Message);
                    }
                });
                Console.WriteLine(field.Name);
                App.Current.Dispatcher.Invoke(new Action(() => {
                    changeData(program);
                }));
                //programList.Add(program);
                test++;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 发布一个程序设计
        /// </summary>
        /// <param name="id"></param>
        /// <param name="localizer">语言包</param>
        /// <returns></returns>
        public string Publish(Guid id, IStringLocalizer localizer = null)
        {
            string key = "ProgramRun_" + id.ToString("N");

            Cache.IO.Remove(key);
            Model.Program programModel = Get(id);
            if (null == programModel)
            {
                return(localizer == null ? "没有找到要发布的程序!" : localizer["NotFoundModel"]);
            }
            //更新状态
            programModel.Status = 1;
            Update(programModel);

            Model.ProgramRun programRunModel = GetRunModel(id);
            if (null == programRunModel)
            {
                return(localizer == null ? "没有找到要发布的程序!" : localizer["NotFoundModel"]);
            }

            #region 加入应用程序库
            AppLibrary appLibrary = new AppLibrary();
            var        appModel   = appLibrary.GetByCode(id.ToString());
            bool       isAdd      = false;
            if (null == appModel)
            {
                isAdd    = true;
                appModel = new Model.AppLibrary
                {
                    Id   = Guid.NewGuid(),
                    Code = id.ToString()
                };
            }
            appModel.Address  = "/RoadFlowCore/ProgramDesigner/Run?programid=" + id.ToString();
            appModel.OpenMode = 0;
            appModel.Title    = programRunModel.Name;
            appModel.Type     = programRunModel.Type;

            //多语言要写入不同语言的标题,这里只写一种
            appModel.Title_en = programRunModel.Name;
            appModel.Title_zh = programRunModel.Name;

            if (isAdd)
            {
                appLibrary.Add(appModel);
            }
            else
            {
                appLibrary.Update(appModel);
            }
            #endregion

            #region 加按钮到应用程序库
            AppLibraryButton appLibraryButton = new AppLibraryButton();
            var buttons        = appLibraryButton.GetListByApplibraryId(appModel.Id);
            var programButtons = new ProgramButton().GetAll(id);
            foreach (var button in programButtons)
            {
                var  model       = buttons.Find(p => p.Id == button.Id);
                bool isAddButton = false;
                if (null == model)
                {
                    isAddButton = true;
                    model       = new Model.AppLibraryButton
                    {
                        Id = button.Id
                    };
                }
                model.AppLibraryId   = appModel.Id;
                model.ButtonId       = button.ButtonId;
                model.Events         = button.ClientScript;
                model.Ico            = button.Ico;
                model.IsValidateShow = button.IsValidateShow;
                model.Name           = button.ButtonName;
                model.ShowType       = button.ShowType;
                model.Sort           = button.Sort;
                if (isAddButton)
                {
                    appLibraryButton.Add(model);
                }
                else
                {
                    appLibraryButton.Update(model);
                }
            }
            foreach (var button in buttons)
            {
                if (!programButtons.Exists(p => p.Id == button.Id))
                {
                    appLibraryButton.Delete(button.Id);
                }
            }
            #endregion
            return("1");
        }
Exemplo n.º 16
0
 /// <summary>
 /// 更新程序设计
 /// </summary>
 /// <param name="program">程序设计实体</param>
 public int Update(Model.Program program)
 {
     return(ProgramData.Update(program));
 }
Exemplo n.º 17
0
 /// <summary>
 /// 添加一个程序设计
 /// </summary>
 /// <param name="program">程序设计实体</param>
 /// <returns></returns>
 public int Add(Model.Program program)
 {
     return(ProgramData.Add(program));
 }
Exemplo n.º 18
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
            {
                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();
        }
Exemplo n.º 20
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();
        }
Exemplo n.º 21
0
        private void importPrograms()
        {
            Console.WriteLine("Importing programs");
            var settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            var xml = XmlReader.Create(Source, settings);
            var dump = 0;
            var session = Raven.OpenSession();
            while (xml.Read())
            {
                if (xml.NodeType == XmlNodeType.Element && xml.Name == "programme")
                {
                    var program = new Model.Program();
                    if (xml.GetAttribute("start") != null)
                        program.StartDate = DateTime.ParseExact(xml.GetAttribute("start"), "yyyyMMddHHmmss zz00", CultureInfo.CurrentCulture.DateTimeFormat);
                    if (xml.GetAttribute("stop") != null)
                        program.EndDate = DateTime.ParseExact(xml.GetAttribute("stop"), "yyyyMMddHHmmss zz00", CultureInfo.CurrentCulture.DateTimeFormat);
                    if (xml.GetAttribute("channel") != null)
                    {
                        program.Channel = channels[xml.GetAttribute("channel").ToString()];
                        if (program.Channel == null)
                            Console.WriteLine("can't find " + xml.GetAttribute("channel").ToString());
                    }
                    else
                    {
                        Console.WriteLine("no channel attribute on node " + xml.Name);
                    }
                    xml.Read();
                    if (xml.NodeType == XmlNodeType.Element && xml.Name == "title")
                    {
                        xml.Read();
                        program.Name = xml.Value;
                        xml.Read();
                    }
                    if (xml.NodeType == XmlNodeType.Element && xml.Name == "desc")
                    {
                        xml.Read();
                        program.Description = xml.Value;

                    }
                    session.Store(program);
                    dump++;
                    if (dump == BulkOperationSize)
                    {
                        dump = 0;
                        session.SaveChanges();
                        session.Dispose();
                        session = Raven.OpenSession();
                    }
                }
            }
            session.SaveChanges();
            session.Dispose();
        }
Exemplo n.º 22
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();
        }
Exemplo n.º 23
0
 public DownloadBW(Model.Program program)
 {
     this.program = program;
 }
Exemplo n.º 24
0
        // Adding group
        private void button1_Click(object sender, EventArgs e)
        {
            Model.Program program   = comboBox1.SelectedItem as Model.Program;
            Classroom     classroom = comboBox4.SelectedItem as Classroom;


            int?     TeacherID, MentorID;
            Employee Mentor = comboBox3.SelectedItem as Employee;

            if (comboBox2.SelectedItem != null)
            {
                Employee Teacher = comboBox2.SelectedItem as Employee;
                TeacherID = Teacher.id;
            }
            else
            {
                TeacherID = null;
            }
            if (comboBox3.SelectedItem != null)
            {
                Employee Teacher = comboBox3.SelectedItem as Employee;
                MentorID = Mentor.id;
            }
            else
            {
                MentorID = null;
            }

            string GrpName = textBox1.Text.ToLower().Trim();

            using (var db = new AcademyDB())
            {
                Group exitGroup = db.Group.FirstOrDefault(gr => gr.Deleted == false && gr.Name.ToLower() == GrpName);

                if (exitGroup == null)
                {
                    if (isValid())
                    {
                        Group grup = new Group()
                        {
                            Name        = textBox1.Text,
                            ProgramID   = program.id,
                            TeacherID   = TeacherID,
                            MentorID    = MentorID,
                            Capacity    = Convert.ToInt32(txtCapacity.Text),
                            ClassroomID = classroom.id
                        };

                        db.Group.Add(grup);
                        if (db.SaveChanges() != 0)
                        {
                            MessageBox.Show("Group added!");
                            fillCombobox();
                            ClearInputs();
                        }
                        else
                        {
                            MessageBox.Show("Error: Group did not added");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("The group width this name alredy exist!");
                }
            }
        }
Exemplo n.º 25
0
        //public IActionResult doLogin(string userName, string password)
        //{
        //    LdapConnection ldapConn = new LdapConnection();
        //    JsonObjModel JsonObj = new JsonObjModel();
        //    UserModel User = new UserModel();


        //    try
        //    {
        //        //Connect function will create a socket connection to the server
        //        //ldapConn.Connect("192.168.0.5", 389);

        //        //Bind function will Bind the user object Credentials to the Server
        //        //ldapConn.Bind("regalscan\\" + userName, password);

        //        User.UserName = userName;
        //        JsonObj.Query = User;

        //        string JsonData = JsonConvert.SerializeObject(JsonObj.Query);


        //        //HttpContext.Session.SetString("User", JsonData);

        //        HttpContext.Session.SetString("User", userName);

        //    }
        //    catch (Exception ex)
        //    {
        //        return RedirectToAction("Index", "Login");
        //    }

        //    return Redirect("/Main/Index");
        //    //return RedirectToAction("Index", "Main");
        //}

        public IActionResult check(string employeeNo, string password)
        {
            LdapConnection ldapConn = new LdapConnection();
            JsonObjModel   JsonObj  = new JsonObjModel();
            UserModel      User     = new UserModel();

            try
            {
                //Connect function will create a socket connection to the server
                //ldapConn.Connect("192.168.0.5", 389);


                //Bind function will Bind the user object Credentials to the Server
                //ldapConn.Bind("regalscan\\" + userName, password);

                var filteredData                 = _db.tbEmployee.AsQueryable();
                var filteredProgData             = _db.tbProgram.AsQueryable();
                List <tbEmployee> listTbEmployee = null;
                List <tbGroup>    listTbGroup    = new List <tbGroup>();
                List <tbProgram>  listTbProgram  = null;
                string            power          = "";
                string            tbGroupPower   = "";
                string            progMainID     = "";//紀錄作業父節點
                int powerLength = 0;


                SHA256 sha256 = new SHA256CryptoServiceProvider();   //建立一個SHA256
                byte[] source = Encoding.Default.GetBytes(password); //將字串轉為Byte[]
                byte[] crypto = sha256.ComputeHash(source);          //進行SHA256加密
                string result = Convert.ToBase64String(crypto);      //把加密後的字串從Byte[]轉為字串

                filteredData     = filteredData.Where(e => e.EmployeeNo == employeeNo).Where(p => p.PassWord == result);
                filteredProgData = filteredProgData.Where(e => e.ProgID != "");

                listTbEmployee = filteredData.ToList();
                listTbProgram  = filteredProgData.OrderBy(e => e.Power).ToList();

                var tmp = (from b in _db.tbEmpGroup
                           join c in _db.tbGroup
                           on b.GroupID equals c.GroupID
                           where b.EmployeeNo == employeeNo
                           select new tbGroup
                {
                    GroupID = c.GroupID,
                    GroupName = c.GroupName,
                    Power = c.Power
                }).AsQueryable();
                listTbGroup = tmp.OrderByDescending(e => e.Power).ToList();

                //作業權限
                User.ProgramDictionary = new Dictionary <string, Model.Program>();
                Model.Program program = new Model.Program();
                if (listTbGroup.Count > 0)
                {
                    tbGroupPower = Convert.ToString(listTbGroup[0].Power, 2);
                    power        = power.PadLeft(tbGroupPower.Length, '0');
                    powerLength  = power.Length;

                    foreach (tbGroup tbGroup in listTbGroup)
                    {
                        tbGroupPower = Convert.ToString(tbGroup.Power, 2);
                        for (int i = 0; i < tbGroupPower.Length; i++)
                        {
                            if (tbGroupPower[i].ToString().Equals("1"))
                            {
                                power = power.Remove(powerLength - tbGroupPower.Length + i, 1);
                                power = power.Insert(powerLength - tbGroupPower.Length + i, "1");
                            }
                        }
                    }
                    for (int i = 0; i < power.Length; i++)
                    {
                        if (power[power.Length - 1 - i].ToString().Equals("1"))
                        {
                            if (!progMainID.Equals(listTbProgram[i].ProgID.ToString().Substring(0, 1)))
                            {
                                if (!progMainID.Equals(""))
                                {
                                    User.ProgramDictionary.Add(progMainID, program);
                                }
                                program    = new Model.Program();
                                progMainID = listTbProgram[i].ProgID.ToString().Substring(0, 1);

                                program.ProgID   = new List <string>();
                                program.ProgName = new List <string>();
                                program.ProgURL  = new List <string>();
                                program.ProgID.Add(listTbProgram[i].ProgID.ToString());
                                program.ProgName.Add(listTbProgram[i].ProgName.ToString());
                                program.ProgURL.Add(listTbProgram[i].Url.ToString());
                            }

                            else
                            {
                                program.ProgID.Add(listTbProgram[i].ProgID.ToString());
                                program.ProgName.Add(listTbProgram[i].ProgName.ToString());
                                program.ProgURL.Add(listTbProgram[i].Url.ToString());
                            }
                        }
                    }
                    if (!progMainID.Equals(""))
                    {
                        User.ProgramDictionary.Add(progMainID, program);
                    }
                }


                if (listTbEmployee.Count == 1)
                {
                    User.EmployeeNo = listTbEmployee[0].EmployeeNo;
                    User.UserName   = listTbEmployee[0].EmployeeName;

                    //tbEmployee[0].

                    JsonObj.Query = User;

                    string JsonData = JsonConvert.SerializeObject(JsonObj.Query);


                    HttpContext.Session.SetString("User", JsonData);

                    return(RedirectToAction("Index", "Main"));

                    //HttpContext.Session.SetString("User", userName);
                }
                //else
                //    return Content("error");
            }
            catch (Exception ex)
            {
                //return Content("error");

                TempData["error"] = ex.Message;
                ViewBag.Error     = TempData["error"];
                return(RedirectToAction("Index"));
            }
            TempData["error"] = "帳號或密碼錯誤";
            ViewBag.Error     = TempData["error"];
            return(RedirectToAction("Index"));
            //return Content("success");
        }
Exemplo n.º 26
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选中需要发送的信息行");
            }
            btnSend.Text = "发送中";
            btnSend.Enabled = false;
            var program = new Model.Program { ClientID = ClientId };
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                var content = row.Cells["Content"].Value;
                if (content == null)
                {
                    MessageBox.Show("你选择的信息不能包含内容为空的数据");
                    break;
                }
                var duration = row.Cells["Duration"].Value;
                program.Messages.Add(new Model.Message
                {
                    Content = content.ToString(),
                    Duration = duration == null ? 0 : int.Parse(duration.ToString())
                });
            }

            program.Messages.Reverse();

            new Thread(() =>
            {
                try
                {
                    var client = Program.GetServiceClient();
                    var ledId = GetSelectedLEDID();
                    var style = FontSettingForm.GetTextStyle(ledId);
                    client.SendProgram(ledId, program, style);
                    client.GetCurrentProgram(ledId);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("调用主机出错:\n" + ex.Message);
                }
                this.BeginInvoke(new Action(() =>
                {
                    btnSend.Text = "发送消息";
                    btnSend.Enabled = true;
                }));
            }).Start();
        }