예제 #1
0
        public MainPage()
        {
            InitializeComponent();
            FileToSend        = new StudentFile();
            RESTApi.ServerUrl = "http://localhost:8082";
            List <State>       states;
            List <StudentFile> problemStates = new List <StudentFile>();
            string             path          = "/states?UserId=" + LoginPage.LogUser.Id;

            states = JsonConvert.DeserializeObject <List <State> >(RESTApi.Get(path));


            foreach (State state in states)
            {
                StudentFile ps = new StudentFile();
                path       = "/problems?Id=" + state.ProblemId;
                ps.problem = JsonConvert.DeserializeObject <List <Problem> >(RESTApi.Get(path))[0];
                ps.state   = state;
                ps.user    = LoginPage.LogUser;

                problemStates.Add(ps);
            }

            ProblesListView.ItemsSource = problemStates;
        }
        private async Task IsValueValid(StudentFile fileLine, int rowCounter)
        {
            List <string> existingEmails = new List <string>();

            foreach (Account account in await _unitOfWork.AccountRepository.GetAllAsync())
            {
                existingEmails.Add(account.Email);
            }

            if (fileLine.FirstName == "")
            {
                throw new FormatException("Name field shouldn't be empty.\n" +
                                          $"Problem was occured in col B, row {rowCounter}");
            }

            if (fileLine.LastName == "")
            {
                throw new FormatException("Name field shouldn't be empty.\n" +
                                          $"Problem was occured in col C, row {rowCounter}");
            }

            if (existingEmails.Contains(fileLine.Email))
            {
                throw new DbUpdateException($"Account with email {fileLine.Email} already exists.\n" +
                                            $"Problem was occured in col A, row {rowCounter}.");
            }
        }
예제 #3
0
파일: Program.cs 프로젝트: Tlalok/DIS_Lab_4
        private static void GenerateTestData()
        {
            var students = new List <Student>();

            students.Add(new Student
            {
                Id           = 0,
                Name         = "Name 1",
                SubjectMarks = new List <SubjectMark>
                {
                    new SubjectMark("Math", 10)
                }
            });
            students.Add(new Student
            {
                Id           = 1,
                Name         = "Name 2",
                SubjectMarks = new List <SubjectMark>
                {
                    new SubjectMark("Physics", 8)
                }
            });
            var xml = new StudentFile
            {
                Students = students
            }.Serialize();

            File.WriteAllText("data.xml", xml);
        }
        public ActionResult Create([Bind(Include = "QueueID")] Processing processing,
                                   [Bind(Include = "ProcPriority, DOD, LDA, FileTypeID")] Record record,
                                   [Bind(Include = "FileSSN, FileName")] StudentFile sFile,
                                   string note)
        {
            if (ModelState.IsValid)
            {
                Note n = new Note();
                n.Note1    = note;
                n.Username = User.Identity.Name;
                if (db.StudentFile.Where(p => p.FileSSN == sFile.FileSSN).Count() > 0)
                {
                    sFile = db.StudentFile.Where(p => p.FileSSN == sFile.FileSSN).First();
                }
                else
                {
                    db.StudentFile.Add(sFile);
                    db.SaveChanges();
                }
                processing.ProcInQueue = DateTime.Now;
                record.StudentFile     = sFile;
                record.Processing.Add(processing);
                record.Note.Add(n);
                db.Record.Add(record);
                db.SaveChanges();

                //db.InsertIntoQueue(sFile.FileSSN,
                //                   sFile.FileName,
                //                   record.FileTypeID,
                //                   processing.QueueID,
                //                   note,
                //                   "",
                //                   User.Identity.Name,
                //                   record.DOD,
                //                   record.LDA);
                //if (record.ProcPriority)
                //{
                //    var rec = db.Processing.Where(p => p.Record.StudentFile.FileSSN == sFile.FileSSN).OrderByDescending(p => p.ProcInQueue).First().RecordID;
                //    var re = db.Record.Find(rec);
                //    re.ProcPriority = true;
                //    db.Entry(re).State = EntityState.Modified;
                //    db.SaveChanges();
                //}


                return(RedirectToAction("Index", new { i = processing.QueueID }));
            }
            else
            {
                ViewBag.QueueID    = new SelectList(db.Queue, "QueueID", "QueueDescription");
                ViewBag.FileTypeID = new SelectList(db.FileType, "FileTypeID", "TypeDescription");
                record.Processing.Add(processing);
                record.StudentFile = sFile;
                return(View(record));
            }
        }
