Пример #1
0
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Student        Stu            = (Student)Session["student"];
        string         ID             = GridViewSelectCourse.SelectedValue.ToString();
        SqlConnection  sqlConnection  = SqlTools.Connection();
        string         sql            = string.Format(@"select course  from SelectCourse where Student={0}", Stu.ID1);
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection);;
        DataSet        dataSet        = new DataSet();

        sqlDataAdapter.Fill(dataSet);
        sqlConnection.Close();
        String[] CourseId = new string[dataSet.Tables[0].Rows.Count];
        int      count    = 0;

        foreach (DataRow col in dataSet.Tables[0].Rows)//获取全部选课的课程号
        {
            CourseId[count] = col["course"].ToString();
            count++;
        }
        if (CourseId.Contains(ID))
        {
            Response.Write("<script>alert('选课失败!已经选择该课~')</script>");
        }
        else
        {
            string sql2 = string.Format(@"insert into SelectCourse values('{0}','{1}')", Stu.ID1, ID);
            int    i    = SqlTools.Excute(sql2);
            if (i == 1)
            {
                Response.Write("<script>alert('选课成功~')</script>");
            }
            else
            {
                Response.Write("<script>alert('选课失败~')</script>");
            }
        }
    }
Пример #2
0
        public RespuestaBD EditarModuloApp(int idModulo, string nombre,
                                           int idSistema, string urlIcono, string urlDestino, string dbConexion, bool activo)
        {
            SqlTools    helpSql = new SqlTools(conexion);
            RespuestaBD resp    = helpSql.ExecuteSP("sps_MDB_seg_regedit_modulo",
                                                    new SqlParameter[] {
                new SqlParameter("@pi_id_modulo", idModulo),
                new SqlParameter("@pc_nombre_modulo", nombre),
                new SqlParameter("@pc_url_icono", urlIcono),
                new SqlParameter("@pc_url_destino", urlDestino),
                new SqlParameter("@pi_id_sistema", idSistema),
                new SqlParameter("@pl_estatus_modulo", activo),
                new SqlParameter("@pc_db_conexion", dbConexion),
            });

            if (resp.EXISTE_ERROR)
            {
                throw new Exception(resp.MENSAJE);
            }
            else
            {
                return(resp);
            }
        }
Пример #3
0
    //修改密码
    public static bool UpdatePwd(string id, string oldPwd, string newPwd, string type)
    {
        string sql = string.Format(@"select * from {0} where id='{1}'and password= '******'", type, id, oldPwd);


        idr = SqlTools.Read(sql);

        if (idr.Read())
        {
            string sql1 = string.Format(@"update {0} set password='******' where id='{2}'", type, newPwd, id);
            int    i    = SqlTools.Excute(sql1);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {         //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //关连接
        if (!idr.IsClosed)
        {
            idr.Close();
        }

        return(false);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Student        Stu            = (Student)Session["student"];
        SqlConnection  sqlConnection  = SqlTools.Connection();
        string         sql            = string.Format(@" select * from Score where student='{0}'", Stu.ID1);
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection);
        DataSet        dataSet        = new DataSet();

        GridViewShowScore.DataKeyNames = new string[] { "id" };
        sqlDataAdapter.Fill(dataSet);
        sqlConnection.Close();



        GridViewShowScore.DataSource = dataSet;
        GridViewShowScore.DataBind();
        for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)//将教师编号替换为教师姓名
        {
            string s      = dataSet.Tables[0].Rows[i]["Course"].ToString();
            Course course = (Course)dao.getBody(s, 4);
            GridViewShowScore.Rows[i].Cells[2].Text = course.Name; //循环修改列传值
            GridViewShowScore.Rows[i].Cells[3].Text = course.Score;
        }
    }
Пример #5
0
        public StartupData GetStartupData(int schoolYearId, int personId, int roleId, DateTime now)
        {
            var ps = new Dictionary <string, object>
            {
                { "@schoolYearId", schoolYearId },
                { "@personId", personId },
                { "@roleId", roleId },
                { "@now", now },
            };
            var res = new StartupData();
            IOrderedEnumerable <ScheduleItem> schedule;
            IList <ClassDetails>  allClasses;
            IList <GradingPeriod> gps;

            using (var reader = ExecuteStoredProcedureReader("spGetStartupData", ps))
            {
                res.AlphaGrades = reader.ReadList <AlphaGrade>();
                reader.NextResult();
                res.AlternateScores = reader.ReadList <AlternateScore>();
                reader.NextResult();
                res.MarkingPeriods = reader.ReadList <MarkingPeriod>();
                reader.NextResult();
                gps = reader.ReadList <GradingPeriod>();
                reader.NextResult();
                res.Person = PersonDataAccess.ReadPersonDetailsData(reader);
                reader.NextResult();
                allClasses = ClassDataAccess.ReadClasses(reader);
                reader.NextResult();
                res.Rooms = reader.ReadList <Room>();
                reader.NextResult();
                schedule = reader.ReadList <ScheduleItem>().OrderBy(x => x.PeriodOrder).ThenBy(x => x.ClassName);
                reader.NextResult();
                res.SchoolOption = reader.Read() ? reader.Read <SchoolOption>() : null;
                reader.NextResult();
                res.GradingComments = reader.ReadList <GradingComment>();
                reader.NextResult();
                res.AttendanceReasons = AttendanceReasonDataAccess.ReadGetAttendanceReasonResult(reader);
                reader.NextResult();
                reader.Read();
                res.UnshownNotificationsCount = SqlTools.ReadInt32(reader, "UnshownNotificationsCount");
                reader.NextResult();
                res.AlphaGradesForClasses = AlphaGradeDataAccess.ReadAlphaGradesForClasses(reader, allClasses.Select(x => x.Id).ToList());
                reader.NextResult();
                res.AlphaGradesForClassStandards = AlphaGradeDataAccess.ReadAlphaGradesForClasses(reader, allClasses.Select(x => x.Id).ToList());
                reader.NextResult();
                res.AlphaGradesForSchoolStandards = reader.ReadList <AlphaGradeDataAccess.SchoolAlphaGrade>();
            }
            res.GradingPeriod = gps.FirstOrDefault(x => x.StartDate <= now && x.EndDate >= now);
            if (res.GradingPeriod == null)
            {
                res.GradingPeriod = gps.OrderByDescending(x => x.StartDate).FirstOrDefault();
            }

            var todayClasses = new List <ClassDetails>();

            foreach (var classPeriod in schedule)
            {
                var c = allClasses.FirstOrDefault(x => x.Id == classPeriod.ClassId);
                if (c != null && todayClasses.All(x => x.Id != c.Id))
                {
                    todayClasses.Add(c);
                }
            }
            var otherClasses = allClasses.Where(x => todayClasses.All(y => y.Id != x.Id)).OrderBy(x => x.Name).ToList();

            res.Classes = todayClasses.Concat(otherClasses).ToList();


            //res.AlphaGradesForClasses = new Dictionary<int, IList<AlphaGrade>>();
            //res.AlphaGradesForClassStandards = new Dictionary<int, IList<AlphaGrade>>();

            //foreach (var classDetail in allClasses)
            //{
            //    res.AlphaGradesForClasses.Add(classDetail.Id, new List<AlphaGrade>());
            //    res.AlphaGradesForClassStandards.Add(classDetail.Id, new List<AlphaGrade>());
            //}
            //var agDic = res.AlphaGrades.ToDictionary(x => x.Id);
            //foreach (var classAlphaGrade in agForClasses)
            //{
            //    res.AlphaGradesForClasses[classAlphaGrade.ClassId].Add(agDic[classAlphaGrade.AlphaGradeId]);
            //}
            //foreach (var classAlphaGrade in agForClassStandards)
            //{
            //    res.AlphaGradesForClassStandards[classAlphaGrade.ClassId].Add(agDic[classAlphaGrade.AlphaGradeId]);
            //}
            res.AttendanceReasons = res.AttendanceReasons.Where(x => x.AttendanceLevelReasons.Count > 0).ToList();
            return(res);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获取要编辑课程
            string id = Request.QueryString["id"];
            Exam   ex = (Exam)dao.getBody(id, 7);

            TextBoxID.Text   = ex.ID;
            TextBoxDate.Text = ex.Date;



            SqlConnection sqlConnection = SqlTools.Connection();

            //获取所有课程名
            SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter("select * from course", sqlConnection);
            DataSet        dataSet1        = new DataSet();
            sqlDataAdapter1.Fill(dataSet1);

            //所有课程名绑定到课程号下拉框
            DropDownListCourse.DataSource    = dataSet1;
            DropDownListCourse.DataTextField = "name";
            DropDownListCourse.DataBind();
            //选中
            DropDownListCourse.SelectedValue = ex.Course;


            //获取所有教室
            SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter("select * from classroom", sqlConnection);
            DataSet        dataSet2        = new DataSet();
            sqlDataAdapter2.Fill(dataSet2);

            //所有教室绑定到地点下拉框
            DropDownListPlace.DataSource    = dataSet2;
            DropDownListPlace.DataTextField = "id";
            DropDownListPlace.DataBind();
            //选中
            DropDownListPlace.SelectedValue = ex.Place;

            //获取所有班级
            SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter("select * from classinfo", sqlConnection);
            DataSet        dataSet3        = new DataSet();
            sqlDataAdapter3.Fill(dataSet3);

            //所有班级绑定到班级下拉框
            DropDownListClass.DataSource    = dataSet3;
            DropDownListClass.DataTextField = "name";
            DropDownListClass.DataBind();
            //选中
            DropDownListClass.SelectedValue = ex.ClassInfo;


            //绑定考试时间
            string[] dayAndNode = ex.Time.Split(',');
            for (int i = 0; i < dayAndNode.Length; i++)
            {
                //第一个字符为1说明是星期一
                if (dayAndNode[i].Substring(0, 1).Equals("1"))
                {
                    RadioButtonMonday.Checked        = true;
                    DropDownListMonday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("2"))
                {
                    RadioButtonTuesday.Checked        = true;
                    DropDownListTuesday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("3"))
                {
                    RadioButtonWed.Checked = true;
                    DropDownListWednesday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("4"))
                {
                    RadioButtonThur.Checked            = true;
                    DropDownListThursday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("5"))
                {
                    RadioButtonFri.Checked           = true;
                    DropDownListFriday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
            }


            sqlConnection.Close();
        }

        //不能改课程号
        TextBoxID.Enabled = false;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["student"] != null)
        {
            DataTable dt = new DataTable(); //实例化一个空数据源
            for (int k = 0; k < 5; k++)     //要添加的行数,这里是5行
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
            }
            this.GridViewCourse.DataSource = dt;
            this.GridViewCourse.DataBind();//初始化表内数据
            GridViewCourse.Rows[0].Cells[0].Text = "第一节";
            GridViewCourse.Rows[1].Cells[0].Text = "第二节";
            GridViewCourse.Rows[2].Cells[0].Text = "第三节";
            GridViewCourse.Rows[3].Cells[0].Text = "第四节";
            GridViewCourse.Rows[4].Cells[0].Text = "第五节";
            Student Stu = (Student)Session["student"];
            LabelShowName.Text    = Stu.Name1;
            LabelShowDept.Text    = Stu.Dept1;
            LabelShowClass.Text   = Stu.Class1;
            LabelShowWelcome.Text = "学生端→欢迎你:" + Stu.Name1 + "(" + Stu.ID1 + ")";
            ImageHead.ImageUrl    = Stu.Photo1;
            SqlConnection  sqlConnection  = SqlTools.Connection();
            string         sql            = string.Format(@"select course  from SelectCourse where Student={0}", Stu.ID1);
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection);;
            DataSet        dataSet        = new DataSet();
            sqlDataAdapter.Fill(dataSet);
            sqlConnection.Close();
            String[] CourseId = new string[dataSet.Tables[0].Rows.Count];
            int      count    = 0;
            Course[] course   = new Course[dataSet.Tables[0].Rows.Count]; //存储所有课程信息
            foreach (DataRow col in dataSet.Tables[0].Rows)               //获取全部选课的课程号
            {
                course[count] = (Course)dao.getBody(col["course"].ToString(), 4);
                count++;
            }
            ClassRoom[] classRoom = new ClassRoom[count];
            for (int i = 0; i < count; i++)
            {
                classRoom[i] = (ClassRoom)dao.getBody(course[i].Place, 6);
            }
            string[,] ShowCourseInfo = new string[count, 5];
            string[,] ShowCoursetime = new string[count, 5];

            for (int j = 0; j < count; j++)
            {
                string[] dayAndNode = course[j].Time.Split(',');

                for (int i = 0; i < dayAndNode.Length; i++)
                {
                    if (dayAndNode[i].Substring(0, 1).Equals("1"))
                    {
                        ShowCourseInfo[j, i] = "星期一";
                        ShowCoursetime[j, i] = dayAndNode[i].Substring(2, 1);
                    }
                    else if (dayAndNode[i].Substring(0, 1).Equals("2"))
                    {
                        ShowCourseInfo[j, i] = "星期二";
                        ShowCoursetime[j, i] = dayAndNode[i].Substring(2, 1);
                    }
                    else if (dayAndNode[i].Substring(0, 1).Equals("3"))
                    {
                        ShowCourseInfo[j, i] = "星期三";
                        ShowCoursetime[j, i] = dayAndNode[i].Substring(2, 1);
                    }
                    else if (dayAndNode[i].Substring(0, 1).Equals("4"))
                    {
                        ShowCourseInfo[j, i] = "星期四";
                        ShowCoursetime[j, i] = dayAndNode[i].Substring(2, 1);
                    }
                    else if (dayAndNode[i].Substring(0, 1).Equals("5"))
                    {
                        ShowCourseInfo[j, i] = "星期五";
                        ShowCoursetime[j, i] = dayAndNode[i].Substring(2, 1);
                    }
                }
            }


            for (int i = 0; i < count; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    switch (ShowCourseInfo[i, j])
                    {
                    case "星期一": { GridViewCourse.Rows[int.Parse(ShowCoursetime[i, j]) - 1].Cells[1].Text += course[i].Name + "<br>" + classRoom[i].Number + "<br>"; } break;

                    case "星期二": { GridViewCourse.Rows[int.Parse(ShowCoursetime[i, j]) - 1].Cells[2].Text += course[i].Name + "<br>" + classRoom[i].Number + "<br>"; } break;

                    case "星期三": { GridViewCourse.Rows[int.Parse(ShowCoursetime[i, j]) - 1].Cells[3].Text += course[i].Name + "<br>" + classRoom[i].Number + "<br>"; } break;

                    case "星期四": { GridViewCourse.Rows[int.Parse(ShowCoursetime[i, j]) - 1].Cells[4].Text += course[i].Name + "<br>" + classRoom[i].Number + "<br>"; } break;

                    case "星期五": { GridViewCourse.Rows[int.Parse(ShowCoursetime[i, j]) - 1].Cells[5].Text += course[i].Name + "<br>" + classRoom[i].Number + "<br>"; } break;

                    default: break;
                    }
                }
            }
        }
        else
        {
            Response.Write(" <script language=javascript>alert('登录过期,请重新登陆');window.window.location.href='./../LoginTest.aspx';</script> ");
        }
    }
