Example #1
0
        // reads message off the queue; calls ProcessMessage
        internal void PeekMessage(string mqPath)
        {
            try
            {
                // grab a handle to the queue
                MessageQueue mq = new MessageQueue(mqPath);
                ((XmlMessageFormatter)mq.Formatter).TargetTypeNames = new string[] { "System.String" };

                // receive the next message with a timeout of 30 seconds
                System.Messaging.Message msg = mq.Peek(new TimeSpan(0, 0, 0, Constants.QUEUE_TIMEOUT, 0));

                // save message ID; will remove from queue later if all is successful
                string msgId = msg.Id;

                // log
                SharedSupport.LogMessage(SharedSupport.GetLocalizedString("ServerAction_PeekMessage") + msg.Label + " " + msg.Body);

                // set boolean to remove from queue
                bool removeFromQueue = ProcessMessage(msg.Body.ToString(), msg.Label.ToString());

                // if ProcessMessage true, remove the message from the queue
                if (removeFromQueue == true)
                {
                    mq.ReceiveById(msgId, new TimeSpan(0, 0, 0, Constants.QUEUE_TIMEOUT, 0));

                    // log
                    SharedSupport.LogMessage(SharedSupport.GetLocalizedString("ServerAction_RemoveMessage") + msg.Label + " " + msg.Body);
                }
            }
            catch (System.Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #2
0
        public void StoreResult()
        {
            if (checkSuccessful)
            {
                try
                {
                    // return results of comparision
                    string checkResults = compareResults();

                    //Load checkResults into XMLDom
                    string      element = string.Empty;
                    XmlDocument doc     = new XmlDocument();
                    doc.LoadXml(checkResults);                          //load the string as xml
                    XPathNavigator    nav = ((IXPathNavigable)doc).CreateNavigator();
                    XPathNodeIterator xpni;

                    xpni = nav.Select("/GradingResults/ResultCode");

                    xpni.MoveNext();
                    element = xpni.Current.Value.ToString();
                    studentAssignment.CheckResultCode = element;
                    xpni = nav.Select("/GradingResults/Details/ActualResults");
                    xpni.MoveNext();
                    element = xpni.Current.Value.ToString();
                    if (element != "<![CDATA[]]>")
                    {
                        studentAssignment.CheckDetails = element;
                    }
                    else
                    {
                        studentAssignment.CheckDetails = String.Empty;
                    }

                    if (checkSuccessful)
                    {
                        studentAssignment.AutoGradeStatus = Constants.AUTOGRADE_SUCCESSFUL_STATUS;
                        studentAssignment.CheckResultCode = Constants.GRADE_SUCCESSFUL_RESULT_CODE.ToString();
                    }
                    else
                    {
                        studentAssignment.AutoGradeStatus = Constants.AUTOGRADE_FAILURE_STATUS;
                        studentAssignment.CheckResultCode = Constants.GRADE_FAILED_RESULT_CODE.ToString();
                    }

                    studentAssignment.Update();
                }
                catch (Exception ex)
                {
                    SharedSupport.HandleError(ex);
                }
            }
            else
            {
                studentAssignment.AutoGradeStatus = Constants.AUTOGRADE_FAILURE_STATUS;
                studentAssignment.CheckDetails    = errorString;
                studentAssignment.LastUpdatedDate = System.DateTime.Now;
                studentAssignment.CheckResultCode = Constants.GRADE_FAILED_RESULT_CODE.ToString();
                studentAssignment.Update();
            }
        }
Example #3
0
        private void saveCourseXML()
        {
            string dir = System.Web.HttpContext.Current.Server.MapPath("..\\") + "\\Courses\\";

            try
            {
                //Check to see if folder and file exist
                if (Directory.Exists(dir))
                {
                    // Use the CourseID to create a unique xml filename for the course.
                    string filename = this.CourseID + ".xml";

                    //Create CourseID.xml file
                    System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(dir + filename, null);
                    xmlwriter.Formatting = System.Xml.Formatting.Indented;
                    xmlwriter.WriteStartDocument(false);
                    // xmlwriter.WriteDocType("Course", null, null, null);
                    xmlwriter.WriteStartElement("course");
                    xmlwriter.WriteStartElement("name");
                    if (this.Name != null && this.Name != "")
                    {
                        xmlwriter.WriteCData(this.Name);
                    }
                    xmlwriter.WriteEndElement();
                    xmlwriter.WriteStartElement("assnmgr");
                    xmlwriter.WriteStartElement("amurl");

                    if (SharedSupport.UsingSsl == true)
                    {
                        xmlwriter.WriteCData(@"https://" + SharedSupport.BaseUrl);
                    }
                    else
                    {
                        xmlwriter.WriteCData(@"http://" + SharedSupport.BaseUrl);
                    }

                    xmlwriter.WriteEndElement();
                    xmlwriter.WriteStartElement("guid");
                    xmlwriter.WriteCData(this._courseGUID.ToString());
                    xmlwriter.WriteEndElement();
                    xmlwriter.WriteEndElement();
                    xmlwriter.WriteEndElement();

                    //write the xml to the file and close
                    xmlwriter.Flush();
                    xmlwriter.Close();
                }
                else
                {
                    throw new Exception(SharedSupport.GetLocalizedString("Course_DirectoryDoesNotExist"));                     //"Directory could not be found. " + dir);
                }
            }
            catch (System.Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #4
0
 public void Fill(DataSet ds)
 {
     adap.SelectCommand = cmd;
     try
     {
         adap.Fill(ds);
     }
     catch (System.Exception e)
     {
         SharedSupport.HandleError(e);
     }
 }
        public static void sendEmailMessageToCourse(string subject, string body, string link, int courseId)
        {
            if (!Convert.ToBoolean(SharedSupport.UsingSmtp))
            {
                throw (new System.Exception(SharedSupport.GetLocalizedString("Global_NoSMTP")));
            }

            try
            {
                // validation
                if (body.Equals(String.Empty))
                {
                    throw new  ArgumentException(SharedSupport.GetLocalizedString("SendEmailMessage_InvalidBody"));
                }
                if (subject.Equals(String.Empty))
                {
                    throw new  ArgumentException(SharedSupport.GetLocalizedString("SendEmailMessage_InvalidSubject"));
                }

                string mailTo          = "";
                System.Data.DataSet ds = new System.Data.DataSet();

                //use generic Assignment Manager From
                string sentByEmail = string.Empty;

                UserList ul      = UserList.GetListFromCourse(courseId);
                int[]    userIDs = ul.UserIDList;
                for (int i = 0; i < userIDs.Length; i++)
                {
                    UserM user = UserM.Load(userIDs[i]);
                    mailTo += user.EmailAddress + ";";
                }

                // use Assignment Manager sysadmin email
                UserM amsaUser = UserM.Load(Constants.ASSIGNMENTMANAGER_SYSTEM_ADMIN_USERID);
                sentByEmail = amsaUser.EmailAddress;

                // add the formatting and action link
                body += "\n" + "\n" + link;

                // send email
                SendMessage(sentByEmail, mailTo, subject, body);
            }
            catch (System.Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #6
0
 public void Execute()
 {
     try
     {
         con.Open();
         cmd.ExecuteNonQuery();
     }
     catch (System.Exception e)
     {
         SharedSupport.HandleError(e);
     }
     finally
     {
         con.Close();
     }
 }
Example #7
0
        private void deleteUserAssignmentDetails(int userAssignmentId, int detailType)
        {
            try
            {
                StudentAssignmentM stuAssign = StudentAssignmentM.Load(userAssignmentId);
                stuAssign.BuildDetails      = "";
                stuAssign.BuildResultCode   = "";
                stuAssign.AutoCompileStatus = Constants.AUTOCOMPILE_PENDING_STATUS;

                stuAssign.CheckDetails    = "";
                stuAssign.CheckResultCode = "";
                stuAssign.Update();
            }
            catch (Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #8
0
        /// <summary>
        ///		Create an Xml document represnting the output from the compile.
        /// </summary>
        /// <param name="exitCode"> </param>
        /// <param name="outputFileLocation"> </param>
        private string createBuildXml(int exitCode, string output)
        {
            try
            {
                string xml = "";
                xml += "<?xml version='1.0'?>";
                xml += "<CompileResult>";
                xml += "<ResultCode>" + exitCode + "</ResultCode>";
                xml += "<Details><![CDATA[" + output + "]]></Details>";
                xml += "</CompileResult>";

                return(xml);
            }
            catch (System.Exception ex)
            {
                SharedSupport.HandleError(ex);
                return(String.Empty);
            }
        }
Example #9
0
        public void RetrieveElements()
        {
            try
            {
                sourceLocation      = string.Empty;
                projectFileLocation = string.Empty;
                projectName         = String.Empty;
                processTime         = 0;
                buildType           = String.Empty;
                buildPath           = String.Empty;

                AssignmentM assign = AssignmentM.Load(studentAssignment.AssignmentID);

                sourceLocation = assign.StorageDirectory + studentAssignment.UserID;
                sourceLocation = SharedSupport.AddBackSlashToDirectory(sourceLocation.Trim());

                //Get the allowable time to compile
                processTime = Convert.ToInt32(SharedSupport.GetSetting(Constants.MAX_PROCESS_SETTING));

                // get project file location and project name
                ProjectInfo objPI = new ProjectInfo(sourceLocation);
                projectFileLocation = objPI.ProjectFile.Trim();
                projectName         = objPI.ProjectName.Trim();
                buildType           = objPI.ConfigName.Trim();
                buildPath           = objPI.BuildPath.Trim();

                //Copy UserAssignment files to temp location
                ServerAction.CopyDirectories(sourceLocation, workingDirectory, true, true);

                // get the projectFile from the path
                string projectFile = Path.GetFileName(projectFileLocation);

                // change the projectFileLocation because we copied to the working directory
                projectFileLocation = SharedSupport.AddBackSlashToDirectory(workingDirectory) + projectFile;
            }
            catch (Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
        /// <summary>
        /// Retrieves value from Settings table
        /// </summary>
        /// <param name="settingName"> </param>
        internal static string GetSetting(string settingName)
        {
            try
            {
                // validate parameter
                if (settingName == null || settingName == String.Empty)
                {
                    throw new ArgumentNullException(SharedSupport.GetLocalizedString("SharedSupport_SettingNameField"),
                                                    SharedSupport.GetLocalizedString("SharedSupport_Missing_SettingName"));
                }

                if (settingName.Equals(Constants.AUTOBUILD_SETTING) || settingName.Equals(Constants.AUTOCHECK_SETTING))
                {
                    // query the status of the actual service
                    return(getServiceStatus(Constants.ACTION_SERVICE_NAME));
                }
                else
                {
                    DatabaseCall dbc = new DatabaseCall("Settings_GetSetting", DBCallType.Select);
                    dbc.AddParameter("@Setting", settingName);
                    System.Data.DataSet ds = new System.Data.DataSet();
                    dbc.Fill(ds);
                    try
                    {
                        return(ds.Tables[0].Rows[0]["Value"].ToString().Trim());
                    }
                    catch
                    {
                        return(String.Empty);
                    }
                }
            }
            catch (System.Exception e)
            {
                SharedSupport.HandleError(e);
                return(null);
            }
        }
Example #11
0
        public void RetrieveElements()
        {
            try
            {
                AssignmentM assign = AssignmentM.Load(studentAssignment.AssignmentID);
                processTime = Convert.ToInt32(SharedSupport.GetSetting(Constants.MAX_PROCESS_SETTING));

                // student source location
                sourceLocation = assign.StorageDirectory + studentAssignment.UserID;

                // get compiled file name (already built by build process)
                ProjectInfo objPI = new ProjectInfo(sourceLocation);
                compiledFileName = objPI.OutputFile;

                inputFileLocation          = assign.InputFile;
                expectedOutputFileLocation = assign.OutputFile;
                actualOutputFile           = expectedOutputFileLocation;
                commandLineParams          = assign.CommandLineArgs;

                compiledFileLocation       = SharedSupport.AddBackSlashToDirectory(workingDirectory) + compiledFileName;
                expectedOutputFileLocation = assign.StorageDirectory + expectedOutputFileLocation;

                //change to use inputFileLocation in tempworkarea
                inputFileLocation = SharedSupport.AddBackSlashToDirectory(assign.StorageDirectory) + inputFileLocation;

                //Get the user's submission folder location
                string userSubmissionRootFolder = SharedSupport.AddBackSlashToDirectory(sourceLocation);

                //Copy all files under the student's submission directory, to the working area.
                ServerAction.CopyDirectories(userSubmissionRootFolder, workingDirectory, true, true);
            }
            catch (Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #12
0
        // validates, processes directions inside XML Message; returns true if ok to remove msg from queue
        internal bool ProcessMessage(string message, string label)
        {
            // always return true because always want to remove message from queue in this implementation
            try
            {
                // raise error if no label or message
                label   = label.Trim();
                message = message.Trim();
                if (label.Equals(String.Empty))
                {
                    SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_MissingLabel")));
                }
                if (message.Equals(String.Empty))
                {
                    SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_MissingBody")));
                }

                // xml object declarations
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(message);                   //load the string as xml
                XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();

                // misc vars
                bool   bCheckRequested  = false;                // track if check requested
                bool   bBuildSuccessful = false;                // track if build successful
                int    buildUserAssnId  = 0;                    // build userAssignmentId
                int    checkUserAssnId  = 0;                    // check userAssignmentId
                string buildResults     = string.Empty;         // results of the build
                string checkResults     = string.Empty;         // results of the check
                string workingDirectory = string.Empty;         // working directory

                //-------------------------------------------------------------------------------------------------------------
                // evaluate label, parse xml message; extract instructions
                //-------------------------------------------------------------------------------------------------------------

                switch (label)
                {
                ////////////////////////////////////////////////////////////////
                // This is a submit action
                ////////////////////////////////////////////////////////////////
                case Constants.AM_SUBMIT_ACTION:

                    // select the serverActions
                    XPathNodeIterator serverActionsIterator = nav.Select("serverActions/serverAction");

                    // retrieve all serverAction actions from xml
                    while (serverActionsIterator.MoveNext())
                    {
                        // perform the appropriate action evaluating the serverAction attribute
                        string actionCommand = serverActionsIterator.Current.GetAttribute("name", doc.NamespaceURI).ToString().Trim();
                        switch (actionCommand)
                        {
                        //////////////////////////////////////////////////////////////
                        // AutoBuild
                        /////////////////////////////////////////////////////////////
                        case Constants.AM_BUILD:
                            // grab the userAssignmentId from the xml
                            buildUserAssnId = Convert.ToInt32(serverActionsIterator.Current.Value.ToString());

                            /////////////////////////////////////////////////
                            // extensibility: add custom parameters here
                            /////////////////////////////////////////////////
                            break;

                        /////////////////////////////////////////////////////////////
                        // AutoCheck
                        /////////////////////////////////////////////////////////////
                        case Constants.AM_CHECK:
                            // set check flag
                            bCheckRequested = true;

                            // grab the userAssignmentId from the xml
                            checkUserAssnId = Convert.ToInt32(serverActionsIterator.Current.Value.ToString());

                            /////////////////////////////////////////////////
                            // extensibility: add custom parameters here
                            /////////////////////////////////////////////////
                            break;

                        /////////////////////////////////////////////////
                        // extensibility: add future submit actions here
                        /////////////////////////////////////////////////
                        // 1. load all actions from ServerActions table
                        // 2. loop actions; do any match xml serverAction element?
                        // 3. if so, retrieve parameters from ServerActions
                        // 4. make 'late bound' call to proper class, method
                        /////////////////////////////////////////////////

                        default:
                            break;
                        }
                    }

                    break;

                /////////////////////////////////////////////////
                // extensibility: add future actions here
                /////////////////////////////////////////////////

                default:
                    throw new System.NotImplementedException(SharedSupport.GetLocalizedString("ServerAction_ActionNotImplemented"));
                }

                //-------------------------------------------------------------------------------------------------------------
                // execute instructions from xml message in proper order
                //-------------------------------------------------------------------------------------------------------------
                // perform prep work, execute build, record results; returns true if successful
                // we always do the build: necessary for check and expected by custom actions

                // set the working directory
                workingDirectory = getUserWorkingDirectory();

                ////////////////////////////////////////////
                // Perform AutoBuild
                ////////////////////////////////////////////

                // check to make sure we have a valid userAssignmentId
                if (buildUserAssnId == 0)
                {
                    if (checkUserAssnId == 0)
                    {
                        // raise error
                        SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_MissingUserAssignmentElement")));
                    }
                    else
                    {
                        // set the buildUserAssnId = check
                        buildUserAssnId = checkUserAssnId;
                    }
                }

                // raise error if no buildUserAssnId
                if (buildUserAssnId <= 0)
                {
                    SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_MissingUserAssignmentElement")));
                }

                // raise error if build disabled on the server
                if (!Convert.ToBoolean(SharedSupport.GetSetting(Constants.AUTOBUILD_SETTING)))
                {
                    SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_BuildDisabled")));
                }

                // delete any previous user assignment detail records for this userassignment and detail type
                deleteUserAssignmentDetails(buildUserAssnId, Constants.AUTO_COMPILE_DETAILTYPE);

                bBuildSuccessful = AutoBuild.Run(buildUserAssnId, workingDirectory);

                // was check requested?
                if (bCheckRequested)
                {
                    ////////////////////////////////////////////
                    // Perform AutoCheck
                    ////////////////////////////////////////////

                    // raise error if no checkUserAssnId
                    if (checkUserAssnId <= 0)
                    {
                        SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_MissingUserAssignmentElement")));
                    }

                    // check that checkUserAssnId = buildUserAssnId;
                    if (checkUserAssnId != buildUserAssnId)
                    {
                        // raise error
                        SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_DifferentUserAssignmentIDs")));
                    }
                    else
                    {
                        // did the build execute ok if it was requested?
                        if (bBuildSuccessful)
                        {
                            // raise error if check disabled on the server
                            if (!Convert.ToBoolean(SharedSupport.GetSetting(Constants.AUTOCHECK_SETTING)))
                            {
                                SharedSupport.HandleError(new System.Exception(SharedSupport.GetLocalizedString("ServerAction_CheckDisabled")));
                            }

                            AutoCheck.Run(buildUserAssnId, workingDirectory);
                        }
                    }
                }
                ////////////////////////////////////////////
                // extensibility: CUSTOM ACTIONS
                ////////////////////////////////////////////
            }
            catch (System.Exception ex)
            {
                SharedSupport.LogMessage(ex.Message + " " + SharedSupport.GetLocalizedString("ServerAction_GeneralProcessError") + " " + label + " " + SharedSupport.GetLocalizedString("ServerAction_GeneralProcessErrorBody") + " " + message + " ", SharedSupport.GetLocalizedString("ServerAction_MethodName"), System.Diagnostics.EventLogEntryType.Warning);
            }

            // returning true here ensures message is removed from the queue
            return(true);
        }
Example #13
0
        /// <summary>
        ///		Copies one directory, all files, and all sub directories to another directory.
        /// </summary>
        /// <param name="sourceDirectory">Directory to copy files and sub-directories from. </param>
        /// <param name="destinationDirectory">Directory to copy files and sub-directories to.  </param>
        /// <param name="overwriteFlag">Determines whether or not to overwrite a file if it already exists at the given location</param>
        internal static void CopyDirectories(string sourceDirectory, string destinationDirectory, bool overwriteFlag, bool useImpersonation)
        {
            SecurityACL dacl = null;

            try
            {
                sourceDirectory      = SharedSupport.AddBackSlashToDirectory(sourceDirectory);
                destinationDirectory = SharedSupport.AddBackSlashToDirectory(destinationDirectory);

                if (!Directory.Exists(sourceDirectory))
                {
                    //If the source directory does not exist throw a new error.
                    throw new DirectoryNotFoundException(SharedSupport.GetLocalizedString("StudentAssignment_DirectoryNotFound") + sourceDirectory);
                }
                if (!Directory.Exists(destinationDirectory))
                {
                    if (useImpersonation)
                    {
                        // Impersonate the AM User
                        ImpersonateUser User = null;
                        try
                        {
                            User = new ImpersonateUser();

                            // Login
                            User.Logon();

                            // start impersonating
                            User.Start();

                            //if the destination does not exist, create it.
                            Directory.CreateDirectory(destinationDirectory);
                        }
                        finally
                        {
                            if (User != null)
                            {
                                // stop impersonating
                                User.Stop();

                                User.Dispose();
                            }
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(destinationDirectory);
                    }
                }
                //copy each file in the current directory
                string[] f = Directory.GetFiles(sourceDirectory);
                dacl = new SecurityACL(Constants.AMUserName);
                for (int i = 0; i < f.Length; i++)
                {
                    if (!File.Exists(f[i].ToString()))
                    {
                        throw new FileNotFoundException(sourceDirectory + f[i].ToString());
                    }
                    else
                    {
                        string sourceFile      = sourceDirectory + Path.GetFileName(f[i].ToString());
                        string destinationFile = destinationDirectory + Path.GetFileName(f[i].ToString());
                        File.Copy(sourceFile, destinationFile, overwriteFlag);
                        dacl.ApplyACLToFile(destinationFile);
                    }
                }
                // recursively copy each subdirectory in the current directory
                string[] d = Directory.GetDirectories(sourceDirectory);
                if (d.Length > 0)
                {
                    for (int i = 0; i < d.Length; i++)
                    {
                        string sourceDir = d[i].ToString();
                        string destDir   = destinationDirectory + d[i].ToString().Replace(sourceDirectory, String.Empty);

                        if (!Directory.Exists(destDir))
                        {
                            if (useImpersonation)
                            {
                                // Impersonate the AM User
                                ImpersonateUser User = null;
                                try
                                {
                                    User = new ImpersonateUser();

                                    // Login
                                    User.Logon();

                                    // start impersonating
                                    User.Start();

                                    //if the destination does not exist, create it.
                                    Directory.CreateDirectory(destDir);
                                }
                                finally
                                {
                                    if (User != null)
                                    {
                                        // stop impersonating
                                        User.Stop();
                                        User.Dispose();
                                    }
                                }
                            }
                            else
                            {
                                Directory.CreateDirectory(destDir);
                            }
                        }
                        ServerAction.CopyDirectories(sourceDir, destDir, overwriteFlag, useImpersonation);
                    }
                }
            }
            catch (Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
            finally
            {
                if (dacl != null)
                {
                    dacl.Dispose();
                }
            }
        }
Example #14
0
        internal void SendActionToQueue(bool build, bool check)
        {
            try
            {
                // at least one action must be true
                if (!build && !check)
                {
                    throw new ApplicationException(SharedSupport.GetLocalizedString("StudentAssignment_Must_Choose_Action"));
                }

                // validate userAssignmentId
                if (_userAssignmentID <= 0)
                {
                    throw new ApplicationException(SharedSupport.GetLocalizedString("StudentAssignment_InvalidUserAssignmentId"));
                }

                // generate the xml
                System.IO.MemoryStream   ms        = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.ASCII);
                xmlwriter.Formatting = System.Xml.Formatting.Indented;
                xmlwriter.WriteStartDocument(false);
                xmlwriter.WriteStartElement("serverActions");

                // build requested?
                if (build)
                {
                    // update auto build status - set to pending
                    this._autoCompileStatus = Constants.AUTOCOMPILE_PENDING_STATUS;
                }

                // include serverAction element for auto build
                xmlwriter.WriteStartElement("serverAction");
                xmlwriter.WriteAttributeString("name", "AutoBuild");
                xmlwriter.WriteElementString("userAssignmentID", this.UserAssignmentID.ToString());
                xmlwriter.WriteEndElement();

                // check requested?
                if (check)
                {
                    // update auto check status - set to pending
                    this._autoGradeStatus = Constants.AUTOGRADE_PENDING_STATUS;

                    // include serverAction element for auto build
                    xmlwriter.WriteStartElement("serverAction");
                    xmlwriter.WriteAttributeString("name", "AutoCheck");
                    xmlwriter.WriteElementString("userAssignmentID", this.UserAssignmentID.ToString());
                    xmlwriter.WriteEndElement();
                }

                xmlwriter.WriteEndElement();
                xmlwriter.Flush();

                //read all of the stream and convert to a string
                string msg = System.Text.Encoding.ASCII.GetString(ms.GetBuffer());

                // close
                xmlwriter.Close();
                ms.Close();

                try
                {
                    SharedSupport.SendMessageToQueue(Constants.ACTION_QUEUE_PATH, Constants.ACTION_QUEUE_NAME, Constants.AM_SUBMIT_ACTION, msg);
                }
                catch (Exception e)
                {
                    SharedSupport.HandleError(e, "ServerAction_InvalidQueue");
                }

                // update the status of the userAssignments
                this.LastUpdatedDate = DateTime.Now;
                this.Update();
            }
            catch (Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
        }
Example #15
0
        public void RunService()
        {
            //Spawn new process - invoking the compiledFile
            UserProcess oProcess = new UserProcess();

            try
            {
                // set actual output file location
                actualOutputFileLocation = workingDirectory + actualOutputFile;

                //Set process start parameters
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.Arguments              = commandLineParams;
                psi.FileName               = compiledFileName;
                psi.WorkingDirectory       = workingDirectory;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError  = false;
                psi.UseShellExecute        = false;

                if (File.Exists(inputFileLocation))
                {
                    oProcess.InputFile = workingDirectory + Guid.NewGuid() + ".txt";
                    File.Copy(inputFileLocation, oProcess.InputFile, true);
                    psi.RedirectStandardInput = true;
                    try
                    {
                        SecurityACL dacl = new SecurityACL(Constants.AMUserName);
                        dacl.ApplyACLToFile(oProcess.InputFile);
                    }
                    catch (Exception)
                    {
                        // Continue on.  If we fail to apply the ACL, we may still be able
                        // to autocheck (i.e. if user has set custom permissions.
                    }
                }

                oProcess.StartInfo  = psi;
                oProcess.OutputFile = actualOutputFileLocation;

                //Log start
                SharedSupport.LogMessage(SharedSupport.GetLocalizedString("StudentAssignment_CheckStart"));

                if (!oProcess.Run(processTime))
                {
                    throw new System.Exception(SharedSupport.GetLocalizedString("ServerAction_FailedCreateTestProcess"));
                }

                //wait to see if process comes back in time.  Otherwise if it runs too long - kill it
                if (!oProcess.HasExited)
                {
                    SharedSupport.LogMessage(SharedSupport.GetLocalizedString("StudentAssignment_CheckKilled"));
                    throw new System.Exception(SharedSupport.GetLocalizedString("StudentAssignemtn_CheckExceededProcessTime"));
                }
                else
                {
                    SharedSupport.LogMessage(SharedSupport.GetLocalizedString("StudentAssignment_CheckEnd"));
                }
            }
            catch (Exception ex)
            {
                checkSuccessful = false;
                errorString     = ex.Message;
                SharedSupport.HandleError(ex);
            }
        }
        public void SendNotifications(object sender, System.Timers.ElapsedEventArgs args)
        {
            // disable the timer
            timer.Enabled = false;

            try
            {
                // use Assignment Manager sysadmin email
                UserM  amsaUser    = UserM.Load(Constants.ASSIGNMENTMANAGER_SYSTEM_ADMIN_USERID);
                string sentByEmail = amsaUser.EmailAddress;

                System.Data.DataSet dsAssignmentList = new System.Data.DataSet();
                DatabaseCall        dbc = new DatabaseCall("Notifications_GetAssignmentList", DBCallType.Select);
                dbc.Fill(dsAssignmentList);
                if (dsAssignmentList.Tables[0].Rows.Count <= 0)
                {
                    return;
                }

                for (int j = 0; j < dsAssignmentList.Tables[0].Rows.Count; j++)
                {
                    int assignmentID = Convert.ToInt32(dsAssignmentList.Tables[0].Rows[j]["AssignmentID"]);
                    // send the notifications
                    try
                    {
                        //////////////////////////////////////////////////////////////////////
                        /// Past Due Notifications
                        //////////////////////////////////////////////////////////////////////
                        System.Data.DataSet ds = new System.Data.DataSet();
                        dbc = new DatabaseCall("Notifications_BrowsePastDueNotifications", DBCallType.Select);
                        dbc.AddParameter("AssignmentID", assignmentID);
                        dbc.Fill(ds);

                        if (ds.Tables[0].Rows.Count <= 0)
                        {
                            continue;
                        }

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["AssignmentID"] != DBNull.Value)
                            {
                                string   assignName     = ds.Tables[0].Rows[i]["ShortName"].ToString();
                                DateTime dueDate        = Convert.ToDateTime(ds.Tables[0].Rows[i]["DueDate"]);
                                string[] AssignmentInfo = new string[] { assignName, string.Format("{0:d}", dueDate) };

                                string pastDueSubject  = SharedSupport.GetLocalizedString("Notification_PastDueSubject", AssignmentInfo);
                                string pastDueBody     = SharedSupport.GetLocalizedString("Notification_PastDueBody", AssignmentInfo);
                                string reminderSubject = SharedSupport.GetLocalizedString("Notification_ReminderSubject", AssignmentInfo);
                                string reminderBody    = SharedSupport.GetLocalizedString("Notification_ReminderBody", AssignmentInfo);

                                TimeSpan difference = dueDate - DateTime.Today;
                                if (Convert.ToBoolean(ds.Tables[0].Rows[i]["SendPastDue"]) &&
                                    (difference.Days == -1 * Convert.ToInt32(ds.Tables[0].Rows[i]["PastDueWarningDays"])))
                                {
                                    UserM user = UserM.Load(Convert.ToInt32(ds.Tables[0].Rows[i]["UserID"]));
                                    MessageM.SendMessage(sentByEmail, user.EmailAddress, pastDueSubject, pastDueBody);
                                }

                                if (Convert.ToBoolean(ds.Tables[0].Rows[i]["SendReminders"]) &&
                                    (difference.Days == Convert.ToInt32(ds.Tables[0].Rows[i]["ReminderWarningDays"])))
                                {
                                    UserM user = UserM.Load(Convert.ToInt32(ds.Tables[0].Rows[i]["UserID"]));
                                    MessageM.SendMessage(sentByEmail, user.EmailAddress, reminderSubject, reminderBody);
                                }
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        SharedSupport.HandleError(ex);
                    }
                }
            }
            catch (System.Exception ex)
            {
                SharedSupport.HandleError(ex);
            }
            finally
            {
                // reset the interval for the next event
                timer.Interval = millisecondsToMidnight();

                // re-enable the timer
                timer.Enabled = true;
            }
        }