예제 #1
0
        public IHttpActionResult Post(Login login)
        {
            Login log = new Login();

            context.Logins.Add(login);
            context.SaveChanges();
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Logins", Method = "GET", Rel = "Self"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Logins/" + log.Id, Method = "GET", Rel = "Specific Resource"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Logins/" + log.Id, Method = "PUT", Rel = "Resource Edit"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Logins/" + log.Id, Method = "DELETE", Rel = "Resource Delete"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Logins", Method = "POST", Rel = "Resource Create"
            });
            return(Created(Url.Link("GetLoginById", new { id = login.Id }), login));
        }
예제 #2
0
        public IHttpActionResult Post(User user)
        {
            User log = new User();

            context.Users.Add(user);
            context.SaveChanges();
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Users", Method = "GET", Rel = "Self"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Users/" + log.Id, Method = "GET", Rel = "Specific Resource"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Users/" + log.Id, Method = "PUT", Rel = "Resource Edit"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Users/" + log.Id, Method = "DELETE", Rel = "Resource Delete"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Users", Method = "POST", Rel = "Resource Create"
            });
            return(Created(Url.Link("GetUserById", new { id = user.Id }), user));
        }
예제 #3
0
        public IHttpActionResult Post(Employee employee)
        {
            Employee log = new Employee();

            context.Employees.Add(employee);
            context.SaveChanges();
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Employees", Method = "GET", Rel = "Self"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Employees/" + log.Id, Method = "GET", Rel = "Specific Resource"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Employees/" + log.Id, Method = "PUT", Rel = "Resource Edit"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Employees/" + log.Id, Method = "DELETE", Rel = "Resource Delete"
            });
            log.links.Add(new Links()
            {
                HRef = "http://localhost:59819/api/Employees", Method = "POST", Rel = "Resource Create"
            });
            return(Created(Url.Link("GetEmployeeById", new { id = employee.Id }), employee));
        }
예제 #4
0
        public IHttpActionResult PutReport(int id, Report report)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != report.Id)
            {
                return(BadRequest());
            }

            db.Entry(report).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReportExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #5
0
 public ActionResult AddOrder(string command)
 {
     if (command == "Insert")
     {
         tbl_order obj = new tbl_order();
         obj.productName = Request.Form["txtpname"].ToString();
         obj.price       = decimal.Parse(Request.Form["txtprice"].ToString());
         obj.customerId  = int.Parse(Request.Form["ddlname"].ToString());
         db.tbl_order.Add(obj);
         var result = db.SaveChanges();
         if (result > 0)
         {
             ModelState.AddModelError("", "Order Placed Successfully");
             return(View());
         }
         else
         {
             ModelState.AddModelError("", "Technical Error Occured:Unable to Place Order !");
             return(View());
         }
     }
     else
     {
         return(View());
     }
 }
예제 #6
0
        public IHttpActionResult PutAuthor([FromUri] int id, Author author)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != author.Id)
            {
                return(BadRequest());
            }

            db.Entry(author).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #7