Пример #8
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            context.Response.ContentType = "text/plain";
            if (this.context.Request.HttpMethod == "POST")
            {
                //如果是POST请求,则响应请求内容
                // ResponseMsg(string OPENID,string first,string keyword1,string keyword2,string keyword3,string remark)
                try
                {
                    if (context.Request.Params["msg"] != null)//座位系统自身消息
                    {
                        string   msg       = AESAlgorithm.AESDecrypt(context.Request.Params["msg"]);
                        string[] kv        = msg.Split('&');
                        string   SchoolNum = kv[0].Split('=')[1];
                        string   StudentNo = kv[1].Split('=')[1];
                        string   MsgType   = kv[2].Split('=')[1];
                        string   Room      = kv[3].Split('=')[1];
                        string   SeatNo    = kv[4].Split('=')[1];
                        string   AddTime   = kv[5].Split('=')[1];
                        string   EndTime   = kv[6].Split('=')[1];
                        string   Msg       = kv[8].Split('=')[1];
                        string   OPENID    = SqlTools.GetOpenId(StudentNo);
                        string   first     = "您的座位状态发生改变"; //context.Request.Params["first"].ToString();
                        string   keyword1  = Room;         //context.Request.Params["keyword1"].ToString();
                        string   keyword2  = SeatNo;       //context.Request.Params["keyword2"].ToString();
                        string   keyword3  = AddTime;      //context.Request.Params["keyword3"].ToString();
                        string   remark    = Msg;          //context.Request.Params["remark"].ToString();
                        SeatManage.SeatManageComm.WriteLog.Write("OPENID:" + OPENID);
                        ResponseMsg(OPENID, first, keyword1, keyword2, keyword3, remark);
                    }
                    else if (context.Request.Params["IsOutMsg"] != null)                 //座位系统系统外部消息
                    {
                        string msgType = context.Request.Params["MsgType"].ToString();   //消息类型
                        // string msgReturnURL = context.Request.Params["MsgReturnURL"].ToString();//点击消息跳转url
                        string toReader = context.Request.Params["ToReader"].ToString(); //发送到的读者学工号,多个读者用逗号隔开
                        switch (msgType)
                        {
                        case "OverdueNotice":    //图书馆超期催还通知
                            string OverdueNoticefirst    = context.Request.Params["Content"].Trim();
                            string OverdueNoticekeyword1 = context.Request.Params["StudentName"].Trim();
                            string OverdueNoticekeyword2 = context.Request.Params["BookName"].Trim();
                            string OverdueNoticekeyword3 = context.Request.Params["BarCode"].Trim();
                            string OverdueNoticekeyword4 = context.Request.Params["GiveBackDate"].Trim();
                            string OverdueNoticekeyword5 = context.Request.Params["OverdueDates"].Trim();
                            string OverdueNoticeremark   = context.Request.Params["Remark"].Trim();
                            ResponseOverdueNoticeMsg(toReader, OverdueNoticefirst, OverdueNoticekeyword1, OverdueNoticekeyword2, OverdueNoticekeyword3, OverdueNoticekeyword4, OverdueNoticekeyword5, OverdueNoticeremark);
                            break;

                        case "GiveBackBookNotice":    //还书通知
                            string GiveBackBookNoticefirst  = context.Request.Params["Content"].Trim();
                            string GiveBackBookNoticename   = context.Request.Params["StudentName"].Trim();
                            string GiveBackBookNoticedate   = context.Request.Params["GiveBackDate"].Trim();
                            string GiveBackBookNoticeremark = context.Request.Params["Remark"].Trim();
                            ResponseGiveBackBookNoticeMsg(toReader, GiveBackBookNoticefirst, GiveBackBookNoticename, GiveBackBookNoticedate, GiveBackBookNoticeremark);
                            break;

                        case "BooksToLibraryNotice":    //委托图书到馆通知
                            string BooksToLibraryNoticefirst    = context.Request.Params["Content"].Trim();
                            string BooksToLibraryNoticekeyword1 = context.Request.Params["BookName"].Trim();
                            string BooksToLibraryNoticekeyword2 = context.Request.Params["ArriveDate"].Trim();
                            string BooksToLibraryNoticeremark   = context.Request.Params["Remark"].Trim();
                            ResponseBooksToLibraryNoticeMsg(toReader, BooksToLibraryNoticefirst, BooksToLibraryNoticekeyword1, BooksToLibraryNoticekeyword2, BooksToLibraryNoticeremark);
                            break;

                        case "GiveBackBookSucceedNotice":    //成功还书通知
                            string GiveBackBookSucceedNoticefirst    = context.Request.Params["Content"].Trim();
                            string GiveBackBookSucceedNoticekeyword1 = context.Request.Params["BookName"].Trim();
                            string GiveBackBookSucceedNoticekeyword2 = context.Request.Params["ReturnDate"].Trim();
                            string GiveBackBookSucceedNoticekeyword3 = context.Request.Params["ShouldReturnDate"].Trim();
                            string GiveBackBookSucceedNoticekeyword4 = context.Request.Params["BorrowAddress"].Trim();
                            string GiveBackBookSucceedNoticeremark   = context.Request.Params["Remark"].Trim();
                            ResponseGiveBackBookSucceedNoticeMsg(toReader, GiveBackBookSucceedNoticefirst, GiveBackBookSucceedNoticekeyword1,
                                                                 GiveBackBookSucceedNoticekeyword2, GiveBackBookSucceedNoticekeyword3, GiveBackBookSucceedNoticekeyword4, GiveBackBookSucceedNoticeremark);
                            break;

                        case "ActivityToBeginningNotice":    //活动即将开始提醒
                            string ActivityToBeginningNoticefirst    = context.Request.Params["Content"].Trim();
                            string ActivityToBeginningNoticekeyword1 = context.Request.Params["StudentName"].Trim();
                            string ActivityToBeginningNoticekeyword2 = context.Request.Params["Organizer"].Trim();
                            string ActivityToBeginningNoticekeyword3 = context.Request.Params["ActivityTime"].Trim();
                            string ActivityToBeginningNoticekeyword4 = context.Request.Params["ActivityAddress"].Trim();
                            string ActivityToBeginningNoticeremark   = context.Request.Params["Remark"].Trim();
                            ResponseActivityToBeginningNoticeMsg(toReader, ActivityToBeginningNoticefirst, ActivityToBeginningNoticekeyword1, ActivityToBeginningNoticekeyword2,
                                                                 ActivityToBeginningNoticekeyword3, ActivityToBeginningNoticekeyword4, ActivityToBeginningNoticeremark);
                            break;

                        case "BorrowBooksSucceedNotice":    //图书馆借书成功通知
                            string BorrowBooksSucceedNoticefirst    = context.Request.Params["Content"].Trim();
                            string BorrowBooksSucceedNoticekeyword1 = context.Request.Params["BookName"].Trim();
                            string BorrowBooksSucceedNoticekeyword2 = context.Request.Params["BorrowDate"].Trim();
                            string BorrowBooksSucceedNoticekeyword3 = context.Request.Params["GiveBackDate"].Trim();
                            string BorrowBooksSucceedNoticekeyword4 = context.Request.Params["BorrowAddress"].Trim();
                            string BorrowBooksSucceedNoticeremark   = context.Request.Params["Remark"].Trim();
                            ResponseBorrowBooksSucceedNoticeMsg(toReader, BorrowBooksSucceedNoticefirst, BorrowBooksSucceedNoticekeyword1,
                                                                BorrowBooksSucceedNoticekeyword2, BorrowBooksSucceedNoticekeyword3, BorrowBooksSucceedNoticekeyword4, BorrowBooksSucceedNoticeremark);
                            break;

                        default:
                            SeatManage.SeatManageComm.WriteLog.Write("未知消息类型:" + msgType + ",请检查请求参数");
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    SeatManage.SeatManageComm.WriteLog.Write("5:Exception ex" + ex);
                    // throw;
                }
            }
            else if (this.context.Request.HttpMethod == "GET")//如果是Get请求,则是接入验证,返回随机字符串。
            {
                signature = context.Request.Params["signature"];
                timestamp = context.Request.Params["timestamp"];
                nonce     = context.Request.Params["nonce"];
                echostr   = context.Request.Params["echostr"];

                if (!service.CheckSignature(signature, timestamp, nonce))//验证请求是否微信发过来的。
                {
                    this.context.Response.End();
                }
                context.Response.Write(echostr);
            }
        }
Пример #9
0
        public static void Seed(IUnitOfWork context)
        {
            // UnitOfWork.IUnitOfWork context = IoC.ApplicationDbContext; //1 способ - получить из IoC

            //если нет статусов абонемента
            if (!context.AbonementStatuses.GetAll().Any())
            {
                context.AbonementStatuses.AddRange(new List <AbonementStatus>()
                {
                    new AbonementStatus {
                        Name = "Активен"
                    },
                    new AbonementStatus {
                        Name = "Не активен"
                    },
                    new AbonementStatus {
                        Name = "Заморожен"
                    }
                });
            }

            //если нет типа абонемента
            if (!context.AbonementTypes.GetAll().Any())
            {
                context.AbonementTypes.AddRange(new List <AbonementType>()
                {
                    new AbonementType {
                        Name = "Утренний"
                    },
                    new AbonementType {
                        Name = "Вечер"
                    },
                    new AbonementType()
                    {
                        Name = "Карта полного дня"
                    }
                });
            }

            //если нет данных об уровне тренировок
            if (!context.TrainingLevels.GetAll().Any())
            {
                context.TrainingLevels.AddRange(new List <TrainingLevel>()
                {
                    new TrainingLevel()
                    {
                        Name = "Для всех уровней подготовки"
                    },
                    new TrainingLevel()
                    {
                        Name = "Низкая интенсивность"
                    },
                    new TrainingLevel()
                    {
                        Name = "Высокая интенсивность"
                    }
                });
            }

            //если нет данных об типе программы
            if (!context.ProgramTypes.GetAll().Any())
            {
                context.ProgramTypes.AddRange(new List <ProgramType>()
                {
                    new ProgramType()
                    {
                        Name = "Специальные программы"
                    },
                    new ProgramType()
                    {
                        Name = "Силовой и функциональный тренинг"
                    },
                    new ProgramType()
                    {
                        Name = "Mind&Body (Мягкий фитнес)"
                    },
                    new ProgramType()
                    {
                        Name = "Кардио тренинг"
                    },
                });
            }

            //если нет данных о залах, создадим
            if (!context.Gyms.GetAll().Any())
            {
                context.Gyms.AddRange(new List <Gym>()
                {
                    new Gym()
                    {
                        Name = "Большой зал"
                    },
                    new Gym()
                    {
                        Name = "Тренажерный зал"
                    },
                    new Gym()
                    {
                        Name = "Зал персональных занятий"
                    },
                });
            }

            //если нет данных о тренировке
            if (!context.TrainingDatas.GetAll().Any())
            {
                context.TrainingDatas.AddRange(new List <TrainingData>()
                {
                    new TrainingData()
                    {
                        TrainingName = "Hatha Yoga", TrainingDescription =
                            "Занятие, на котором помимо асан и пранаямы делается акцент на "
                            + "концентрацию внимания и медитацию. Урок рекомендован для всех уровней подготовки",
                        Level         = context.TrainingLevels.Get(2),
                        ProgramType   = context.ProgramTypes.Get(2),
                        IsNewTraining = true
                    },
                    new PayTraining()
                    {
                        TrainingName = "TRX", TrainingDescription =
                            "TRX - тренировка мышц всего тела с помощью уникального оборудования - " +
                            "TRX-петель. Это тренировка, которая позволяет не только развивать все мышечные группы, " +
                            "укреплять связки и сухожилия, но и развивать гибкость, ловкость, выносливость и многое " +
                            "другое. Данная тренировка имеет еще одно важное достоинство - эффективное развитие мышц так " +
                            "называемого кора(мышц-стабилизаторов). Упражнения подходят для всех возрастных групп, " +
                            "для мужчин и женщин, для лиц с отклонениями в состоянии здоровья, так как в этой тренировке " +
                            "нет никакой осевой (вертикальной) нагрузки на позвоночник",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(1),
                        PlacesCount = 10,
                    },
                    new TrainingData()
                    {
                        TrainingName = "New Body", TrainingDescription =
                            "NEW BODY (55 мин) («Новое тело») - силовой урок, направленный на тренировку всех " +
                            "групп мышц. Специально подобранные комплексы упражнений помогут скорректировать проблемные зоны, " +
                            "независимо от того, каким телосложением вы обладаете. Урок рекомендован как для среднего так и для " +
                            "продвинутого уровня подготовки",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "ABS and Stretch", TrainingDescription =
                            "Урок, направленный на развитие гибкости, с использованием специальных упражнений на растягивание. " +
                            "Увеличивает подвижность суставов, эластичность связок, дает общее расслабление и релаксацию.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Pilates", TrainingDescription =
                            "Урок направлен на укрепление мышц-стабилизаторов, упражнгения пилатес " +
                            "способствуют снятию напряжению с позвоночника, восстановлению эластичности " +
                            "связочного аппарата и мышц. Урок рекомендован для всех уровней подготовки",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(3),
                        Ispopular   = true
                    },
                    new TrainingData()
                    {
                        TrainingName = "Здоровая спина", TrainingDescription = "Улучшит функционирование внутренних органов " +
                                                                               "и систем организма, укрепит мышечно-связочный аппарат, " +
                                                                               "скорректирует мышечный дисбаланс, будет способствовать развитию" +
                                                                               " гибкости позвоночника и тела в целом, позволит выработать правильную осанку." +
                                                                               " Урок рекомендован для всех уровней подготовки.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(1),
                        Ispopular   = true
                    },
                    new TrainingData()
                    {
                        TrainingName = "STEP ABS", TrainingDescription = "Step+ABS – это отличная комбинированная кардио тренировка, " +
                                                                         "сочетающая нагрузку на мышцы брюшного пресса и занятия на степ-платформе.",
                        Level       = context.TrainingLevels.Get(3),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "#запускягодицы", TrainingDescription = "Функциональная тренировка, направленная на проработку ягодичных мышц " +
                                                                               "и мышц брюшного пресса. Тренировка состоит из нескольких блоков, с использованием" +
                                                                               " различного оборудования или выполнения упражнений с собственным весом.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Upper Body", TrainingDescription = "(англ. «upper» – верх и «body» – тело) —силовой урок, направленный на проработку мышечных " +
                                                                           "групп верхней части тела: рук, плечевого пояса, спины и брюшного пресса. При этом могут использоваться " +
                                                                           "дополнительные отягощения: гантели, бодибары, степ платформы и т.д Тренировка подходит для любого " +
                                                                           "уровня подготовленности.Главная задача тренировки Upper Body. – это подтянуть живот, сделав мышцы пресса " +
                                                                           "крепкими, а талию узкой, привести мышцы рук в тонус, а также укрепить мышцы груди и спины, что важно для " +
                                                                           "красивой осанки.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Stretch", TrainingDescription = "Урок, направленный на развитие гибкости, с использованием специальных упражнений на растягивание. " +
                                                                        "Увеличивает подвижность суставов, эластичность связок, даёт общее расслабление и релаксацию.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(3)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Callanetics", TrainingDescription = "Уникальная система упражнений, возбуждающая активность глубоко расположенных мышечных групп," +
                                                                            " способствующая оздоровлению организма, снижению веса и уменьшению объемов тела. В статичном режиме " +
                                                                            "тренируются все мышечные группы и связочный аппарат.",
                        Level       = context.TrainingLevels.Get(1),
                        ProgramType = context.ProgramTypes.Get(3)
                    },
                    new TrainingData()
                    {
                        TrainingName = "STEP INTERVAL", TrainingDescription = "Step interval - это аэробно-силовой фитнес, сочетающий чередование упражнений " +
                                                                              "(прыжков, приседаний, отжиманий и т.д.) с базовыми шагами на степ-платформе. ",
                        Level       = context.TrainingLevels.Get(3),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Soft Mix", TrainingDescription = "Фитнес микс – это синтез различных видов фитнеса, которые комбинированно применяются" +
                                                                         " в условиях одной тренировки либо чередуются от занятия к занятию.",
                        Level       = context.TrainingLevels.Get(2),
                        ProgramType = context.ProgramTypes.Get(3)
                    },
                    new TrainingData()
                    {
                        TrainingName = "PUMP", TrainingDescription = "Это целостная система низко-ударной тренировки с использованием облегченной штанги." +
                                                                     " Благодаря PUMP прорабатываются, укрепляются и приводятся в тонус все мышцы тела. " +
                                                                     "Тренировка характеризуется особым агрессивным драйвом и приносит гораздо больше результатов " +
                                                                     "и удовольствия, чем традиционное монотонное поднятие тяжестей. Она подходит как для мужчин, " +
                                                                     "так и для женщин всех возрастов. Для продвинутого уровня подготовки.",
                        Level       = context.TrainingLevels.Get(3),
                        ProgramType = context.ProgramTypes.Get(2)
                    },
                    new TrainingData()
                    {
                        TrainingName = "Тabata", TrainingDescription = "Интервальная тренировка, которая включает в себя 10 блоков по 4 минуты. " +
                                                                       "Табата – это сочетание кардио и силовой нагрузок. Тренирует выносливость " +
                                                                       "как ни одна классическая тренировка. В короткий промежуток времени выполняя " +
                                                                       "упражнения происходит максимально быстрое жиросжигание. Упражнения различные по " +
                                                                       "степени сложности. Урок подходит для людей с разным уровнем подготовки.",
                        Level       = context.TrainingLevels.Get(3),
                        ProgramType = context.ProgramTypes.Get(4)
                    },
                    new PayTraining()
                    {
                        TrainingName = "Шпагат", TrainingDescription = "Занятие включает в себя комплекс упражнений, направленных на улучшение эластичности " +
                                                                       "мышц, подвижность суставов, что позволит вам легко садиться на продольный и поперечный " +
                                                                       "шпагат",
                        Level       = context.TrainingLevels.Get(3),
                        ProgramType = context.ProgramTypes.Get(4),
                        PlacesCount = 5
                    },
                    new TrainingData()
                    {
                        TrainingName = "#Superпресс", TrainingDescription = "Занятие направлено на укрепление брюшного пресса и спины. Сочетает в себе разминку, " +
                                                                            "разогревающую позвоночник, суставы и непосредственно мышцы живота и спины , и комплекс упражнений, позволяющий быстро " +
                                                                            "и эффективно проработать все мышцы брюшного пресса и спины.",
                        Level       = context.TrainingLevels.Get(2),
                        ProgramType = context.ProgramTypes.Get(3)
                    }
                });
            }

            //если нет тренировки в расписании
            if (!context.Trainings.GetAll().Any())
            {
                context.Trainings.AddRange(new List <Training>()
                {
                    #region Тренировки на первый день

                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Здоровая спина")
                    },
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 0, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "TRX"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 0
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "STEP ABS")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 11, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "#запускягодицы")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 15, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Upper Body")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 16, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Stretch")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 17, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Callanetics")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "STEP INTERVAL")
                    },
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 30, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "TRX"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 1
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(2),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Hatha Yoga")
                    },
                    #endregion

                    #region Тренировки на второй день
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 9, 0, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "TRX"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 2
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 9, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Здоровая спина")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 10, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "#Superпресс")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 11, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "#запускягодицы")
                    },
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 11, 0, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "TRX"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 3
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 14, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Tabata")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 15, 0, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Callanetics")
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 17, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "ABS and Stretch")
                    },
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 17, 30, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "Шпагат"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 3
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 18, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(1),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "#запускягодицы")
                    },
                    new Training()
                    {
                        StartTime       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 18, 30, 0),
                        Minutes         = 55,
                        Gym             = context.Gyms.Get(2),
                        TrainingData    = context.TrainingDatas.Find(tr => tr.TrainingName == "TRX"),
                        PlacesCount     = ((PayTraining)context.TrainingDatas.Find(tr => tr.TrainingName == "TRX")).PlacesCount,
                        BusyPlacesCount = 4
                    },
                    new Training()
                    {
                        StartTime    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 19, 30, 0),
                        Minutes      = 55,
                        Gym          = context.Gyms.Get(2),
                        TrainingData = context.TrainingDatas.Find(tr => tr.TrainingName == "Hatha Yoga")
                    }
                    #endregion
                });
            }

            ////если нет таблицы TrainingDataTrainings
            //if (!context.TrainingDataTrainings.GetAll().Any())
            //{
            //    context.Trainings.Get(1).TrainingDataTrainings.Add(new TrainingDataTraining() { TrainingDataId = context.TrainingDatas.Get(1).Id, TrainingId = context.Trainings.Get(1).Id });
            //    context.Trainings.Get(1).TrainingDataTrainings.Add(new TrainingDataTraining() { TrainingDataId = context.TrainingDatas.Get(2).Id, TrainingId = context.Trainings.Get(2).Id });
            //    context.Trainings.Get(1).TrainingDataTrainings.Add(new TrainingDataTraining() { TrainingDataId = context.TrainingDatas.Get(3).Id, TrainingId = context.Trainings.Get(3).Id });
            //    //создаем замененную тернировку
            //    context.Trainings.Get(1).ReplcedTrainings.Add(new ReplcedTraining() { TrainingDataId = context.TrainingDatas.Get(4).Id, TrainingId = context.Trainings.Get(4).Id });
            //}

            //Создадим клиента
            if (!context.Clients.GetAll().Any())
            {
                context.Clients.AddRange(new List <Client>()
                {
                    new Client()
                    {
                        Family                      = "Куликов", Name = "Антон", LastName = "Юрьевич",
                        DateOfBirdth                = DateTime.Parse("24.03.2000"),
                        Photo                       = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "kulikov.png", "\\InitializeData\\HumanPhoto\\"),
                        AbonementStatus             = context.AbonementStatuses.Get(1),
                        AbonementType               = context.AbonementTypes.Get(3),
                        AbonementDateOfRegistration = DateTime.Now,
                        AbonementNumber             = AbonementGenerator.CreateNumberSubscription(context),
                        PasportData                 = $"2409 N460870 ОУФМС РОССИИ {DateTime.Parse("04.05.2012")}",
                        PasswordHash                = "2705",
                        AbonementStatusId           = context.AbonementStatuses.Get(1).Id,
                        AbonementActionTime         = DateTime.Parse("30.05.2019"),
                        AbonementDateOfActivate     = DateTime.Now
                    }
                });
            }

            //добавим тренировки клиенту по предварительной записи //пока опустим
            //if (!context.TrainingClients.GetAll().Any())
            //{
            //    context.Clients.Get(1).TrainingClients.Add(new TrainingClient() { ClientId = context.Clients.Get(1).Id, TrainingId = context.Trainings.Get(2).Id });
            //    context.Complete(); //сохраняем изменения
            //}

            //проинициализируем роли пользователей системы
            if (!context.Roles.GetAll().Any())
            {
                context.Roles.AddRange(new List <Role>
                {
                    new Role()
                    {
                        Description = "Инструктор групповых программ"
                    },
                    new Role()
                    {
                        Description = "Администратор"
                    },
                    new Role()
                    {
                        Description = "Клиент"
                    }
                });
            }

            //добавим тренеров
            if (!context.Employees.GetAll().Any())
            {
                context.Employees.AddRange(new List <Employee>()
                {
                    new Employee()
                    {
                        Name  = "Галина", Family = "Елизарова", LastName = "Семеновна", Login = "******", PasswordHash = "hash1", DateOfBirdth = DateTime.Parse("10.05.1978"), Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "elizarova-galina.jpg"),
                        Desc  = "К йоге я пришла более 10 лет назад. И как мне казалось случайно. " +
                                "Больше всего, изначально, меня зацепило то, что мой преподаватель " +
                                "постоянно повторял:«Йога не для всех, она сама выбирает, кто в ней " +
                                "останется, а кто уйдет»! Я говорила себе - так, что значит, йога меня выберет " +
                                "или нет,-захочу и буду заниматься. И каждый раз, когда мне было лень идти на практику " +
                                "я вспоминала именно эти слова и то, что я сама, вроде как, решила заниматься йогой," +
                                "собиралась и шла практиковать"
                    },
                    new Employee()
                    {
                        Name  = "Анастасия", Family = "Молькова", LastName = "Сергеевна", DateOfBirdth = DateTime.Parse("10.01.1979"), Login = "******", PasswordHash = "ana1", Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "Molkova Anastasija.jpg"),
                        Desc  = "Инструктор групповых порграмм. Персональный тренер зала ГП. Составление тренировочных программ и " +
                                "стиля питания для корректировки фигуры. Сертифицированный тренер TRX."
                    },
                    new Employee()
                    {
                        Name  = "Елена", Family = "Куликова", LastName = "Алексеевна", Login = "******", PasswordHash = "ele1", DateOfBirdth = DateTime.Parse("10.03.1965"), Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "kulikova_elena2.jpg"),
                        Desc  = "Инструктор групповых порграмм. Составление программ по снижению веса и коррекции фигуры, повышение " +
                                "выносливости,развитие гибкости. Силовые уроки, степ-аэробика, каланетика в зале."
                    },
                    new Employee()
                    {
                        Name  = "Полина", Family = "Соловьева", LastName = "Николаева", Login = "******", PasswordHash = "pol1", DateOfBirdth = DateTime.Parse("10.04.1985"), Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "Soloveva Polina.jpg"),
                        Desc  = "Инструктор групповых порграмм. Уроки мягкого фитнеса в зале групповых программ. Составление индивидуальных " +
                                "программ по развитию гибкости мышц, связок и позвоночника. Тренер тренажерного зала."
                    },
                    new Employee()
                    {
                        Name  = "Ершова", Family = "Анастасия", LastName = "Олеговна", Login = "******", PasswordHash = "an1", DateOfBirdth = DateTime.Parse("14.02.1987"), Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "erchova anastasya.jpg"),
                        Desc  = "Инструктор групповых порграмм. Персональный тренер. Член национального союза фитнеса."
                    },

                    new Employee()
                    {
                        Name  = "Ольга", Family = "Осипова", LastName = "Антоновна", Login = "******", DateOfBirdth = DateTime.Parse("14.02.1980"), PasswordHash = "ol1", Role = context.Roles.Get(1),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "Osipova Olga.jpg"),
                        Desc  = "Мастер-тренер тренажерного зала. Составление программ по снижению веса и коррекции фигуры; " +
                                "танцевальные программы, мягкий фитнес; силовые программы в зале групповых программ. Сертифицированый инструктор " +
                                "по пилатесу,функциональному тренингу, силовым программам и зумбе"
                    },
                    new Employee()
                    {
                        Name  = "Ольга", Family = "Винник", LastName = "Сергеевна", Login = "******", PasswordHash = "ov1", Role = context.Roles.Get(1), DateOfBirdth = DateTime.Parse("14.02.1980"),
                        Photo = SqlTools.ConvertImageToByteArray(SqlTools.GetPath(), "vinnik_2.jpg"),
                        Desc  = "Победитель шейпинг-конкурса «Пигмалион и Галатея« 2014 год (проводится под эгидой Федерации шейпинга среди клубов с лицензированным шейпигом) в номинации «Шейпинг-модель»."
                    }
                });
            }

            //добавим тренера к тренировке
            if (!context.CoachesTrainings.GetAll().Any())
            {
                #region Тренировки на первый день
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(1).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(2).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(3).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(4).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(4).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(5).Id, CoachId = context.Employees.Get(4).Id
                });
                context.Employees.Get(4).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(6).Id, CoachId = context.Employees.Get(4).Id
                });
                context.Employees.Get(4).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(7).Id, CoachId = context.Employees.Get(4).Id
                });
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(8).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(9).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(1).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(10).Id, CoachId = context.Employees.Get(1).Id
                });
                #endregion

                #region Тренировки на второй день
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(11).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(12).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(13).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(14).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(15).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(5).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(16).Id, CoachId = context.Employees.Get(5).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(17).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(4).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(18).Id, CoachId = context.Employees.Get(4).Id
                });
                context.Employees.Get(6).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(19).Id, CoachId = context.Employees.Get(6).Id
                });
                context.Employees.Get(2).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(20).Id, CoachId = context.Employees.Get(2).Id
                });
                context.Employees.Get(1).CoachTrainings.Add(new CoachTraining()
                {
                    TrainingId = context.Trainings.Get(21).Id, CoachId = context.Employees.Get(1).Id
                });
                #endregion
            }

            context.Complete(); //сохраняем изменения

            ////https://www.youtube.com/watch?v=oDz7ku6fRkg
        }
Пример #10
0
    //通过id查询返回个体
    public static object getBody(String id, int type)
    {
        //学生
        if (type == 1)
        {
            string sql = string.Format(@"select * from Student where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Student s = new Student(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6), idr.GetString(7), idr.GetString(8), idr.GetString(9), idr.GetString(10), idr.GetString(11));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(s);
            }
        }
        //老师
        else if (type == 2)
        {
            string sql = string.Format(@"select * from Teacher where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Teacher t = new Teacher(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6), idr.GetString(7), idr.GetString(8), idr.GetString(9), idr.GetString(10), idr.GetString(11));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(t);
            }
        }
        //管理员
        else if (type == 3)
        {
            string sql = string.Format(@"select * from Admin where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Admin t = new Admin(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(t);
            }
        }
        //返回课程
        else if (type == 4)
        {
            string sql = string.Format(@"select * from course where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Course t = new Course(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6), idr.GetString(7));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(t);
            }
        }
        //返回成绩
        else if (type == 5)
        {
            string sql = string.Format(@"select * from score where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Score sc = new Score(idr.GetInt32(0) + "", idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(sc);
            }
        }
        //返回教室
        else if (type == 6)
        {
            string sql = string.Format(@"select * from Classroom where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                ClassRoom sc = new ClassRoom(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(sc);
            }
        }
        //返回考试
        else if (type == 7)
        {
            string sql = string.Format(@"select * from exam where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Exam ex = new Exam(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(ex);
            }
        }
        //返回系别
        else if (type == 8)
        {
            string sql = string.Format(@"select * from dept where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Dept de = new Dept(idr.GetString(0), idr.GetString(1), idr.GetString(2));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(de);
            }
        }
        else if (type == 9)
        {
            string sql = string.Format(@"select * from Classinfo where id='{0}'", id);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                ClassInfo classInfo = new ClassInfo(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(classInfo);
            }
        }
        //关连接
        if (!idr.IsClosed)
        {
            idr.Close();
        }
        return(null);
    }
