public ApiData Get(int id)
 {
     using (ProjectDBEntities entities = new ProjectDBEntities())
     {
         return(entities.ApiDatas.FirstOrDefault(e => e.ID == id));
     }
 }
Esempio n. 2
0
 {/// <summary>
  /// מחזירה את כל סוגי הרשימות של קוד החשבון שנשלח
  /// </summary>
  /// <param name="accountId"></param>
  /// <returns></returns>
     public static List <TypeListDTO> GetAllTypesList(long accountId)
     {
         using (ProjectDBEntities db = new ProjectDBEntities())
         {
             return(CONVERTERS.TypeListConverter.ConvertTypeListListToDTO(db.TypesLists.Where(a => a.AccountId == accountId).ToList()));
         }
     }
Esempio n. 3
0
        public ActionResult ListSongsOfAlbum(Guid albumID, int page = 1)
        {
            if (page == 0)
            {
                page = 1;
            }

            var Context = new ProjectDBEntities();

            var album = Context.Albums.Where(x => x.AlbumID == albumID).FirstOrDefault <Album>();

            if (album == null)
            {
                return(HttpNotFound());
            }

            ViewBag.TextToDisplay = "Album : ";
            ViewBag.Message       = album.AlbumTitle;

            var userID = (Context.SiteUsers.Where(sux => sux.UserName == User.Identity.Name).FirstOrDefault <SiteUser>()).UserID;

            var totalTracksCount = Context.Tracks.Count();

            var currentTrackPage = Context.Tracks
                                   .Where(tx => tx.UserID == userID && tx.AlbumID == albumID)
                                   .OrderBy(x => x.DateAdded)
                                   .Skip((page - 1) * TracksPerPage)
                                   .Take(TracksPerPage)
                                   .ToList();

            return(View("ListSongs", new SongsListViewModel
            {
                Tracks = new PageData <Track>(currentTrackPage, totalTracksCount, page, TracksPerPage)
            }));
        }
Esempio n. 4
0
        public ActionResult VOrder()
        {
            ProjectDBEntities db = new ProjectDBEntities();
            var order            = db.Orders;

            return(View(order.ToList()));
        }
Esempio n. 5
0
 public ActionResult ContactUs()
 {
     using (ProjectDBEntities db = new ProjectDBEntities())
     {
         return(View(db.Feedbacks.ToList().OrderByDescending(x => x.FeedbackId)));
     }
 }
Esempio n. 6
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()));
            }
        }
Esempio n. 7
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));
        }
Esempio n. 8
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"));
            }
        }
 public string getStudentInfo(string id)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     Student student = new Student();
     try
     {
         IQueryable<StudentInfo> allInfo = from stu in PDb.StudentInfo
                                           where stu.SID == id
                                           select stu;
         if (allInfo.Count() == 0)
             return "False";
         foreach (StudentInfo item in allInfo)
         {
             student.ID = item.SID;
             student.Name = item.S_NAME;
             student.Gender = item.S_GENDER;
             student.School = item.S_SCHOOL;
             student.Birthday = item.S_BIRTHDAY;
             student.Grade = item.S_GRADE;
         }
         string reRes = JsonConvert.SerializeObject(student);
         return reRes;
     }
     catch
     {
         return "False";
     }
 }
Esempio n. 10
0
        /// <summary>
        /// פונקציה הבודקת אם שם משתמש וסיסמא קיימים במערכת
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public static UsersAccountDTO checkLogin(LoginDTO login)
        {
            User    user;
            Account account;

            using (ProjectDBEntities db = new ProjectDBEntities())
            {
                user = db.Users.FirstOrDefault(a => a.UserName == login.userName);
                if (user == null)
                {
                    return(null);
                }
                long userId = user.UserId;
                account = db.Accounts.FirstOrDefault(a => a.Password == login.userPassword);
                if (account == null)
                {
                    return(null);
                }
                long accountId = account.AccountId;
                if (db.UsersAccounts.FirstOrDefault(a => a.UserId == userId && a.AccountId == accountId) != null)
                {
                    return(CONVERTERS.UserAccountConverter.ConvertUsersAccountToDTO(db.UsersAccounts.FirstOrDefault
                                                                                        (a => a.UserId == userId && a.AccountId == accountId)));
                }
                else
                {
                    return(null);
                }
            }
        }
Esempio n. 11
0
 public static UserDTO GetUser(long userId)
 {
     using (ProjectDBEntities db = new ProjectDBEntities())
     {
         return(CONVERTERS.UserConverter.ConvertUserToDTO(db.Users.Where(u => u.UserId == userId).ToList()[0]));
     }
 }
Esempio n. 12
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()));
        }
Esempio n. 13
0
 /// <summary>
 /// מחזירה חשבון על פי קוד חשבון
 /// </summary>
 /// <param name="accountId"></param>
 /// <returns></returns>
 public static AccountDTO GetAccount(long accountId)
 {
     using (ProjectDBEntities db = new ProjectDBEntities())
     {
         return(CONVERTERS.AccountConverter.ConvertAccountToDTO(db.Accounts.Where(a => a.AccountId == accountId).ToList()[0]));
     }
 }
Esempio n. 14
0
        public ActionResult ResetPassword(string userId)
        {
            try
            {
                Guid guid = Guid.Parse(userId);
                using (var Context = new ProjectDBEntities())
                {
                    var User = Context.SiteUsers.Where(sxu => sxu.UserID == guid).FirstOrDefault <SiteUser>();

                    if (User != null)
                    {
                        UsersResetPasswordViewModel Model = new UsersResetPasswordViewModel();
                        Model.UserID   = User.UserID;
                        Model.UserPass = Hashing.GeneratePassword();
                        return(View(Model));
                    }
                    else
                    {
                        return(HttpNotFound());
                    }
                }
            }
            catch (Exception)
            {
                return(HttpNotFound());
            }
        }
Esempio n. 15
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());
            }
        }
Esempio n. 16
0
        public ActionResult ReqLoan(Models.Loan lm)//view to verify if accountno avilable in database and to display message accordingly
        {
            using (var contex = new ProjectDBEntities())
            {
                Issuccess        = true;
                ViewBag.success  = Issuccess;
                TempData["loan"] = lm;
                TempData.Keep();
                bool isValid = contex.Accounts.Any(x => x.AccountID == lm.AccountID);
                if (isValid)
                {
                    if (ViewBag.success)
                    {
                        return(Content("<script language='javascript' type='text/javascript'>alert('Your Loan Application has been Submitted.!');" +
                                       "window.location='Index';</script>"));//alertMessage for loan application submission
                    }



                    return(View());
                }
                ModelState.AddModelError("", "You doesnot have Account in this bank or your Accont Number is wrong.Please check again!!");

                return(View());
            }
        }
Esempio n. 17
0
        public ActionResult ListSongs(int page = 1)
        {
            if (page == 0)
            {
                page = 1;
            }

            var Context = new ProjectDBEntities();

            var userID = (Context.SiteUsers.Where(sux => sux.UserName == User.Identity.Name).FirstOrDefault <SiteUser>()).UserID;

            var totalTracksCount = Context.Tracks.Count();

            var currentTrackPage = Context.Tracks
                                   .Where(tx => tx.UserID == userID)
                                   .OrderBy(x => x.DateAdded)
                                   .Skip((page - 1) * TracksPerPage)
                                   .Take(TracksPerPage)
                                   .ToList();

            return(View(new SongsListViewModel
            {
                Tracks = new PageData <Track>(currentTrackPage, totalTracksCount, page, TracksPerPage)
            }));
        }
Esempio n. 18
0
        public ActionResult AddSongsInAlbum()
        {
            using (var Context = new ProjectDBEntities())
            {
                var userID = (Context.SiteUsers.Where(x => x.UserName == User.Identity.Name).FirstOrDefault <SiteUser>()).UserID;

                ViewBag.Albums = Context.Albums
                                 .Where(x => x.UserID == userID && x.IsActive == true && x.UserID == userID)
                                 .ToList();

                ViewBag.SharingTypes = Context.SharingTypes.ToList();

                return(View(new AddSongsInAlbumViewModel
                {
                    Generes = Context.Generes
                              .Where(x => x.IsActive == true)
                              .Select(genere => new GenereCheckBox
                    {
                        ID = genere.GenereID,
                        Name = genere.GenereDetail,
                        IsChecked = false
                    }).ToList()
                }));
            }
        }
Esempio n. 19
0
        public override string[] GetRolesForUser(string username)
        {
            using (ProjectDBEntities Context = new ProjectDBEntities())
            {
                var user = Context.SiteUsers.Where(cx => cx.UserName == username).ToList();

                if (user.Count == 1)
                {
                    return new string[] { "user" }
                }
                ;
                else
                {
                    var admin = Context.Administrators.Where(ax => ax.AdminUserName == username).ToList();

                    if (admin.Count == 1)
                    {
                        return new string[] { "admin" }
                    }
                    ;
                    else
                    {
                        return(null);
                    }
                }
            }
        }