예제 #5
0
        public async Task <IActionResult> Create(int assignmentId, EditSubmissionModel model, ICollection <IFormFile> files)
        {
            if (files.Count == 0)
            {
                return(new BadRequestObjectResult(new { error = "No files selected" }));
            }

            var user = User.Claims.FirstOrDefault(c => c.Type.Equals("name"))?.Value;
            // TODO: Validate user

            var submission = new Submission
            {
                AssignmentId = assignmentId,
                FirstName    = model.FirstName,
                LastName     = model.LastName
            };

            // save submission first
            if (!await this.submissionManager.SaveSubmissionAsync(submission))
            {
                return(BadRequest());
            }

            var submissionFiles = new List <StudentFile>();

            // add files:
            // TODO: Check for supported File Extensions
            foreach (var file in files)
            {
                var submissionFile = new StudentFile
                {
                    SubmissionId = submission.Id,
                    FileName     = file.FileName
                };

                // TODO: Check encoding etc. Assume UTF-8 for now
                using (var fileStream = file.OpenReadStream())
                {
                    var buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, int.MaxValue);
                    var content = System.Text.Encoding.UTF8.GetString(buffer);
                    submissionFile.Content = content;
                }

                submissionFiles.Add(submissionFile);
            }

            await this.submissionManager.SaveFilesAsync(submissionFiles);

            var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");

            Task.Run(() => this.serviceConsumer.TokenizeSubmissions(submission.Id, user, accessToken));
            return(RedirectToAction("Index", new { assignmentId = assignmentId }));
        }
예제 #6
0
        public ActionResult StudentSearchResult1(StudentFile fl, string returnUrl)
        {
            var result = _db.StudentFiles.SingleOrDefault(u => u.UniversityID == fl.UniversityID);

            Debug.WriteLine("The result" + result.StudentName);
            ViewBag.StudentID   = result.UniversityID.ToString();
            ViewBag.StudentName = result.StudentName.ToString();
            ViewBag.Section     = result.Section.ToString();
            ViewBag.Day         = result.Day.ToString();
            ViewBag.Date        = result.Date.ToString();
            ViewBag.Time        = result.Time.ToString();
            ViewBag.Lab         = result.Lab.ToString();
            ViewBag.Building    = result.Building.ToString();
            ViewBag.Floor       = result.Floor.ToString();
            ViewBag.Course      = result.Course.ToString();
            ViewBag.FullDate    = result.FullDate.ToString();
            ViewBag.Password    = result.Password.ToString();
            return(View("StudentSearch1"));
        }
예제 #7
0
        public async Task <string> DeleteFile(int file_id)
        {
            try
            {
                using (StudentRecordsEntities db = new StudentRecordsEntities())
                {
                    StudentFile file = await db.StudentFiles.FindAsync(file_id);

                    string x = file.FileName;

                    db.StudentFiles.Remove(file);

                    await db.SaveChangesAsync();

                    return(await Task.FromResult(x));
                }
            }
            catch (Exception)
            {
                return(await Task.FromResult(""));
            }
        }
예제 #8
0
        public ActionResult Delete(int StudentFileId)
        {
            try
            {
                StudentFile studentFile = context.StudentFiles.Find(StudentFileId);
                string      filePath    = Request.MapPath("~/UploadedFiles/") + studentFile.File;

                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }

                context.StudentFiles.Remove(studentFile);
                context.SaveChanges();

                TempData["SuccessMessage"] = "File has been deleted";
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Could not delete file, please try again.";
            }
            return(RedirectToAction("UploadedFiles"));
        }
