Beispiel #1
0
        public async Task <IActionResult> Edit(int id, [Bind("SchoolID,SchoolCode,SchoolName,orgID")] school school)
        {
            if (id != school.SchoolID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(school);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!schoolExists(school.SchoolID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(school));
        }
Beispiel #2
0
        public ActionResult addtodb(int sid, string sname, int scount, int eid, string city)
        {
            automatedexamsEntities1 e = new automatedexamsEntities1();
            school sc   = new school();
            bool   flag = false;

            foreach (var v in e.exams)
            {
                if (v.eid == eid)
                {
                    flag = true;
                }
            }
            if (flag)
            {
                sc.sid    = sid;
                sc.sname  = sname;
                sc.count  = scount;
                sc.examid = eid;
                sc.city   = city;
                e.schools.Add(sc);
                e.SaveChanges();
            }

            return(View());
        }
Beispiel #3
0
        public static int InsertSchool(String name, String description)
        {
            bindedinEntities bie = SingletonEntities.Instance;
            var existingSchool   = from s in bie.schools
                                   where s.name.Equals(name)
                                   where s.description.Equals(description)
                                   select s;

            if (existingSchool.Count() == 0)
            {
                school sc = new school
                {
                    name        = name,
                    description = description
                };

                bie.AddToschools(sc);
                bie.SaveChanges();
            }
            var id = from s in bie.schools
                     where s.name.Equals(name)
                     where s.description.Equals(description)
                     select s.id;

            return(id.First());
        }
Beispiel #4
0
        private CanvasCourseModel GetCourse(int crsuniq, int funiq, int schuniq)
        {
            school sisSchool   = SISdb.schools.Find(schuniq);
            int    schoolYear  = Convert.ToInt32(SISdb.schools.Max(s => s.schyear));
            string sisCourseId = schoolYear + ":" + crsuniq + ":" + funiq;

            //get the account id
            int accountId;

            AccountIDs.TryGetValue(sisSchool.schoolc, out accountId);
            using (var client = new WebClient())
            {
                string getCourseURL = CanvasUrl + "accounts/" + accountId + "/courses/?per_page=999999999999&access_token=" + OAuthKey;
                var    json         = client.DownloadString(getCourseURL);
                var    serializer   = new JavaScriptSerializer();
                List <CanvasCourseModel> courses = serializer.Deserialize <List <CanvasCourseModel> >(json);
                var vCourse =
                    courses.Where(c => c.sis_course_id == sisCourseId);
                if (vCourse.Any())
                {
                    return(vCourse.First());
                }
            }

            return(null);
        }
Beispiel #5
0
        }//end public void scan()

        /// <summary>
        /// 讲读取出的学校存入列表schoolsList
        /// </summary>
        public void schools()
        {
            for (int i = 0; schoolArr[i] != null; i++)
            {
                school aSchool = new school();//创建一个school对象
                string schoolX = stopsArr[i][1];
                ///输出此school的坐标
//                Console.WriteLine("x=" + schoolArr[i][1] + "\ty=" + schoolArr[i][2]);

                aSchool.schoolID = schoolArr[i][0];
                aSchool.schoolX  = double.Parse(stopsArr[i][1]);
                aSchool.schoolY  = double.Parse(schoolArr[i][2]);
                aSchool.AMEarly  = schoolArr[i][3];
                aSchool.AMLate   = schoolArr[i][4];
                schoolsList.Add(aSchool);
            } //end for
            ///遍历schoolsList
            Console.WriteLine("所有的学校******************************************************************************");
            Console.WriteLine("schoolID schoolX\tschooY\tAMEarly\tAMLate");
            for (int i = 0; i < schoolsList.Count; i++)
            {
                Console.WriteLine(schoolsList[i].schoolID + "\t" + schoolsList[i].schoolX + "\t"
                                  + schoolsList[i].schoolY + "\t" + schoolsList[i].AMEarly + "\t"
                                  + schoolsList[i].AMLate);
            }
        }