Esempio n. 20
0
        public ActionResult ListAlbums(int page = 1)
        {
            if (page == 0)
            {
                page = 1;
            }

            var Context = new ProjectDBEntities();

            var userID = (Context.SiteUsers.Where(sux => sux.UserName == User.Identity.Name).FirstOrDefault <SiteUser>()).UserID;

            var totalAlbumsCount = Context.Albums.Count();

            var currentAlbumPage = Context.Albums
                                   .Where(x => x.UserID == userID && x.AlbumTitle != "Default")
                                   .OrderBy(x => x.DateAdded)
                                   .Skip((page - 1) * AlbumsPerPage)
                                   .Take(AlbumsPerPage)
                                   .ToList();

            return(View(new AlbumsListViewModel
            {
                Albums = new PageData <Album>(currentAlbumPage, totalAlbumsCount, page, AlbumsPerPage)
            }));
        }
Esempio n. 21
0
 public IEnumerable <ApiData> Get()
 {
     using (ProjectDBEntities entities = new ProjectDBEntities())
     {
         return(entities.ApiDatas.ToList());
     }
 }
Esempio n. 22
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"));
            }
        }
 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";
 }
Esempio n. 24
0
        public ActionResult Download(Guid id)
        {
            var Context = new ProjectDBEntities();

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

            if (track == null)
            {
                Content("test");
            }

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "track.mp3",

                Inline = false,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());


            var path = Server.MapPath("~" + track.TrackPath);

            byte[] file = System.IO.File.ReadAllBytes(path);

            return(File(file, "application/octet-stream"));
        }
Esempio n. 25
0
        public ActionResult GridView()
        {
            ProjectDBEntities db = new ProjectDBEntities();
            var data             = db.Customers;

            return(View(data.ToList()));
        }
Esempio n. 26
0
 /// <summary>
 /// פונקציה המחזירה את כל הרשימות שעוד לא הושלמו קנייתם
 /// </summary>
 /// <param name="accountId"></param>
 public static List <ListDTO> GetActiveLists(int accountId)
 {
     using (ProjectDBEntities db = new ProjectDBEntities())
     {
         return(CONVERTERS.ListConverter.ConvertArrayListToDTO(db.Lists.Where(list => list.TypesList.AccountId == accountId && list.EndDate != null && list.EndDate >= DateTime.Today && list.ProductToLists.Count(p => p.DateOfBuy == null) > 0).ToList()));
     }
 }
Esempio n. 27
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));
        }
Esempio n. 28
0
        public ActionResult Login(AdminLoginViewModel model)
        {
            if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
            {
                return(RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" }));
            }
            else
            {
                if (!ModelState.IsValid)
                {
                    return(View(new AdminLoginViewModel()));
                }

                using (ProjectDBEntities Context = new ProjectDBEntities())
                {
                    model.Password = Hashing.CreateHash(model.Password);

                    var admin = Context.Administrators.Where(x => x.AdminUserName == model.Username && x.AdminPassword == model.Password).FirstOrDefault <Administrator>();

                    if (admin != null)
                    {
                        FormsAuthentication.SetAuthCookie(admin.AdminUserName, true);
                        return(RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" }));
                    }
                }

                ViewBag.Message = "Incorrect username/password combination..";
                return(View(new AdminLoginViewModel()));
            }
        }
Esempio n. 29
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));
        }
Esempio n. 30
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());
        }
Esempio n. 31
0
 public bool IsEmailExist(string EmailId)
 {
     using (ProjectDBEntities db = new ProjectDBEntities())
     {
         var v = db.Customers.Where(a => a.EmailId == EmailId).FirstOrDefault();
         return(v != null);
     }
 }
Esempio n. 32
0
        //מחזיר את רשימת המוצרים לחשבון שצריך להתריע עליהם
        public static List <AlertDTO> GetAlertsForAccount(int accountId)
        {
            using (ProjectDBEntities db = new ProjectDBEntities())

            {
                return(db.Alerts.Where(p => p.FollowUpList.AccountId == accountId && p.IsActivated == true).ToList().Select(p => CONVERTERS.AlertConverter.ConvertAlertToDTO(p)).ToList());
            }
        }
Esempio n. 33
0
 public string isReg(string id)
 {
     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";
     else
         return "True";
 }
 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";
     }
 }