0
 public JsonResult SaveUser(UserModel model)
 {
     try
     {
         if (model.UserID > 0)
         {
             User user = db.Users.SingleOrDefault(u => u.UserID == model.UserID);
             user.Name   = model.Name;
             user.Mobile = model.Mobile;
             user.Email  = model.Email;
             db.SaveChanges();
         }
         else
         {
             User user = new User();
             user.Name   = model.Name;
             user.Mobile = model.Mobile;
             user.Email  = model.Email;
             db.Users.Add(user);
             db.SaveChanges();
             model.UserID = user.UserID;
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return(Json(model, JsonRequestBehavior.AllowGet));
 }
예제 #8
0
        public ActionResult Total(Order order)
        {
            List <Cart> li = TempData["cart"] as List <Cart>;
            tbl_invoice iv = new tbl_invoice();

            iv.CustomerId        = Convert.ToInt32(Session["CustomerId"].ToString());
            iv.InvoiceDate       = System.DateTime.Now;
            iv.Invoice_TotalBill = Convert.ToDecimal(TempData["total"]);
            db.tbl_invoice.Add(iv);
            db.SaveChanges();
            foreach (var item in li)
            {
                Order o = new Order();
                o.NewspaperId = item.PaperId;
                // o.Newspaper.NewspaperName = item.PaperName;
                o.InvoiceId       = iv.InvoiceId;
                o.OrderDate       = System.DateTime.Now;
                o.Order_Unitprice = Convert.ToInt32(item.price);
                o.OrderQty        = item.qty;
                o.OrderBill       = decimal.ToDouble(item.bill);
                db.Orders.Add(o);
                db.SaveChanges();
            }
            TempData.Remove("total");
            TempData.Remove("cart");
            TempData["message"] = "Transaction completed";
            TempData.Keep();
            return(RedirectToAction("Index", "Payment"));
        }
        public ActionResult Create(Company company, HttpPostedFileBase imgFile)
        {
            if (ModelState.IsValid)
            {
                /*  if (company.Capital < 10000)
                 * {
                 *    ModelState.AddModelError("", "Capital should grater than 10000");
                 *    return View(company);
                 * }*/
                string path = "";
                if (imgFile.FileName.Length > 0)
                {
                    path = "~/images/" + Path.GetFileName(imgFile.FileName);
                    imgFile.SaveAs(Server.MapPath(path));
                }
                company.Logo = path;


                db.Companies.Add(company);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }


            return(View(company));
        }
예제 #10
0
        public ActionResult Create([Bind(Include = "NewspaperId,NewspaperName,Price")] Newspaper newspaper)
        {
            if (ModelState.IsValid)
            {
                db.Newspapers.Add(newspaper);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(newspaper));
        }
예제 #11
0
        public ActionResult Create([Bind(Include = "role_id,role")] Role role)
        {
            if (ModelState.IsValid)
            {
                db.Roles.Add(role);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(role));
        }
예제 #12
0
        public ActionResult Create([Bind(Include = "ModuleID,ModuleName")] Module module)
        {
            if (ModelState.IsValid)
            {
                db.Modules.Add(module);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(module));
        }
예제 #13
0
 public ActionResult Edit([Bind(Include = "StudentID,FirstName,LastName,Email")] Student student)
 {
     if (ModelState.IsValid)
     {
         db.Entry(student).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.StudentID = new SelectList(db.Students, "StudentID", "FirstName", student.StudentID);
     ViewBag.StudentID = new SelectList(db.Users, "UserID", "Password", student.StudentID);
     return(View(student));
 }
예제 #14
0
        public ActionResult Create([Bind(Include = "UserID,Password,Role")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.UserID = new SelectList(db.Lecturers, "LecturerID", "FirstName", user.UserID);
            ViewBag.UserID = new SelectList(db.Students, "StudentID", "FirstName", user.UserID);
            return(View(user));
        }
예제 #15
0
        public ActionResult Create(Survey survey, string action)
        {
            if (ModelState.IsValid)
            {
                db.Surveys.Add(survey);
                db.SaveChanges();
                return(RedirectToAction("Index", new { id = survey.SurveyID }));
            }
            TempData["error"] = "An error occurred while attempting to create this survey.";

            ViewBag.ModuleID = new SelectList(db.Modules, "ModuleId", "ModuleName", survey.ModuleID);
            return(View(survey));
        }
예제 #16
0
        public ActionResult Create([Bind(Include = "EnrollmentID,ModuleID,StudentID")] Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Enrollments.Add(enrollment);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ModuleID  = new SelectList(db.Modules, "ModuleID", "ModuleName", enrollment.ModuleID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "FirstName", enrollment.StudentID);
            return(View(enrollment));
        }
예제 #17
0
        public IHttpActionResult PUT([FromUri] int id, [FromBody] FeaturedBook fb)
        {
            var item = context.FeaturedBooks.Where(c => c.Id == id).FirstOrDefault();

            if (item == null)
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }
            else
            {
                item.Book_Id = fb.Book_Id;
                context.SaveChanges();
                return(Ok(item));
            }
        }
예제 #18
0
        public ActionResult Create(int post_id, string comment)
        {
            if (ModelState.IsValid)
            {
                Comment newComment = new Comment();
                newComment.comment = comment;
                newComment.user_id = (int)Session["user_id"];
                newComment.post_id = post_id;
                newComment.created = DateTime.Now;
                db.Comments.Add(newComment);
                db.SaveChanges();
            }

            return(RedirectToAction("Details", "Posts", new { id = post_id }));
        }
예제 #19
0
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            var Message = "";

            if (ModelState.IsValid)
            {
                using (ProjectDBEntities db = new ProjectDBEntities())
                {
                    var cust = db.Customers.Where(a => a.ResetPasswordCode == model.ResetCode).FirstOrDefault();
                    if (cust != null)
                    {
                        cust.Password          = Crypto.Hash(model.NewPassword);
                        cust.ResetPasswordCode = "";// to avoid using same code for multiple time
                        db.Configuration.ValidateOnSaveEnabled = false;
                        db.SaveChanges();
                        Message = "New Password updated Successfully";
                    }
                }
            }
            else
            {
                Message = "Something Invalid";
            }

            ViewBag.Message = Message;
            return(View(model));
        }
예제 #20
0
        public ActionResult ForgotPassword(string EmailID)
        {
            //verify EmailId
            //Generate Reset password link
            //Send Email
            string message = "";
            bool   status  = false;

            using (ProjectDBEntities db = new ProjectDBEntities())
            {
                var account = db.Customers.Where(a => a.EmailId == EmailID).FirstOrDefault();
                if (account != null)
                {
                    //send email for reset password
                    string resetCode = Guid.NewGuid().ToString();
                    SendVerificationLinkEmail(account.EmailId, resetCode, "ResetPassword");
                    account.ResetPasswordCode = resetCode;
                    //this is added here to avoid confirm password not match issue, as we had added a confirm password property
                    //in model class
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();
                    message = "Reset password link has been sent to your Email id";
                }
                else
                {
                    message = "Account not found";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
예제 #21
0
        public IHttpActionResult Post(Customer c)
        {
            context.Customers.Add(c);
            context.SaveChanges();

            return(StatusCode(HttpStatusCode.Created));
        }
예제 #22
0
        public ActionResult ForgotPassword(AdminForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var Context = new ProjectDBEntities())
                {
                    var admin = Context.Administrators.Where(x => x.AdminEmail == model.Email).FirstOrDefault <Administrator>();
                    if (admin == null)
                    {
                        ViewBag.Message = "No Such User..";
                        return(View(model));
                    }

                    string generatedPassword = Hashing.GeneratePassword();
                    if (Mailer.ForgotPasswordAdmin(admin.AdminUserName, generatedPassword))
                    {
                        admin.AdminPassword = Hashing.CreateHash(generatedPassword);
                        Context.SaveChanges();
                        ViewBag.Message = "New Password has been sent to admin email..";
                        return(View(new AdminForgotPasswordViewModel()));
                    }
                    else
                    {
                        ViewBag.Message = "SMTP is not working.. try later..";
                        return(View(new AdminForgotPasswordViewModel()));
                    }
                }
            }

            return(View(model));
        }
예제 #23
0
        public ActionResult Block(string userId)
        {
            try
            {
                Guid guid = Guid.Parse(userId);
                using (var Context = new ProjectDBEntities())
                {
                    var User = Context.SiteUsers.Where(sxu => sxu.UserID == guid).ToList();

                    if (User.Count > 0)
                    {
                        User[0].UserStatusID = 3;

                        if (Context.SaveChanges() == 1)
                        {
                            ViewBag.Message = "User status updated successfully..";
                        }
                        else
                        {
                            ViewBag.Message = "Unable to update user..";
                        }
                    }
                    else
                    {
                        ViewBag.Message = "No such user..";
                    }

                    return(RedirectToAction("All"));
                }
            }
            catch (Exception)
            {
                return(HttpNotFound());
            }
        }
예제 #24
0
        public ActionResult DeleteSong(Guid trackId)
        {
            using (var Context = new ProjectDBEntities())
            {
                var guid = (Context.SiteUsers.Where(sxu => sxu.UserName == User.Identity.Name).FirstOrDefault <SiteUser>()).UserID;

                var track = Context.Tracks.Find(trackId);

                if (track == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    var trackShare = Context.UserTrackShares
                                     .Where(x => x.TrackID == track.TrackID)
                                     .FirstOrDefault <UserTrackShare>();

                    Context.UserTrackShares.Remove(trackShare);

                    Context.Tracks.Remove(track);
                    Context.SaveChanges();

                    RemoveOld(track.TrackCoverPath);
                    RemoveOld(track.TrackPath);
                }
                return(RedirectToAction("ListSongs"));
            }
        }
예제 #25
0
        public ActionResult New(UsersCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var Context = new ProjectDBEntities())
                {
                    var UserStatus = Context.UserStatus.Where(usx => usx.UserStatusDetail == "Pending").FirstOrDefault <UserStatu>();

                    model.DateCreated   = DateTime.Now;
                    model.DateActivated = DateTime.Now;

                    Mapper.CreateMap <UsersCreateViewModel, SiteUser>();
                    SiteUser User = Mapper.Map <SiteUser>(model);


                    User.UserStatusID = UserStatus.UserStatusID;
                    User.UserPass     = Hashing.CreateHash(model.UserPass);

                    Context.SiteUsers.Add(User);

                    if (Context.SaveChanges() == 1)
                    {
                        ViewBag.Message = "User added successfully..";
                    }
                    else
                    {
                        ViewBag.Message = "User cannot be added at the moment..";
                    }
                }
            }
            return(View(new UsersCreateViewModel()));
        }
예제 #26
0
        public ActionResult DeleteAlbum(Guid albumId)
        {
            using (var Context = new ProjectDBEntities())
            {
                var guid = (Context.SiteUsers
                            .Where(sxu => sxu.UserName == User.Identity.Name)
                            .FirstOrDefault <SiteUser>()
                            ).UserID;

                var album = Context.Albums
                            .Where(nx => nx.AlbumID == albumId && nx.UserID == guid && nx.AlbumTitle != "Default")
                            .FirstOrDefault <Album>();

                if (album == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    Context.Albums.Remove(album);
                    Context.SaveChanges();
                    RemoveOld(album.AlbumCoverPath);
                }
                return(RedirectToAction("ListAlbums"));
            }
        }
예제 #27
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (var Context = new ProjectDBEntities())
            {
                var oldPassword = Hashing.CreateHash(model.OldPassword);
                var user        = Context.SiteUsers
                                  .Where(x => x.UserName == User.Identity.Name && x.UserPass == oldPassword)
                                  .FirstOrDefault <SiteUser>();

                if (user == null)
                {
                    ViewBag.Message = "Old password doesn't match..";
                    return(View(model));
                }

                user.UserPass = Hashing.CreateHash(model.NewPassword);

                Context.SaveChanges();

                ViewBag.Message = "Password Changed Successfully..";
                return(View(new ChangePasswordViewModel()));
            }
        }
