示例#1
0
        public FileContentResult BuildPDFReport(int?formResultId = null)
        {
            Debug.WriteLine("* * *  COADAPController:BuildPDFReport method  * * *");
            if (!SessionHelper.IsUserLoggedIn)
            {
                string msg = "User not logged into application.";
                // byte[] emptyFile = new byte[] {0x20, 0x00};
                return(new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html"));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            if (formResultId == null)
            {
                formResultId = SessionHelper.SessionForm.formResultId;
            }

            try
            {
                AccessLogging.InsertAccessLogRecord(formsRepo, formResultId.Value, (int)AccessLogging.accessLogFunctions.REPORT, "Generated Report");
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("Access Logging error: " + xcptn.Message);
                mLogger.Error("Access Logging error: " + xcptn.Message);
            }

            string outpath             = ControllerContext.HttpContext.Server.MapPath("../Content/report_" + System.DateTime.Now.Ticks + ".pdf");
            FormResultPdfReport report = new AdapPdfReport(formsRepo, formResultId.Value, outpath, false);

            report.BuildReport();

            //output to file locally, and stream to end-user
            FileContentResult result;

            try
            {
                report.outputToFile();
                result = File(System.IO.File.ReadAllBytes(outpath), "application/pdf", "report.pdf");
                System.IO.File.Delete(outpath);
            }
            catch (Exception xcptn)
            {
                string msg = "Build Report output failed.  Exception: " + xcptn.Message;
                mLogger.Error(msg);
                result = new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html");
            }

            return(result);
        }
示例#2
0
        public ContentResult UploadFormResultsJSON()
        {
            //use session variables to pick a FormResults object from the database
            string formId = Request["formId"] as string;

            Debug.WriteLine("* * *  GetFormResultsJSON formId: " + formId);
            Session["formId"] = formId;
            int iFormId = Convert.ToInt32(formId);

            string formResultId = Request["formResultId"] as string;

            Debug.WriteLine("* * *  GetFormResultsJSON formResultId: " + formId);
            Session["formResultId"] = formResultId;
            int frmRsltId = Convert.ToInt32(formResultId);

            formsEntities db = DataContext.GetDbContext();

            db.Configuration.LazyLoadingEnabled = false;

            def_FormResults frmRslt = db.def_FormResults.Where(fr => fr.formId == iFormId).Include(fr => fr.def_ItemResults.Select(r => r.def_ResponseVariables)).First(fr => fr.formResultId == frmRsltId);

            string jsonString = fastJSON.JSON.ToJSON(frmRslt);

            //write json string to file, then stream it out
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FormResultJSON));
            string       outpath      = ControllerContext.HttpContext.Server.MapPath("../Content/formResults_" + System.DateTime.Now.Ticks + ".json");
            FileStream   stream       = new FileStream(outpath, FileMode.CreateNew);
            StreamWriter streamWriter = new StreamWriter(stream);

            streamWriter.Write(jsonString);
            streamWriter.Close();
            stream.Close();

            //used localhost for testing, should be changed to master server url
            // string url = "http://localhost:50209";
            string url = ConfigurationManager.AppSettings["SISOnlineURL"];

            //upload to master server
            string result;

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var data = "json=" + System.IO.File.ReadAllText(outpath, Encoding.UTF8);
                result = client.UploadString(url + "/Defws/ImportFormResultJSON", "POST", data);
            }

            AccessLogging.InsertAccessLogRecord(formsRepo, frmRsltId, (int)AccessLogging.accessLogFunctions.EXPORT, "Export JSON of assessment.");

            return(Content("formResultID on master server: " + result));
        }
