// 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); } }
internal static System.Data.DataSet ParseDelimitedFile(string textFileName, string delimiter, int numRows) { //verify that file is there. if (!System.IO.File.Exists(textFileName)) { throw new System.IO.FileNotFoundException(); } //Create a new dataset DataSet ds = new DataSet(); //Create a new DataTable inside the dataset DataTable dt = ds.Tables.Add(); //Open text file and read into stream. System.IO.StreamReader sReader = System.IO.File.OpenText(textFileName); //Read the first line into the string string strline = sReader.ReadLine(); // make sure we have a valid file w/data if (strline == null) { throw new System.IO.FileNotFoundException(SharedSupport.GetLocalizedString("User_UploadFileNotFound")); } string[] strArray = strline.Split(delimiter.ToCharArray()); for (int c = 0; c < strArray.Length; c++) { //add a column to the data table dt.Columns.Add(); } //Only grab the number of rows from the parameter passed in. //If numRows = -1 then the function has been overloaded and loop through entire file. //initialize counter int i = 0; while (strline != null && (i < numRows || numRows == -1)) { //Split string into array strArray = strline.Split(delimiter.ToCharArray()); //Create the row System.Data.DataRow dr = dt.NewRow(); for (int c = 0; c < strArray.Length; c++) { dr[c] = strArray[c].Trim(); } //add the row to the table. dt.Rows.Add(dr); //Increment the counter i++; //Read the next line in the file strline = sReader.ReadLine(); strArray = null; } //Close the stream reader for the text file sReader.Close(); //return the created dataset return(ds); }
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); } }
public void SendPasswordToUser() { // use Assignment Manager sysadmin email UserM amsaUser = UserM.Load(Constants.ASSIGNMENTMANAGER_SYSTEM_ADMIN_USERID); string sentByEmail = amsaUser.EmailAddress; string emailSubject = SharedSupport.GetLocalizedString("User_EmailSubject"); string[] replacements = new string[2] { this._username, this._password }; string emailBody = SharedSupport.GetLocalizedString("User_EmailBody", replacements); MessageM.SendMessage(sentByEmail, this._emailAddress, emailSubject, emailBody); }
private string getProjectFile(string projPath) { //grab the project file from the directory passed in if (System.IO.Directory.Exists(projPath)) { string SEARCH_PATTERN = "*.*proj"; string[] projFile = System.IO.Directory.GetFiles(projPath, SEARCH_PATTERN); //return the first project file found. return(projFile[0]); } else { throw new System.IO.DirectoryNotFoundException(SharedSupport.GetLocalizedString("ProjectInfo_DirNotFound") + projPath); } }
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); } }
internal static void SendMessage(string from, string mailTo, string subject, string body) { //this code calls the SendMessage function to send an EMAIL message. try { MailMessage mail = new MailMessage(); mail.From = from; mail.Subject = subject; mail.Body = body; mail.Bcc = mailTo; SmtpMail.Send(mail); } catch (System.Web.HttpException) { throw new System.Exception(SharedSupport.GetLocalizedString("ComposeMessage_SMTPError")); } }
/// <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); } }
// 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); }
/// <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(); } } }
internal void getProjectFileInfo(string fileName, out string name, out string outputFile, out string configurationName, out string buildPath) { EnvDTE._DTE dte = null; EnvDTE.Configuration config = null; string Name, OutputFile, ConfigurationName, BuildPath; buildPath = String.Empty; configurationName = String.Empty; outputFile = String.Empty; name = String.Empty; try { EnvDTE.Project proj = null; EnvDTE.OutputGroup group = null; string outputURLDir, projectFileDir; Object[] OutputFiles = null; Object[] OutputURLs = null; int nIndex; dte = (EnvDTE._DTE) new VisualStudio_DTE_7_1(); dte.Solution.AddFromFile(fileName, false); proj = dte.Solution.Projects.Item(1); Name = proj.Name; config = proj.ConfigurationManager.ActiveConfiguration; ConfigurationName = config.ConfigurationName; // Loop through the possibly-many set of output groups, looking for the // one that has the build output. If we don't can't locate it, we will // attempt to use the first one in the list. nIndex = config.OutputGroups.Count; do { group = config.OutputGroups.Item(nIndex); nIndex--; } while ((nIndex > 0) && (group.CanonicalName != "Built")); OutputFiles = (Object[])group.FileNames; OutputFile = (string)OutputFiles[0]; OutputURLs = (Object[])group.FileURLs; outputURLDir = (string)OutputURLs[0]; // Given a full URL to the file path (file://c:\....) and the base path // to the project file (c:\...), determine the set of additional directories // into which the build is being performed. projectFileDir = getPath(fileName); projectFileDir = projectFileDir.ToUpper(); outputURLDir = outputURLDir.ToUpper(); nIndex = outputURLDir.LastIndexOf(projectFileDir); BuildPath = outputURLDir.Substring(nIndex + projectFileDir.Length); BuildPath = getPath(BuildPath); name = Name; outputFile = OutputFile; configurationName = ConfigurationName; buildPath = BuildPath; } catch (System.Exception) { throw new System.Exception(SharedSupport.GetLocalizedString("ProjectInfo_ProjFileInvalid")); } finally { if (dte != null) { try { dte.Solution.Close(false); dte.Quit(); } catch (System.Exception) { // Ignore errors when shutting down out-of-process IDE. } } } }
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); } }
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); } }
/// <summary> /// Open both files and read the bytes. /// Convert the bytes into strings into strings. /// Compare the strings. /// If the strings are equal, the solution passed. /// If the string are different, the solution failed. /// </summary> /// <param name="outputFile">Professor-defined output file - Student's resulting file should be exactly the same.</param> /// <param name="generatedOutputResultsFile">Student's results file</param> private string compareResults() { try { string actualOutputFileString = String.Empty; //open pre-defined output file into a stream Stream oActualOutputFile = File.OpenRead(actualOutputFileLocation); StreamReader actualFileReader = new StreamReader(oActualOutputFile); actualOutputFileString = actualFileReader.ReadToEnd(); actualFileReader.Close(); string expectedOutputFileString = String.Empty; //open generated output file into a stream Stream oExpectedOutputFile = File.OpenRead(expectedOutputFileLocation); StreamReader expectedFileReader = new StreamReader(oExpectedOutputFile); expectedOutputFileString = expectedFileReader.ReadToEnd(); expectedFileReader.Close(); //build xml string with results string xml = ""; xml += "<?xml version='1.0'?>"; xml += "<GradingResults>"; xml += "<ResultCode>"; if (actualOutputFileString == expectedOutputFileString) { xml += Constants.GRADE_SUCCESSFUL_RESULT_CODE.ToString(); //Successful checkSuccessful = true; } else { xml += Constants.GRADE_FAILED_RESULT_CODE.ToString(); //Failed checkSuccessful = false; } xml += "</ResultCode>"; xml += "<Details>"; xml += "<ExpectedResults><![CDATA["; xml += expectedOutputFileString; xml += "]]></ExpectedResults>"; xml += "<ActualResults><![CDATA["; xml += actualOutputFileString; xml += "]]></ActualResults>"; xml += "</Details>"; xml += "</GradingResults>"; return(xml); } catch { //build xml string with results string xml = ""; xml += "<?xml version='1.0'?>"; xml += "<GradingResults>"; xml += "<ResultCode>"; xml += Constants.GRADE_FAILED_RESULT_CODE.ToString(); //Failed checkSuccessful = false; xml += "</ResultCode>"; xml += "<Details>"; xml += "<ActualResults><![CDATA["; xml += SharedSupport.GetLocalizedString("StudentAssignment_NoExpectedOutputFile_Error"); xml += "]]></ActualResults>"; xml += "</Details>"; xml += "</GradingResults>"; return(xml); } }
public void RunService() { //Create a new Process UserProcess compile = new UserProcess(); try { System.Text.ASCIIEncoding AE = new System.Text.ASCIIEncoding(); byte[] ByteArray = { 34 }; // " string singleQuote = AE.GetString(ByteArray); // path to output file string outputFilePath = SharedSupport.AddBackSlashToDirectory(workingDirectory) + OUTPUT_FILE; if (File.Exists(outputFilePath)) { File.Delete(outputFilePath); } //put quotes around command line arguments to avoid problems with spaces projectFileLocation = "\"" + projectFileLocation + "\""; buildType = "\"" + buildType + "\""; projectName = "\"" + projectName + "\""; //populate the process information compile.StartInfo.WorkingDirectory = workingDirectory; compile.StartInfo.FileName = getDevEnvPath() + DEVENV; compile.StartInfo.Arguments = projectFileLocation + BACKSLASH_BUILD + buildType + BACKSLASH_PROJECT + projectName + BACKSLASH_OUT + OUTPUT_FILE; compile.OutputFile = outputFilePath; compile.StartInfo.RedirectStandardOutput = true; compile.StartInfo.RedirectStandardError = false; compile.StartInfo.UseShellExecute = false; //start the compile process if (!compile.Run(processTime)) { throw new System.Exception(SharedSupport.GetLocalizedString("ServerAction_FailedCreateBuildProcess")); } // if the process exceeds allotted time, kill if (!compile.HasExited) { outputExitCode = Constants.AUTOCOMPILE_RETURN_CODE_FAILURE; buildResults = SharedSupport.GetLocalizedString("StudentAssignment_Killed"); } else { // ok: exited before allotted time outputExitCode = (int)compile.ExitCode; // retrieve outcome from output.log file StreamReader sr = new StreamReader(new FileStream(outputFilePath, FileMode.Open, FileAccess.Read)); buildResults = sr.ReadToEnd(); sr.Close(); } // return compile results (true/false) if (outputExitCode == Constants.AUTOCOMPILE_RETURN_CODE_SUCCESS) { buildSuccessful = true; } } catch (System.Exception ex) { buildResults = ex.Message; buildSuccessful = false; } }
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; } }