public List <string> Validate(string path, ref int countCourses, ref int countValidCourses, ref int countInvalidCourses)
        {
            List <string> messages = new List <string>();

            var pathToExtract = Path.Combine(GetFolderPath(), Guid.NewGuid().ToString());

            Zipper.ExtractZipFile(path, pathToExtract);

            if (Directory.GetFiles(pathToExtract, "*.disc").Count() == 0)
            {
                messages.Add("Archive doesn't contain file with .disc extension");
            }

            string[] files = Directory.GetFiles(pathToExtract, "*.zip");
            countCourses = files.Count();

            foreach (var courseFile in files)
            {
                List <string> courseMessages = PackageValidator.Validate(courseFile);
                messages.AddRange(courseMessages.AsEnumerable());

                if (courseMessages.Contains("Package is valid."))
                {
                    countValidCourses++;
                }
                else
                {
                    countInvalidCourses++;
                }
            }

            Directory.Delete(pathToExtract, true);

            return(messages);
        }
        void ValidatePackage()
        {
            PackageDetails details = store.LoadPackageFromStore(Location);

            if (details != null)
            {
                Warnings = details.Warnings;
                Id       = details.PackageId;
            }
            else
            {
                PackageValidatorSettings settings = new PackageValidatorSettings(ValidationBehavior.LogWarning, ValidationBehavior.None, ValidationBehavior.Enforce, ValidationBehavior.LogWarning);
                ValidationResults        log      = PackageValidator.Validate(reader, settings);
                if (log.HasErrors)
                {
                    // Shouldn't have any since enforcing errors.
                    throw new SafeToDisplayException(log, culture.Format(culture.Resources.PackageNotValid, string.Empty));
                }
                else if (log.HasWarnings)
                {
                    using (System.Xml.XmlReader xmlLog = log.ToXml())
                    {
                        Warnings = LearningStoreXml.CreateAndLoad(xmlLog);
                    }
                }
            }
        }
        public bool Validate(HttpPostedFileBase file)
        {
            var fileName = GetImportFileName(Path.GetFileNameWithoutExtension(file.FileName));
            var path     = Path.Combine(GetFolderPath(), fileName);

            Directory.CreateDirectory(GetFolderPath());
            file.SaveAs(path);
            var pathToExtract = Path.Combine(GetFolderPath(), Guid.NewGuid().ToString());

            Zipper.ExtractZipFile(path, pathToExtract);

            if (Directory.GetFiles(pathToExtract, "*.disc").Count() == 0)
            {
                Directory.Delete(pathToExtract, true);
                return(false);
            }

            foreach (var courseFile in Directory.GetFiles(pathToExtract, "*.zip"))
            {
                if (!PackageValidator.Validate(courseFile).Contains("Package is valid."))
                {
                    Directory.Delete(pathToExtract, true);
                    return(false);
                }
            }

            Directory.Delete(pathToExtract, true);
            return(true);
        }
示例#4
0
        public void PackageValidatorInvalidPackageTest()
        {
            var  path = Path.Combine(this.root, @"Invalid package.zip");
            bool valid;
            var  res = PackageValidator.Validate(path, out valid);

            Assert.IsTrue(res.Count == 6);
        }
示例#5
0
        public void PackageValidatorValidPackageTest()
        {
            //path to file which we want to validate
            var  path = Path.Combine(this.root, @"Valid package.zip");
            bool valid;
            var  res = PackageValidator.Validate(path, out valid);

            Assert.IsTrue(res.Count == 1);
        }
        public bool Validate(string path)
        {
            var pathToExtract = Path.Combine(GetFolderPath(), Guid.NewGuid().ToString());

            Zipper.ExtractZipFile(path, pathToExtract);

            if (Directory.GetFiles(pathToExtract, "*.disc").Count() == 0)
            {
                Directory.Delete(pathToExtract, true);
                return(false);
            }

            foreach (var courseFile in Directory.GetFiles(pathToExtract, "*.zip"))
            {
                if (!PackageValidator.Validate(courseFile).Contains("Package is valid."))
                {
                    Directory.Delete(pathToExtract, true);
                    return(false);
                }
            }

            Directory.Delete(pathToExtract, true);
            return(true);
        }