예제 #28
0
        public ActionResult ChangePassword(AdminChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
                {
                    using (var Context = new ProjectDBEntities())
                    {
                        var OldHashedPassword = Hashing.CreateHash(model.OldPassword);

                        var user = Context.Administrators.Where(ax => ax.AdminUserName == User.Identity.Name && ax.AdminPassword == OldHashedPassword).FirstOrDefault <Administrator>();
                        if (user != null)
                        {
                            user.AdminPassword = Hashing.CreateHash(model.NewPassword);
                            Context.SaveChanges();
                            ViewBag.Message = "Password Changed Successfully to " + model.NewPassword;
                            return(View(new AdminChangePasswordViewModel()));
                        }
                        else
                        {
                            ViewBag.Message = "Old password seems different";
                            return(View(new AdminChangePasswordViewModel()));
                        }
                    }
                }
            }

            return(Content(User.Identity.Name));
        }
예제 #29
0
 public string addEvent(string id, string json)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     StudentEvent se = new StudentEvent();
     se = JsonConvert.DeserializeObject<StudentEvent>(json);
     ProjectDBEntities PDb = new ProjectDBEntities();
     int count = PDb.StudentInfo.Where(s => s.SID == id).Count();
     if (count != 0)
     {
         Event e = new Event
         {
             SID = id,
             E_TITLE = se.Title,
             E_LOCATION = se.Location,
             E_PEOPLE = se.People,
             E_DETAIL = se.Detail,
             E_START = se.Start,
             E_END = se.End,
             E_ALLDAY = se.isAllDay,
             E_DATE = se.Date
         };
         PDb.Event.Add(e);
         PDb.SaveChanges();
         return "True";
     }
     else
         return "False";
 }
예제 #30
0
        public IHttpActionResult Post(Order order)
        {
            context.Orders.Add(order);
            context.SaveChanges();

            return(Created(Url.Link("GetOrderById", new { id = order.Id }), order));
        }
예제 #31
0
        /// <summary>
        /// הגדרת תדירות למוצר ועדכונה כל קניה
        /// </summary>
        /// <param name="follow"></param>
        public static void SetFrequency(FollowUpList follow)

        {
            using (ProjectDBEntities db = new ProjectDBEntities())
            {
                int    daysbefore = 0, daysafter = 0;
                double rangeDates = 0;
                //lastbuys שולף את כל הפעמים שנקנה המוצר וממין מהתאריך קנייה האחרון ומטה
                List <ProductToList> lastBuys = db.ProductToLists.
                                                Where(p => p.DateOfBuy != null && p.ProductId == follow.ProductId && p.List.TypesList.AccountId == follow.AccountId).
                                                OrderByDescending(p => p.DateOfBuy).ToList();
                //אם מעודכן תדירות כבר למוצר, מחשב את הזמנים שאפשר לחרוג בקניית המוצר
                if (follow.Frequency != null)
                {
                    daysbefore = follow.Frequency.NumDays - follow.Frequency.Exception; // חריגה לפני
                    daysafter  = follow.Frequency.NumDays + follow.Frequency.Exception; //חריגה אחרי
                }
                // אם קנה מוצר זה יותר מפעמיים אז מחשב את הפרש זמן הקנייה מהקנייה העכשוית לקניה הקודמת לה
                if (lastBuys.Count >= 2)
                {
                    rangeDates = (lastBuys[0].DateOfBuy - lastBuys[1].DateOfBuy).Value.TotalDays;
                }
                // אם תקין- קיימת תדירות ויש יותר וקנה את המוצר יותר מ 3 םעמים וגם קניית המוצר עכשיו היא עדיין בטווח החריגה או שבכלל אין לו על מה לעבוד עדיין כי אין לו כמות מספקת בשביל החישוב
                if ((follow.Frequency != null && lastBuys.Count >= 3 && rangeDates >= daysbefore && rangeDates <= daysafter) ||
                    lastBuys.Count < 3)
                {
                    return;
                }
                // מחשב הפרשי קנייה של 3 הפעמים האחרונות שקנה את המוצר
                int[] differences = new int[2];
                for (int i = 0; i < 2; i++)
                {
                    differences[i] = (int)(lastBuys[i].DateOfBuy - lastBuys[i + 1].DateOfBuy).Value.TotalDays;//הפרש בין התאריכים האחרונים
                }
                // בודק אם ההפרשים נמצאים באחד מהטווחים הנתונים כבר
                foreach (var frequency in db.Frequencies)
                {
                    int i = 0;
                    for (; i < 2; i++)
                    {
                        if (!(IsNumberInFreequencyRange(differences[i], frequency)))
                        {
                            break;
                        }
                    }
                    if (i < 2)
                    {
                        continue;
                    }
                    // אם כל ההפרשים מקיימים את אחד מהטווחים מעדכן את התדירות למוצר זה
                    db.FollowUpLists.FirstOrDefault(f => f.FollowUpListId == follow.FollowUpListId).FrequencyId = frequency.FrequencyId;
                    //frequency.FrequencyId;
                    break;
                }
                db.SaveChanges();
            }
        }
예제 #32
0
 public string deleteEvent(string id, int eid)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     try
     {
         IQueryable<Event> allEvent = from eve in PDb.Event
                                      where eve.SID == id && eve.EID == eid
                                      select eve;
         if (allEvent.Count() == 0)
             return "False";
         foreach (Event item in allEvent)
         {
             PDb.Event.Remove(item);
         }
         PDb.SaveChanges();
         return "True";
     }
     catch
     {
         return "False";
     }
 }
예제 #33
0
 public string receiveStudentCourses(string id, string json)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     int count = PDb.StudentInfo.Where(s => s.SID == id).Count();
     if (count == 0)
         return "False";
     string[] jsons = Validation.Split(json);
     foreach(string item in jsons)
     {
         Course cos = JsonConvert.DeserializeObject<Course>(item);
         StuCourses sc = new StuCourses
         {
             SID = id,
             C_NAME = cos.Name,
             C_WEEK = cos.Week,
             C_DAY = cos.Day,
             C_SECTION = cos.Section,
             C_LOCATION = cos.Location,
             C_TEACHER = cos.Teacher,
             C_CREDIT = cos.Credit,
             C_CATEGORY = cos.Category,
             C_TESTTYPE = cos.TestType,
             C_DURATION = cos.Duration
         };
         PDb.StuCourses.Add(sc);
     }
     try
     {
         PDb.SaveChanges();
     }
     catch
     {
         return "Fail";
     }
     return "True";
 }
예제 #34
0
 public string Reg(string input)
 {
     Student student = new Student();
     student = JsonConvert.DeserializeObject<Student>(input);
     ProjectDBEntities PDb = new ProjectDBEntities();
     int count = PDb.StudentInfo.Where(s => s.SID == student.ID).Count();
     if (count == 0)
     {
         StudentInfo st = new StudentInfo
         {
             SID = student.ID,
             S_NAME = student.Name,
             S_GENDER = student.Gender,
             S_BIRTHDAY = student.Birthday,
             S_SCHOOL = student.School,
             S_GRADE = student.Grade
         };
         PDb.StudentInfo.Add(st);
         PDb.SaveChanges();
         return "True";
     }
     else
         return "False";
 }
        public string getRemoteGrade(string id, string pw)
        {
            if (!Validation.IDValidation(id))
                return "Wrong Input";
            try
            {
                ProjectDBEntities PDb = new ProjectDBEntities();
                int count = PDb.StudentInfo.Where(s => s.SID == id).Count();
                if (count == 0)
                    return "False";

                IQueryable<StuGrade> allGrades = from eve in PDb.StuGrade
                                                 where eve.SID == id
                                                 select eve;
                foreach (StuGrade item in allGrades)
                {
                    PDb.StuGrade.Remove(item);
                }
                CookieContainer cookieContainer = new CookieContainer();
                Encoding GB2312Encoding = Encoding.GetEncoding("GB2312");
                // Login to JWC.CQU.EDU.CN
                // Note that this url changes from time to time
                string loginUrl = @"http://202.202.1.176/login.asp";
                string loginParameters = "username="******"&password="******";
                RequestHandler.SendSynchronousRequest(loginUrl, loginParameters, "POST", GB2312Encoding, cookieContainer);
                string getUrl = @"http://202.202.1.176/score/sel_score/sum_score_sel.asp";
                string result = RequestHandler.SendSynchronousRequest(getUrl, loginParameters, "GET", GB2312Encoding, cookieContainer);
                //Regex GPARegex = new Regex(@"\d\.\d\d");
                //var GPARegexMatches = GPARegex.Matches(result);
                //String GPA = GPARegexMatches[0].Value;
                //string CoursesRegexString = "/(?<=    <td VALIGN=\"center\" width=\"210\" height=\"23\"> [^.][^.][^.][^.]      ).*/g";
                string CoursesRegexString = "(?<=    <td VALIGN=\"center\" width=\"210\" height=\"23\"> \r\n      ).*";
                Regex CoursesRegex = new Regex(CoursesRegexString);
                var CoursesRegexMatches = CoursesRegex.Matches(result);
                string GradeRegexString = "(?<=    <td  align=\"center\" VALIGN=\"center\" width=\"43\" height=\"23\">\r\n).*";
                Regex GradeRegex = new Regex(GradeRegexString);
                var GradeRegexMatches = GradeRegex.Matches(result);
                string CreditRegexString = "(?<=    <td  align=\"center\" VALIGN=\"center\" width=\"43\" height=\"23\"> \r\n      ).*";
                Regex CreditRegex = new Regex(CreditRegexString);
                var CreditRegexMatches = CreditRegex.Matches(result);
                string TypeRegexString = "(?<=    <td  align=\"center\" VALIGN=\"center\" width=\"53\" height=\"23\"> \r\n      \r\n).*";
                Regex TypeRegex = new Regex(TypeRegexString);
                var TypeRegexMatches = TypeRegex.Matches(result);
                string TeacherRegexString = "(?<=    <td align=\"center\"  VALIGN=\"center\" width=\"60\" height=\"23\"> \r\n       ).*";
                Regex TeacherTypeRegex = new Regex(TeacherRegexString);
                var TeacherTypeRegexMatches = TeacherTypeRegex.Matches(result);
                string TestTypeRegexString = "(?<=    <td align=\"center\"  VALIGN=\"center\" width=\"54\" height=\"23\"> \r\n).*";
                Regex TestTypeRegex = new Regex(TestTypeRegexString);
                var TestTypeRegexMatches = TestTypeRegex.Matches(result);
                //System.Console.WriteLine(CreditRegexMatches.Count);
                //System.Console.WriteLine(CoursesRegexMatches.Count);
                //System.Console.WriteLine(GradeRegexMatches.Count);
                //System.Console.WriteLine(TypeRegexMatches.Count);
                //System.Console.WriteLine(TeacherTypeRegexMatches.Count);
                //System.Console.WriteLine(TestTypeRegexMatches.Count);
                List<GradeItem> gList = new List<GradeItem>();
                for (int i = 0; i < CoursesRegexMatches.Count; i++)
                {
                    GradeItem gi = new GradeItem();
                    gi.Name = CoursesRegexMatches[i].Value;
                    gi.Name = gi.Name.Substring(0, gi.Name.Length - 1);
                    gi.Grade = GradeRegexMatches[i].Value;
                    gi.Grade = gi.Grade.Substring(1, gi.Grade.Length - 2);
                    gi.Type = TypeRegexMatches[i].Value.Substring(3);
                    gi.Credit = CreditRegexMatches[i].Value;
                    gi.Credit = gi.Credit.Substring(0, gi.Credit.Length - 1);
                    gi.Teacher = TeacherTypeRegexMatches[i].Value;
                    gi.Teacher = gi.Teacher.Substring(0, gi.Teacher.Length - 1);
                    gi.TestType = TestTypeRegexMatches[i].Value.Substring(1);
                    gi.TestType = gi.TestType.Substring(0, gi.TestType.Length - 1);
                    gList.Add(gi);
                }
                foreach (GradeItem item in gList)
                {
                    StuGrade sg = new StuGrade
                    {
                        SID = id,
                        G_NAME = item.Name,
                        G_GRADE = item.Grade,
                        G_CREDIT = item.Credit,
                        G_TEACHER = item.Teacher,
                        G_TYPE = item.Type,
                        G_TESTTYPE = item.TestType
                    };
                    PDb.StuGrade.Add(sg);
                }
                PDb.SaveChanges();
                return "True";
            }
            catch
            {
                return "False";
            }
        }
        public string getRemoteCourses(string id, string pw)
        {
            if (!Validation.IDValidation(id))
                return "Wrong Input";

            ProjectDBEntities PDb = new ProjectDBEntities();
            int count = PDb.StudentInfo.Where(s => s.SID == id).Count();
            if (count == 0)
                return "False";
            IQueryable<StuCourses> allCourses = from eve in PDb.StuCourses
                                            where eve.SID == id
                                            select eve;
            foreach (StuCourses item in allCourses)
            {
                PDb.StuCourses.Remove(item);
            }
            // Set up the encoding nice and neat
            Encoding GB2312Encoding = Encoding.GetEncoding("GB2312");

            // Since two continuous POST request is being sent, there has to be a cookie that remembers everything
            CookieContainer cookieContainer = new CookieContainer();

            // Login to JWC.CQU.EDU.CN
            // Note that this url changes from time to time
            string loginUrl = @"http://202.202.1.176:8080/_data/index_login.aspx";
            string loginParameters = "Sel_Type=STU&UserID=";
            loginParameters += id;
            loginParameters += "&PassWord="******"POST", GB2312Encoding, cookieContainer);

            // Retrieve the course table HTML and save in a string
            string courseUrl = @"http://202.202.1.176:8080/znpk/Pri_StuSel_rpt.aspx";
            string parametersToGetCourses = "Sel_XNXQ=20121&rad=1&px=1";
            string courseHtmlPage = RequestHandler.SendSynchronousRequest(courseUrl, parametersToGetCourses, "POST", GB2312Encoding, cookieContainer);
            try
            {
                Regex regex = new Regex(@"<td(?:\s[^>]*)?>(.*?)</td>");
                var regexMatches = regex.Matches(courseHtmlPage);

                // Stores the name and student ID of the student
                String studentName;
                String studentID;
                String studentInformation = regexMatches[0].Value;

                int subStrLimitForID = studentInformation.IndexOf("&nbsp;&nbsp;姓名:");
                studentID = studentInformation.Substring(3, subStrLimitForID - 3);
                int subStrLimitForName = studentInformation.IndexOf("&nbsp;&nbsp;讲授/上机");
                studentName = studentInformation.Substring(26, subStrLimitForName - 26);

                List<String> linearTableContent = new List<String>();

                // Remove all "<"s and ">"s
                for (int i = 0; i < regexMatches.Count; i++)
                {
                    Match match = regexMatches[i];
                    String s = match.Value.TrimStart('<');
                    int firstRightBraket = s.IndexOf('>') + 1;
                    int firstLeftBraket = s.IndexOf('<');
                    String content = s.Substring(firstRightBraket, firstLeftBraket - firstRightBraket);
                    if (i > 14) linearTableContent.Add(content);
                }

                // The number of properties of a course (usually this is the number of columns in the course table)
                int columnCount = 13;

                // fit number to the multiple of @columnCount
                int contentCount = linearTableContent.Count;
                int contentCountCopy = contentCount;
                while (contentCountCopy > columnCount)
                {
                    contentCountCopy -= columnCount;
                }
                contentCount -= contentCountCopy;

                // Save all courses in a list of Course objects
                List<Course> courses = new List<Course>();
                Course course = new Course();
                for (int i = 0; i < contentCount; i++)
                {
                    if (i % columnCount == 0)
                    {         // 序号
                        course = new Course();
                    }
                    else if (i % columnCount == 1)
                    {    // 课程
                        course.Name = linearTableContent[i];
                    }
                    else if (i % columnCount == 2)
                    {    // 学分
                        course.Credit = linearTableContent[i];
                    }
                    else if (i % columnCount == 3)
                    {    // 总学时
                        course.Duration = linearTableContent[i];
                    }
                    else if (i % columnCount == 4)
                    {    // 讲授学时
                        // Do nothing
                    }
                    else if (i % columnCount == 5)
                    {    // 上机学时
                        // Do nothing
                    }
                    else if (i % columnCount == 6)
                    {    // 类别
                        course.Category = linearTableContent[i];
                    }
                    else if (i % columnCount == 7)
                    {    // 授课方式

                    }
                    else if (i % columnCount == 8)
                    {    // 考核方式
                        course.TestType = linearTableContent[i];
                    }
                    else if (i % columnCount == 9)
                    {    // 任课教师
                        course.Teacher = linearTableContent[i];
                    }
                    else if (i % columnCount == 10)
                    {   // 周次
                        // Your processing method here
                        course.Week = OtherFunctions.FormatWeek(linearTableContent[i]);
                    }
                    else if (i % columnCount == 11)
                    {   // 节次
                        // Your processing method here
                        course.Section = OtherFunctions.FormatSection(linearTableContent[i]);
                        course.Day = OtherFunctions.FormatDay(linearTableContent[i]);
                        //course.EndTime = linearTableContent[i];
                    }
                    else if (i % columnCount == 12)
                    {   // 地点
                        course.Location = linearTableContent[i];
                        courses.Add(course);
                    }
                }
                if (courses.Count() == 0)
                    return "False";

                for (int i = 0; i < courses.Count(); i++)//each (Course item in courses)
                {
                    if ( i != 0 )
                    {
                        if(courses[i].Name == "")
                            courses[i].Name = courses[i - 1].Name;
                        if(courses[i].Teacher == "")
                            courses[i].Teacher = courses[i - 1].Teacher;
                        if (courses[i].Category == "")
                            courses[i].Category = courses[i - 1].Category;
                        if (courses[i].Credit == "")
                            courses[i].Credit = courses[i - 1].Credit;
                        if (courses[i].TestType == "")
                            courses[i].TestType = courses[i - 1].TestType;
                        if (courses[i].Duration == "")
                            courses[i].Duration = courses[i - 1].Duration;
                    }
                    StuCourses sc = new StuCourses
                    {
                        SID = id,
                        C_NAME = courses[i].Name,
                        C_WEEK = courses[i].Week,
                        C_DAY = courses[i].Day,
                        C_SECTION = courses[i].Section,
                        C_LOCATION = courses[i].Location,
                        C_TEACHER = courses[i].Teacher,
                        C_CREDIT = courses[i].Credit,
                        C_CATEGORY = courses[i].Category,
                        C_TESTTYPE = courses[i].TestType,
                        C_DURATION = courses[i].Duration
                    };
                    PDb.StuCourses.Add(sc);
                }
                PDb.SaveChanges();
            }
            catch
            {
                return "Failed";
            }
            return "True";
                //return OtherFunctions.FormatWeek(courses[k].Week) + "__" + courses[k].Week;//"True";
                //return courses[2].Day;//"True";
        }
예제 #37
0
 public string updateEvent(string id,int eid,string attr,string value)
 {
     if (!Validation.EventAttrValidation(attr))
         return "Wrong Input";
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     string QueryAttr = Validation.EventAttrConvert(attr);
     try
     {
         var query = PDb.Event.Where("SID = @0 and EID = @1", id, eid);
         if (query.Count() == 0)
             return "False";
         foreach (Event item in query)
         {
             item.GetType().GetProperty(QueryAttr).SetValue(item,value,null);//.GetValue(value, null);
         }
         PDb.SaveChanges();
         return "True";
     }
     catch
     {
         return "False";
     }
 }