Esempio n. 35
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 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";
        }
 public string getGPA(string type, string id)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     if (type != "1" && type != "2" && type != "3" && type != "4")
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     double totalGrades = 0;
     double totalCredits = 0;
     List<int> grades = new List<int>();
     List<double> credits = new List<double>();
     try
     {
         IQueryable<StuGrade> allGrade = from grd in PDb.StuGrade
                                         where grd.SID == id
                                         select grd;
         if (allGrade.Count() == 0)
             return "False";
         foreach (StuGrade item in allGrade)
         {
             int tempGrade = 0;
             if (item.G_GRADE == "优")
             {
                 tempGrade = 95;
             }
             else if (item.G_GRADE == "良")
             {
                 tempGrade = 85;
             }
             else if (item.G_GRADE == "中")
             {
                 tempGrade = 75;
             }
             else if (item.G_GRADE == "及")
             {
                 tempGrade = 65;
             }
             else if (Convert.ToInt16(item.G_GRADE) > 100)
             {
                 continue;
             }
             else
             {
                 tempGrade = Convert.ToInt16(item.G_GRADE);
             }
             double tempCredit = Convert.ToDouble(item.G_CREDIT);
             grades.Add(tempGrade);
             credits.Add(tempCredit);
         }
         for (int i = 0; i < credits.Count; i++)
         {
             totalCredits += credits[i];
         }
         if (type == "1") //标准
         {
             for (int i = 0; i < grades.Count; i++)
             {
                 if (grades[i] >= 90)
                     totalGrades += 4.0 * credits[i];
                 else if (grades[i] < 90 && grades[i] >= 80)
                     totalGrades += 3.0 * credits[i];
                 else if (grades[i] < 80 && grades[i] >= 70)
                     totalGrades += 2.0 * credits[i];
                 else if (grades[i] < 70 && grades[i] >= 60)
                     totalGrades += 1.0 * credits[i];
                 else
                     totalGrades += 0 * credits[i];
             }
             return ((float)totalGrades / totalCredits).ToString();
         }
         else if (type == "2") //改进1
         {
             int count = 0;
             for (int i = 0; i < grades.Count; i++)
             {
                 if (grades[i] >= 85)
                     totalGrades += 4.0 * credits[i];
                 else if (grades[i] < 85 && grades[i] >= 70)
                     totalGrades += 3.0 * credits[i];
                 else if (grades[i] < 70 && grades[i] >= 60)
                     totalGrades += 2.0 * credits[i];
                 else
                     totalGrades += 0 * credits[i];
             }
             return ((float)totalGrades / totalCredits).ToString();
         }
         else if (type == "3") //北大4.0
         {
             int count = 0;
             for (int i = 0; i < grades.Count; i++)
             {
                 if (grades[i] >= 90)
                     totalGrades += 4.0 * credits[i];
                 else if (grades[i] < 90 && grades[i] >= 85)
                     totalGrades += 3.7 * credits[i];
                 else if (grades[i] < 85 && grades[i] >= 82)
                     totalGrades += 3.3 * credits[i];
                 else if (grades[i] < 82 && grades[i] >= 78)
                     totalGrades += 3.0 * credits[i];
                 else if (grades[i] < 78 && grades[i] >= 75)
                     totalGrades += 2.7 * credits[i];
                 else if (grades[i] < 75 && grades[i] >= 72)
                     totalGrades += 2.3 * credits[i];
                 else if (grades[i] < 72 && grades[i] >= 68)
                     totalGrades += 2.0 * credits[i];
                 else if (grades[i] < 68 && grades[i] >= 64)
                     totalGrades += 1.5 * credits[i];
                 else if (grades[i] < 64 && grades[i] >= 60)
                     totalGrades += 1.0 * credits[i];
                 else
                     totalGrades += 0 * credits[i];
             }
             return ((float)totalGrades / totalCredits).ToString();
         }
         else //加拿大
         {
             int count = 0;
             for (int i = 0; i < grades.Count; i++)
             {
                 if (grades[i] >= 90)
                     totalGrades += 4.3 * credits[i];
                 else if (grades[i] < 90 && grades[i] >= 85)
                     totalGrades += 4.0 * credits[i];
                 else if (grades[i] < 85 && grades[i] >= 80)
                     totalGrades += 3.7 * credits[i];
                 else if (grades[i] < 80 && grades[i] >= 75)
                     totalGrades += 3.3 * credits[i];
                 else if (grades[i] < 75 && grades[i] >= 70)
                     totalGrades += 3.0 * credits[i];
                 else if (grades[i] < 70 && grades[i] >= 65)
                     totalGrades += 2.7 * credits[i];
                 else if (grades[i] < 65 && grades[i] >= 60)
                     totalGrades += 2.3 * credits[i];
                 else
                     totalGrades += 0 * credits[i];
             }
             return ((float)totalGrades / totalCredits).ToString();
         }
     }
     catch
     {
         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 getStudentGrade(string id)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     List<GradeShow> seList = new List<GradeShow>();
     //StudentEvent se  = new StudentEvent();
     try
     {
         IQueryable<StuGrade> allGrade = from grd in PDb.StuGrade
                                      where grd.SID == id
                                      select grd;
         if (allGrade.Count() == 0)
             return "False";
         foreach (StuGrade item in allGrade)
         {
             GradeShow se = new GradeShow();
             se.Name = item.G_NAME;
             se.Grade = item.G_GRADE;
             se.Teacher = item.G_TEACHER;
             se.TestType = item.G_TESTTYPE;
             se.Credit = item.G_CREDIT;
             seList.Add(se);
         }
         string reRes = JsonConvert.SerializeObject(seList);
         return reRes;
     }
     catch
     {
         return "False";
     }
 }
 public string getAllEvents(string id)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     List<StudentEvent> seList = new List<StudentEvent>();
     //StudentEvent se  = new StudentEvent();
     try
     {
         IQueryable<Event> allEvent = from eve in PDb.Event
                                           where eve.SID == id
                                           select eve;
         if (allEvent.Count() == 0)
             return "False";
         foreach(Event item in allEvent) {
             StudentEvent se = new StudentEvent();
             se.EID = item.EID.ToString();
             se.Title = item.E_TITLE;
             se.Detail = item.E_DETAIL;
             se.Location = item.E_LOCATION;
             se.People = item.E_PEOPLE;
             se.Start = item.E_START;
             se.End = item.E_END;
             se.isAllDay = item.E_ALLDAY;
             se.Date = item.E_DATE;
             seList.Add(se);
         }
         string reRes = JsonConvert.SerializeObject(seList);
         return reRes;
     }
     catch
     {
         return "False";
     }
 }
 public string getEventsByDate(string id, string sDate, string eDate)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     try
     {
         DateTime sDT = Convert.ToDateTime(sDate);
         DateTime eDT = Convert.ToDateTime(eDate);
         if (sDT > eDT)
             return "Wrong Input";
         ProjectDBEntities PDb = new ProjectDBEntities();
         List<StudentEvent> seList = new List<StudentEvent>();
         IQueryable<Event> allEvent = from eve in PDb.Event
                                             where eve.SID == id
                                             select eve;
         if (allEvent.Count() == 0)
             return "False";
         foreach (Event item in allEvent)
         {
             DateTime DT = Convert.ToDateTime(item.E_DATE);
             if ((sDT <= DT) && (DT <= eDT))
             {
                 StudentEvent se = new StudentEvent();
                 se.Title = item.E_TITLE;
                 se.Detail = item.E_DETAIL;
                 se.Location = item.E_LOCATION;
                 se.People = item.E_PEOPLE;
                 se.Start = item.E_START;
                 se.End = item.E_END;
                 se.isAllDay = item.E_ALLDAY;
                 se.Date = item.E_DATE;
                 seList.Add(se);
             }
         }
         if (seList.Count == 0)
             return "False";
         string reRes = JsonConvert.SerializeObject(seList);
         return reRes;
     }
     catch (FormatException e)
     {
         return "Wrong Input";
     }
 }
Esempio n. 42
0
 public string sendStudentCourses(string id)
 {
     if (!Validation.IDValidation(id))
         return "Wrong Input";
     ProjectDBEntities PDb = new ProjectDBEntities();
     List<Course> coList = new List<Course>();
     IQueryable<StuCourses> coInfo = from co in PDb.StuCourses
                                     where co.SID == id
                                     select co;
     if (coInfo.Count() == 0)
         return "False";
     foreach (StuCourses item in coInfo)
     {
         Course co = new Course();
         co.Name = item.C_NAME;
         co.Week = item.C_WEEK;
         co.Day = item.C_DAY;
         co.Section = item.C_SECTION;
         co.Location = item.C_LOCATION;
         co.Teacher = item.C_TEACHER;
         co.Credit = item.C_CREDIT;
         co.Category = item.C_CATEGORY;
         co.TestType = item.C_TESTTYPE;
         co.Duration = item.C_DURATION;
         coList.Add(co);
     }
     string retJson = JsonConvert.SerializeObject(coList);
     return retJson;
 }
 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";
     }
 }
Esempio n. 44
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";
 }