Пример #11
0
        /// <summary>
        /// Метод переопределяется с целью фактического добавления данных в конекст для заполнения начальными значениями
        /// </summary>
        /// <param name="context"></param>
        protected override void Seed(DataBaseFcContext context)
        {
            base.Seed(context);

            if (context == null)
            {
                return;
            }

            #region Добавление справочника должностей с зарплатами
            ObservableCollection <EmployeeRole> roles = new ObservableCollection <EmployeeRole>
            {
                new EmployeeRole {
                    EmployeeRoleName = "Администратор", EmployeeSalaryValue = 27000.0m
                },
                new EmployeeRole {
                    EmployeeRoleName = "Фитнес-инструктор", EmployeeSalaryValue = 30000.0m
                },
                new EmployeeRole {
                    EmployeeRoleName = "Менеджер", EmployeeSalaryValue = 25000.0m
                },
                new EmployeeRole {
                    EmployeeRoleName = "Руководитель", EmployeeSalaryValue = 50000.0m
                }
            };
            context.EmployeeRoles.AddRange(roles);
            #endregion

            #region Добавление статусов работников фитнес-клуба
            ObservableCollection <EmployeeWorkingStatus> employeeWorkingStatuses =
                new ObservableCollection <EmployeeWorkingStatus>
            {
                new EmployeeWorkingStatus {
                    EmployeeWorkingStatusName = "На работе"
                },
                new EmployeeWorkingStatus {
                    EmployeeWorkingStatusName = "На больничном"
                },
                new EmployeeWorkingStatus {
                    EmployeeWorkingStatusName = "В отпуске"
                }
            };
            context.EmployeeWorkingStatuses.AddRange(employeeWorkingStatuses);
            #endregion

            #region Добавление работников фитнес-клуба
            ObservableCollection <Employee> employees = new ObservableCollection <Employee>
            {
                new Employee {
                    HumanFirstName        = "Антон",
                    HumanLastName         = "Юрьевич",
                    HumanFamilyName       = "Куликов",
                    HumanDateOfBirdth     = new DateTime(1989, 05, 24),
                    HumanAdress           = "ул. Мальцева, д.5, кв.10",
                    HumanPhoneNumber      = "8-920-345-57-57",
                    EmployeeLoginName     = "IvanovWorker",
                    EmployeePasswordHash  = "be50825e1851dfd342ddd6fce6cbd7fa",
                    HumanPhoto            = SqlTools.ConvertImageToByteArray(@"Z:\Projects\FitnessClub\FitnesClubMWWM\UI\Ui.Desktop\Photos\men.png"),
                    HumanMail             = "*****@*****.**",
                    EmployeeWorkingStatus = employeeWorkingStatuses[(int)EWorkingStaus.EWorking],
                    EmployeeRole          = roles[2]
                },
                new Employee {
                    HumanFirstName        = "Петров",
                    HumanLastName         = "Петр",
                    HumanFamilyName       = "Петрович",
                    HumanDateOfBirdth     = new DateTime(1980, 01, 21),
                    HumanAdress           = "ул. Пушкина, д.15, кв.13",
                    HumanPhoneNumber      = "8-915-345-52-57",
                    EmployeeLoginName     = "PetrovWorker",
                    EmployeePasswordHash  = "ace8eca0be0bead807aec0c2d18a77dc",
                    HumanMail             = "*****@*****.**",
                    EmployeeWorkingStatus = employeeWorkingStatuses[(int)EWorkingStaus.ESick],
                    EmployeeRole          = roles[2]
                },
                new Employee {
                    HumanFirstName        = "Сергеев",
                    HumanLastName         = "Сергей",
                    HumanFamilyName       = "Сергеевич",
                    HumanDateOfBirdth     = new DateTime(1970, 10, 21),
                    HumanAdress           = "ул. Пушкина, д.5, кв.1",
                    HumanPhoneNumber      = "8-915-435-52-51",
                    EmployeeLoginName     = "SergeevWorker",
                    EmployeePasswordHash  = "ecb76c003e29175d00c24ea72334a91f",
                    HumanMail             = "*****@*****.**",
                    EmployeeWorkingStatus = employeeWorkingStatuses[(int)EWorkingStaus.EVacation],
                    EmployeeRole          = roles[2]
                },
            };
            context.Employees.AddRange(employees);
            #endregion


            #region Добавление новой услуги
            ObservableCollection <Service> services = new ObservableCollection <Service>()
            {
                new Service {
                    ServiceName = "Групповое занятие в фитнес-зале"
                },
                new Service {
                    ServiceName = "Йога"
                },
                new Service {
                    ServiceName = "Занятие в тренажерном зале"
                },
            };
            context.Services.AddRange(services);
            #endregion

            #region Добавление списка видов тренировок и услуг (прайс - лист)
            ObservableCollection <PriceTrainingList> trainingsLists = new ObservableCollection <PriceTrainingList>()
            {
                new PriceTrainingList {
                    TrainingListName = services[0], TrainingCurrentCost = 200.0m
                },
                new PriceTrainingList {
                    TrainingListName = services[1], TrainingCurrentCost = 400.0m
                },
                new PriceTrainingList {
                    TrainingListName = services[2], TrainingCurrentCost = 600.0m
                },
            };
            context.TrainingLists.AddRange(trainingsLists);
            #endregion

            #region Добавление статусов тренировки
            ObservableCollection <StatusTraining> statusTrainingLists = new ObservableCollection <StatusTraining>()
            {
                new StatusTraining {
                    StatusName = "Ведется запись"
                },
                new StatusTraining {
                    StatusName = "Группа заполнена, запись невозможна"
                },
            };
            context.StatusTrainings.AddRange(statusTrainingLists);
            #endregion

            #region Добавление статусов аккаунта
            ObservableCollection <AbonementStatus> abonementStatusList = new ObservableCollection <AbonementStatus>()
            {
                new AbonementStatus {
                    StatusName = "Активен"
                },
                new AbonementStatus {
                    StatusName = "Не активен"
                },
                new AbonementStatus {
                    StatusName = "Заморожен"
                },
            };
            context.AbonementStatuses.AddRange(abonementStatusList);
            #endregion

            #region Добавление списка залов
            ObservableCollection <Gym> gymLists = new ObservableCollection <Gym>()
            {
                new Gym {
                    GymName = "Зал N1", GymCapacity = 15
                },
                new Gym {
                    GymName = "Зал N2", GymCapacity = 10
                },
                new Gym {
                    GymName = "Зал N3", GymCapacity = 20
                },
            };
            context.Gyms.AddRange(gymLists);
            #endregion

            ObservableCollection <Abonement> abonements = new ObservableCollection <Abonement>()
            {
                new Abonement()
                {
                    VisitedTrainingCount      = 2,
                    AbonementTotalCost        = 4300.0m,
                    CountDays                 = DateTime.Parse("10.06.2018"),
                    ArrServicesInSubscription = new ObservableCollection <ServicesInSubscription>()
                    {
                        new ServicesInSubscription()
                        {
                            SiSTrainingCount        = 7,
                            SiSVisitedTrainingCount = 4,
                            TotalCost = 1005.0m,
                            PriceType = trainingsLists[2]
                        },
                        new ServicesInSubscription()
                        {
                            SiSTrainingCount        = 15,
                            SiSVisitedTrainingCount = 5,
                            TotalCost = 2000.0m,
                            PriceType = trainingsLists[0]
                        }
                    },

                    AbonmentStatus = abonementStatusList[0],
                },

                new Abonement()
                {
                    VisitedTrainingCount      = 2, AbonementTotalCost = 3000.0m, CountDays = DateTime.Parse("10.06.2018"),
                    ArrServicesInSubscription = new ObservableCollection <ServicesInSubscription>()
                    {
                        new ServicesInSubscription()
                        {
                            SiSTrainingCount = 7, SiSVisitedTrainingCount = 4, TotalCost = 1005.0m, PriceType = trainingsLists[2]
                        },
                        new ServicesInSubscription()
                        {
                            SiSTrainingCount = 15, SiSVisitedTrainingCount = 5, TotalCost = 2000.0m, PriceType = trainingsLists[0]
                        }
                    },
                    AbonmentStatus = abonementStatusList[1]
                },
            };


            #region Добавление аккаунтов клиентов (посетителей фитнес-клуба)
            ObservableCollection <Account> accounts = new ObservableCollection <Account>
            {
                new Account {
                    Abonement = abonements[0],
                    //NumberSubscription = AbonementGenerator.CreateNumberSubscription(),
                    //AccountregistrationDate = DateTime.Now,
                    //TrainingCount = 10,
                    //VisitedTrainingCount = 5,
                    //TotalCost = 1000.0m, //сделать вычисляемым полем
                    HumanFirstName           = "Антон",
                    HumanLastName            = "Юрьевич",
                    HumanFamilyName          = "Куликов",
                    HumanGender              = "Муж.",
                    HumanDateOfBirdth        = DateTime.Parse("27.05.1989"),
                    HumanAdress              = "г.Иваново, ул.Бакинский проезд, д.82, кв.11",
                    HumanPhoneNumber         = "8-920-672-00-68",
                    HumanMail                = "*****@*****.**",
                    HumanPhoto               = SqlTools.ConvertImageToByteArray(@"Z:\Projects\FitnessClub\FitnesClubMWWM\UI\Ui.Desktop\Photos\men.png"),
                    HumanPasportDataSeries   = "2409",
                    HumanPasportDataNumber   = "460870",
                    HumanPasportDataIssuedBy = "ОУФМС РОССИИ",
                    HumanPasportDatеOfIssue  = DateTime.Parse("04.05.2009"),
                    //Employee = employees[0],
                    //TypeAbonement = trainingsLists[0],
                    //AccountStatus = accountStatusList[0],
                    //CountDays = 30,
                    //AbonementActivationDateTime = DateTime.Parse("24.03.2018"),
                },
                new Account {
                    Abonement = abonements[1],
                    //NumberSubscription = AbonementGenerator.CreateNumberSubscription(),
                    //AccountregistrationDate = DateTime.Now,
                    //TrainingCount = 15,
                    //VisitedTrainingCount = 5,
                    //TotalCost = 3000.0m, //сделать вычисляемым полем
                    HumanFirstName           = "Анастасия",
                    HumanLastName            = "Николаевна",
                    HumanFamilyName          = "Смирнова",
                    HumanGender              = "Жен.",
                    HumanDateOfBirdth        = DateTime.Parse("24.03.2000"),
                    HumanAdress              = "г.Иваново, ул.Бакинский проезд, д.82, кв.11",
                    HumanPhoneNumber         = "8-920-672-00-68",
                    HumanMail                = "*****@*****.**",
                    HumanPhoto               = SqlTools.ConvertImageToByteArray(@"Z:\Projects\FitnessClub\FitnesClubMWWM\UI\Ui.Desktop\Photos\girl.jpg"),
                    HumanPasportDataSeries   = "2409",
                    HumanPasportDataNumber   = "460870",
                    HumanPasportDataIssuedBy = "ОУФМС РОССИИ",
                    HumanPasportDatеOfIssue  = DateTime.Parse("04.05.2012"),
                    //Employee = employees[0],
                    //TypeAbonement = trainingsLists[2],
                    //AccountStatus = accountStatusList[1],
                    //CountDays = 25,
                    //AbonementActivationDateTime = DateTime.Parse("20.01.2018"),
                    //ArrServicesInSubscription = new ObservableCollection<ServicesInSubscription>()
                    //{
                    //    new ServicesInSubscription(){ SiSTrainingCount = 3, SiSVisitedTrainingCount=3, TotalCost = 1200.0m, arrPriceType =trainingsLists[1] },
                    //    new ServicesInSubscription(){ SiSTrainingCount = 8, SiSVisitedTrainingCount=5, TotalCost = 2040.0m, arrPriceType =trainingsLists[2] }
                    //}
                },
            };


            #endregion

            //ObservableCollection<Abonement> _Abonements = new ObservableCollection<Abonement>();
            //context.Abonements.AddRange(_Abonements);



            #region Добавление тренировки, которая предстоит
            ObservableCollection <UpcomingTraining> trainings = new ObservableCollection <UpcomingTraining>()
            {
                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 24, 15, 30, 00),
                    NumberOfSeats    = 10,
                    StatusTraining   = statusTrainingLists[0],
                    Abonements       = new ObservableCollection <Abonement> {
                        accounts[0].Abonement, accounts[1].Abonement
                    },
                    Service  = services[0],
                    Gym      = gymLists[0],
                    Employee = employees[2]
                },

                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 24, 16, 30, 00),
                    NumberOfSeats    = 12,
                    StatusTraining   = statusTrainingLists[0],
                    Abonements       = new ObservableCollection <Abonement> {
                        accounts[0].Abonement, accounts[1].Abonement
                    },
                    Service  = services[0],
                    Gym      = gymLists[1],
                    Employee = employees[2]
                },

                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 24, 16, 30, 00),
                    NumberOfSeats    = 8,
                    StatusTraining   = statusTrainingLists[0],
                    Abonements       = new ObservableCollection <Abonement> {
                        accounts[0].Abonement, accounts[1].Abonement
                    },
                    Service  = services[2],
                    Gym      = gymLists[2],
                    Employee = employees[1]
                },
                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 26, 17, 45, 00),
                    NumberOfSeats    = 8,
                    StatusTraining   = statusTrainingLists[0],
                    Service          = services[2],
                    Gym      = gymLists[2],
                    Employee = employees[1]
                },

                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 26, 18, 00, 00),
                    NumberOfSeats    = 8,
                    StatusTraining   = statusTrainingLists[0],
                    Service          = services[2],
                    Gym      = gymLists[2],
                    Employee = employees[1]
                },
                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 05, 27, 16, 30, 00),
                    NumberOfSeats    = 8,
                    StatusTraining   = statusTrainingLists[0],
                    Service          = services[0],
                    Gym      = gymLists[0],
                    Employee = employees[1]
                },

                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 06, 14, 12, 30, 00),
                    NumberOfSeats    = 12,
                    StatusTraining   = statusTrainingLists[0],
                    Service          = services[1],
                    Gym      = gymLists[1],
                    Employee = employees[1]
                },

                new UpcomingTraining
                {
                    TrainingDateTime = new DateTime(2018, 06, 20, 14, 30, 00),
                    NumberOfSeats    = 10,
                    StatusTraining   = statusTrainingLists[0],
                    Service          = services[1],
                    Gym      = gymLists[2],
                    Employee = employees[1]
                },
            };
            context.UpcomingTrainings.AddRange(trainings);

            //ObservableCollection<ServicesInSubscription> _collectionSiS = new ObservableCollection<ServicesInSubscription>()
            //{
            //    new ServicesInSubscription() { SiSTrainingCount = 3, SiSVisitedTrainingCount=1, TotalCost=254.0m, PriceType = trainingsLists[0]},
            //    new ServicesInSubscription() { SiSTrainingCount = 2, SiSVisitedTrainingCount=0, TotalCost=204.0m, PriceType = trainingsLists[1]}
            //};



            abonements[0].Account = accounts[0];
            abonements[1].Account = accounts[1];

            //accounts[0].Abonement.ArrServicesInSubscription.Add(_collectionSiS[0]);
            //accounts[0].Abonement.ArrServicesInSubscription.Add(_collectionSiS[1]);

            //accounts[1].Abonement.ArrServicesInSubscription.Add(_collectionSiS[0]);
            //accounts[1].Abonement.ArrServicesInSubscription.Add(_collectionSiS[1]);
            context.Abonements.AddRange(abonements);

            context.Accounts.AddRange(accounts);
            //  context.ServicesInSubscription.AddRange(_collectionSiS);

            #endregion
            context.SaveChanges();
        }
Пример #12
0
    //添加个体
    public static bool AddBody(object o, int type)
    {
        //学生
        if (type == 1)
        {
            Student s = (Student)o;

            //判断是否已存在该学号
            string sql1 = string.Format("select * from student where id='{0}'", s.ID1);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            //查询出班级名对应的班级号
            string classid = "";
            string sql2    = string.Format("select id from classinfo where name='{0}'", s.Class1);
            idr = SqlTools.Read(sql2);
            if (idr.Read())
            {
                classid = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }


            string sql = string.Format(@"insert into student values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", s.ID1, s.Password1, s.Name1, s.Sex1, classid, s.Dept1, s.State1, s.Birth1, s.Address1, "https://z3.ax1x.com/2021/05/15/g6hH39.gif", s.Email1, s.Telephone1);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //老师
        else if (type == 2)
        {
            Teacher t = (Teacher)o;

            //判断是否已存在该工号
            string sql1 = string.Format("select * from teacher where id='{0}'", t.ID1);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            //查询出学院所对应的部门号
            string num  = "";
            string sql2 = string.Format("select id from dept where name='{0}'", t.Department1);
            idr = SqlTools.Read(sql2);
            if (idr.Read())
            {
                num = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }


            string sql = string.Format(@"insert into teacher(id,password,name,state,sex,birthday,arrivedate,telephone,address,email,department) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')", t.ID1, t.Password1, t.Name1, t.State1, t.Sex1, t.Birthday1, t.ArriveDate1, t.Telephone1, t.Address1, t.Email1, num);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //管理员
        else if (type == 3)
        {
        }
        //课程
        else if (type == 4)
        {
            Course c = (Course)o;

            //判断是否已存在该课程号
            string sql1 = string.Format("select * from course where id='{0}'", c.ID);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }
            //查询出该课程的老师
            string teacherId = "";
            string sql3      = string.Format("select id from teacher where name='{0}'", c.Teacher);
            idr = SqlTools.Read(sql3);
            if (idr.Read())
            {
                teacherId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }


            string sql = string.Format(@"insert into course values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", c.ID, c.Name, teacherId, c.Date, c.Time, c.Week, c.Place, c.Score);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //成绩
        else if (type == 5)
        {
            Score sc = (Score)o;

            //查询学生名对应的学号
            string studentId = "";
            string sql3      = string.Format("select id from student where name='{0}'", sc.Student1);
            idr = SqlTools.Read(sql3);
            if (idr.Read())
            {
                studentId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            //判断是否存在相同的课程号和学生名
            string sql1 = string.Format("select * from score where student='{0}' and course='{1}'", studentId, sc.Course1);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            string sql = string.Format(@"insert into score values('{0}','{1}','{2}','{3}','{4}')", studentId, sc.Course1, sc.Scores1, sc.Submittime, sc.Submittime);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //教室
        else if (type == 6)
        {
        }
        //考试
        else if (type == 7)
        {
            Exam ex = (Exam)o;

            //判断是否已存在
            string sql1 = string.Format("select * from exam where id='{0}'", ex.ID);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            //课程名查课程号
            string selectcourseId = string.Format("select id from course where name='{0}'", ex.Course);
            idr = SqlTools.Read(selectcourseId);
            string courseId = "";
            if (idr.Read())
            {
                courseId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            //班级名查班级号
            string selectclassId = string.Format("select id from classinfo where name='{0}'", ex.ClassInfo);
            idr = SqlTools.Read(selectclassId);
            string classid = "";
            if (idr.Read())
            {
                classid = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            //判断是否同科目同班级
            string sql3 = string.Format("select * from exam where course='{0}' classinfo class='{1}'", courseId, classid);
            idr = SqlTools.Read(sql3);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }


            string sql = string.Format(@"insert into exam values('{0}','{1}','{2}','{3}','{4}','{5}')", ex.ID, courseId, ex.Date, ex.Time, ex.Place, classid);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //院系
        if (type == 8)
        {
            Dept de = (Dept)o;

            //判断是否已存在该院系号
            string sql1 = string.Format("select * from dept where id='{0}'", de.ID);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            //name select id
            string selectteacherId = string.Format("select id from teacher where name='{0}'", de.Leader);
            string teacherId       = "";
            idr = SqlTools.Read(selectteacherId);
            if (idr.Read())
            {
                teacherId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            string sql = string.Format(@"insert into dept values('{0}','{1}','{2}')", de.ID, de.Name, teacherId);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
        }
        //消息
        if (type == 9)
        {
            Message m = (Message)o;


            String RegexStr = @"\d+";
            //如果发送者中含有数字说明发送者为个体,需要判断该个体是否存在
            if (Regex.IsMatch(m.Receiver, RegexStr) || (!m.Receiver.Equals("全部") && !m.Receiver.Equals("全体老师") && !m.Receiver.Equals("全体学生")))
            {
                string sql1 = string.Format("select * from student,teacher where student.id='{0}' or teacher.id='{1}'", m.Receiver, m.Receiver);
                idr = SqlTools.Read(sql1);
                //若存在则添加
                if (idr.Read())
                {
                    string sql5 = string.Format(@"insert into publicinformation(submitperson,news,receiver,title) values('{0}','{1}','{2}','{3}')", m.Submitperson, m.News, m.Receiver, m.Title);
                    int    i5   = SqlTools.Excute(sql5);
                    if (i5 == 0)
                    {        //关连接
                        if (!idr.IsClosed)
                        {
                            idr.Close();
                        }
                        return(false);
                    }
                    else
                    {        //关连接
                        if (!idr.IsClosed)
                        {
                            idr.Close();
                        }
                        return(true);
                    }
                }

                //没查询到存在则返回false
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }

            string sql = string.Format(@"insert into publicinformation(submitperson,news,receiver,title) values('{0}','{1}','{2}','{3}')", m.Submitperson, m.News, m.Receiver, m.Title);
            int    i   = SqlTools.Excute(sql);
            if (i == 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }



            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }



        {        //关连接
            if (!idr.IsClosed)
            {
                idr.Close();
            }
            return(false);
        }
    }
Пример #13
0
 //删除个体
 public static bool DeleteBody(string id, int type)
 {
     //学生
     if (type == 1)
     {
         string sql = string.Format(@"delete from student where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     //老师
     if (type == 2)
     {
         string sql = string.Format(@"delete from teacher where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     //管理员
     if (type == 3)
     {
     }
     //课程
     if (type == 4)
     {
         string sql = string.Format(@"delete from course where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     //成绩
     if (type == 5)
     {
         string sql = string.Format(@"delete from score where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     //教室
     if (type == 6)
     {
     }
     //考试
     if (type == 7)
     {
         string sql = string.Format(@"delete from exam where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     //院系
     if (type == 8)
     {
         string sql = string.Format(@"delete from dept where id='{0}'", id);
         int    i   = SqlTools.Excute(sql);
         if (i == 0)
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(false);
         }
         else
         {        //关连接
             if (!idr.IsClosed)
             {
                 idr.Close();
             }
             return(true);
         }
     }
     {        //关连接
         if (!idr.IsClosed)
         {
             idr.Close();
         }
         return(false);
     }
 }
Пример #14
0
    //修改个体信息
    public static bool UpdateBody(object o, int type)
    {
        //学生
        if (type == 1)
        {
            Student s   = (Student)o;
            string  sql = string.Format(@"update {0} set  password='******' ,name='{2}' ,sex='{3}' ,class='{4}' ,dept='{5}' ,state='{6}' ,birth='{7}' ,address='{8}' ,photo='{9}' ,email='{10}' ,telephone='{11}' where id='{12}'", "student", s.Password1, s.Name1, s.Sex1, s.Class1, s.Dept1, s.State1, s.Birth1, s.Address1, s.Photo1, s.Email1, s.Telephone1, s.ID1);
            int     i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        //教师
        else if (type == 2)
        {
            Teacher t = (Teacher)o;
            //查询出学院所对应的部门号
            string num  = "";
            string sql1 = string.Format("select id from dept where name='{0}'", t.Department1);
            idr = SqlTools.Read(sql1);
            if (idr.Read())
            {
                num = idr.GetString(0);
            }
            else
            {         //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            string sql = string.Format(@"update {0} set  password='******' ,name='{2}',state='{3}' ,sex='{4}' ,birthday='{5}',arrivedate='{6}',telephone='{7}',address='{8}'  ,email='{9}',department='{10}'  where id='{11}'", "teacher", t.Password1, t.Name1, t.State1, t.Sex1, t.Birthday1, t.ArriveDate1, t.Telephone1, t.Address1, t.Email1, num, t.ID1);
            int    i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        //管理员
        else if (type == 3)
        {
        }
        //课程
        else if (type == 4)
        {
            Course c = (Course)o;

            //查询出该课程的老师
            string selectteacherId = string.Format("select id from teacher where name='{0}'", c.Teacher);
            string teacherId       = "";
            idr = SqlTools.Read(selectteacherId);
            if (idr.Read())
            {
                teacherId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }



            string sql = string.Format(@"update {0} set  name='{1}' ,teacher='{2}',date='{3}' ,time='{4}' ,week='{5}',place='{6}',score='{7}'where id='{8}'", "course", c.Name, teacherId, c.Date, c.Time, c.Week, c.Place, c.Score, c.ID);
            int    i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        //成绩
        else if (type == 5)
        {
            Score sc = (Score)o;

            string sql = string.Format(@"update {0} set  score='{1}' ,submittime='{2}' where id={3}", "score", sc.Scores1, sc.Submittime, sc.ID1);
            int    i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        //教室
        else if (type == 6)
        {
        }
        //考试
        else if (type == 7)
        {
            Exam ex = (Exam)o;

            //课程名查课程号
            string selectcourseId = string.Format("select id from course where name='{0}'", ex.Course);
            idr = SqlTools.Read(selectcourseId);
            string courseId = "";
            if (idr.Read())
            {
                courseId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            //班级名查班级号
            string selectclassId = string.Format("select id from classinfo where name='{0}'", ex.ClassInfo);
            idr = SqlTools.Read(selectclassId);
            string classid = "";
            if (idr.Read())
            {
                classid = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }


            //判断是否同科目同班级
            string sql3 = string.Format("select * from exam where course='{0}' classinfo class='{1}'", courseId, classid);
            idr = SqlTools.Read(sql3);
            if (idr.Read())
            {
                {        //关连接
                    if (!idr.IsClosed)
                    {
                        idr.Close();
                    }
                    return(false);
                }
            }


            string sql = string.Format(@"update {0} set course='{1}',date='{2}',time='{3}',place='{4}',classinfo='{5}' where id='{6}'", "exam", courseId, ex.Date, ex.Time, ex.Place, classid, ex.ID);
            int    i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        //系别
        if (type == 8)
        {
            Dept de = (Dept)o;

            //name select id
            string selectteacherId = string.Format("select id from teacher where name='{0}'", de.Leader);
            string teacherId       = "";
            idr = SqlTools.Read(selectteacherId);
            if (idr.Read())
            {
                teacherId = idr.GetString(0);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }

            string sql = string.Format(@"update {0} set  name='{1}' ,leader='{2}'where id='{3}'", "dept", de.Name, teacherId, de.ID);
            int    i   = SqlTools.Excute(sql);
            if (i != 0)
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(true);
            }
            else
            {        //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(false);
            }
        }
        {        //关连接
            if (!idr.IsClosed)
            {
                idr.Close();
            }
            return(false);
        }
    }
Пример #15
0
    //登录
    public static object Login(String id, String pwd, int type)
    {
        //学生
        if (type == 1)
        {
            string sql = string.Format(@"select * from Student where id='{0}'and password= '******'", id, pwd);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Student s = new Student(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6), idr.GetString(7), idr.GetString(8), idr.GetString(9), idr.GetString(10), idr.GetString(11));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(s);
            }
        }
        //老师
        else if (type == 2)
        {
            string sql = string.Format(@"select * from Teacher where id='{0}'and password= '******'", id, pwd);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Teacher t = new Teacher(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6), idr.GetString(7), idr.GetString(8), idr.GetString(9), idr.GetString(10), idr.GetString(11));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(t);
            }
        }
        //管理员
        else if (type == 3)
        {
            string sql = string.Format(@"select * from Admin where id='{0}'and password= '******'", id, pwd);

            idr = SqlTools.Read(sql);

            if (idr.Read())
            {
                Admin t = new Admin(idr.GetString(0), idr.GetString(1), idr.GetString(2), idr.GetString(3), idr.GetString(4), idr.GetString(5), idr.GetString(6));
                //关连接
                if (!idr.IsClosed)
                {
                    idr.Close();
                }
                return(t);
            }
        }

        //关连接
        if (!idr.IsClosed)
        {
            idr.Close();
        }

        return(null);
    }
Пример #16
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            // Placer ici le code utilisateur pour initialiser la page
            try
            {
                PanelChunk.Visible = ContainerInfoPanel.Visible = false;
                string key = System.Web.HttpUtility.HtmlEncode(Request["key"].ToString()).Replace(" ", "+");
                key = SqlTools.DecryptString(key);
                //Response.Write(key);
                string[] parameters = key.Split(',');
                switch (parameters[0])
                {
                case "d":
                    ContainerInfoPanel.ContainerId = Convert.ToInt32(parameters[1]);
                    ContainerInfoPanel.Visible     = true;
                    PanelChunk.Visible             = PanelChunkDetail.Visible = false;
                    break;

                case "i":
                    Page.Response.Redirect("TR_Properties.aspx?tr=" + parameters[1]);
                    break;

                case "c":
                    Item  item  = Item.GetByKey(Convert.ToInt64(parameters[1]));
                    Chunk chunk = Chunk.GetByKey(Convert.ToInt64(parameters[1]), Convert.ToInt32(parameters[2]), HyperCatalog.Shared.SessionState.MasterCulture.Code);
                    HyperCatalog.Business.Culture culture = HyperCatalog.Business.Culture.GetByKey(parameters[3].ToString());
                    if (Request["tab"] == null)
                    {
                        PanelChunk.Visible       = true;
                        PanelChunkDetail.Visible = false;
                        webTab.Tabs.GetTab(0).ContentPane.TargetUrl = "Preview.aspx?key=" + key + "&tab=1";
                        webTab.Tabs.GetTab(1).ContentPane.TargetUrl = "../../Acquire/qde/QDE_FormContent.aspx?i=" + item.Id + "&f=IF_-1&c=" + culture.Code;
                        if (item != null)
                        {
                            webTab.Tabs[0].Text = chunk.ContainerName;
                            uwToolbarTitle.Items.FromKeyLabel("ItemName").Text = item.Name;
                        }
                        if (culture != null)
                        {
                            uwToolbarTitle.Items.FromKeyLabel("Culture").Image = "/hc_v4/img/flags/" + culture.CountryCode + ".gif";
                            uwToolbarTitle.Items.FromKeyLabel("Culture").Text  = culture.Name + "&nbsp;";
                        }
                    }
                    else
                    {
                        PanelChunkDetail.Visible = true;
                        if (chunk != null)
                        {
                            txtValue.Text = chunk.Text;
                            if (chunk.Text == HyperCatalog.Business.Chunk.BlankValue)
                            {
                                txtValue.Text = HyperCatalog.Business.Chunk.BlankText;
                            }
                            imgStatus.ImageUrl       = "/hc_v4/img/S" + HyperCatalog.Business.Chunk.GetStatusFromEnum(chunk.Status) + ".gif";
                            lbStatus.Text            = "[" + chunk.Status.ToString() + "]";
                            ChunkComment1.Chunk      = ChunkModifier1.Chunk = chunk;
                            PanelChunkDetail.Visible = true;
                            ChunkComment1.Visible    = chunk.Comment != string.Empty;
                        }
                        else
                        {
                            Business.Debug.Trace("ASP", key, Business.DebugSeverity.Medium);
                            UITools.JsCloseWin("Chunk not found (possible reason is deletion)");
                        }
                    }
                    break;

                default:
                    UITools.JsCloseWin("Incorrect query!");
                    break;
                }
            }
            catch (Exception ex)
            {
                Business.Debug.Trace("ASP", ex.Message, Business.DebugSeverity.High);
                UITools.JsCloseWin("Unauthorized access - " + ex.ToString());
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获取要编辑课程
            string id = Request.QueryString["id"];
            Course c  = (Course)dao.getBody(id, 4);

            TextBoxID.Text    = c.ID;
            TextBoxName.Text  = c.Name;
            TextBoxScore.Text = c.Score;
            TextBoxDate.Text  = c.Date;



            //获取所有老师
            SqlConnection  sqlConnection   = SqlTools.Connection();
            SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter("select * from teacher", sqlConnection);
            DataSet        dataSet1        = new DataSet();
            sqlDataAdapter1.Fill(dataSet1);

            //所有老师绑定到系别下拉框
            DropDownListTeacher.DataSource    = dataSet1;
            DropDownListTeacher.DataTextField = "name";
            DropDownListTeacher.DataBind();
            //下拉框选中该课程老师
            //1.查询老师编号对应的老师姓名
            string      teacherName = "";
            string      sql1        = string.Format("select name from teacher where id='{0}'", c.Teacher);
            IDataReader idr         = SqlTools.Read(sql1);
            if (idr.Read())
            {
                teacherName = idr.GetString(0);
            }
            //2.选中
            DropDownListTeacher.SelectedValue = teacherName;


            //绑定上课时间
            string[] dayAndNode = c.Time.Split(',');
            for (int i = 0; i < dayAndNode.Length; i++)
            {
                //第一个字符为1说明是星期一
                if (dayAndNode[i].Substring(0, 1).Equals("1"))
                {
                    RadioButtonMonday.Checked        = true;
                    DropDownListMonday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("2"))
                {
                    RadioButtonTuesday.Checked        = true;
                    DropDownListTuesday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("3"))
                {
                    RadioButtonWed.Checked = true;
                    DropDownListWednesday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("4"))
                {
                    RadioButtonThur.Checked            = true;
                    DropDownListThursday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
                else if (dayAndNode[i].Substring(0, 1).Equals("5"))
                {
                    RadioButtonFri.Checked           = true;
                    DropDownListFriday.SelectedValue = dayAndNode[i].Substring(2, 1);
                }
            }

            //绑定课程周次
            string[] startAndEnd = c.Week.Split('-');
            DropDownListStart.SelectedValue = startAndEnd[0];
            DropDownListEnd.SelectedValue   = startAndEnd[1];


            //获取所有教室
            SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter("select * from classroom", sqlConnection);
            DataSet        dataSet2        = new DataSet();
            sqlDataAdapter2.Fill(dataSet2);
            //所有教室绑定到系别下拉框
            DropDownListPlace.DataSource    = dataSet2;
            DropDownListPlace.DataTextField = "id";
            DropDownListPlace.DataBind();
            //选中上课地点
            DropDownListTeacher.SelectedValue = c.Place;


            sqlConnection.Close();
        }

        //不能改课程号
        TextBoxID.Enabled = false;
    }