示例#3
0
        public FileContentResult BuildReport()
        {
            Debug.WriteLine("* * *  SisPdfRptsController:BuildReport method  * * *");
            //fetch options
            //bool b = Request.Form["grayscale"] == "on";
            //string sGrayscale = Request["grayscale"] as string;
            //bool grayscale = sGrayscale != null && sGrayscale.ToLower().Equals("true");

            if (!SessionHelper.IsUserLoggedIn)
            {
                string msg = "User not logged into application.";
                // byte[] emptyFile = new byte[] {0x20, 0x00};
                return(new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html"));
            }

            //setup session vars if necessary, add access log record
            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }
            string routedFormResultId = Request["formResultId"];

            if (routedFormResultId != null)
            {
                SessionHelper.SessionForm.formResultId = Convert.ToInt32(routedFormResultId);
            }
            AccessLogging.InsertAccessLogRecord(formsRepo, SessionHelper.SessionForm.formResultId, (int)AccessLogging.accessLogFunctions.REPORT, "Generated Report");


            SisPdfReportOptions options;

            //if report options are present in the request, use those.
            if (Request["hasOptions"].ToLower().Equals("true"))
            {
                options = new SisPdfReportOptions(Request);
            }

            //...otherwise use default options for this enterpise
            else
            {
                int?entId = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId).EnterpriseID;
                options = AJBoggs.Sis.Reports.SisReportOptions.BuildPdfReportOptions(entId);
            }

            DateTime          startTime = DateTime.Now;
            FileContentResult r         = BottomBuildReport(SessionHelper.SessionForm.formResultId, options);

            Debug.WriteLine("SisPdfRptsController.BuildReport(): BottomBuildReport duration: "
                            + DateTime.Now.Subtract(startTime).TotalSeconds + " seconds");
            return(r);
        }
        public void ChangeStatusToCheckedOut()
        {
            List <int> formResultIds = SessionHelper.Read <List <int> >("formResultIds");

            if (formResultIds != null)
            {
                foreach (int formResultId in formResultIds)
                {
                    def_FormResults formResult = formsRepo.GetFormResultById(formResultId);

                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.CHECKED_OUT, "Checked out to Venture by " + SessionHelper.LoginInfo.LoginID);

                    Updates.AddField(formsRepo, Updates.SIS_HIDDEN, formResult, Updates.CHECKED_OUT_TO, SessionHelper.LoginInfo.LoginID);

                    AccessLogging.InsertAccessLogRecord(formsRepo, formResultId, (int)AccessLogging.accessLogFunctions.CHECK_OUT, "Checked out to Venture by " + SessionHelper.LoginInfo.LoginID);
                }
            }
        }
        public string MoveAssessment(int formResultId, int userId, int groupId, int enterpriseId)
        {
            try
            {
                def_FormResults formResult = formsRepo.GetFormResultById(formResultId);
                int             prevUser   = (int)formResult.assigned;
                if (userId > -1)
                {
                    formResult.assigned = userId;
                }
                else
                {
                    formResult.assigned = null;
                }
                if (groupId > -1) // a group has been selected from the drop down list
                {
                    formResult.GroupID = groupId;
                }
                else if (groupId == -2) // empty selection in drop down list (null group)
                {
                    formResult.GroupID = null;
                }
                if (enterpriseId > -1)
                {
                    formResult.EnterpriseID = enterpriseId;
                }
                formsRepo.SaveFormResults(formResult);
                EmailUpdate(formResultId, prevUser, userId);

                if (ventureMode == false)
                {
                    AccessLogging.InsertAccessLogRecord(formsRepo, formResult.formResultId, (int)AccessLogging.accessLogFunctions.MOVE, "Move assessment.");
                }

                return("Assessment has been successfully moved.");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("MoveAssessment exception: " + ex.Message);
                return("Error: " + ex.Message);
            }
        }
        public ActionResult GoAction(FormCollection formCollection)
        {
            string      recId             = formCollection["recId"];
            string      paramFormResultId = formCollection["sisId"];
            string      paramFormId       = formCollection["formId"];
            string      category          = formCollection["CategoryID"];
            SearchModel model             = new SearchModel();

            if (SessionHelper.SessionForm == null)
            {
                // return RedirectToAction("Index", "Search", null);
                SessionHelper.SessionForm = new SessionForm();
            }
            SessionForm sf = SessionHelper.SessionForm;

            if (String.IsNullOrWhiteSpace(category))
            {
                return(RedirectToAction("Index", "Search"));
            }
            else if (category.ToLower().Equals("edit") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of assessment.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("review"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.REVIEW, "Assessment accessed for review.");
                    }

                    if (model.unlock == true)
                    {
                        formsRepo.LockFormResult(formResult.formResultId);
                    }

                    if (formResult.reviewStatus != (int)ReviewStatus.REVIEWED && formResult.reviewStatus != (int)ReviewStatus.APPROVED && formResult.reviewStatus != (int)ReviewStatus.PRE_QA)
                    {
                        def_FormResults preQAcopy = AssessmentCopy.CopyAssessment(formsRepo, formResult.formResultId);

                        if (WebServiceActivity.IsWebServiceEnabled())
                        {
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.REVIEW, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }

                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.REVIEWED, "Initiate review of assessment");

                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];


                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("approve"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.APPROVED, "Approve review of assessment");

                    if (WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.APPROVE, "formResultId=" + formResult.formResultId.ToString());
                    }
                }
            }
            else if (category.ToLower().Equals("create"))
            {
                if (model.create == true)
                {
                    string          formId = String.IsNullOrEmpty(paramFormId) ? "1" : paramFormId;
                    def_FormResults frmRes = FormResults.CreateNewFormResultFull(formId,
                                                                                 SessionHelper.LoginStatus.EnterpriseID.ToString(),
                                                                                 SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString(),
                                                                                 recId,
                                                                                 SessionHelper.LoginStatus.UserID.ToString()
                                                                                 );
                    string strFormResultId = String.Empty;
                    try
                    {
                        int formRsltId = formsRepo.AddFormResult(frmRes);
                        strFormResultId = formRsltId.ToString();
                        Debug.WriteLine("GoAction create FormResultId strFormResultId:" + strFormResultId);
                    }
                    catch (Exception excptn)
                    {
                        Debug.WriteLine("GoAction Defws.CreateNewFormResultFull formsRepo.AddFormResult  exception:" + excptn.Message);
                        Debug.WriteLine("   GoAction formId:" + formId
                                        + "   entId: " + SessionHelper.LoginStatus.EnterpriseID.ToString()
                                        + "   GroupId: " + SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString()
                                        + "   recId: " + recId.ToString()
                                        + "   UserId: " + SessionHelper.LoginStatus.UserID.ToString()
                                        );
                    }

                    if ((!String.IsNullOrEmpty(strFormResultId)) && !String.IsNullOrEmpty(recId))
                    {
                        int intRecId;

                        if (int.TryParse(recId, out intRecId))
                        {
                            using (var context = DataContext.getSisDbContext())
                            {
                                // Contact tempContact = new Contact();
                                Contact tempContact = (from c in context.Contacts
                                                       where c.ContactID == intRecId
                                                       select c).FirstOrDefault();

                                // Address tempAddress = new Address();
                                Address tempAddress = (from a in context.Addresses
                                                       where (a.ContactID == tempContact.ContactID) &&
                                                       (a.AddressType == "R")
                                                       select a).FirstOrDefault();

                                Dictionary <string, string> responsesByIdentifier = new Dictionary <string, string>();
                                responsesByIdentifier.Add("sis_cl_first_nm", tempContact.FirstName);
                                responsesByIdentifier.Add("sis_cl_last_nm", tempContact.LastName);

                                if (tempAddress != null)
                                {
                                    responsesByIdentifier.Add("sis_cl_addr_line1", tempAddress.Address1);
                                    responsesByIdentifier.Add("sis_cl_city", tempAddress.City);
                                    responsesByIdentifier.Add("sis_cl_st", tempAddress.StateCode);
                                    responsesByIdentifier.Add("sis_cl_zip", tempAddress.Zip);
                                }

                                string msg = formsRepo.CreateNewResponseValues(strFormResultId, responsesByIdentifier);
                                Debug.WriteLine("GoAction CreateNewResponseValues strFormResultId: " + strFormResultId + "    msg: " + msg);
                            }
                        }

                        // Retrieve and set SessionForm params
                        sf.formId       = 1; // Temporary
                        sf.formResultId = Convert.ToInt32(strFormResultId);

                        // Get the sectionId of the first section of the first part based on the formId
                        def_Forms frm = formsRepo.GetFormById(sf.formId);
                        def_Parts prt = formsRepo.GetFormParts(frm)[0];
                        sf.partId       = prt.partId;
                        Session["part"] = prt.partId;
                        def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                        return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                    }
                }
            }
            else if (category.ToLower().Equals("delete"))
            {
                if (model.delete == true)
                {
                    formsRepo.FormResultDeleteLogically(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.DELETE, "Delete assessment.");
                    }


                    if (ventureMode == false && WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + paramFormResultId);
                        def_FormResults preQAcopy = ReviewStatus.GetLatestPreQACopy(formsRepo, Convert.ToInt32(paramFormResultId));

                        if (preQAcopy != null)
                        {
                            formsRepo.FormResultDeleteLogically(preQAcopy.formResultId);
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }
                }
            }
            else if (category.ToLower().Equals("lock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.LockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("unlock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.UnlockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("archive"))
            {
                if (model.archive == true)
                {
                    formsRepo.ArchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.ARCHIVE, "Archive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("unarchive"))
            {
                if (model.archive == true)
                {
                    formsRepo.UnarchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNARCHIVE, "Unarchive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("upload"))
            {
                def_FormResults fr = formsRepo.GetFormResultById(Convert.ToInt32(paramFormResultId));

                if (fr.formStatus == (byte)FormResults_formStatus.COMPLETED)
                {
                    SessionHelper.Write("uploadFormResultId", Convert.ToInt32(paramFormResultId));
                    return(RedirectToAction("UploadSingle", "DataSync"));
                }
            }
            else if (category.ToLower().Equals("undelete"))
            {
                if (model.undelete == true)
                {
                    formsRepo.FormResultUndelete(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNDELETE, "Undelete assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("planning") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetPartByFormAndIdentifier(frm, "Other");
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of interview planning.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }

            return(RedirectToAction("Index", "Search"));
        }
        private FileContentResult BuildFormResultsCSV(List <string> leadingHeaders)
        {
            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " started");

            string includeParts = Request["includeParts"] as string;
            Dictionary <string, int> formPartMap = (Dictionary <string, int>)Session["formPartMap"];
            string formId = Request["formId"] as string;

            ExportModel exportModel = (ExportModel)Session["ExportModel"];
            int         iFormId     = Convert.ToInt32(formId);

            List <def_Forms> forms = new List <def_Forms>();

            if (iFormId == 0)
            {
                foreach (int?id in exportModel.formIds)
                {
                    forms.Add(formsRepo.GetFormById(Convert.ToInt32(id)));
                }
            }
            else
            {
                forms.Add(formsRepo.GetFormById(iFormId));
            }


            string    outpath = ControllerContext.HttpContext.Server.MapPath("../Content/formResults_" + System.DateTime.Now.Ticks + ".csv");
            Stream    stream  = new FileStream(outpath, FileMode.Create);
            CsvWriter writer  = new CsvWriter(stream);

            // Build a map of with all relevent itemVariable identifiers
            Dictionary <int, string> ivIdentifiersById = new Dictionary <int, string>();

            foreach (string leadingIdent in leadingHeaders)
            {
                int id = leadingIdent.StartsWith("FORMRESULT_") ? -1 - ivIdentifiersById.Count :
                         formsRepo.GetItemVariableByIdentifier(leadingIdent).itemVariableId;
                ivIdentifiersById.Add(id, leadingIdent);
            }
            int i = 0;
            Dictionary <int, List <string> > formIdentMap = new Dictionary <int, List <string> >();

            foreach (def_Forms form in forms)
            {
                List <string> map = new List <string>();
                // Use the formPartMap when its not empty.
                i = (formPartMap.Count() > 0) ? formPartMap[form.formId + " start"] : 0;
                foreach (def_Parts prt in formsRepo.GetFormParts(form))
                {
                    if (prt.identifier.Contains("Scores"))
                    {
                        continue;
                    }
                    if (includeParts[i++] == '1')
                    {
                        //formPartMap.Add(form.formId + " " + prt.partId + " ident start", ivIdentifiersById.Count());
                        foreach (def_Sections sctn in formsRepo.GetSectionsInPart(prt))
                        {
                            formsRepo.CollectItemVariableIdentifiersById(sctn, ivIdentifiersById);
                            foreach (def_Items item in formsRepo.GetAllItemsForSection(sctn))
                            {
                                map.AddRange(formsRepo.GetItemVariablesByItemId(item.itemId).Select(iv => iv.identifier).ToList());
                            }
                        }

                        Debug.WriteLine("Added more sections to ivIdentifiersById, form: " + form.formId + " part: " + prt.partId + " new Count: " + ivIdentifiersById.Count());
                        //formPartMap.Add(form.formId + " " + prt.partId + " ident end", ivIdentifiersById.Count());
                    }
                }
                formIdentMap.Add(form.formId, map);
            }

            //add additional columns for any unhandled data the comes back from CommonExport.GetFormResultValues
            foreach (FormResultExportTagName tagName in Enum.GetValues(typeof(FormResultExportTagName)))
            {
                string header = "FORMRESULT_" + tagName.ToString();
                if (!ivIdentifiersById.Values.Contains(header))
                {
                    int id = -1 - ivIdentifiersById.Count; //not used, but must be unique to act as dictionary key
                    ivIdentifiersById.Add(id, header);
                }
            }

            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished Build a map of with all column identifiers");

            // Build a list of formresults to export
            List <int?>            formResultIds = exportModel.formResultIds;
            List <def_FormResults> formResultsToExport;

            if (iFormId == 0)
            {
                formResultsToExport = new List <def_FormResults>();
                foreach (def_Forms form in forms)
                {
                    formResultsToExport.AddRange(formsRepo.GetFormResultsByFormId(form.formId).Where(r => formResultIds.Contains(r.formResultId)).ToList());
                }
            }
            else
            {
                if (formResultIds == null)
                {
                    formResultsToExport = formsRepo.GetFormResultsByFormId(iFormId).ToList();
                }
                else
                {
                    formResultsToExport = formsRepo.GetFormResultsByFormId(iFormId).Where(r => formResultIds.Contains(r.formResultId)).ToList();
                }
            }
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished building a list of formresults to export");

            //build a header record with identifiers
            int           n           = ivIdentifiersById.Count;
            List <int>    ivIds       = new List <int>();
            List <string> identifiers = new List <string>();
            List <string> headerText  = new List <string>();
            int           j           = 0;

            foreach (KeyValuePair <int, string> de in ivIdentifiersById)
            {
                ivIds.Add(de.Key);
                identifiers.Add(de.Value);
                headerText.Add(de.Value.Replace("FORMRESULT_", ""));
                j++;
            }
            HeaderRecord hr = new HeaderRecord(true, headerText);

            writer.WriteRecord(hr);
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished build a header record with identifiers");

            //Build a DataRecord with item labels (second row in the output file)
            string[] values = new string[n]; //used to temporarily store the values for each row in the export
            for (int k = 0; k < n; k++)
            {
                if (identifiers[k].StartsWith("FORMRESULT_"))
                {
                    FormResultExportTagName tag = (FormResultExportTagName)Enum.Parse(typeof(FormResultExportTagName), headerText[k]);
                    values[k] = getCSVSecondRowLabelForFormResultTagName(tag);
                }
                else
                {
                    values[k] = formsRepo.GetItemVariableById(ivIds[k]).def_Items.label;
                }
            }
            writer.WriteRecord(new DataRecord(hr, values));
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished Build a DataRecord with item labels");

            //insert access logs (one for each assessment being exported)
            int[] arrFrIds = formResultIds.Where(id => id.HasValue).Select(id => id.Value).ToArray();
            AccessLogging.InsertMultipleAccessLogRecords(formsRepo, arrFrIds, (int)AccessLogging.accessLogFunctions.EXPORT, "Export CSV of assessment");

            // Build a DataRecord for each form result
            int count = 0, total = formResultsToExport.Count();

            foreach (def_FormResults fr in formResultsToExport)
            {
                //pull all necessary data for this formResult
                List <ValuePair> rspValues = CommonExport.GetDataByFormResultId(fr.formResultId);
                List <ValuePair> frValues  = CommonExport.GetFormResultValues(fr, forms.Where(f => f.formId == fr.formId).FirstOrDefault());

                //fill in values from formResult
                for (int k = 0; k < n; k++)
                {
                    if (identifiers[k].StartsWith("FORMRESULT_"))
                    {
                        //values[k] = GetFormResultValue(fr, headerText[k]);
                        ValuePair vp = frValues.Where(vpt => vpt.identifier == headerText[k]).FirstOrDefault();
                        if (vp != null)
                        {
                            values[k] = vp.rspValue;
                        }
                        else
                        {
                            values[k] = "";
                        }
                    }
                }

                //replace reponse values (numbers) with meaningful text for certain cells
                //FormResults_formStatus status;
                //Enum.TryParse(values[colIndex_status], out status);
                //values[colIndex_status] = status.ToString();
                //values[colIndex_sis_why] = GetDropdownText("assmtReason", values[colIndex_sis_why]);

                //fill in values from responseVariables
                for (i = 0; i < n; i++)
                {
                    if (identifiers[i].StartsWith("FORMRESULT_"))
                    {
                        continue;
                    }
                    ValuePair vp = null;
                    if (identifiers[i].StartsWith("FORMRESULT_") || formIdentMap[fr.formId].Contains(identifiers[i]))
                    {
                        vp = rspValues.Where(vpt => vpt.identifier == identifiers[i]).FirstOrDefault();
                    }
                    values[i] = vp == null ? "" : vp.rspValue;
                }
                writer.WriteRecord(new DataRecord(hr, values));

                //debug
                Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished " + (++count) + "/" + total + " records");
            }
            writer.Close(); //<- calls stream.Close()


            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished everything");

            return(File(System.IO.File.ReadAllBytes(outpath), "text/csv", "results.csv"));
        }
示例#8
0
        /// <summary>
        /// Updating Assessment by Venture for old versions of Venture (new versions should use new function).
        /// </summary>
        /// <param name="json"></param>
        /// <returns>string - exception message if any.</returns>
        public static string UpdateAssessmentJSON(IFormsRepository formsRepo, string json)
        {
            string result = String.Empty;

            try
            {
                var dResults = fastJSON.JSON.Parse(json);
                Dictionary <string, Object> resDict = (Dictionary <string, Object>)dResults;

                List <Object> resList = (List <Object>)resDict[""];

                List <Object> firstList = (List <Object>)resList[0];

                int formStatus   = Int32.Parse(firstList[4].ToString());
                int formResultId = Int32.Parse(firstList[3].ToString());
                Debug.WriteLine("Defws UpdateAssessmentJSON formResultId:" + firstList[3].ToString());

                def_FormResults fr = formsRepo.GetFormResultById(formResultId);
                fr.formStatus  = (byte)formStatus;
                fr.dateUpdated = DateTime.Parse(firstList[5].ToString());

                SessionHelper.SessionForm = new SessionForm()
                {
                    formId       = fr.formId,
                    formResultId = formResultId
                };

                AccessLogging.InsertAccessLogRecord(formsRepo, formResultId, (int)AccessLogging.accessLogFunctions.IMPORT, "Imported assessment from Venture.");

                int          sectionId = Int32.Parse(firstList[0].ToString());
                def_Sections section   = formsRepo.GetSectionById(sectionId);
                SessionHelper.SessionForm.sectionId = sectionId;

                FormCollection fc      = new FormCollection();
                List <Object>  rspData = null;

                foreach (Object res in resList)
                {
                    rspData = (List <Object>)res;

                    int nextSectionId = Int32.Parse(rspData[0].ToString());

                    if (nextSectionId != sectionId)
                    {
                        // New section; save last section's form collection
                        if (section == null)
                        {
                            Debug.WriteLine("Missing section " + sectionId + " on server.");
                            sectionId = nextSectionId;
                            continue; // If a section is missing, go to the next one but log error to console
                            //throw new Exception("Missing section " + sectionId + " on server.");
                        }

                        //* * * OT 03/10/16 Switched to using AJBoggs\Def\Domain\UserData.SaveFormCollection.cs
                        new UserData(formsRepo).FormResultsSaveSaveSectionItems(section, fc, formResultId);
                        sectionId = nextSectionId;
                        section   = formsRepo.GetSectionById(sectionId);

                        SessionHelper.SessionForm.sectionId = sectionId;
                        fc.Clear();
                    }

                    string identifier = rspData[2].ToString();

                    string value = String.Empty;
                    if (rspData[1] != null)
                    {
                        value = rspData[1].ToString();
                    }

                    fc.Add(identifier, value);
                }

                if (section != null)
                {
                    //ResultsController r = new ResultsController(formsRepo);

                    //* * * OT 03/10/16 Switched to using AJBoggs\Def\Domain\UserData.SaveFormCollection.cs
                    new UserData(formsRepo).FormResultsSaveSaveSectionItems(section, fc, formResultId);
                }
                else
                {
                    Debug.WriteLine("Missing section " + sectionId + " on server.");
                }
                formsRepo.SaveFormResults(fr);

                AccessLogging.InsertAccessLogRecord(formsRepo, fr.formResultId, (int)AccessLogging.accessLogFunctions.CHECK_IN, "Check in of assessment from Venture by " + SessionHelper.LoginInfo.LoginID);
                ReviewStatus.ChangeStatus(formsRepo, fr, ReviewStatus.CHECKED_IN, "Checked in from Venture by " + SessionHelper.LoginInfo.LoginID);
                ReviewStatus.AssessmentIsCompleted(formsRepo, fr);
            }
            catch (Exception excptn)
            {
                Debug.WriteLine("Defws UpdateAssessmentJSON exception:" + excptn.Message);
                result = excptn.Message;
                if ((excptn.InnerException != null) && (excptn.InnerException.Message != null))
                {
                    result = result + " " + excptn.InnerException.Message;
                }
            }

            return(result);
        }
示例#9
0
        public static string ImportFormResultJSON(IFormsRepository formsRepo, string json)
        {
            string result = String.Empty;

            try
            {
                var dFormResults = fastJSON.JSON.Parse(json);
                Dictionary <string, Object> resDict = (Dictionary <string, Object>)dFormResults;

                ////add the def_FormResults object to the database, which will assign and return a formResultId
                //int formRsltId = formsRepo.AddFormResult((def_FormResults) dFormResults);

                def_FormResults formResult = new def_FormResults()
                {
                    formId        = Convert.ToInt32(resDict["formId"]),
                    dateUpdated   = DateTime.Now,
                    formStatus    = Convert.ToByte(resDict["formStatus"]),
                    sessionStatus = Convert.ToByte(resDict["sessionStatus"])
                };

                int formRsltId = formsRepo.AddFormResult(formResult);

                List <Object> itemObjectList = (List <Object>)resDict["def_ItemResults"];
                foreach (Object o in itemObjectList)
                {
                    Dictionary <string, object> dict        = (Dictionary <string, object>)o;
                    def_ItemResults             itemResults = new def_ItemResults
                    {
                        formResultId  = formRsltId,
                        itemId        = Convert.ToInt32(dict["itemId"]),
                        sessionStatus = Convert.ToInt32(dict["sessionStatus"]),
                        dateUpdated   = Convert.ToDateTime(dict["dateUpdated"])
                    };

                    int itemResultId = formsRepo.AddItemResult(itemResults);

                    List <Object> respVarObjectList = (List <Object>)dict["def_ResponseVariables"];

                    foreach (Object r in respVarObjectList)
                    {
                        Dictionary <string, object> rDict = (Dictionary <string, object>)r;

                        DateTime?date;
                        if (rDict["rspDate"] == null)
                        {
                            date = null;
                        }
                        else
                        {
                            date = Convert.ToDateTime(rDict["rspDate"]);
                        }

                        def_ResponseVariables dResponseVariables = new def_ResponseVariables
                        {
                            itemResultId   = itemResultId,
                            itemVariableId = Convert.ToInt32(rDict["itemVariableId"]),
                            rspInt         = Convert.ToInt32(rDict["rspInt"]),
                            rspFloat       = Convert.ToDouble(rDict["rspFloat"]),
                            rspDate        = date,
                            rspValue       = Convert.ToString(rDict["rspValue"])
                        };

                        formsRepo.AddResponseVariableNoSave(dResponseVariables);
                    }
                }

                formsRepo.Save();

                //pass the formResultId to the return value container
                result = formRsltId.ToString();

                AccessLogging.InsertAccessLogRecord(formsRepo, formRsltId, (int)AccessLogging.accessLogFunctions.IMPORT, "Imported assessment from JSON.");
            }
            catch (Exception excptn)
            {
                Debug.WriteLine("Def3WebServices.LoadFormResultJSON exception:" + excptn.Message);
            }

            return(result);
        }
示例#10
0
        /// <summary>
        /// New function to handle a uploading an assessment in the JSON format created in the FormsSql CreateFormResultJSON.
        ///
        /// Reads in a form result record first and updates it.
        ///
        /// Adds/modifies item results and response variables for this form result.
        ///
        /// Item result and response variable data is in the following order:
        ///
        /// responseVariableId, itemId, itemVariableId, rspValue
        ///
        /// The data is sorted by itemId
        ///
        /// responseVariableId is only included so that the data table on the client side has a primary key
        /// (we may find a better way to do this later)
        /// </summary>
        /// <param name="json"></param>
        /// <returns>string - Exception message if any.</returns>

        public static string UpdateAssessmentJSONVenture(IFormsRepository formsRepo, string json)
        {
            string result = String.Empty;

            try
            {
                var dResults = fastJSON.JSON.Parse(json);
                Dictionary <string, Object> resDict = (Dictionary <string, Object>)dResults;

                Dictionary <string, object> formResultDict = (Dictionary <string, object>)resDict["FormResult"];

                // Find the form result we are updating.
                def_FormResults formResult = formsRepo.GetFormResultById(Int32.Parse(formResultDict["newFormResultId"].ToString()));

                // Update the form result's data (More values can be added here as needed to fill in other def_FormResults table fields)
                if (formResult != null)
                {
                    // 4/4/2016 Bug #13143 LK All uploaded assessments should have completed status; some were being set to uploaded somehow. Sets to completed.
                    formResult.formStatus  = 2; // Hard code status "2" for "Complete" (all uploaded assessments must be Complete). To see other formStatus, visit: AJBoggs.Sis.Domain.FormResults_formStatus. OLD code: //Byte.Parse(formResultDict["formStatus"].ToString());
                    formResult.dateUpdated = DateTime.Parse(formResultDict["dateUpdated"].ToString());
                    formResult.interviewer = Int32.Parse(formResultDict["interviewer"].ToString());
                }

                // Get a list of all the data

                List <object> data = (List <object>)resDict["Data"];

                def_ItemResults itemResult = null;

                bool newItemResult = false;


                // Loop over the data items and process them, adding/modifying item results and response variables as needed
                foreach (object dataValue in data)
                {
                    // Order of data in this list is: responseVariableId, itemId, itemVariableId, rspValue
                    Dictionary <string, object> dataValueDict = (Dictionary <string, object>)dataValue;

                    int itemId = Int32.Parse(dataValueDict["itemId"].ToString());


                    // Find the item result corresponding to the form result and item
                    if (itemResult == null)
                    {
                        itemResult = formsRepo.GetItemResultByFormResItem(formResult.formResultId, itemId);
                    }
                    else if (itemResult.itemId != itemId) // we have moved on to the next item
                    {
                        // if the item result was new, and it has response variables, it is added to the item result list of the form result
                        // (this will be saved later)
                        if (newItemResult == true && itemResult.def_ResponseVariables.Count > 0)
                        {
                            formResult.def_ItemResults.Add(itemResult);
                            newItemResult = false;
                        }

                        // Attempt to get the next item result
                        itemResult = formsRepo.GetItemResultByFormResItem(formResult.formResultId, itemId);
                    }

                    // Create a new item result if it doesn't already exist
                    if (itemResult == null)
                    {
                        itemResult               = new def_ItemResults();
                        itemResult.itemId        = itemId;
                        itemResult.formResultId  = formResult.formResultId;
                        itemResult.sessionStatus = 0;
                        newItemResult            = true;
                    }

                    // Set the date updated for the item result (new or old) to now
                    itemResult.dateUpdated = DateTime.Now;


                    int itemVariableId = Int32.Parse(dataValueDict["itemVariableId"].ToString());

                    string rspValue = String.Empty;
                    if (dataValueDict["rspValue"] != null)
                    {
                        rspValue = dataValueDict["rspValue"].ToString();
                    }

                    // Attempt to find a response variable corresponding to the item variable id and form result
                    def_ResponseVariables responseVariable = formsRepo.GetResponseVariablesByFormResultItemVarId(formResult.formResultId, itemVariableId);

                    def_ItemVariables itemVariable = formsRepo.GetItemVariableById(itemVariableId);

                    // If no response variable is found, create one, convert it, and add it to the item result's response variable collection
                    if (responseVariable == null)
                    {
                        responseVariable = new def_ResponseVariables();
                        responseVariable.itemVariableId = itemVariableId;
                        responseVariable.rspValue       = rspValue;

                        formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);

                        itemResult.def_ResponseVariables.Add(responseVariable);
                    }
                    else // A response variable was found. Change the value and convert it.
                    {
                        responseVariable.rspValue = rspValue;

                        formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);
                    }
                }

                // After all changes are made, save everything.
                formsRepo.Save();

                // check is this assessment has been scored.  If not, update the scores.
                def_ItemVariables     iv = formsRepo.GetItemVariableByIdentifier("scr_total_rawscores_all_SIS_sections");
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResult.formResultId, iv.itemVariableId);
                if (rv == null || String.IsNullOrEmpty(rv.rspValue))
                {
                    new Assessments(formsRepo).UpdateAssessmentScores(formResult);
                }

                try
                {
                    // Add access log record for check in.
                    AccessLogging.InsertAccessLogRecord(formsRepo, formResult.formResultId, (int)AccessLogging.accessLogFunctions.CHECK_IN, "Check in of assessment from Venture by " + SessionHelper.LoginInfo.LoginID);

                    // Add status log record for check in.
                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.CHECKED_IN, "Checked in from Venture by " + SessionHelper.LoginInfo.LoginID);

                    // Change assessment status to completed (multiple workflows determined by enterprise; has separate method from ChangeStatus)
                    ReviewStatus.AssessmentIsCompleted(formsRepo, formResult);

                    // If webservice is enabled, add record to webservice activity table
                    if (WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.UPLOAD, "formResultId=" + formResult.formResultId.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.StackTrace);
                }
            }
            catch (Exception excptn)
            {
                // If any exception is thrown, put the messages from it into the result returned to the client for troubleshooting purposes.

                Debug.WriteLine("JsonImports UpdateAssessmentJSON exception:" + excptn.Message);
                Debug.WriteLine(excptn.StackTrace);
                result = excptn.Message + "\n" + excptn.StackTrace;
                if ((excptn.InnerException != null) && (excptn.InnerException.Message != null))
                {
                    result = result + "\n " + excptn.InnerException.Message;
                }
                Debug.WriteLine("JsonImports UpdateAssessmentJSONVenture exception json:" + json);
            }


            return(result);
        }
        public FileContentResult GetFormResultsXML()
        {
            string currentIdentifier = String.Empty;
            string outpath           = ControllerContext.HttpContext.Server.MapPath("../Content/formResults_" + System.DateTime.Now.Ticks + ".xml");

            Debug.WriteLine("* * *  GetFormResultsXML ConnectionString: " + formsRepo.GetDatabase().Connection.ConnectionString);

            string formId = Request["formId"] as string;

            Debug.WriteLine("* * *  GetFormResultsXML formId: " + formId);
            Session["formId"] = formId;
            int iFormId = Convert.ToInt32(formId);

            // *****  HARD CODED FOR TESTING ****
            iFormId = 1;

            try
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.Indent             = true;
                xws.OmitXmlDeclaration = true;
                xws.CloseOutput        = false;
                // xws.CheckCharacters = false;


                XmlWriter xw = XmlWriter.Create(outpath, xws);
                using (xw)
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("forms");

                    //int iFormId = 1;
                    def_Forms frm = formsRepo.GetFormById(iFormId);
                    xw.WriteStartElement("form");
                    xw.WriteAttributeString("identifier", frm.identifier);
                    xw.WriteAttributeString("title", frm.title);

                    // Get the identifiers for Part (create an array for each Part)
                    List <def_Parts> formParts = formsRepo.GetFormParts(frm);

                    Debug.WriteLine("* * *  GetFormResultsXML Start formParts.Count: " + formParts.Count.ToString());
                    List <String>[] partIdentifiers = new List <String> [formParts.Count];
                    int             iPrt            = 0;

                    foreach (def_Parts prt in formParts)
                    {
                        Debug.WriteLine("* * *  GetFormResultsXML Start loading identifiers for: " + prt.identifier);
                        partIdentifiers[iPrt] = new List <String>();
                        foreach (def_Sections sctn in formsRepo.GetSectionsInPart(prt))
                        {
                            formsRepo.CollectItemVariableIdentifiers(sctn, partIdentifiers[iPrt]);
                        }
                        Debug.WriteLine("* * *  GetFormResultsXML Finished loading identifiers for: " + prt.identifier + "   # of idnts: " + partIdentifiers[iPrt].Count);
                        iPrt++;
                    }

                    // Output the XML
                    Debug.WriteLine("* * *  GetFormResultsXML Output the XML");
                    IEnumerable <def_FormResults> formResults = formsRepo.GetFormResultsByFormId(iFormId);
                    foreach (def_FormResults frmRslt in formResults)
                    {
                        if (frmRslt.formResultId == 1000193)       // Just write out 1 Assessments
                        {
                            continue;
                        }

                        AccessLogging.InsertAccessLogRecord(formsRepo, frmRslt.formResultId, (int)AccessLogging.accessLogFunctions.EXPORT, "Export XML of assessment");

                        xw.WriteStartElement("Assessment");
                        xw.WriteAttributeString("Client_ID", "123456");
                        xw.WriteAttributeString("SIS_Id", frmRslt.formResultId.ToString());
                        xw.WriteAttributeString("identifier", frm.identifier);
                        xw.WriteAttributeString("group", frmRslt.GroupID.HasValue ? frmRslt.GroupID.ToString() : String.Empty);
                        xw.WriteAttributeString("interviewer", frmRslt.interviewer.HasValue ? frmRslt.interviewer.ToString() : String.Empty);
                        xw.WriteAttributeString("status", frmRslt.formStatus.ToString());
                        xw.WriteAttributeString("dateCompleted", frmRslt.dateUpdated.ToShortDateString());
                        xw.WriteAttributeString("deleted", frmRslt.deleted.ToString());
                        xw.WriteAttributeString("locked", frmRslt.locked.ToString());
                        xw.WriteAttributeString("archived", frmRslt.archived.ToString());

                        int iPart = 0;
                        foreach (def_Parts prt in formParts)
                        {
                            /*
                             * if (prt.identifier.Equals("Reports"))
                             * {
                             *  continue;
                             * }
                             */
                            Debug.WriteLine("* * *  GetFormResultsXML Output Section: " + prt.identifier);
                            xw.WriteStartElement("Section");
                            xw.WriteAttributeString("identifier", prt.identifier);

                            foreach (String idnt in partIdentifiers[iPart])
                            {
                                currentIdentifier = idnt;           // To assist with debugging during an Exception
                                if (prt.identifier.Contains("Scores") && !idnt.StartsWith("scr"))
                                {
                                    continue;
                                }
                                //string xmlName = Char.IsDigit(idnt[0]) ? "Q" + idnt : idnt;
                                if (Char.IsDigit(idnt[0]))
                                {
                                    throw new Exception("for xml exporting, identifiers cannot begin with numbers: \"" + idnt + "\"");
                                }

                                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(frmRslt.formResultId, idnt);
                                string val = (rv == null) ? String.Empty : rv.rspValue;
                                xw.WriteElementString(idnt, String.IsNullOrEmpty(val) ? String.Empty : val.Trim());
                            }

                            xw.WriteEndElement();       // SIS Section
                            iPart++;
                        }

                        xw.WriteEndElement();   // Assessment
                    }
                    xw.WriteEndElement();       // form
                    xw.WriteEndElement();       // forms

                    xw.WriteEndDocument();
                }
                xw.Flush();
                xw.Close();
            }
            catch (SqlException sqlXcptn)
            {
                Debug.WriteLine("* * *  GetFormResultsXML SqlException: " + sqlXcptn.Message);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("* * *  GetFormResultsXML currentIdentifier: " + currentIdentifier + "    Exception.Message: " + ex.Message);
            }

            return(File(System.IO.File.ReadAllBytes(outpath), "text/xml", "results.xml"));
        }