示例#7
0
    public static void RunProgram(string classWebUrl)
    {
        Stack <IDisposable> disposer = new Stack <IDisposable>();

        try
        {
            // "log in" to SLK as the current user, and set <memberships> to information about
            // the instructors and learners in the class Web site (i.e. the SPWeb with URL
            // <classWebUrl>)
            SPSite spSite = new SPSite(classWebUrl);
            disposer.Push(spSite);
            SPWeb spWeb = spSite.OpenWeb();
            disposer.Push(spWeb);
            SlkStore       slkStore    = SlkStore.GetStore(spWeb);
            SlkMemberships memberships = slkStore.GetMemberships(spWeb, null, null);

            // make sure there's at least one instructor and one learner on the class Web; these
            // roles are defined by the "SLK Instructor" and "SLK Learner" permissions (as defined
            // in the SharePoint Learning Kit configuration page in SharePoint Central
            // Administration)
            if (memberships.Instructors.Count == 0)
            {
                throw new Exception("Class Web must have at least one instructor");
            }
            if (memberships.Learners.Count == 0)
            {
                throw new Exception("Class Web must have at least one learner");
            }

            // arbitrarily choose the first instructor in the class as the user who will create
            // the assignments
            SlkUser primaryInstructor = memberships.Instructors[0];

            // set <classWeb> to the SPWeb of the SharePoint Web site that the new assignment will
            // be associated with; "log into" this Web site as the instructor retrieved above
            SPSite classSite = new SPSite(classWebUrl, primaryInstructor.SPUser.UserToken);
            disposer.Push(classSite);
            SPWeb classWeb = classSite.OpenWeb();
            disposer.Push(classWeb);

            // set <slkStore> to the SharePoint Learning Kit store associated with the SPSite of
            // <classWeb>
            slkStore = SlkStore.GetStore(classWeb);

            // set <packageLocations> to the SharePointPackageStore-format location strings
            // corresponding to each element of <PackageUrls>; "log into" these Web sites as the
            // instructor retrieved above
            string[] packageLocations = new string[PackageUrls.Length];
            for (int packageIndex = 0; packageIndex < packageLocations.Length; packageIndex++)
            {
                // set <packageWeb> to the SPWeb of the SharePoint Web site containing the package
                // or document to assign
                string packageUrl  = PackageUrls[packageIndex];
                SPSite packageSite = new SPSite(packageUrl, primaryInstructor.SPUser.UserToken);
                disposer.Push(packageSite);
                SPWeb packageWeb = packageSite.OpenWeb();
                disposer.Push(packageWeb);

                // set <spFile> to the SPFile of the package or document to assign
                SPFile spFile = packageWeb.GetFile(packageUrl);

                // set the current element of <packageLocation> to the SharePointPackageStore
                // format location string that uniquely identifies the current version of the
                // <spFile>
                packageLocations[packageIndex] = new SharePointFileLocation(
                    packageWeb, spFile.UniqueId, spFile.UIVersion).ToString();
            }

            // create a random number generator
            s_random = new Random(RandomNumberSeed);

            // set <maxNumberOfLearners> to the number of learners in the class
            int maxNumberOfLearners = memberships.Learners.Count;

            // set <learners> to an array of learners of this class; for each assignment, we'll
            // shuffle this array and choose a subset to be learners on the assignment
            SlkUser[] learners = new SlkUser[memberships.Learners.Count];
            memberships.Learners.CopyTo(learners, 0);

            // display table header
            Console.WriteLine("Assign. No. of    Due       Not");
            Console.WriteLine("ID      Learners  Date      Started Active Completed Final");
            Console.WriteLine("----------------------------------------------------------");

            // create assignments as specified by the constants at the top of this source file
            for (int assignmentIndex = 0; assignmentIndex < NumberOfAssignments; assignmentIndex++)
            {
                // set <fraction> to be proportional to <assignmentIndex>, between 0.0 and 1.0
                double fraction = (double)assignmentIndex / NumberOfAssignments;

                // randomly choose an e-learning package or non-e-learning document to be assigned
                string packageLocation = packageLocations[s_random.Next(0, PackageUrls.Length)];

                // get some information about the package/document; set <isNonELearning> to true if
                // if it's a non-e-learning document; NOTE: this is oversimplified code -- proper
                // production code should handle error conditions more carefully
                SPFile spFile = SlkUtilities.GetSPFileFromPackageLocation(packageLocation);
                bool   isNonELearning;
                SharePointFileLocation spFileLocation;
                SharePointFileLocation.TryParse(packageLocation, out spFileLocation);
                using (SharePointPackageReader spPackageReader =
                           new SharePointPackageReader(slkStore.SharePointCacheSettings, spFileLocation))
                {
                    isNonELearning = PackageValidator.Validate(spPackageReader).HasErrors;
                }

                // set <assignmentProperties> to the default assignment properties for the package
                // or document being assigned; some of these properties will be overridden below
                LearningStoreXml packageWarnings;
                int?organizationIndex = (isNonELearning ? (int?)null : 0);
                AssignmentProperties assignmentProperties =
                    slkStore.GetNewAssignmentDefaultProperties(
                        classWeb, packageLocation, organizationIndex, SlkRole.Instructor,
                        out packageWarnings);

                // randomly generate a title for the assignment
                assignmentProperties.Title = CreateRandomTitle();

                // set the due date of the assignment based on <fraction>,
                // <OldestAssignmentDaysAgo>, and <NewestAssignmentDaysFromNow>
                assignmentProperties.DueDate = DateTime.Now.AddDays(
                    (OldestAssignmentDaysAgo + NewestAssignmentDaysFromNow)
                    * fraction - OldestAssignmentDaysAgo);

                // set the start date of the assignment to be a day earlier than the earliest
                // due date
                assignmentProperties.StartDate = DateTime.Today.AddDays(
                    -OldestAssignmentDaysAgo - 1);

                // randomly set Points Possible
                if ((assignmentProperties.PointsPossible == null) &&
                    (s_random.NextDouble() > FractionOfBlankPointsPossible))
                {
                    const int divideBy = 4;
                    const int maxValue = 100;
                    assignmentProperties.PointsPossible = (float)Math.Round(
                        s_random.NextDouble() * divideBy * maxValue) / maxValue;
                }

                // make all instructors of this class (i.e. all SharePoint users that have the SLK
                // Instructor permission) be instructors on this assignment
                assignmentProperties.Instructors.Clear();
                foreach (SlkUser slkUser in memberships.Instructors)
                {
                    assignmentProperties.Instructors.Add(slkUser);
                }

                // shuffle <learners>
                for (int learnerIndex = 0; learnerIndex < learners.Length; learnerIndex++)
                {
                    int     otherLearnerIndex = s_random.Next(0, learners.Length);
                    SlkUser temp = learners[learnerIndex];
                    learners[learnerIndex]      = learners[otherLearnerIndex];
                    learners[otherLearnerIndex] = temp;
                }

                // randomly choose a number of learners for this assignment
                int numberOfLearners = s_random.Next(
                    Math.Min(maxNumberOfLearners, MinLearnersPerAssignment),
                    maxNumberOfLearners + 1);

                // copy the first <numberOfLearners> learners to <assignmentProperties>
                assignmentProperties.Learners.Clear();
                for (int learnerIndex = 0; learnerIndex < numberOfLearners; learnerIndex++)
                {
                    assignmentProperties.Learners.Add(learners[learnerIndex]);
                }

                // create the assignment
                AssignmentItemIdentifier assignmentId = slkStore.CreateAssignment(classWeb,
                                                                                  packageLocation, organizationIndex, SlkRole.Instructor, assignmentProperties);

                // set <gradingPropertiesList> to information about the learner assignments of the
                // new assignment; in particular, we need the learner assignment IDs
                AssignmentProperties basicAssignmentProperties;
                ReadOnlyCollection <GradingProperties> gradingPropertiesList =
                    slkStore.GetGradingProperties(assignmentId, out basicAssignmentProperties);

                // adjust the status of each learner assignment of this assignment according to
                // the rules specified in constants at the top of this source file
                int[] newStatusCount = new int[(int)LearnerAssignmentState.Final + 1];
                for (int learnerIndex = 0;
                     learnerIndex < gradingPropertiesList.Count;
                     learnerIndex++)
                {
                    // set <gradingProperties> to information about this learner assignment
                    GradingProperties gradingProperties = gradingPropertiesList[learnerIndex];

                    // set <newStatus> to the new status of the assignment, applying the rules
                    // specified in constants at the top of this source file
                    if (fraction > 1 - FractionOfAssignmentsNotStarted)
                    {
                        gradingProperties.Status = LearnerAssignmentState.NotStarted;
                    }
                    else
                    if (fraction < FractionOfAssignmentsAllFinal)
                    {
                        gradingProperties.Status = LearnerAssignmentState.Final;
                    }
                    else
                    {
                        gradingProperties.Status = (LearnerAssignmentState)
                                                   s_random.Next(0, (int)LearnerAssignmentState.Final + 1);
                    }

                    // if we're transitioning learner assignment to Final state, optionally
                    // assign a final points value
                    if ((gradingProperties.Status == LearnerAssignmentState.Final) &&
                        (assignmentProperties.PointsPossible != null))
                    {
                        if (s_random.NextDouble() < FractionOfOverriddenFinalPoints)
                        {
                            const int divideBy = 4;
                            gradingProperties.FinalPoints = (float)Math.Round(
                                s_random.NextDouble() * divideBy *
                                assignmentProperties.PointsPossible.Value) / divideBy;
                        }
                    }

                    // update statistics
                    newStatusCount[(int)gradingProperties.Status]++;
                }

                // save changes to the assignment
                string warnings = slkStore.SetGradingProperties(assignmentId,
                                                                gradingPropertiesList);
                Debug.Assert(warnings == null, warnings);

                // display feedback
                Console.WriteLine("{0,-8}{1,-10}{2,-10:d}{3,-8}{4,-7}{5,-10}{6,-6}",
                                  assignmentId.GetKey(), assignmentProperties.Learners.Count,
                                  assignmentProperties.DueDate, newStatusCount[0], newStatusCount[1],
                                  newStatusCount[2], newStatusCount[3]);
            }
        }
        finally
        {
            // dispose of objects used by this method
            while (disposer.Count > 0)
            {
                disposer.Pop().Dispose();
            }
        }
    }
示例#8
0
        public PackageRoutes(
            IPackageService packageSvc,
            PackageValidator validator,
            IQueueService queueSvc)
            : base("v1")
        {
            this.RequiresAuthentication();
            this.packageSvc = packageSvc;
            this.queueSvc   = queueSvc;

            #region POST
            Post("/package", _ =>
            {
                try
                {
                    this.RequiresClaims(c => c.Type == HttpMethod.Post.Verb());

                    // Bind POST request to data contract
                    var request = this.Bind <PackageRequest>();

                    // Translate data contract to business model
                    var pkgBusiness = Mapper.Map <Package>(request);

                    // Verify if there are any validation errors. If so, return error
                    List <ValidationResult> results = new List <ValidationResult>();
                    results.Add(validator.Validate(pkgBusiness, ruleSet: PackageValidatorRuleSet.PostPackage.ToString()));
                    if (results.Where(c => (!c.IsValid)).Count() > 0)
                    {
                        // Return status
                        return(Negotiate.WithModel(results.Where(c => (!c.IsValid))

                                                   .Select(c => c.Errors.Select(d => d.ErrorMessage)))
                               .WithStatusCode(HttpStatusCode.BadRequest));
                    }

                    // Save package
                    var savedPkg = packageSvc.SavePackage(pkgBusiness);

                    // Send notification to subscribed queues
                    DeterminePackageReset(pkgBusiness);

                    // Return response
                    return(Mapper.Map <PackageRequest>(savedPkg));
                }
                catch (Exception e)
                {
                    throw e;
                }
            });
            #endregion

            #region Delete
            Delete("/package", _ =>
            {
                this.RequiresClaims(c => c.Type == HttpMethod.Delete.Verb());
                var request = this.Bind <PackageRequest>();

                // Translate data contract to package business model
                var pkg = Mapper.Map <Package>(request);

                // validate
                List <ValidationResult> results = new List <ValidationResult>();
                results.Add(validator.Validate(pkg, ruleSet: PackageValidatorRuleSet.DeletePackage.ToString()));

                // Verify if there are any validation errors. If so, return error
                if (results.Where(c => (!c.IsValid)).Count() > 0)
                {
                    // Return status
                    return(Negotiate.WithModel(results.Where(c => (!c.IsValid))
                                               .Select(c => c.Errors.Select(d => d.ErrorMessage)))
                           .WithStatusCode(HttpStatusCode.BadRequest));
                }

                if (packageSvc.Delete(ref pkg))
                {
                    DeterminePackageReset(pkg);
                    return(new
                    {
                        Message = "Package deleted successfully"
                    });
                }
                else
                {
                    return(Negotiate.WithModel("Package with provided data was not found.")
                           .WithStatusCode(HttpStatusCode.BadRequest));
                }
            });
            #endregion
        }
        /// <summary>
        /// Validate the package selected by the user.
        /// </summary>
        ///
        void ValidateSelectedPackage()
        {
            // do nothing if no package is selected
            if (packageListBox.SelectedIndex < 0)
            {
                return;
            }

            // execute the remainder of this method with a wait cursor displayed
            Cursor = Cursors.WaitCursor;
            try
            {
                // set <filePath> to the path to the package the user selected
                FileListItem fileListItem = (FileListItem)packageListBox.SelectedItem;
                string       filePath     = fileListItem.FilePath;

                // empty <logTextBox>, and add the file name
                logTextBox.Clear();
                logTextBox.AppendText(String.Format("Validating: {0}\r\n\r\n", filePath));

                // validate the package
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    bool anyMessages = false;
                    using (PackageReader packageReader = PackageReader.Create(stream))
                    {
                        // set package validator settings based on the setting of the <additionalScormWarningsCheckBox> control
                        PackageValidatorSettings settings;
                        if (additionalScormWarningsCheckBox.Checked)
                        {
                            // perform the same validation as SLK, plus look for additional SCORM issues
                            settings = new PackageValidatorSettings(
                                ValidationBehavior.LogWarning, ValidationBehavior.LogWarning,
                                ValidationBehavior.LogError, ValidationBehavior.LogWarning);
                        }
                        else
                        {
                            // perform the same validation as SLK
                            settings = new PackageValidatorSettings(
                                ValidationBehavior.LogWarning, ValidationBehavior.None,
                                ValidationBehavior.LogError, ValidationBehavior.LogWarning);
                        }

                        // validate the package; set <results> to the list of results
                        ValidationResults results;
                        try
                        {
                            results = PackageValidator.Validate(packageReader, settings);
                        }
                        catch (InvalidPackageException ex)
                        {
                            logTextBox.AppendText(String.Format("Package is invalid.\r\n\r\n{0}", ex.Message));
                            return;
                        }

                        // display <results>
                        foreach (ValidationResult result in results.Results)
                        {
                            string message;
                            if (result.IsError)
                            {
                                message = String.Format("MLC Error: {0}\r\n\r\n", result.Message);
                            }
                            else
                            {
                                message = String.Format("SCORM Warning: {0}\r\n\r\n", result.Message);
                            }
                            logTextBox.AppendText(message);
                            anyMessages = true;
                        }
                    }

                    // if there were no messages, give feedback to that effect to the user
                    if (!anyMessages)
                    {
                        logTextBox.AppendText("Package is valid.");
                    }
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }