Ejemplo n.º 1
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Verify user input.
            if (!Utilities.IsEmailValid(txtEmail.Text))
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorInvalidEmail").ToString();
                return;
            }

            if (!Utilities.IsPasswordValid(txtPwd1.Text))
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Profile.aspx", "ErrorInvalidPwd").ToString();
                return;
            }

            if (txtPwd1.Text != txtPwd2.Text)
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Profile.aspx", "ErrorPwdNoMatch").ToString();
                return;
            }

            if (txtAccessCode.Text == "")
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = GetLocalResourceObject("ErrorInvalidAccessCode").ToString();
                return;
            }

            //if (txtCompanyCode.Text == "")
            //{
            //    lblErrMsg.Visible = true;
            //    lblErrMsg.Text = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorInvalidCompany").ToString();
            //    return;
            //}

            ClientSetting cs = ClientSettings.Get("astellas"); //txtCompanyCode.Text

            if (cs == null)
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorInvalidCompany").ToString();
                return;
            }
            else
            {
                if (!cs.Enabled)
                {
                    lblErrMsg.Visible = true;
                    lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorDisabledCompany").ToString();
                    return;
                }
            }

            //initialize connection string
            LmsUser.DBConnString = cs.EntityConnStr;

            // check
            lms_Entities     db       = new ClientDBEntities();
            User_Info_Result userInfo = db.User_Info(txtEmail.Text.Trim()).FirstOrDefault();

            if (userInfo == null)
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text    = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorUnknownEmail").ToString(); //"Error: Your email is not registered in the system.";
            }
            else
            {
                // user exists
                if (userInfo.activationCode == txtAccessCode.Text.Trim())
                {
                    // activate the user's account.
                    User usr = db.Users.Where(u => u.userId == userInfo.userId).FirstOrDefault();
                    usr.enabled  = true;
                    usr.password = txtPwd1.Text.Trim();
                    db.SaveChanges();

                    // set session items.
                    LmsUser.SetInfo(userInfo.userId, userInfo.firstName, userInfo.lastName, userInfo.role, cs.Name, cs.AssetsFolder);

                    // write the session data to the log.
                    Log.Info("User: "******" account verified. Logging in for the 1st time.");
                    FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, false);
                }
                else
                {
                    lblErrMsg.Visible = true;
                    lblErrMsg.Text    = GetLocalResourceObject("ErrorInvalidAccessCode").ToString();
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            CourseInfo?courseInfo = null;
            string     errMsg     = "";
            string     filename   = "";
            int?       courseId   = null;
            CourseType courseType = (CourseType)short.Parse(context.Request.Form["type"]);

            // check if a file needs to be uploaded
            if (context.Request.Files.Count == 1)
            {
                HttpPostedFile uploadedFile = context.Request.Files[0];
                if (uploadedFile?.ContentLength > 0)
                {
                    filename = uploadedFile.FileName;
                    courseId = Utilities.TryToParseAsInt(context.Request.Form["courseId"]);
                    if (courseId == null)
                    {
                        errMsg = "No course ID was specified";
                    }
                    else
                    {
                        string courseAbsPath = Path.Combine(new string[] {
                            HttpContext.Current.Server.MapPath("~/" + Global.WEBSITE_COURSES_FOLDER),
                            LmsUser.companyFolder,
                            courseId.ToString()
                        });

                        if (courseType == CourseType.AICC || courseType == CourseType.SCORM)
                        {
                            if (filename.EndsWith(".zip"))
                            {
                                try
                                {
                                    // make sure the folder exists
                                    if (Directory.Exists(courseAbsPath))
                                    {
                                        EmptyDirectory(courseAbsPath);
                                    }
                                    else
                                    {
                                        Directory.CreateDirectory(courseAbsPath);
                                    }

                                    //unzip it
                                    Log.Info("Unzipping " + filename + " to " + courseAbsPath);
                                    ZipArchive zipArch = new ZipArchive(uploadedFile.InputStream);
                                    zipArch.ExtractToDirectory(courseAbsPath);

                                    //get the manifests' data
                                    if (courseType == CourseType.AICC)
                                    {
                                        string   auManifest;
                                        string   crsManifest;
                                        string[] files;
                                        files = Directory.GetFiles(courseAbsPath, "*.au");
                                        if (files.Length == 0)
                                        {
                                            errMsg = "The \".AU\" file (manifest) was not found.";
                                        }
                                        else
                                        {
                                            auManifest = files[0];
                                            files      = Directory.GetFiles(courseAbsPath, "*.crs");
                                            if (files.Length == 0)
                                            {
                                                errMsg = "The \".CRS\" file (manifest) was not found";
                                            }
                                            else
                                            {
                                                crsManifest = files[0];
                                                courseInfo  = GetAICCManifestData(courseAbsPath, auManifest, crsManifest, out errMsg);

                                                if (courseInfo == null)
                                                {
                                                    // errMsg already set by function if courseInfo == null;
                                                }
                                                else
                                                {
                                                    //check data in manifest
                                                    if (courseInfo?.title.Trim().Length == 0)
                                                    {
                                                        errMsg = "The title is empty in the manifest";
                                                    }
                                                    if (courseInfo?.startPage.Trim().Length == 0)
                                                    {
                                                        errMsg = "The start page is empty in the manifest";
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (courseType == CourseType.SCORM)
                                    {
                                        if (File.Exists(courseAbsPath + "\\imsmanifest.xml"))
                                        {
                                            courseInfo = GetSCORMManifestData(courseAbsPath, out errMsg);

                                            if (courseInfo == null)
                                            {
                                                // errMsg already set by function if courseInfo == null;
                                            }
                                            else
                                            {
                                                //check data in manifest
                                                if (courseInfo?.title.Trim().Length == 0)
                                                {
                                                    errMsg = "The title is empty in the manifest";
                                                }
                                                if (courseInfo?.startPage.Trim().Length == 0)
                                                {
                                                    errMsg = "The start page is empty in the manifest";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            errMsg = "Missing imsmanifest.xml file.";
                                        }
                                    }
                                }
                                catch (IOException exc)
                                {
                                    //error configuration/write permission error
                                    Log.Error(exc);
                                    errMsg = exc.Message;
                                }
                            }
                            else
                            {
                                errMsg = "Uploaded file is not a Zip file";
                            }
                        }
                        else
                        {
                            if (courseType == CourseType.READ_AND_SIGN)
                            {
                                // make sure the folder exists
                                if (Directory.Exists(courseAbsPath))
                                {
                                    EmptyDirectory(courseAbsPath);
                                }
                                else
                                {
                                    Directory.CreateDirectory(courseAbsPath);
                                }

                                //save file
                                uploadedFile.SaveAs(courseAbsPath + "\\" + filename);
                            }
                            else
                            {
                                errMsg = "No course type was specified";
                            }
                        }
                    }
                }
                else
                {
                    //error empty file or incorrect data submitted
                    errMsg = "File uploaded is empty";
                }
            }
            else
            {
                //error no file submitted
                errMsg = "No file uploaded";
            }



            if (errMsg.Length == 0)
            {
                //============================================
                // At this point the upload process went ok so
                // update the db course info with updated info
                //============================================
                try
                {
                    lms_Entities db  = new ClientDBEntities();
                    Course       csr = db.Courses.Where(u => u.courseId == courseId).FirstOrDefault();
                    if (courseType == CourseType.READ_AND_SIGN)
                    {
                        csr.type = (short)courseType;
                        csr.url  = Global.WEBSITE_COURSES_FOLDER + "/" + LmsUser.companyFolder + "/" + courseId + "/" + filename;
                        Log.Info("CourseId " + courseId + " updated file:" + filename);
                    }
                    else
                    {
                        csr.title       = courseInfo?.title;
                        csr.description = courseInfo?.description;
                        csr.type        = (short)courseType;
                        csr.url         = Global.WEBSITE_COURSES_FOLDER + "/" + LmsUser.companyFolder + "/" + courseId + "/" + courseInfo?.startPage;
                        Log.Info("CourseId " + courseId + " updated from manifest.");
                    }
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    errMsg = e.Message;
                    Log.Error(e);
                }
            }
            else
            {
                Log.Error(errMsg);
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonResponse.Data(errMsg, courseInfo));
        }
Ejemplo n.º 3
0
        public static string Save(
            string title,
            string description,
            bool enabled,
            string registerCode,
            DateTime?dueDate,
            int?dueDays,
            bool emailOnAssigned,
            bool emailPeriodic,
            int?periodicDays,
            bool emailNearDueDate,
            int?nearDueDateDays,
            bool emailOnDueDate,
            bool emailOverdue,
            int?overdueDays)
        {
            try
            {
                lms_Entities db = new ClientDBEntities();
                Assignment   asg;

                string aid          = Utilities.GetQueryString("aId");
                int?   assignmentId = Utilities.TryToParseAsInt(aid);

                //check if Registration Code is already used in another assignment
                if (registerCode?.Trim().Length > 0)
                {
                    asg = db.Assignments.Where(a => a.registerCode == registerCode && a.assignmentId != assignmentId).FirstOrDefault();
                    if (asg != null)
                    {
                        return(JsonResponse.Error("The registration code entered is already in use. Please select another."));
                    }
                }

                if (assignmentId == null)
                {
                    //this is a new assignment
                    asg                      = new Assignment();
                    asg.type                 = (int)AssignmentType.LEARNING_PLAN;
                    asg.enabled              = enabled;
                    asg.title                = title;
                    asg.description          = description;
                    asg.registerCode         = registerCode.Trim();
                    asg.dueDate              = dueDate;
                    asg.dueDaysAfterAssigned = dueDays;
                    if (dueDate != null && dueDays != null)
                    {
                        asg.dueDaysAfterAssigned = null;                                     //default to dueDate if both provided
                    }
                    asg.sendEmailOnAssigned  = emailOnAssigned;
                    asg.sendEmailPeriodic    = emailPeriodic;
                    asg.periodicDays         = periodicDays;
                    asg.sendEmailNearDueDate = emailNearDueDate;
                    asg.nearDueDateDays      = nearDueDateDays;
                    asg.sendEmailOnDueDate   = emailOnDueDate;
                    asg.sendEmailOverdue     = emailOverdue;
                    asg.overdueDays          = overdueDays;
                    asg.timestamp            = DateTime.Now;
                    db.Assignments.Add(asg);
                    db.SaveChanges();
                }
                else //this is an update of existing assignment
                {
                    //check if due date is in the future
                    //if (dueDate != null)
                    //{
                    //    if (((DateTime)dueDate).Subtract(DateTime.Today).Days < 1)
                    //    {
                    //        return JsonResponse.Error("The due date must be a future date. Please select another.");
                    //    }
                    //}

                    //update
                    asg             = db.Assignments.Where(a => a.assignmentId == assignmentId).FirstOrDefault();
                    asg.enabled     = enabled;
                    asg.title       = title;
                    asg.description = description;
                    //asg.allowSelfRegister = allowSelfRegister;
                    asg.registerCode         = registerCode.Trim();
                    asg.dueDate              = dueDate;
                    asg.dueDaysAfterAssigned = dueDays;
                    if (dueDate != null && dueDays != null)
                    {
                        asg.dueDaysAfterAssigned = null;                                     //default to dueDate if both provided
                    }
                    asg.sendEmailOnAssigned  = emailOnAssigned;
                    asg.sendEmailPeriodic    = emailPeriodic;
                    asg.periodicDays         = periodicDays;
                    asg.sendEmailNearDueDate = emailNearDueDate;
                    asg.nearDueDateDays      = nearDueDateDays;
                    asg.sendEmailOnDueDate   = emailOnDueDate;
                    asg.sendEmailOverdue     = emailOverdue;
                    asg.overdueDays          = overdueDays;
                    db.SaveChanges();
                }


                return(JsonResponse.NoError);
            }
            catch (Exception e)
            {
                return(JsonResponse.Error(e));
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            string err = "";

            // check if a file needs to be uploaded
            if (context.Request.Files.Count == 1)
            {
                HttpPostedFile uploadedFile = context.Request.Files[0];
                if (uploadedFile?.ContentLength > 0)
                {
                    try
                    {
                        string category1 = null;
                        string category2 = null;
                        string category3 = null;
                        string category4 = null;
                        string category5 = null;

                        StreamReader st = new StreamReader(uploadedFile.InputStream);
                        //-----------------------------------------------
                        // scan the entire file and make sure it's CLEAN
                        //-----------------------------------------------
                        bool     cleanData = true;
                        int      row       = 1;
                        string   line;
                        string[] columns;
                        while ((line = st.ReadLine()) != null)
                        {
                            columns = line.Split('\t'); // split by TABS

                            if (row == 1)
                            {
                                //get headers - if any
                                if (columns.Length > 6)
                                {
                                    category1 = columns[6];
                                }
                                if (columns.Length > 7)
                                {
                                    category2 = columns[7];
                                }
                                if (columns.Length > 8)
                                {
                                    category3 = columns[8];
                                }
                                if (columns.Length > 9)
                                {
                                    category4 = columns[9];
                                }
                                if (columns.Length > 10)
                                {
                                    category5 = columns[10];
                                }
                            }
                            else
                            {
                                //check if there are TABS
                                if (columns.Length == 1)
                                {
                                    err       = "Data rows need to be TAB delimited (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }

                                //check if there are at LEAST 6 columns
                                if (columns.Length < 7)
                                {
                                    err       = "There should there be at least 6 columns (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }

                                //check data lengths of all required columns
                                if (columns[0].Trim().Length > 50) //check email
                                {
                                    err       = "The max length of this email has been exceeded (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }
                                if (columns[1].Trim().Length > 50) //check first name
                                {
                                    err       = "The max length of this first name has been exceeded (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }
                                if (columns[2].Trim().Length > 50) //check last name
                                {
                                    err       = "The max length of this last name has been exceeded (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }
                                if (columns[3].Trim().Length == 0) //check default password
                                {
                                    err       = "No default password has been specified (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }
                                if (columns[4].Trim().Length > 50) //check if title is too long
                                {
                                    err       = "The max length of this title has been exceeded (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }
                                if (columns[5].Trim().Length > 50) //check if manager's email is too long
                                {
                                    err       = "The max length of this manager's email has been exceeded (row " + row + ")";
                                    cleanData = false;
                                    break;
                                }

                                //check optional columns
                                if (category1?.Length > 0)
                                {
                                    if (columns[6].Trim().Length > 50) //check if optional field 1 is too long
                                    {
                                        err       = "The max length of this optional field 1 has been exceeded (row " + row + ")";
                                        cleanData = false;
                                        break;
                                    }
                                }
                                if (category2?.Length > 0)
                                {
                                    if (columns[7].Trim().Length > 50) //check if optional field 2 is too long
                                    {
                                        err       = "The max length of this optional field 2 has been exceeded (row " + row + ")";
                                        cleanData = false;
                                        break;
                                    }
                                }
                                if (category3?.Length > 0)
                                {
                                    if (columns[8].Trim().Length > 50) //check if optional field 3 is too long
                                    {
                                        err       = "The max length of this optional field 3 has been exceeded (row " + row + ")";
                                        cleanData = false;
                                        break;
                                    }
                                }
                                if (category4?.Length > 0)
                                {
                                    if (columns[9].Trim().Length > 50) //check if optional field 4 is too long
                                    {
                                        err       = "The max length of this optional field 4 has been exceeded (row " + row + ")";
                                        cleanData = false;
                                        break;
                                    }
                                }
                                if (category5?.Length > 0)
                                {
                                    if (columns[10].Trim().Length > 50) //check if optional field 5 is too long
                                    {
                                        err       = "The max length of this optional field 5 has been exceeded (row " + row + ")";
                                        cleanData = false;
                                        break;
                                    }
                                }
                            }

                            row++;
                        }

                        if (cleanData)
                        {
                            lms_Entities db = new ClientDBEntities();

                            //-----------------------------------------------
                            // import the data file
                            //-----------------------------------------------
                            uploadedFile.InputStream.Position = 0;
                            row = 1;
                            while ((line = st.ReadLine()) != null)
                            {
                                if (row > 1) //skip headers
                                {
                                    columns = line.Split('\t');

                                    //import user data
                                    string email    = columns[0].Trim();
                                    string fname    = columns[1].Trim();
                                    string lname    = columns[2].Trim();
                                    string pwd      = columns[3].Trim();
                                    string title    = columns[4].Trim();
                                    string mgrEmail = columns[5].Trim();
                                    string group1   = category1?.Length > 0 && columns.Length > 6 ? columns[6].Trim() : null;
                                    string group2   = category2?.Length > 0 && columns.Length > 7 ? columns[7].Trim() : null;
                                    string group3   = category3?.Length > 0 && columns.Length > 8 ? columns[8].Trim() : null;
                                    string group4   = category4?.Length > 0 && columns.Length > 9 ? columns[9].Trim() : null;
                                    string group5   = category5?.Length > 0 && columns.Length > 10 ? columns[10].Trim() : null;

                                    if (email.Length > 0)
                                    {
                                        //check if the user already exists
                                        int  userId;
                                        User usr = db.Users.Where(u => u.email == email).FirstOrDefault();
                                        if (usr == null)
                                        {
                                            // user does not exist - add
                                            usr = new User
                                            {
                                                email     = email,
                                                firstName = fname,
                                                lastName  = lname,
                                                mgrEmail  = mgrEmail,
                                                title     = title,
                                                enabled   = false, //disabled.. enabled after they set their password via access code
                                                role      = (int)Role.Learner,
                                                timestamp = DateTime.Now
                                            };
                                            db.Users.Add(usr);
                                            db.SaveChanges();
                                            userId = usr.userId;
                                        }
                                        else
                                        {
                                            // user exists - update some data only
                                            usr.firstName = fname;
                                            usr.lastName  = lname;
                                            usr.title     = title;
                                            usr.mgrEmail  = mgrEmail;
                                            db.SaveChanges();
                                            userId = usr.userId;
                                        }

                                        //clear out all previous imported user's group memberships
                                        //this will not modify manually-added user assignments
                                        db.User_CategoryGroupSet(userId, null, null);

                                        //do optional fields
                                        if (category1?.Length > 0)
                                        {
                                            db.User_CategoryGroupSet(userId, category1, group1); // assign group to user
                                        }
                                        if (category2?.Length > 0)
                                        {
                                            db.User_CategoryGroupSet(userId, category2, group2); // assign group to user
                                        }
                                        if (category3?.Length > 0)
                                        {
                                            db.User_CategoryGroupSet(userId, category3, group3); // assign group to user
                                        }
                                        if (category4?.Length > 0)
                                        {
                                            db.User_CategoryGroupSet(userId, category4, group4); // assign group to user
                                        }
                                        if (category5?.Length > 0)
                                        {
                                            db.User_CategoryGroupSet(userId, category5, group5); // assign group to user
                                        }
                                    }
                                }
                                row++;
                            }

                            err = "Success! " + (row - 2) + " row(s) were processed.";
                        }
                    }
                    catch (Exception ex)
                    {
                        err = ex.Message;
                        Log.Error(ex);
                    }
                }
                else
                {
                    //error empty file or incorrect data submitted
                    err = "Empty file";
                }
            }
            else
            {
                err = "No file was uploaded";
            }

            context.Response.ContentType = "application/json";
            context.Response.Write("{\"error\":\"" + err + "\"}");
        }
Ejemplo n.º 5
0
        public void ProcessRequest(HttpContext context)
        {
            int?assignmentId = Utilities.TryToParseAsInt(context.Request.QueryString["aid"]);
            int?courseId     = Utilities.TryToParseAsInt(context.Request.QueryString["cid"]);
            int userId;

            //set UserID coming from course primarily
            if (context.Request.QueryString["uid"] == null)
            {
                userId = LmsUser.UserId;
            }
            else
            {
                userId = (int)Utilities.TryToParseAsInt(context.Request.QueryString["uid"]);
            }

            context.Response.CacheControl = "no-cache";                        // must never be cached
            context.Response.ContentType  = "application/json; charset=utf-8"; //set json as default response

            lms_Entities db = new ClientDBEntities();

            //call functions
            switch (context.Request.QueryString["m"].ToUpper())
            {
            case "GET_COURSE_STATS":
                //-----------------------------------------------
                // displays data in curriculum page - per course
                //-----------------------------------------------
                if (userId == 0)
                {
                    Log.Error("User:UNKNOWN SESSION called GET_COURSE_STATS function");
                    context.Response.Write("NO_SESSION");
                }
                else
                {
                    Course_BasicInfo_Result res = db.Course_BasicInfo(assignmentId, courseId, userId).FirstOrDefault();
                    context.Response.Write(
                        "{" +
                        @"""startDate"":" + (res.startDate == null ? "null" : @"""" + String.Format("{0:d}", res.startDate) + @"""") + "," +
                        @"""completedDate"":" + (res.completedDate == null ? "null" : "\"" + String.Format("{0:d}", res.completedDate) + @"""") + "," +
                        @"""maxScore"":" + (res.maxScore == null ? "null" : res.maxScore.ToString()) +
                        "}"
                        );
                }
                break;

            case "SCORM_COURSE_INITIAL_DEFAULTS":
                //load all initial scorm values and send to scorm.js manager
                Log.Info("User " + userId + " launched course:" + courseId + ", assignmentId:" + assignmentId);
                db.Course_ScormValueSet(userId, assignmentId, courseId, "SET-STARTDATE", null);     //this forces a set of "startDate" if necessary
                Course_StartupDefaults_Result initInfo = db.Course_StartupDefaults(userId, assignmentId, courseId).FirstOrDefault();

                string suspend_data = initInfo.suspend_data?.Replace("\"", "\\\"");     //encode double quotes
                string total_time   = initInfo.totalTimeUsage == null ? "0000:00:00.00" : String.Format("00{0:%hh}:{0:%mm}:{0:%s}", initInfo.totalTimeUsage);

                context.Response.Write(
                    @"{""cmi"":{" +
                    @"""launch_data"":""""," +
                    @"""interactions"": {""_count"": 0}," +
                    @"""student_data"": {""mastery_score"": """"}," +
                    @"""core"":{" +
                    @"""total_time"":""" + total_time + @"""," +
                    @"""student_id"":" + userId + "," +
                    @"""lesson_mode"":""normal""," +
                    @"""lesson_status"":""" + initInfo.lesson_status + @"""," +
                    @"""lesson_location"":""" + initInfo.lesson_location + @"""," +
                    @"""student_name"":""" + initInfo.student_name + @"""," +
                    @"""score"": {" +
                    @"""raw"":" + (initInfo.maxScore == null ? @"""""" : initInfo.maxScore.ToString()) + "}" +
                    @"}," +
                    @"""suspend_data"":""" + suspend_data + @"""" +
                    "}" +
                    "}"
                    );
                break;

            case "KEEP_SESSION_ALIVE":
                context.Response.ContentType = "text/plain";     //override to plain text
                context.Response.Write("<html>");
                context.Response.Write("<head>");
                context.Response.Write("<meta http-equiv=\"refresh\" content=\"" + context.Request.QueryString["secs"] + "\">");     //every 5 minutes (300 seconds)
                context.Response.Write("<meta http-equiv=\"pragma\"  content=\"no-cache\">");
                context.Response.Write("<meta http-equiv=\"expires\" content=\"0\">");
                context.Response.Write("</head>");
                context.Response.Write("<body></body>");
                context.Response.Write("</html>");
                break;

            case "CMI.INTERACTIONS.0.STUDENT_RESPONSE":
                //THIS MESSAGE IGNORED IN THIS PARTICULAR LMS INSTANCE
                context.Response.Write("{\"result\":true}");
                break;

            case "CMI.CORE.LESSON_STATUS":
                Log.Info("User " + userId + " status set to:\"" + context.Request.Form["data"] + "\", course:" + courseId + ", assignmentId:" + assignmentId);
                if (context.Request.QueryString["dir"] == "set")
                {
                    //allowed values:passed, completed, failed, incomplete, browsed, not attempted
                    int?affected = db.Course_ScormValueSet(userId, assignmentId, courseId, "CMI.CORE.LESSON_STATUS", context.Request.Form["data"]).FirstOrDefault();
                    context.Response.Write(@"{""result"":" + (affected == 1 ? "true" : "false") + "}");
                }
                else
                {
                    context.Response.Write("{\"result\":false}");
                }
                break;

            case "CMI.CORE.LESSON_LOCATION":
                if (context.Request.QueryString["dir"] == "set")
                {
                    int?affected = db.Course_ScormValueSet(userId, assignmentId, courseId, "CMI.CORE.LESSON_LOCATION", context.Request.Form["data"]).FirstOrDefault();
                    context.Response.Write(@"{""result"":" + (affected == 1 ? "true" : "false") + "}");
                }
                else
                {
                    context.Response.Write("{\"result\":false}");
                }
                break;

            case "CMI.SUSPEND_DATA":
                if (context.Request.QueryString["dir"] == "set")
                {
                    int?affected = db.Course_ScormValueSet(userId, assignmentId, courseId, "CMI.SUSPEND_DATA", context.Request.Form["data"]).FirstOrDefault();
                    context.Response.Write(@"{""result"":" + (affected == 1 ? "true" : "false") + "}");
                }
                else
                {
                    context.Response.Write("{\"result\":false}");
                }
                break;

            case "CMI.CORE.SESSION_TIME":
                if (context.Request.QueryString["dir"] == "set")
                {
                    string session_time = context.Request.Form["data"];
                    //NOTE: session time comes in a format like "0000:00:02.75"... 4 digits for hour
                    if (session_time.Length == 0)
                    {
                        session_time = null;
                    }
                    else
                    {
                        //take only the first 99 hours
                        string[] tmp = session_time.Split(':');
                        if (tmp[0].Length == 4)
                        {
                            tmp[0]       = tmp[0].Substring(2);
                            session_time = string.Join(":", tmp);
                        }
                    }
                    int?affected = db.Course_ScormValueSet(userId, assignmentId, courseId, "CMI.CORE.SESSION_TIME", session_time).FirstOrDefault();
                    context.Response.Write(@"{""result"":" + (affected == 1 ? "true" : "false") + "}");
                }
                else
                {
                    context.Response.Write("{\"result\": false}");
                }
                break;

            case "CMI.CORE.SCORE.RAW":
                Log.Info("Score received:\"" + context.Request.Form["data"] + "\" for course id:" + courseId + ", userId:" + userId + ", assignmentId:" + assignmentId);
                if (context.Request.QueryString["dir"] == "set")
                {
                    double?score = Utilities.TryToParseAsDouble(context.Request.Form["data"]);
                    if (score == null)
                    {
                        Log.Info("Score ignored.");
                        context.Response.Write("{\"result\": true}");     //just to keep the course happy
                    }
                    else
                    {
                        int?affected = db.Course_ScormValueSet(userId, assignmentId, courseId, "CMI.CORE.SCORE.RAW", context.Request.Form["data"]).FirstOrDefault();
                        Log.Info("Score saved:\"" + context.Request.Form["data"] + "\" for course id:" + courseId + ", userId:" + userId + ", assignmentId:" + assignmentId + ", records changed=" + affected);
                        context.Response.Write(@"{""result"":" + (affected == 1 ? "true" : "false") + "}");
                    }
                }
                else
                {
                    context.Response.Write("{\"result\":false}");
                }
                break;

            case "CMI.CORE.EXIT":
                context.Response.Write("{\"result\": true}");
                break;

            case "COURSE_LAUNCH_PARAMS":
                Course crs = db.Courses.Where(c => c.courseId == courseId).FirstOrDefault();
                context.Response.Write(
                    "{" +
                    "\"title\":\"" + crs.title + "\"," +
                    "\"url\":\"" + crs.url + "\"," +
                    "\"type\":" + crs.type + "," +
                    "\"width\":" + (crs.browserWidth == null? "null": crs.browserWidth.ToString()) + "," +
                    "\"height\":" + (crs.browserHeight == null ? "null" : crs.browserHeight.ToString()) +
                    "}"
                    );
                break;

            default:
                Log.Info("User:"******" unknown message \"" + context.Request.QueryString["m"] + "\", course:" + courseId + ", assignmentId:" + assignmentId);
                context.Response.Write("{\"result\":false}");
                break;
            }
        }
Ejemplo n.º 6
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string email = Email.Text.Trim();

            if (!Utilities.IsEmailValid(email))
            {
                ErrorMsg.Visible = true;
                ErrorMsg.Text    = GetLocalResourceObject("ErrorInvalidEmail").ToString();
                return;
            }

            //if (CompanyCode.Text.Trim()=="")
            //{
            //    ErrorMsg.Visible = true;
            //    ErrorMsg.Text = GetLocalResourceObject("ErrorNoCompany").ToString();
            //    return;
            //}

            //-------------------------------------------------
            //check company code - must have a valid company ID
            //-------------------------------------------------
            ClientSetting cs = ClientSettings.Get("astellas");

            if (cs == null)
            {
                ErrorMsg.Visible = true;
                ErrorMsg.Text    = GetLocalResourceObject("ErrorInvalidCompany").ToString();
                return;
            }
            else
            {
                if (cs.Enabled)
                {
                    //initialize user's unique connection string (company database)
                    //this should be done 1st before any db-specific call
                    LmsUser.DBConnString = cs.EntityConnStr;
                }
                else
                {
                    ErrorMsg.Visible = true;
                    ErrorMsg.Text    = GetLocalResourceObject("ErrorDisabledCompany").ToString();
                    return;
                }
            }


            lms_Entities     db       = new ClientDBEntities();
            User_Info_Result userInfo = db.User_Info(email).FirstOrDefault();

            if (userInfo == null)
            {
                //no email record found
                ErrorMsg.Visible = true;
                ErrorMsg.Text    = GetLocalResourceObject("ErrorUnknownEmail").ToString();
                Log.Info("Login:\"" + email + "\" invalid email address.");
            }
            else
            {
                //-------------------------------------------------
                // ALL USERS must have an activation code, ie. they
                // have to setup their new personal password
                //-------------------------------------------------
                if (string.IsNullOrEmpty(userInfo.activationCode))
                {
                    // Redirect the user to the access code page.
                    Response.Redirect("AccessCode.aspx?e=" + email + "&c=1");
                }
                else
                {
                    // user has an activation code, check if enabled
                    if (userInfo.enabled)
                    {
                        //user is enabled... check password
                        if (userInfo.password == Pwd.Text)
                        {
                            //password is good.. log user in
                            LmsUser.SetInfo(userInfo.userId, userInfo.firstName, userInfo.lastName, userInfo.role, cs.Name, cs.AssetsFolder);

                            // Write the session data to the log.
                            Log.Info(email + " has logged in. (SessionID=" + Session.SessionID + ")");
                            FormsAuthentication.RedirectFromLoginPage(email, false);
                        }
                        else
                        {
                            ErrorMsg.Visible = true;
                            ErrorMsg.Text    = GetLocalResourceObject("ErrorInvalidPwd").ToString();
                            Log.Info("Login:\"" + email + "\" entered an incorrect password.");
                        }
                    }
                    else
                    {
                        //user account is disabled, so no access given
                        ErrorMsg.Visible = true;
                        ErrorMsg.Text    = GetLocalResourceObject("ErrorDisabledAcct").ToString();
                        Log.Info("Login:\"" + email + "\" account is disabled.");
                    }
                }
            }
        }
        public static string Save(bool isScoreType, decimal?score, string scoreDate, string startDate, string endDate)
        {
            string rowIdStr = Utilities.GetQueryString("rowId");
            int?   rowId    = Utilities.TryToParseAsInt(rowIdStr);

            try
            {
                Courses_Scores cs;
                Courses_Usage  cu;
                lms_Entities   db = new ClientDBEntities();
                if (rowId == null)
                {
                    //this is a new event
                    if (isScoreType)
                    {
                        DateTime?dateStamp;
                        if (scoreDate == "")
                        {
                            dateStamp = DateTime.Now;
                        }
                        else
                        {
                            dateStamp = Utilities.TryToParseAsDateTime(scoreDate);
                            if (dateStamp == null)
                            {
                                return(JsonResponse.Error("Incorrect date/time format entered. Please try again."));
                            }
                            else
                            {
                                cs           = new Courses_Scores();
                                cs.score     = Utilities.TryToParseAsDec(score.ToString()); //clean just in case
                                cs.dateStamp = (DateTime)dateStamp;
                                db.Courses_Scores.Add(cs);
                            }
                        }
                    }
                    else
                    {
                        DateTime?startDateTime = Utilities.TryToParseAsDateTime(startDate);
                        if (startDateTime == null)
                        {
                            return(JsonResponse.Error("Incorrect STARTED date/time format entered. Please try again."));
                        }
                        else
                        {
                            DateTime?endDateTime;
                            if (endDate == "")
                            {
                                endDateTime = null;
                            }
                            else
                            {
                                endDateTime = Utilities.TryToParseAsDateTime(endDate);
                                if (endDateTime == null)
                                {
                                    return(JsonResponse.Error("Incorrect COMPLETED date/time format entered. Please try again."));
                                }
                            }
                            cu = new Courses_Usage();
                            cu.assignmentId = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("aId"));
                            cu.courseId     = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("cId"));
                            cu.userId       = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("uId"));
                            cu.startDate    = (DateTime)startDateTime;
                            cu.endDate      = endDateTime;
                            db.Courses_Usage.Add(cu);
                        }
                    }
                }
                else
                {
                    //this is an update
                    if (isScoreType)
                    {
                        DateTime?dateStamp;
                        if (scoreDate == "")
                        {
                            dateStamp = DateTime.Now;
                        }
                        else
                        {
                            dateStamp = Utilities.TryToParseAsDateTime(scoreDate);
                            if (dateStamp == null)
                            {
                                return(JsonResponse.Error("Incorrect date/time format entered. Please try again."));
                            }
                            else
                            {
                                cs           = db.Courses_Scores.Where(c => c.rowId == rowId).FirstOrDefault();
                                cs.score     = Utilities.TryToParseAsDec(score.ToString());
                                cs.dateStamp = (DateTime)dateStamp;
                            }
                        }
                    }
                    else
                    {
                        DateTime?startDateTime = Utilities.TryToParseAsDateTime(startDate);
                        if (startDateTime == null)
                        {
                            return(JsonResponse.Error("Incorrect STARTED date/time format entered. Please try again."));
                        }
                        else
                        {
                            DateTime?endDateTime;
                            if (endDate == "")
                            {
                                endDateTime = null;
                            }
                            else
                            {
                                endDateTime = Utilities.TryToParseAsDateTime(endDate);
                                if (endDateTime == null)
                                {
                                    return(JsonResponse.Error("Incorrect COMPLETED date/time format entered. Please try again."));
                                }
                            }
                            cu = db.Courses_Usage.Where(c => c.rowId == rowId).FirstOrDefault();
                            cu.assignmentId = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("aId"));
                            cu.courseId     = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("cId"));
                            cu.userId       = (int)Utilities.TryToParseAsInt(Utilities.GetQueryString("uId"));
                            cu.startDate    = (DateTime)startDateTime;
                            cu.endDate      = endDateTime;
                        }
                    }
                }
                db.SaveChanges();
                return(JsonResponse.NoError);
            }
            catch (Exception ex)
            {
                return(JsonResponse.Error(ex));
            }
        }
Ejemplo n.º 8
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!Utilities.IsEmailValid(txtNewEmail.Text))
            {
                ErrorMsg.Text = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorInvalidEmail").ToString();
                return;
            }


            //check company code
            ClientSetting cs = ClientSettings.Get("astellas");

            if (cs == null)
            {
                ErrorMsg.Text = HttpContext.GetLocalResourceObject("~/Login.aspx", "ErrorInvalidCompany").ToString();
                return;
            }
            else
            {
                //initialize user's unique connection string (company database)
                //this should be done 1st before any db-specific call
                LmsUser.DBConnString = cs.EntityConnStr;
            }


            //check if email is already in system
            lms_Entities     db       = new ClientDBEntities();
            User_Info_Result userInfo = db.User_Info(txtNewEmail.Text).FirstOrDefault();

            if (userInfo != null)
            {
                //email record found
                ErrorMsg.Text = GetLocalResourceObject("ErrorEmailExists").ToString();
                return;
            }


            //check if Registration code is valid
            Assignment asg = db.Assignments.Where(a => a.registerCode == txtRegisterCode.Text).SingleOrDefault();

            if (asg == null)
            {
                //unknown registration code
                ErrorMsg.Text = GetLocalResourceObject("ErrorRegCodeNotFound").ToString();
                return;
            }

            int assignmentId = asg.assignmentId;


            //create new user
            User usr = new User
            {
                enabled   = true,
                firstName = txtFName.Text.Trim(),
                lastName  = txtLName.Text.Trim(),
                email     = txtNewEmail.Text.Trim(),
                //mgrEmail = txtMgrEmail.Text,
                title = txtTitle.Text.Trim(),
                //password = txtPwd1.Text,
                role         = (int)Role.Learner,
                organization = ddOrganization.SelectedValue,
                timestamp    = DateTime.Now
            };

            db.Users.Add(usr);
            db.SaveChanges();
            int userId = usr.userId;


            //assign user to this assignment
            db.Assignment_UsersSet(assignmentId, userId.ToString(), true);


            //all done.. redirect to access page
            Response.Redirect("AccessCode.aspx?e=" + usr.email + "&c=1");
        }
Ejemplo n.º 9
0
        public static string SaveUser(
            string fname,
            string lname,
            string title,
            string email,
            string password,
            string organization,
            bool enabled,
            int role,
            string groupIds)
        {
            try
            {
                string uid    = Utilities.GetQueryString("uid");
                int?   userId = Utilities.TryToParseAsInt(uid);

                lms_Entities db = new ClientDBEntities();
                if (userId == null)
                {
                    //this is a new user
                    User newUser = new User
                    {
                        firstName    = fname,
                        lastName     = lname,
                        title        = title,
                        enabled      = enabled,
                        email        = email,
                        role         = role,
                        password     = password,
                        organization = organization,
                        timestamp    = DateTime.Now
                    };
                    db.Users.Add(newUser);
                    db.SaveChanges();
                    userId = newUser.userId;
                }
                else
                {
                    //this is an update
                    User usr = db.Users.Where(u => u.userId == userId).FirstOrDefault();
                    usr.firstName    = fname;
                    usr.lastName     = lname;
                    usr.title        = title;
                    usr.email        = email;
                    usr.enabled      = enabled;
                    usr.role         = role;
                    usr.password     = password;
                    usr.organization = organization;
                    db.SaveChanges();
                }

                //save group assignments
                db.User_GroupsSet(userId, groupIds);

                return(JsonResponse.NoError);
            }
            catch (Exception ex)
            {
                return(JsonResponse.Error(ex));
            }
        }