예제 #9
0
        public ActionResult Upload(UploadFileViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (model.File.ContentLength > 0)
                    {
                        string fileName = Path.GetFileName(model.File.FileName);
                        string path     = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
                        model.File.SaveAs(path);

                        StudentFile studentFile = new StudentFile
                        {
                            StudentId   = User.Identity.GetUserId(),
                            File        = fileName,
                            Description = model.Description,
                            UploadedOn  = DateTime.Now
                        };

                        context.StudentFiles.Add(studentFile);
                        context.SaveChanges();

                        TempData["SuccessMessage"] = "File was successfully uploaded!";
                    }
                    else
                    {
                        throw new Exception("Please select a valid file.");
                    }
                }
                catch (Exception)
                {
                    TempData["ErrorMessage"] = "File was not uploaded, please try again.";
                }
            }
            return(RedirectToAction("Upload"));
        }
예제 #10
0
        public async Task <ActionResult> Edit([Bind(Include = "RecordID, ProcPriority,DOD,LDA,FileTypeID,FileID,FileSSN,FileName")] Record record, [Bind(Include = "FileID,FileSSN,FileName")] StudentFile studentFile, string mainReturn)
        {
            ViewBag.mainReturn = mainReturn;
            if (ModelState.IsValid)
            {
                db.Entry(record).State      = EntityState.Modified;
                db.Entry(studentFile).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(Redirect(mainReturn));
            }
            //
            ViewBag.FileTypeID = new SelectList(db.FileType, "FileTypeID", "TypeDescription", record.FileTypeID);
            return(View(record));
        }
 public ActionResult Add(StudentFile s)
 {
     return(View());
 }
        public async Task <Result <List <StudentFile> > > ImportFileAsync(long groupId, IFormFile uploadedFile)
        {
            List <StudentFile> importedAccounts = new List <StudentFile>();
            var groupName = _unitOfWork.StudentGroupRepository.SearchStudentGroup(groupId).Name;

            if (!await _unitOfWork.StudentGroupRepository.IsGroupNameExistAsync(groupName))
            {
                return(Result <List <StudentFile> > .GetError(ErrorCode.NotFound, $"Group {groupName} doesn't exist."));
            }

            if (uploadedFile != null)
            {
                var book          = new XLWorkbook(await CreateFile(uploadedFile));
                var studentsSheet = book.Worksheet("Students");

                Type studentType = typeof(StudentFile);
                char charPointer = 'A';
                int  rowCounter  = 2;

                var properties = studentType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.Name != Convert.ToString(studentsSheet.Cell($"{charPointer}1").Value))
                    {
                        return(Result <List <StudentFile> > .GetError(ErrorCode.ValidationError,
                                                                      "The format of the downloaded file is not suitable."
                                                                      + "Check headers in the file."));
                    }
                    charPointer++;
                }

                while (!IsEndOfFile(rowCounter, studentsSheet))
                {
                    try
                    {
                        StudentFile fileLine = new StudentFile
                        {
                            Email     = studentsSheet.Cell($"A{rowCounter}").Value.ToString(),
                            FirstName = studentsSheet.Cell($"B{rowCounter}").Value.ToString(),
                            LastName  = studentsSheet.Cell($"C{rowCounter}").Value.ToString()
                        };

                        await IsValueValid(fileLine, rowCounter);

                        CreateAccountDto studentAccount = new CreateAccountDto
                        {
                            Email           = fileLine.Email,
                            FirstName       = fileLine.FirstName,
                            LastName        = fileLine.LastName,
                            Password        = "******",
                            ConfirmPassword = "******"
                        };

                        await _accountService.CreateAccountAsync(studentAccount);

                        importedAccounts.Add(fileLine);
                        rowCounter++;
                    }
                    catch (FormatException ex)
                    {
                        _unitOfWork.Rollback();

                        return(Result <List <StudentFile> > .GetError(ErrorCode.ValidationError,
                                                                      "The format of the inputed data is incorrect.\n" + ex.Message));
                    }
                    catch (DbUpdateException ex)
                    {
                        _unitOfWork.Rollback();

                        return(Result <List <StudentFile> > .GetError(ErrorCode.ValidationError,
                                                                      "Inputed data is incorrect.\n" + ex.Message));
                    }
                }
            }
            await _unitOfWork.CommitAsync();

            Array.ForEach(Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files")), File.Delete);

            await BoundStudentsToTheGroupAsync(importedAccounts, groupId);

            return(Result <List <StudentFile> >
                   .GetSuccess(_mapper.Map <List <StudentFile> >(importedAccounts)));
        }
