//Method that returns a list of answers based from question

        public static List<String> LoadAnswers2(int aId)
        {
            List<String> ans = new List<String>();//create a new list string
            OleDbConnection myConnection = GetConnection();
            string myQuery = "SELECT  answer, testAnswers.questionId FROM testAnswers WHERE testAnswers.questionId = " + aId;//SQL Statement which get questionid from test answers table and get question id from int aId.
            OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

            try
            {
                myConnection.Open();
                OleDbDataReader myReader = myCommand.ExecuteReader();

                while (myReader.Read()) //while reading it add answer to string in list
                {
                    ans.Add(myReader["answer"].ToString());
                }
                return ans;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);// handle exception occurs
                return null;
            }
            finally
            {
                myConnection.Close();// important to close connect of database
            }
        }
Exemplo n.º 2
0
        public string Display(Output action)
        {
            var s = new StringBuilder();
            s.Append("{weekFrom: ").Append(WeekFrom).Append(", trips: [");

            var tripStrings = new List<string>();
            ForEach((trip) => tripStrings.Add(action.Invoke(trip)));
            s.Append(String.Join(", ", tripStrings.ToArray()));

            return s.Append("]}").ToString();
        }
Exemplo n.º 3
0
        Thread[] loadThreads; //нити, которые будут загружать картинки в программу

        private void button1_Click(object sender, EventArgs e) //событие нажатия на кнопку "Открыть папку"
        {


            FolderBrowserDialog fbd = new FolderBrowserDialog(); //диалог открытия папки
            if (fbd.ShowDialog() == DialogResult.OK) //если, когда мы его вызвали, пользователь нажал "ОК" (а не, например, "Отмена"), то
            {

                List<string> imageFiles = new List<string>(); //создаем новый список, в котором будем хранить пути к нашим изображениям

                foreach (var extension in imageFormats) //для каждого расширения в массиве расширений:
                {
                    imageFiles.AddRange(Directory.GetFiles(fbd.SelectedPath, "*." + extension).ToList()); //ищем все файлы в указанной папке, у которых такое расширение и добавляем их в список
                }


                //Теперь мы знаем, сколько у нас будет картинок. Переопределяем массивы, чтобы элементов в них было столько же:
                Images = new ImageStruct[imageFiles.Count];
                loadThreads = new Thread[imageFiles.Count];


                //Теперь мы будем загружать элементы в массив

                for (int i = 0; i < Images.Length; i++) //Проходим по всему массиву
                {
                    Images[i] = new ImageStruct //Загружаем в массив путь к файлу и его номер
                    {
                        Index = i,
                        Path = imageFiles[i]
                    };
                    //Саму картинку загрузим через нить. Для этого:
                    loadThreads[i] = new Thread(LoadImage); //Инициализируем нить
                    loadThreads[i].Start(Images[i]); //Запускаем её, передав наши аргументы (в том числе, адрес картинки)
                }


                foreach (var t in loadThreads) //Ждём, пока все нити закончат работать
                {
                    t.Join();
                }
                //На этом этапе нити закончили работать, а значит, загрузили наши картинки. Теперь добавим эти картинки на форму.

                panel1.Controls.Clear(); //Очищаем панель, чтобы загрузить в неё новые картинки

                foreach (ImageStruct myImageStruct in Images) //проходим по всем элементам в нашем массиве
                {
                    panel1.Controls.Add(myImageStruct.Container); //Добавляем картинку из каждого элемента на форму.
                }
            }
        }
        // Method that returns a list of Question objects with the details from the DB
        public static List<Questions> LoadQuestions()
        {
            List<Questions> quest = new List<Questions>();// create new lists quest
            OleDbConnection myConnection = GetConnection();//connection for access database

            string myQuery = "SELECT TOP 10 * FROM testQuestions"; // in string myquery it has the SQL Statement which return top 10 from database
            

            OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
                              
            try// try and catch for event handling
            {
                
                myConnection.Open();//open connection
                OleDbDataReader myReader = myCommand.ExecuteReader(); // read from access 
                while (myReader.Read()) 
                {

                                        //convert question id to int and question to string and store in class Question                                    
                   Questions A = new Questions(int.Parse(myReader["questionid"].ToString()), myReader["question"].ToString());
                   quest.Add(A); //list add class                 
                                  

                }

                return quest;
           
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);
                return null;
            }
            finally
            {
                myConnection.Close();
            }
        }
Exemplo n.º 5
0
        private void button4_Click(object sender, EventArgs e) //Событие нажатия кнопки "Сохранить картинку"
        {
            if (Images != null) //Если картинки вообще есть, то
            {
                FolderBrowserDialog ofd = new FolderBrowserDialog(); //Инициализируем диалог выбора папки для сохранения

                FontDialog fd = new FontDialog(); //Инициализируем диалог выбора шрифта водяного знака

                if (fd.ShowDialog() == DialogResult.OK) //Если в диалоге выбора шрифта мы нажали ОК
                {
                    if (ofd.ShowDialog() == DialogResult.OK) //И в диалоге выбора папки мы нажали ОК, то
                    {

                        saveThreads = new List<Thread>(); //Инициализируем список нитей для сохранения
                        for (int i = 0; i < Images.Length; i++) //Проходим по всем загруженным картинкам
                        {
                            if (Images[i].Container.Checked) //Если картинка отмечена галочкой (т.е. её надо сохранить)
                            {

                                string savePath = ofd.SelectedPath + '\\' + getFileName(Images[i].Path); //Вычисляем путь, по которому будем сохранять эту картинку
                                SaveStruct saver = new SaveStruct(Images[i].Image, savePath, fd.Font); //Создаем экземпляр класса для сохранения
                                saveThreads.Add(new Thread(EditAndSave)); //Создаем новую нить для сохранения картинки и добавляем её в список нитей
                                saveThreads[saveThreads.Count - 1].Start(saver);//Запускаем нашу нить. Она будет последним элементом в списке (потому что мы её только что туда добавили). 
                            }
                        }

                        foreach (var t in saveThreads) //Ждём, пока все нити завершат работу
                        {
                            t.Join();
                        }

                        MessageBox.Show("Completed!"); //Выводим сообщение о том, что работа завершена
                    }

                }

            }

        }
Exemplo n.º 6
0
 public WeeklyBalance(List<Trip> tripss, Date weekFrom)
 {
     WeekFrom = weekFrom;
     _weekTo = WeekFrom.AddDays(6);
     Trips = tripss;
 }
        public static List<String> LoadCorrect(int aId)//load correct answer from question
        {
            List<String> correct = new List<String>();// create new string list 
            OleDbConnection myConnection = GetConnection();// get connection
            string myQuery = "SELECT correctanswer FROM testQuestions WHERE testQuestions.questionid =" + aId;// SQL Statement for correctanswer from testQuestion table where question id get from int aId.
            OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);

            try
            {
                myConnection.Open();
                OleDbDataReader myReader = myCommand.ExecuteReader();

                while (myReader.Read()) //while reading add correctanswer to correct list in string.
                {
                    correct.Add(myReader["correctanswer"].ToString());
                }
                return correct;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);
                return null;
            }
            finally
            {
                myConnection.Close();
            }
        }
Exemplo n.º 8
0
Arquivo: Admin.cs Projeto: PavelPZ/REW
    static void SetUsers(CmdSetUsers dt) {
      var db = Lib.CreateContext();

      /************ Users *****************/
      if (dt.Users != null && dt.Users.Length > 0) {
        //LMComId > 0 => uprav existujiciho usera
        var ids = dt.Users.Where(u => u.LMComId != 0).Select(u => u.LMComId).ToArray();
        foreach (var usr in db.Users.Where(u => ids.Contains(u.Id)))
          if (dt.Users.First(u => u.LMComId == usr.Id).Deleted) usr.Roles &= ~(long)Role.Comps; //deleted => zrus Comps roli
          else usr.Roles |= (long)Role.Comps; //neni Deleted => nastav Comps roli
        //LMComId == 0 => adjust usera
        var emails = dt.Users.Where(u => u.LMComId == 0).Select(u => u.EMail).ToList(); //vsechny nove emaily
        foreach (var usr in db.Users.Where(u => emails.Contains(u.EMail))) { //nacti existujici z DB
          usr.Roles |= (long)Role.Comps; //nastav Comps roli
          emails.Remove(usr.EMail); //vymaz z pozadovanych emailu
        }
        foreach (var em in emails) NewData.Login.PrepareUser(em, db, true); //compId nenalezen v DB => zaloz users v prepared stavu
      }
      Lib.SaveChanges(db);

      List<int> deletedComps = new List<int>(); //evicence vymazanych companies, abych je v "Company User Roles" ignoroval

      /************ Users *****************/
      if (dt.Comps != null && dt.Comps.Length > 0) {
        //new comps
        var newComps = dt.Comps.Where(c => c.Id == 0);
        var emails = newComps.Select(c => c.EMail).Where(c => c != null).ToArray();
        var newUsers = db.Users.Where(u => emails.Contains(u.EMail));
        //zaloz novou company (s primitivnim department) a ev. compUsera a Usera
        foreach (var comp in newComps) {
          var usr = newUsers.FirstOrDefault(u => u.EMail == comp.EMail);
          if (usr == null) usr = NewData.Login.PrepareUser(comp.EMail, db); //zaloz users v prepared stavu
          createCompany(db, comp.Title, usr, false);
          //var compDb = new Company() { Title = comp.Title, Created = DateTime.UtcNow }; db.Users.Add(compDb);
          //db.CompanyDepartments.Add(new CompanyDepartment() { Title = comp.Title, Company = compDb });
          //var userObj = newUsers.FirstOrDefault(u => u.compId == comp.compId);
          //if (userObj == null) userObj = NewData.Login.PrepareUser(comp.compId, db); //zaloz users v prepared stavu
          //var compUser = new CompanyUser() { Created = DateTime.UtcNow, Company = compDb, User = userObj, Roles = (long)CompRole.Admin };
          //db.CompanyUsers.Add(compUser);
        }
        //Uprav stavajici company
        var ids = dt.Comps.Where(c => c.Id != 0).Select(c => c.Id).ToArray(); //compId's existujici companies
        var compsDb = db.Companies.Where(c => ids.Contains(c.Id)).ToArray(); //nacti companies z DB
        foreach (var comp in dt.Comps.Where(c => c.Id != 0)) {
          var compDb = compsDb.First(c => c.Id == comp.Id); //aktualni comp v db
          if (comp.Deleted) { deletedComps.Add(comp.Id); db.Companies.Remove(compDb); continue; } //delete company
          compDb.Title = comp.Title; //aktualizuj //compDb.PublisherId = comp.PublisherId; 
          var old = dt.OldComps.First(c => c.Id == comp.Id); //najdi starou verzi
          if (old.EMail != comp.EMail) {//User je zmeneny
            //db.CompanyUsers.First(u => u.compId == old.email).Roles &= ~(long)CompRole.Admin; //zrus admina u old email
            db.CompanyUsers.First(u => u.Id == old.UserId).RolesEx &= ~(long)CompRole.Admin; //zrus admina u old email
            //adjust noveho admina 
            var usr = newUsers.FirstOrDefault(u => u.EMail == comp.EMail); //Zacni Userem
            CompanyUser compUsr = null;
            if (usr == null) usr = NewData.Login.PrepareUser(comp.EMail, db); //pro neexistujiciho zaloz usera v prepared stavu
            else compUsr = usr.CompanyUsers.FirstOrDefault(cu => cu.CompanyId == comp.Id); //pro existujiciho usera nalezni Cmpany Usera
            if (compUsr == null) compUsr = new CompanyUser() { Created = DateTime.UtcNow, Company = compDb, User = usr, RolesEx = (long)CompRole.Admin }; //Company User neexistuje => zaloz
            //else compUsr.Roles |= (long)CompRole.Admin; //existuje, dej mu Admin roli
            else compUsr.RolesEx |= (long)CompRole.Admin; //existuje, dej mu Admin roli
          }
        }
      }
      Lib.SaveChanges(db);

      /************ Company User Roles *****************/
      if (dt.CompUsers != null && dt.CompUsers.Length > 0) {
        //kontrola companies, ktere byly mozna vymazany v predchozim kroku
        CompUserItem[] actUsers = dt.CompUsers.Where(u => !deletedComps.Contains(u.CompanyId)).ToArray();

        //Uprav stavajici users
        var ids = actUsers.Where(u => u.UserId > 0).Select(u => u.UserId).ToArray();
        var dbUsers = db.CompanyUsers.Where(u => ids.Contains(u.Id)).ToArray(); //nacti stavajicu users z DB
        foreach (var dbUser in dbUsers) {
          var usr = actUsers.First(u => u.UserId == dbUser.Id); //dato s novou verzi
          var oldRoles = (CompRole)dbUser.Roles; var newRoles = usr.RoleEx.Role;
          oldRoles = usr.Deleted ? oldRoles & CompRole.HumanEvalator : (oldRoles & CompRole.HumanEvalator) | newRoles;
          dbUser.RolesEx = (long)oldRoles; //nastav novou roli
        }
        //Zaloz nove users
        var emails = actUsers.Where(u => u.UserId == 0).Select(u => u.EMail).ToList(); //vsechny nove emaily
        var newUsers = db.Users.Where(u => emails.Contains(u.EMail)).ToArray(); //existujici Users
        foreach (var cusr in actUsers.Where(u => u.UserId == 0)) {
          //adjust noveho admina 
          var usr = newUsers.FirstOrDefault(u => u.EMail == cusr.EMail); //Zacni Userem
          CompanyUser compUsr = null;
          if (usr == null) usr = NewData.Login.PrepareUser(cusr.EMail, db); //pro neexistujiciho zaloz usera v prepared stavu
          else compUsr = usr.CompanyUsers.FirstOrDefault(cu => cu.CompanyId == cusr.CompanyId); //pro existujiciho usera nalezni Cmpany Usera
          var newRoles = cusr.RoleEx.Role;
          if (compUsr == null)
            db.CompanyUsers.Add(compUsr = new CompanyUser() { Created = DateTime.UtcNow, CompanyId = cusr.CompanyId, User = usr, RoleParEx = cusr.RoleEx }); //Company User neexistuje => zaloz
          else {
            var oldRoles = (CompRole)compUsr.Roles;
            newRoles |= oldRoles & CompRole.HumanEvalator;
            compUsr.RolesEx = (long)newRoles;
          }
        }
      }

      Lib.SaveChanges(db);
    }
Exemplo n.º 9
0
    public class SkillLevel { public Skills Skill; public Levels Level; } //level pro danou skill

    public void initSkillLevels(Levels lev) { //inicializuje SkillLevels, vsechny na jednu level
      SkillLevels = lev == Levels.Assessment || lev == Levels.EslTest || lev == Levels.Demo ? null : LowUtils.EnumGetValues<Skills>().Select(s => new SkillLevel() { Skill = s, Level = lev }).ToList();
    }
Exemplo n.º 10
0
Arquivo: Admin.cs Projeto: PavelPZ/REW
    static AdminServ() {

      /* GetUsers */
      Handlers.CmdService.registerCommand<CmdGetUsers, CmdGetUsersResult>(par => {
        return new RpcResponse(GetUsers(par));
      });

      /* SetUsers */
      Handlers.CmdService.registerCommand<CmdSetUsers, bool>(par => {
        SetUsers(par);
        return new RpcResponse();
      });

      /* CmdGetProducts */
      Handlers.CmdService.registerCommand<CmdGetProducts, Product[]>(par => {
        return new RpcResponse(GetProducts(par));
      });

      /* CmdSetProducts */
      Handlers.CmdService.registerCommand<CmdSetProducts, bool>(par => {
        SetProducts(par);
        return new RpcResponse();
      });

      /* CmdGetDepartment */
      Handlers.CmdService.registerCommand<CmdGetDepartment, CmdGetDepartmentResult>(par => {
        return new RpcResponse(GetDepartment(par.CompanyId));
      });

      /* CmdSetDepartment */
      Handlers.CmdService.registerCommand<CmdSetDepartment, bool>(par => {
        SetDepartment(par);
        return new RpcResponse();
      });

      /* CmdAlocKeys */
      Handlers.CmdService.registerCommand<CmdAlocKeys, int>(par => {
        return new RpcResponse(AlocKeys(par));
      });

      /* CmdDsgnReadFile */
      Handlers.CmdService.registerCommand<CmdDsgnReadFile, string>(par => {
        try {
          return new RpcResponse(File.ReadAllText(Machines.basicPath + par.FileName));
        } catch {
          return new RpcResponse(1, Machines.basicPath + par.FileName);
        }
      });

      /* CmdDsgnReadFiles */
      Handlers.CmdService.registerCommand<CmdDsgnReadFiles, CmdDsgnResult>(par => {
        List<string> res = new List<string>();
        foreach (var fn in par.FileNames)
          try {
            res.Add(File.ReadAllText(Machines.basicPath + fn));
          } catch {
            res.Add(null);
          }
        return new RpcResponse(new CmdDsgnResult() { Data = res.ToArray() });
      });

      /* CmdDsgnWriteFile */
      Handlers.CmdService.registerCommand<CmdDsgnWriteDictWords, bool>(par => {
        try {
          var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<schools.DictWords>(par.Data);
          var f = obj.courses.First();
          XmlUtils.ObjectToFile(Machines.rootPath + @"RwDicts\UsedWords\" + par.FileName + "_" + f.lang.ToString() + ".xml", new schools.DictCrsWords() {
            lang = f.lang,
            exs = obj.courses.SelectMany(c => c.exs).ToArray()
          });
          return new RpcResponse(true);
        } catch {
          return new RpcResponse(1, Machines.basicPath + par.FileName);
        }
      });

      /* CmdDsgnWriteFile */
      Handlers.CmdService.registerCommand<DictEntryCmd, DictEntryRes>(par => {
        return new RpcResponse(dictLingea.processCommand(par));
      });

      /* CmdGetPublProjects */
      Handlers.CmdService.registerCommand<CmdGetPublProjects, CmdGetPublProjectsResult>(par => {
        return new RpcResponse(GetPublProjects(par));
      });

      /* CmdCreatePublProject */
      Handlers.CmdService.registerCommand<CmdPublChangePassword, bool>(par => {
        return new RpcResponse(PublChangePassword(par));
      });

      /* CmdPublBuild */
      Handlers.CmdService.registerCommand<CmdPublBuild, bool>(par => {
        return new RpcResponse(PublBuild(par));
      });

      /* CmdCreatePublProject */
      Handlers.CmdService.registerCommand<CmdCreatePublProject, bool>(par => {
        return new RpcResponse(CreatePublProject(par));
      });

    }
Exemplo n.º 11
0
 public Menu(List<MenuEntry> choises)
 {
     Choises = choises;
 }
Exemplo n.º 12
0
 public Menu(string title, List<MenuEntry> choises)
 {
     Title = title;
     Choises = choises;
 }
Exemplo n.º 13
0
 protected static Exercise[] expandHelper(Exercise[] excs) {
   if (excs == null || !excs.Any(e => e is IExpandable)) return excs;
   List<Exercise> res = new List<Exercise>();
   foreach (Exercise ex in excs)
     if (ex is IExpandable) res.AddRange(((IExpandable)ex).Expand()); else res.Add(ex);
   return res.ToArray();
 }
Exemplo n.º 14
0
 public Guid Version; //verze Exercise, jehoz nese tento Result vysledky
 public void Reset() { Results = null; Version = Guid.Empty; Status = ExerciseStatus.Unknown; }