Beispiel #6
0
        public JsonResult GetCoursesBySchoolCode(int schuniq)
        {
            //calculate the school year
            int schoolYear = Convert.ToInt32(SISdb.schools.Max(s => s.schyear));

            school school = SISdb.schools.Find(schuniq);

            var vSchedules = from c in SISdb.courses
                             join tc in SISdb.trkcrs on c.crsuniq equals tc.crsuniq
                             join tr in SISdb.tracks on tc.trkuniq equals tr.trkuniq
                             join ms in SISdb.mstscheds on tc.trkcrsuniq equals ms.trkcrsuniq
                             join fd in SISdb.facdemoes on ms.funiq equals fd.funiq
                             where tr.schoolc == school.schoolc
                             where tr.schyear == schoolYear
                             where !fd.lastname.Contains("College")
                             where !fd.lastname.Contains("Admin")
                             orderby c.descript
                             select ms;

            List <mstsched> schedules    = vSchedules.ToList();
            List <object>   courseInfoes = new List <object>();

            foreach (mstsched schedule in schedules)
            {
                course course = schedule.trkcr.course;

                object courseInfo = new { text = course.descript + " : " + schedule.facdemo.firstname + " " + schedule.facdemo.lastname, value = course.crsuniq + ":" + schedule.facdemo.funiq };
                courseInfoes.Add(courseInfo);
            }

            return(Json(new { success = "true", courses = courseInfoes.Distinct() }));
        }
Beispiel #7
0
        internal static ResultCode AddScholl(school school)
        {
            ResultCode result = new ResultCode();

            result.codeResult = CodeResult.Normal;
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    using (ApplicationContext dbContext = new ApplicationContext())
                    {
                        if (dbContext.Schools.Any())
                        {
                            school.schoolId = dbContext.Schools.Max(MAX => MAX.schoolId) + 1;
                        }
                        else
                        {
                            school.schoolId = 1;
                        }
                        dbContext.Schools.Add(school);
                        dbContext.SaveChanges();
                    }

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.codeResult   = CodeResult.Faild;
                result.ErrorMessage = ex.Message;
            }
            return(result);
        }
Beispiel #8
0
        public ActionResult DeleteConfirmed(int id)
        {
            school school = db.Movies.Find(id);

            db.Movies.Remove(school);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #9
0
        private schoolDTO ToDTO(school r)
        {
            schoolDTO s = new schoolDTO();

            s.schoolname     = r.schoolname;
            s.CreateDateTime = r.CreateDateTime;
            return(s);
        }
Beispiel #10
0
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            Spell sp = new Spell();

            try
            {
                sp.id    = textBoxId.Text;
                sp.index = Int32.Parse(textBoxIndex.Text);
                sp.name  = textBoxName.Text;
                List <string> description = new List <string>();
                description.Add(textBoxDescription.Text);
                sp.desc = description.ToArray();
                List <string> higherLvl = new List <string>();
                description.Add(textBoxHigherlvl.Text);
                sp.higher_level = higherLvl.ToArray();
                sp.page         = textBoxPage.Text;
                sp.range        = textBoxRange.Text;
                List <string> components = new List <string>();
                description.Add(textBoxComponents.Text);
                sp.components    = components.ToArray();
                sp.material      = textBoxMaterial.Text;
                sp.ritual        = textBoxRitual.Text;
                sp.duration      = textBoxDuration.Text;
                sp.concentration = textBoxConcentration.Text;
                sp.casting_time  = textBoxCastingTime.Text;
                sp.level         = Int32.Parse(textBoxlevel.Text);

                school school = new school();

                school.name = textBoxSchool.Text;
                school.url  = "http://" + school.name;

                sp.school = school;

                List <CharacterClass> charClasses = new List <CharacterClass>();
                CharacterClass        charClass   = new CharacterClass();
                charClass.name = textBoxClasses.Text;
                charClass.url  = "http://" + charClass.name;
                charClasses.Add(charClass);
                sp.characterClasses = charClasses.ToArray();

                List <Subclass> subclasses = new List <Subclass>();
                Subclass        subclass   = new Subclass();
                subclass.name = textBoxClasses.Text;
                subclass.url  = "http://" + subclass.name;
                subclasses.Add(subclass);

                sp.subclasses = subclasses.ToArray();
                sp.url        = textBoxUrl.Text;

                bm2.add2(sp);
                this.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Wypełnij poprawnie wszystkie pola!");
            }
        }
Beispiel #11
0
        private void Initialize()
        {
            SqlConnection LocalCon = Connection.Conn();

            if (LocalCon.State != ConnectionState.Open)
            {
                LocalCon.Open();
            }
            try
            {
                SqlDataReader rd = Connection.GetDataReader("select * from tbl_ProductReg");
                if (rd.Read())
                {
                    school sc         = new school();
                    string key        = rd["prodkey"].ToString();
                    string user       = rd["username"].ToString();
                    string schoolName = rd["schoolname"].ToString();
                    string city       = rd["city"].ToString();
                    string branch     = rd["branchname"].ToString();

                    pnlActKey.Visible = true;
                    PopulateControls(key, user, schoolName, city, branch);

                    if (key == school.trialProdKey)
                    {
                        btnUseTrial.Enabled = false;
                        int days = GetDaysLeftForTrial();
                        if (days <= 0)
                        {
                            lblTrial.Text = "Your trial has expired. Please activate your product to continue using it.";
                        }
                        else
                        {
                            lblTrial.Text = "Your trial period is left for " + days + " days";
                        }
                    }
                    else
                    {
                        DisableAllControls();
                        lblTrial.Visible = false;

                        lblActive.Text = "Your product is activated";
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (LocalCon.State == ConnectionState.Open)
                {
                    LocalCon.Close();
                }
            }
        }
Beispiel #12
0
 public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] school school)
 {
     if (ModelState.IsValid)
     {
         db.Entry(school).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(school));
 }
Beispiel #13
0
 public ActionResult Edit([Bind(Include = "school_id,school_name,Xth_marks,XIIth_marks")] school school)
 {
     if (ModelState.IsValid)
     {
         db.Entry(school).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(school));
 }
Beispiel #14
0
        public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] school school)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(school);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(school));
        }
Beispiel #15
0
        public async Task <IActionResult> Create([Bind("SchoolID,SchoolCode,SchoolName,orgID")] school school)
        {
            if (ModelState.IsValid)
            {
                _context.Add(school);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(school));
        }
Beispiel #16
0
        public ActionResult Create([Bind(Include = "school_id,school_name,Xth_marks,XIIth_marks")] school school)
        {
            if (ModelState.IsValid)
            {
                db.schools.Add(school);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(school));
        }
        public ActionResult SchoolLocation(school sc)
        {
            var cu = Session["user"] as ContextUser;
            var coordinatorRepo = new CoordinatorRepository();
            var cor             = coordinatorRepo.GetBySchool(sc.Id);

            //cor.school.Lat = sc.Lat;
            //cor.school.Lng = sc.Lng;
            cor.school.SchoolGeoLocation = sc.SchoolGeoLocation;
            coordinatorRepo.Put(cor.Id, cor);
            return(RedirectToAction("Index", "Session"));
        }
Beispiel #18
0
        // GET: schools/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            school school = db.Movies.Find(id);

            if (school == null)
            {
                return(HttpNotFound());
            }
            return(View(school));
        }
        internal static school getSchoolDetails(string SchoolName)
        {
            school result = new school();

            using (ApplicationContext db = new ApplicationContext())
            {
                result = db.Schools.FirstOrDefault(s => s.Name == SchoolName);
                if (result != null)
                {
                    result.Pupils   = db.Pupils.Where(w => w.SchoolNumber == result.schoolId).ToList();
                    result.Teachers = db.Teachers.Where(t => t.SchoolNumber == result.schoolId).ToList();
                    result.Admins   = db.Admins.Where(a => a.SchoolNumber == result.schoolId).ToList();
                }
            }

            return(result);
        }
Beispiel #20
0
 public bool AddSchool(string name)
 {
     using (Dbcontext ctx = new Dbcontext())
     {
         try
         {
             school s = new school();
             s.schoolname = name;
             ctx.school.Add(s);
             ctx.SaveChanges();
             return(true);
         }
         catch
         {
             return(false);
         }
     }
 }
        private ClaimsIdentity GetIdentity(string username, string password)
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                Person person = db.Persons.FirstOrDefault(p => p.Login == username && p.Password == password);

                if (person != null)
                {
                    if (person.Password == password)
                    {
                        var claims = new List <Claim>
                        {
                            new Claim(ClaimsIdentity.DefaultNameClaimType, person.Login),
                            new Claim(ClaimsIdentity.DefaultRoleClaimType, person.Role)
                        };

                        ClaimsIdentity claimsIdentity =
                            new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                               ClaimsIdentity.DefaultRoleClaimType);
                        return(claimsIdentity);
                    }
                }
                else
                {
                    school schools = db.Schools.FirstOrDefault(s => s.schoolId == 1);
                    if (schools == null)
                    {
                        var claims = new List <Claim>
                        {
                            new Claim(ClaimsIdentity.DefaultNameClaimType, "*****@*****.**"),
                            new Claim(ClaimsIdentity.DefaultRoleClaimType, "Admin")
                        };

                        ClaimsIdentity claimsIdentity =
                            new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                               ClaimsIdentity.DefaultRoleClaimType);
                        return(claimsIdentity);
                    }
                }
            }
            return(null);
        }
Beispiel #22
0
        public ActionResult EditSchool([FromBody] JObject SchoolJson)
        {
            ResultCode result   = new ResultCode();
            Admin      admin    = new Admin();
            school     schoolOb = new school();

            schoolOb = JsonConvert.DeserializeObject <school>(SchoolJson.ToString());

            if (schoolOb != null)
            {
                result = admin.EditSchool(schoolOb);
            }

            if (result.codeResult == CodeResult.Faild)
            {
                NotFound(result.ErrorMessage);
            }

            return(Ok());
        }
        internal static ResultCode AddSchoolWithDetails(school schoolDetales, List <Teacher> teachers, List <Pupil> pupils, List <Admin> admins)
        {
            ResultCode result = new ResultCode();

            result.codeResult = CodeResult.Normal;

            try
            {
                if (schoolDetales != null)
                {
                    AddScholl(schoolDetales);
                }
                else
                {
                    result.codeResult   = CodeResult.Faild;
                    result.ErrorMessage = "School Details not found";
                    return(result);
                }

                if (teachers.Count > 0)
                {
                    AddTeachers(teachers);
                }

                if (pupils.Count > 0)
                {
                    AddPupil(pupils);
                }

                if (admins.Count > 0)
                {
                    AddAdmin(admins);
                }
            }
            catch (Exception Ex)
            {
                result.codeResult   = CodeResult.Faild;
                result.ErrorMessage = Ex.Message;
            }
            return(result);
        }
Beispiel #24
0
        public void Read(TProtocol iprot)
        {
            iprot.IncrementRecursionDepth();
            try
            {
                TField field;
                iprot.ReadStructBegin();
                while (true)
                {
                    field = iprot.ReadFieldBegin();
                    if (field.Type == TType.Stop)
                    {
                        break;
                    }
                    switch (field.ID)
                    {
                    case 0:
                        if (field.Type == TType.Struct)
                        {
                            Success = new school();
                            Success.Read(iprot);
                        }
                        else
                        {
                            TProtocolUtil.Skip(iprot, field.Type);
                        }
                        break;

                    default:
                        TProtocolUtil.Skip(iprot, field.Type);
                        break;
                    }
                    iprot.ReadFieldEnd();
                }
                iprot.ReadStructEnd();
            }
            finally
            {
                iprot.DecrementRecursionDepth();
            }
        }
Beispiel #25
0
        private void CheckForSubcription()
        {
            DataSet dschk = Connection.GetDataSet("Select * from tbl_ProductReg ");

            if (dschk.Tables[0].Rows.Count < 1)
            {
                Registration r = new Registration();
                this.Hide();
                r.Show();
                r.BringToFront();
            }
            else
            {
                if (dschk.Tables[0].Rows[0]["prodkey"] == null || string.Equals(dschk.Tables[0].Rows[0]["prodkey"], school.trialProdKey) || string.IsNullOrEmpty(dschk.Tables[0].Rows[0]["prodkey"].ToString()))
                {
                    DataSet dsTrial = Connection.GetDataSet("Select * from SMSsystem ");
                    long    regDate = Convert.ToInt64(dsTrial.Tables[0].Rows[0]["RegDate"]);

                    DateTime dt      = DateTime.FromBinary(regDate);
                    long     runTime = Convert.ToInt64(dsTrial.Tables[0].Rows[0]["RunTime"]);

                    int daysLeft = dt.AddDays(30).Subtract(DateTime.Now).Days + 1;

                    int runCount = Convert.ToInt32(dsTrial.Tables[0].Rows[0]["RunCount"]);

                    int daysUsed = dt.AddSeconds(runTime).Subtract(dt).Days;

                    if (daysLeft <= 0 || daysUsed > 30 || runCount > 45)
                    {
                        this.Hide();
                        MessageBox.Show("Your trial subscription has ended. Please activate your product.", "Subscription Ended", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Registration r = new Registration();
                        r.Show();
                        r.BringToFront();
                    }
                    else if (daysLeft < 15)
                    {
                        if (MessageBox.Show(
                                "Your trial will end in " + daysLeft + " days. Would you like to activate your product now?",
                                "Alert", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            this.Hide();
                            Registration r = new Registration();
                            r.Show();
                            r.BringToFront();
                        }
                        else
                        {
                            Loginform lf = new Loginform();
                            this.Hide();
                            lf.Show();
                            lf.BringToFront();
                        }
                    }
                    else
                    {
                        Loginform lf = new Loginform();
                        this.Hide();
                        lf.Show();
                        lf.BringToFront();
                    }
                }

                else
                {
                    DataSet dsSchool = Connection.GetDataSet("Select schoolname, schoolcity from tbl_school ");

                    DataSet dsTrial = Connection.GetDataSet("Select * from SMSsystem ");
                    long    regDate = Convert.ToInt64(dsTrial.Tables[0].Rows[0]["RegDate"]);

                    DateTime dt = DateTime.FromBinary(regDate);

                    school sc   = new school();
                    string pKey = sc.ConstructProductKey(dsSchool.Tables[0].Rows[0]["schoolname"].ToString().Replace(" ", "").Replace(".", ""),
                                                         dsSchool.Tables[0].Rows[0]["schoolcity"].ToString().Replace(" ", ""), dt.Day.ToString(), dt.Month.ToString(), dt.Year.ToString());

                    if (string.Equals(dschk.Tables[0].Rows[0]["prodkey"], pKey))
                    {
                        DateTime dtnew = DateTime.Now;
                        TimeSpan t     = dtnew.Subtract(dt);
                        int      k     = t.Days;
                        if (k > 365)
                        {
                            MessageBox.Show("Your Subscription has expired.");
                            Help r = new Help();
                            r.Show();
                            this.Hide();
                            r.BringToFront();
                        }
                        else
                        {
                            if (k > 350 && k < 365)
                            {
                                int l1 = 365 - k;
                                MessageBox.Show("Number of days left " + l1.ToString() +
                                                ", please renew your Subscription.");
                            }

                            Loginform lf = new Loginform();
                            this.Hide();
                            lf.Show();
                            lf.BringToFront();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Your Product Key is invalid. Please contact our support team for help.");
                        Help r = new Help();
                        r.Show();
                        this.Hide();
                        r.BringToFront();
                    }
                }
            }
        }
Beispiel #26
0
        private CanvasUserModel CreateCanvasUser(int suniq, int schuniq)
        {
            school sisSchool = SISdb.schools.Find(schuniq);

            //get the account id
            int accountId;

            AccountIDs.TryGetValue(sisSchool.schoolc, out accountId);

            //make sure the user doesn't exist
            CanvasUserModel user = GetUserBySISId(suniq.ToString());

            if (user != null)
            {
                //the user exists
                return(user);
            }

            //the user does not exist
            studemo student  = SISdb.studemoes.Find(suniq);
            string  password = student.FirstName.Substring(0, 1).ToUpper() +
                               student.LastName.Substring(0, 1).ToLower() + student.suniq.ToString().Substring(student.suniq.ToString().Length - 4);
            string userJson = "{\"user\": {" +
                              "\"name\": \"" + student.FirstName.Trim() + " " + student.LastName.Trim() + "\"," +
                              "\"short_name\": \"" + student.PreferredFirstName.Trim() + "\"," +
                              "\"sortable_name\": \"" + student.LastName.Trim() + ", " + student.FirstName.Trim() + "\"}," +
                              "\"pseudonym\": {" +
                              "\"unique_id\": \"" + student.emailaddr + "\"," +
                              "\"password\": \"" + password + "\"," +
                              "\"sis_user_id\": \"" + suniq + "\"," +
                              //this should be set to true on live
                              "\"send_confirmation\": \"false\"}," +
                              "\"communication_channel\": {" +
                              "\"type\":\"email\"," +
                              "\"address\": \"" + student.emailaddr + "\"," +
                              "\"skip_confirmation\": \"true\"}}";


            //send the data
            string createUserURL  = CanvasUrl + "accounts/" + accountId + "/users?access_token=" + OAuthKey;
            var    httpWebRequest = (HttpWebRequest)WebRequest.Create(createUserURL);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            CanvasUserModel newUser = new CanvasUserModel();

            try
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(userJson);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var serializer = new JsonSerializer();
                        using (var jsonTextReader = new JsonTextReader(streamReader))
                        {
                            newUser = serializer.Deserialize <CanvasUserModel>(jsonTextReader);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                newUser = null;
            }

            return(newUser);
        }
Beispiel #27
0
        public JsonResult UpdateStudentsInSection(string mstuniq)
        {
            int            usersAdded      = 0;
            int            usersRemoved    = 0;
            int            usersLeftAlone  = 0;
            int            usersWithErrors = 0;
            List <studemo> errorUsers      = new List <studemo>();
            //calculate the school year
            int schoolYear = Convert.ToInt32(SISdb.schools.Max(s => s.schyear));

            mstsched period = SISdb.mstscheds.Find(Convert.ToInt32(mstuniq));

            if (period == null)
            {
                return(Json(new
                {
                    success = "false",
                    message = "Period does not exist in SIS!"
                }));
            }

            CanvasSectionModel section = GetSectionBySISId(schoolYear + ":" + mstuniq + ":" + period.facdemo.funiq);

            if (section == null)
            {
                return(Json(new
                {
                    success = "false",
                    message = "Section does not exist in Canvas!"
                }));
            }

            //get the students in the section in canvas
            List <CanvasUserModel> users         = GetUsersInSection(section.id);
            List <CanvasUserModel> usersNotInSIS = GetUsersInSection(section.id);

            //get the students in the period in sis
            DateTime tomorrow  = DateTime.Now.AddDays(-365);
            var      vStuSched = SISdb.stuscheds.Where(s => s.mstmeet.mstuniq == period.mstuniq && (s.xdate >= tomorrow || s.xdate == null));

            foreach (stusched student in vStuSched)
            {
                //check to see if they are in the section
                CanvasUserModel canvasStudent = users.Find(u => u.sis_user_id == student.suniq.ToString());
                if (canvasStudent == null)
                {
                    //add the student
                    //see if student exists in canvas
                    canvasStudent = GetUserBySISId(student.suniq.ToString());
                    if (canvasStudent == null)
                    {
                        //create the user
                        school sisSchool = SISdb.schools.First(s => s.schoolc == period.trkcr.track.schoolc);
                        canvasStudent = CreateCanvasUser(student.suniq, sisSchool.schuniq);
                    }

                    if (canvasStudent != null)
                    {
                        //enroll the current user
                        EnrollStudentInSection(canvasStudent.id, section.id);
                        usersAdded++;
                    }
                    else
                    {
                        errorUsers.Add(student.studemo);
                        usersWithErrors++;
                    }
                }
                else
                {
                    //student is in sis and the course in canvas do nothing with them.
                    usersLeftAlone++;
                }

                if (canvasStudent != null)
                {
                    usersNotInSIS.RemoveAll(c => c.id == canvasStudent.id);
                }
            }

            foreach (CanvasUserModel canvasStudent in usersNotInSIS)
            {
                UnEnrollStudentFromSection(canvasStudent.id, section.course_id);
                usersRemoved++;
            }

            if (errorUsers.Any())
            {
                string message = "These users failed to enroll, likely because they are deleted in canvas: <br /><ul>";
                foreach (studemo errorUser in errorUsers)
                {
                    message += "<li>" + errorUser.FirstName + " " + errorUser.LastName + " Email Address:" + errorUser.emailaddr + "</li>";
                }
                message += "</ul>";

                EmailSender.EmailSender.sendTemplatedMessage("*****@*****.**",
                                                             Globals.EMAIL_ADDRESSES, "Failed to enroll students in class", message, "High");
            }


            return(Json(new
            {
                success = "true",
                studentsAdded = usersAdded,
                studentsRemoved = usersRemoved,
                studentsLeftAlone = usersLeftAlone,
                studentsCurrentlyEnrolled = vStuSched.Count(),
                studentsWithErrors = usersWithErrors
            }));
        }
Beispiel #28
0
        public JsonResult CreateCourse(int crsuniq, int funiq, int schuniq)
        {
            course  sisCourse     = SISdb.courses.Find(crsuniq);
            school  sisSchool     = SISdb.schools.Find(schuniq);
            facdemo courseTeacher = SISdb.facdemoes.Find(funiq);
            int     schoolYear    = Convert.ToInt32(SISdb.schools.Max(s => s.schyear));
            string  sisCourseId   = schoolYear + ":" + crsuniq + ":" + funiq;

            //get the account id
            int accountId;

            AccountIDs.TryGetValue(sisSchool.schoolc, out accountId);

            //make sure the course doesn't exist
            CanvasCourseModel vCourse = GetCourse(crsuniq, funiq, schuniq);

            if (vCourse != null)
            {
                //the course exists return the id
                return(Json(new
                {
                    success = "true",
                    courseId = vCourse.id
                }));
            }

            CanvasCourseModel vSisCourse = GetCourseBySISId(sisCourseId);

            if (vSisCourse != null)
            {
                //the course exists return the id
                return(Json(new
                {
                    success = "true",
                    courseId = vSisCourse.id
                }));
            }


            string courseJson = "{ \"account_id\": \"" + accountId + "\"," +
                                "\"course\": {" +
                                "\"name\": \"" + sisCourse.descript + " : " + courseTeacher.lastname.Trim() + " " + courseTeacher.firstname.Trim() + "\"," +
                                "\"course_code\": \"" + sisCourse.descript + " : " + courseTeacher.lastname.Trim() + " " + courseTeacher.firstname.Trim() + "\"," +
                                "\"sis_course_id\": \"" + sisCourseId + "\"}}";


            //send the data
            string createCourseURL = CanvasUrl + "accounts/" + accountId + "/courses?access_token=" + OAuthKey;
            var    httpWebRequest  = (HttpWebRequest)WebRequest.Create(createCourseURL);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            CanvasCourseModel newCourse = new CanvasCourseModel();

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(courseJson);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var serializer = new JsonSerializer();
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                    {
                        newCourse = serializer.Deserialize <CanvasCourseModel>(jsonTextReader);
                    }
                }
            }

            //attach the teacher
            AssignTeacherToCourse(funiq, newCourse.id, schuniq);

            return(Json(new
            {
                success = "true",
                courseId = newCourse.id
            }));
        }
        internal static ResultCode EditSchool(school schoolDetails)
        {
            ResultCode result = new ResultCode();

            result.codeResult = CodeResult.Normal;
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    if (schoolDetails != null)
                    {
                        using (ApplicationContext contextDB = new ApplicationContext())
                        {
                            List <school> oldSchoolFind = contextDB.Schools.Where(s => s.Name == schoolDetails.Name).ToList(); //<school>(s => s.Name == schoolDetails.Name);

                            if (oldSchoolFind.Count == 0)
                            {
                                result.codeResult = CodeResult.Faild;

                                result.ErrorMessage = "NOT FOUND";
                                return(result);
                            }

                            if (schoolDetails.Teachers.Count != 0)
                            {
                                List <Teacher> Teachers = schoolDetails.Teachers;

                                Teachers?.ForEach(item =>
                                {
                                    if (contextDB.Teachers.Any(t => t.Login == item.Login))
                                    {
                                        Teacher teacher    = contextDB.Teachers.First(t => t.Login == item.Login);
                                        teacher.Adress     = item.Adress;
                                        teacher.Age        = item.Age;
                                        teacher.FirstName  = item.FirstName;
                                        teacher.LastName   = item.LastName;
                                        teacher.Password   = item.Password;
                                        teacher.PersonId   = item.PersonId;
                                        teacher.Profession = item.Profession;
                                        contextDB.SaveChanges();
                                    }
                                    else
                                    {
                                        item.PersonId = contextDB.Persons.Max(MAX => MAX.PersonId) + 1;
                                        contextDB.Teachers.Add(item);
                                        contextDB.SaveChanges();
                                    }
                                });
                            }

                            if (schoolDetails.Pupils.Count != 0)
                            {
                                List <Pupil> Pupils = schoolDetails.Pupils;

                                Pupils?.ForEach(item =>
                                {
                                    if (contextDB.Pupils.Any(p => p.Login == item.Login))
                                    {
                                        Pupil pupil      = contextDB.Pupils.First(p => p.Login == item.Login);
                                        pupil.Adress     = item.Adress;
                                        pupil.Age        = item.Age;
                                        pupil.FirstName  = item.FirstName;
                                        pupil.LastName   = item.LastName;
                                        pupil.Password   = item.Password;
                                        pupil.PersonId   = item.PersonId;
                                        pupil.Class      = item.Class;
                                        pupil.StudyLevel = item.StudyLevel;
                                        contextDB.SaveChanges();
                                    }
                                    else
                                    {
                                        item.PersonId = contextDB.Persons.Max(MAX => MAX.PersonId) + 1;
                                        contextDB.Pupils.Add(item);
                                        contextDB.SaveChanges();
                                    }
                                });
                            }

                            if (schoolDetails.Admins.Count != 0)
                            {
                                List <Admin> Admins = schoolDetails.Admins;

                                Admins?.ForEach(item =>
                                {
                                    if (contextDB.Admins.Any(a => a.Login == item.Login))
                                    {
                                        Admin admin     = contextDB.Admins.First(a => a.Login == item.Login);
                                        admin.Adress    = item.Adress;
                                        admin.Age       = item.Age;
                                        admin.FirstName = item.FirstName;
                                        admin.LastName  = item.LastName;
                                        admin.Password  = item.Password;
                                        admin.PersonId  = item.PersonId;
                                        admin.Role      = "Admin";
                                        contextDB.SaveChanges();
                                    }
                                    else
                                    {
                                        item.PersonId = contextDB.Persons.Max(MAX => MAX.PersonId) + 1;
                                        contextDB.Admins.Add(item);
                                        contextDB.SaveChanges();
                                    }
                                });
                            }
                        }
                    }
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.codeResult   = CodeResult.Faild;
                result.ErrorMessage = ex.Message;
            }

            return(result);
        }
        static void Main(string[] args)
        {
            int i = 0;
            var sportsmanIdMap    = new Dictionary <string, int>();
            var connSource        = new infointesourceContext();
            var connTarget        = new infointeContext();
            var transactionSource = connSource.Database.BeginTransaction();
            var transactionTarget = connTarget.Database.BeginTransaction();

            connTarget.ChangeTracker.AutoDetectChangesEnabled = false;
            connSource.ChangeTracker.AutoDetectChangesEnabled = false;
            try
            {
                var masters = connSource.master.ToList();

                masters.ForEach(m =>
                {
                    var sportsman = new sportsman
                    {
                        birthCity    = m.birthcity,
                        birthCountry = m.birthcountry,
                        birthState   = m.birthstate,
                        bats         = m.bats,
                        debut        = m.debut,
                        bbrefID      = m.bbrefid,
                        weight       = m.weight,
                        throws       = m.throws,
                        retroID      = m.retroid,
                        nameGiven    = m.namegiven,
                        lastname     = m.namelast,
                        firstname    = m.namefirst,
                        height       = m.height,
                        finalGame    = m.finalgame,
                        deathCity    = m.deathcity,
                        deathCountry = m.deathcountry,
                        deathDay     = m.deathday,
                        deathMonth   = m.deathmonth,
                        deathState   = m.deathstate,
                        deathYear    = m.deathyear
                    };

                    if (m.birthday != null && m.birthmonth != null && m.birthyear != null)
                    {
                        DateTime dateTime   = new DateTime(m.birthyear.Value, m.birthmonth.Value, m.birthday.Value);
                        sportsman.birthdate = dateTime;
                    }

                    connTarget.sportsman.Add(sportsman);
                    connTarget.SaveChanges();
                    sportsmanIdMap.Add(m.playerid, sportsman.id);

                    foreach (var hofEntry in connSource.halloffame.Where(hof => hof.playerid == m.playerid))
                    {
                        var tmpHofEntry = new hall_of_fame()
                        {
                            ballots      = hofEntry.ballots,
                            category     = hofEntry.category,
                            inducted     = hofEntry.inducted,
                            needed       = hofEntry.needed,
                            needed_note  = hofEntry.needed_note,
                            sportsman_id = sportsman.id,
                            voted_by     = hofEntry.votedby,
                            votes        = hofEntry.votes,
                            year         = hofEntry.yearid
                        };

                        Console.WriteLine(sportsman.id.ToString());
                        connTarget.hall_of_fame.Add(tmpHofEntry);
                    }

                    connTarget.SaveChanges();

                    ++i;
                    Console.WriteLine("Inserted Masters: " + i.ToString());

                    if (i % 250 == 0)
                    {
                        transactionSource.Commit();
                        transactionTarget.Commit();
                        transactionSource = connSource.Database.BeginTransaction();
                        transactionTarget = connTarget.Database.BeginTransaction();
                    }
                });

                i = 0;
                var schools = connSource.schools.ToList();

                schools.ForEach(s =>
                {
                    var school = new school()
                    {
                        id        = s.schoolid,
                        city      = s.city,
                        name_full = s.name_full,
                        country   = s.country,
                        state     = s.state
                    };

                    connTarget.school.Add(school);

                    ++i;
                    Console.WriteLine("Inserted Schools: " + i.ToString());

                    connTarget.SaveChanges();
                    if (i % 250 == 0)
                    {
                        transactionSource.Commit();
                        transactionTarget.Commit();
                        transactionSource = connSource.Database.BeginTransaction();
                        transactionTarget = connTarget.Database.BeginTransaction();
                    }
                });

                i = 0;
                var collegePlayings = connSource.collegeplaying.ToList();

                collegePlayings.ForEach(cp =>
                {
                    var collegePlaying = new college_playing()
                    {
                        year         = cp.yearid,
                        school_id    = cp.schoolid,
                        sportsman_id = sportsmanIdMap[cp.playerid]
                    };

                    connTarget.Add(collegePlaying);

                    ++i;
                    Console.WriteLine("Inserted College: " + i.ToString());

                    connTarget.SaveChanges();
                    if (i % 250 == 0)
                    {
                        transactionSource.Commit();
                        transactionTarget.Commit();
                        transactionSource = connSource.Database.BeginTransaction();
                        transactionTarget = connTarget.Database.BeginTransaction();
                    }
                });

                transactionTarget.Commit();
                transactionSource.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
                transactionTarget.Rollback();
                transactionSource.Rollback();
            }

            Console.ReadKey();
        }