예제 #13
0
        public ActionResult TaskFile2(int taskID, FormCollection collection)
        {
            User user = Users.GetLoggedInUser();

            UserTaskData data = Tasks.GetUserTaskData(taskID, user.UserID);

            Guid uniqueID = Guid.NewGuid();
            string originalFilename = "";
            string originalExtension = "";
            int fileID = 0;
            HttpPostedFileBase file = null;

            // save file
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
                file = Request.Files[0];

                originalFilename = Path.GetFileName(file.FileName);
                originalExtension = Path.GetExtension(file.FileName);

                string filePath = Path.Combine(Settings.StudentFilesLocation, uniqueID.ToString() + originalExtension);
                file.SaveAs(filePath);

                StudentFile studentFile = new StudentFile();
                studentFile.UserID = user.UserID;
                studentFile.UniqueID = uniqueID;
                studentFile.ContentType = file.ContentType;
                studentFile.Length = file.ContentLength;
                studentFile.Filename = originalFilename;
                studentFile.UploadedDate = DateTime.Now;

                var db = new DidacheDb();
                db.StudentFiles.Add(studentFile);
                db.SaveChanges();

                fileID = studentFile.FileID;
            }

            // do processing
            object returnObject = new {
                success= true,
                fileID = fileID,
                fileLength=file.ContentLength,
                filename=originalFilename
            }; // Didache.TaskTypes.TaskTypeManager.ProcessFormCollection(data.Task.TaskTypeName, taskID, userID, collection, Request);

            return Json(returnObject);

            //return Redirect("/courses/" + data.Task.Course.Slug + "/schedule/" + data.Task.UnitID);
        }
예제 #14
0
        static void Main(string[] args)
        {
            RESTApi.ServerUrl = "http://*****:*****@gmail.com");
                                //msg.To.Add(tmp.user.Email);
                                msg.To.Add("*****@*****.**");
                                msg.Subject                  = "Status your work " + DateTime.Now.ToString();
                                msg.Body                     = tmp.user.FullName + ", " + tmp.problem.Subject + " " + tmp.state.Status;
                                SmtpClient client            = new SmtpClient();
                                client.UseDefaultCredentials = true;
                                client.Host                  = "smtp.gmail.com";
                                client.Port                  = 587;
                                client.EnableSsl             = true;
                                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                                client.Credentials           = new NetworkCredential("*****@*****.**", "Qwerty`123");
                                client.Timeout               = 20000;
                                try
                                {
                                    client.Send(msg);
                                    Console.WriteLine("Mail has been successfully sent!");
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Fail Has error" + ex.Message);
                                }
                                finally
                                {
                                    msg.Dispose();
                                }

                                tempStudentFiles[tmp.problem.TeacherId].Add(tmp);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        };
                        channel.BasicConsume("QStudentFiles", true, consumer);

                        Console.WriteLine(" Press [enter] to exit.");
                        Console.ReadLine();
                    }
            }
                                       );

            worker.Start();

            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler().Result;

            sched.Start();


            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("myJob", "group1")
                             .Build();


            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("myTrigger", "group1")
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInMinutes(1)
                                                   .RepeatForever())
                               .Build();

            sched.ScheduleJob(job, trigger);
        }
예제 #15
0
        public JsonResult UploadExcel(StudentFile users, HttpPostedFileBase FileUpload)
        {
            List <string> data = new List <string>();

            if (FileUpload != null)
            {
                // tdata.ExecuteCommand("truncate table OtherCompanyAssets");
                if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    string filename   = FileUpload.FileName;
                    string targetpath = Server.MapPath(null);
                    Debug.WriteLine("File path" + targetpath);
                    FileUpload.SaveAs(targetpath + filename);
                    string pathToExcelFile  = targetpath + filename;
                    var    connectionString = "";
                    if (filename.EndsWith(".xls"))
                    {
                        connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
                    }
                    else if (filename.EndsWith(".xlsx"))
                    {
                        connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
                    }

                    var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
                    var ds      = new DataSet();

                    adapter.Fill(ds, "ExcelTable");

                    DataTable dtable = ds.Tables["ExcelTable"];

                    string sheetName = "Sheet1";

                    var excelFile    = new ExcelQueryFactory(pathToExcelFile);
                    var artistAlbums = from a in excelFile.Worksheet <StudentFile>(sheetName) select a;

                    foreach (var a in artistAlbums)
                    {
                        try
                        {
                            if (a.StudentName != "" && a.Day != "" && a.Time != "")
                            {
                                StudentFile TU = new StudentFile();
                                TU.SN           = a.SN;
                                TU.UniversityID = a.UniversityID;
                                TU.StudentName  = a.StudentName;
                                TU.Section      = a.Section;
                                TU.Day          = a.Day;
                                TU.Date         = a.Date;
                                TU.Time         = a.Time;
                                TU.Lab          = a.Lab;
                                TU.Building     = a.Building;
                                TU.Floor        = a.Floor;
                                TU.Course       = a.Course;
                                TU.FullDate     = a.FullDate;
                                TU.Password     = a.Password;
                                _db.StudentFiles.Add(TU);

                                _db.SaveChanges();
                            }
                            else
                            {
                                data.Add("<ul>");
                                if (a.StudentName == "" || a.StudentName == null)
                                {
                                    data.Add("<li> name is required</li>");
                                }
                                if (a.Day == "" || a.Day == null)
                                {
                                    data.Add("<li> Day is required</li>");
                                }
                                if (a.Time == "" || a.Time == null)
                                {
                                    data.Add("<li>Time is required</li>");
                                }

                                data.Add("</ul>");
                                data.ToArray();
                                return(Json(data, JsonRequestBehavior.AllowGet));
                            }
                        }

                        catch (DbEntityValidationException ex)
                        {
                            foreach (var entityValidationErrors in ex.EntityValidationErrors)
                            {
                                foreach (var validationError in entityValidationErrors.ValidationErrors)
                                {
                                    Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                                }
                            }
                        }
                    }
                    //deleting excel file from folder
                    if ((System.IO.File.Exists(pathToExcelFile)))
                    {
                        System.IO.File.Delete(pathToExcelFile);
                    }
                    return(Json("Successfully Uploaded", JsonRequestBehavior.AllowGet));
                }
                else
                {
                    //alert message for invalid file format
                    data.Add("<ul>");
                    data.Add("<li>Only Excel file format is allowed</li>");
                    data.Add("</ul>");
                    data.ToArray();
                    return(Json(data, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                data.Add("<ul>");
                if (FileUpload == null)
                {
                    data.Add("<li>Please choose Excel file</li>");
                }
                data.Add("</ul>");
                data.ToArray();
                return(Json(data, JsonRequestBehavior.AllowGet));
            }
        }
예제 #16
0
        // open button click event handler, open file and load representation to "buffer"
        private void openButton_Click(object sender, EventArgs e)
        {
            // declarations
            StreamReader fileReader;
            DialogResult result;
            string       fileName, studentRecord;

            // clear rtb
            outputRichTextBox.Clear();

            // open file
            using (OpenFileDialog fileChooser = new OpenFileDialog())
            {
                fileChooser.Filter = "Text files (*.txt)|*.txt";
                result             = fileChooser.ShowDialog();
                fileName           = fileChooser.FileName;
            }
            if (result == DialogResult.OK)
            {
                try
                {
                    // delcarations
                    fileBuffer = new StudentFile();
                    // open stream
                    FileStream input = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    fileReader = new StreamReader(input);

                    // create records in "buffer"
                    studentRecord = fileReader.ReadLine();
                    while (studentRecord != null)
                    {
                        string[] recordFields = studentRecord.Split(',');
                        foreach (string field in recordFields)
                        {
                            field.Trim();
                        }
                        fileBuffer.studentRecords.Add(
                            new StudentFile.StudentRecord(
                                recordFields[0],
                                recordFields[1],
                                recordFields[2],
                                recordFields[3],
                                recordFields[4]));
                        studentRecord = fileReader.ReadLine();
                    }

                    // close stream
                    fileReader.Close();
                    input.Close();

                    // enable buttons
                    if (!studentButton.Enabled)
                    {
                        studentButton.Enabled = true;
                    }
                    if (!classButton.Enabled)
                    {
                        classButton.Enabled = true;
                    }
                    if (!gradeButton.Enabled)
                    {
                        gradeButton.Enabled = true;
                    }
                }
                catch (IOException)
                {
                    MessageBox.Show("Error reading from file", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }