コード例 #1
0
        public void SaveDiagram([FromBody] DiagramRequest req)
        {
            // get the assessment ID from the JWT
            TokenManager tm           = new TokenManager();
            int          userId       = (int)tm.PayloadInt(Constants.Token_UserId);
            int?         assessmentId = tm.PayloadInt(Constants.Token_AssessmentId);

            lock (_object)
            {
                using (var db = new CSET_Context())
                {
                    try
                    {
                        BusinessManagers.DiagramManager dm = new BusinessManagers.DiagramManager(db);
                        XmlDocument xDoc = new XmlDocument();
                        if (string.IsNullOrEmpty(req.DiagramXml))
                        {
                            req.DiagramXml = "<mxGraphModel grid=\"1\" gridSize=\"10\"><root><mxCell id=\"0\"><mxCell id=\"1\" parent=\"0\" /></mxCell></root></mxGraphModel>";
                        }
                        xDoc.LoadXml(req.DiagramXml);
                        dm.SaveDiagram((int)assessmentId, xDoc, req);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
        }
コード例 #2
0
        public List <IDiagramAnalysisNodeMessage> PerformAnalysis(DiagramRequest req, int assessmentId)
        {
            try
            {
                var messages = new List <IDiagramAnalysisNodeMessage>();
                if (!string.IsNullOrEmpty(req.DiagramXml))
                {
                    using (var db = new CSET_Context())
                    {
                        // persist the analysis switch setting
                        var assessment = db.ASSESSMENTS.Where(x => x.Assessment_Id == assessmentId).First();
                        assessment.AnalyzeDiagram = req.AnalyzeDiagram;
                        db.SaveChanges();

                        XmlDocument xDoc = new XmlDocument();
                        xDoc.LoadXml(req.DiagramXml);

                        DiagramAnalysis analysis = new DiagramAnalysis(db, assessmentId);
                        messages = analysis.PerformAnalysis(xDoc);
                    }
                }

                return(messages);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #3
0
        public string ImportCsetd([FromBody] DiagramRequest importRequest)
        {
            if (importRequest == null)
            {
                return("request payload not sent");
            }

            // get the assessment ID from the JWT
            TokenManager tm           = new TokenManager();
            int          userId       = (int)tm.PayloadInt(Constants.Token_UserId);
            int?         assessmentId = tm.PayloadInt(Constants.Token_AssessmentId);

            try
            {
                using (CSET_Context db = new CSET_Context())
                {
                    DiagramManager dm = new DiagramManager(db);
                    return(dm.ImportOldCSETDFile(importRequest.DiagramXml, (int)assessmentId));
                }
            }
            catch (Exception exc)
            {
                return(exc.ToString());
            }
        }
コード例 #4
0
        public async Task <EngineProcessDiagram> GetDiagram(DiagramRequest request)
        {
            using (_httpClient = new HttpClient())
            {
                SetDefaultHeaders(_httpClient);

                _httpClient.DefaultRequestHeaders.Add("responseType", "blob");

                var baseUrl = WorkflowSettingSingleTon.WorkflowSetting.BaseUrl;
                var url     = $@"{baseUrl}/runtime/process-instances/{request.processInstanceId}/diagram";
                var resp    = await _httpClient.GetAsync(url);

                if ((int)resp.StatusCode == 200)
                {
                    return(new EngineProcessDiagram {
                        Content = await resp.Content.ReadAsByteArrayAsync()
                    });
                }
                else if ((int)resp.StatusCode == 400)
                {
                    var errorxml = await resp.Content.ReadAsStringAsync();

                    throw new ActivitiEngineClientException("پارامتر های اشتباه " + errorxml);
                }
                else
                {
                    var errorxml = await resp.Content.ReadAsStringAsync();

                    throw new Exception(errorxml);
                }
            }
        }
コード例 #5
0
        public List <IDiagramAnalysisNodeMessage> PerformAnalysis([FromBody] DiagramRequest req)
        {
            // get the assessment ID from the JWT
            TokenManager tm           = new TokenManager();
            int?         assessmentId = tm.PayloadInt(Constants.Token_AssessmentId);

            return(performAnalysis(req, assessmentId ?? 0));
        }
コード例 #6
0
        public async Task <EngineProcessDiagram> GetDiagram(DiagramRequest request)
        {
            ValidateGetDiagram(request);

            var engineClient = InjectorSingleTon.Inject <IWorkflowEngineClient>();


            return(await engineClient.GetDiagram(request));
        }
コード例 #7
0
ファイル: DiagramControllerTests.cs プロジェクト: tmcmil/cset
        public void PerformAnalysisTestRule1()
        {
            DiagramController controller = new DiagramController();
            DiagramRequest    request    = new DiagramRequest();

            request.DiagramXml = File.ReadAllText("TestItems\\SampleDiagram.txt");
            var test    = controller.PerformAnalysis(request, 1);
            var jstring = Newtonsoft.Json.JsonConvert.SerializeObject(test);

            Trace.Write(jstring);
            Assert.AreEqual(test.Count, 3);
        }
コード例 #8
0
ファイル: DiagramControllerTests.cs プロジェクト: tmcmil/cset
        public void PerformAnalysisTestRule4()
        {
            DiagramController controller = new DiagramController();
            DiagramRequest    request    = new DiagramRequest();

            request.DiagramXml = File.ReadAllText("TestItems\\Rule4.xml");
            var test = controller.PerformAnalysis(request, 1);

            Assert.IsTrue(test.Count == 6, "Rule 4");
            var jstring = Newtonsoft.Json.JsonConvert.SerializeObject(test);

            Trace.Write(jstring);
        }
コード例 #9
0
        public async Task <EngineProcessDiagram> GetPhoto(DiagramRequest request)
        {
            using (_httpClient = new HttpClient())
            {
                _httpClient.DefaultRequestHeaders.Accept.Clear();

                /*
                 * _httpClient.DefaultRequestHeaders.Accept.Add(
                 *  new MediaTypeWithQualityHeaderValue("application/json"));
                 */

                _httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue(
                        "Basic", Convert.ToBase64String(
                            Encoding.UTF8.GetBytes(
                                $"{WorkflowSettingSingleTon.WorkflowSetting.Username}:{WorkflowSettingSingleTon.WorkflowSetting.Password}")));


                // ایجاد کاربر در engine اگر وجود نداشته باشد
                IsUserExistsOrNotCreateIt();


                var baseUrl = WorkflowSettingSingleTon.WorkflowSetting.BaseUrl;
                var url     = $@"{baseUrl}/getPhoto?key={request.processDefinitionKey}";
                var resp    = await _httpClient.GetAsync(url);

                if ((int)resp.StatusCode == 200)
                {
                    return(new EngineProcessDiagram {
                        Content = await resp.Content.ReadAsByteArrayAsync()
                    });
                }
                else if ((int)resp.StatusCode == 400)
                {
                    var errorxml = await resp.Content.ReadAsStringAsync();

                    throw new ActivitiEngineClientException("پارامتر های اشتباه " + errorxml);
                }
                else
                {
                    var errorxml = await resp.Content.ReadAsStringAsync();

                    throw new Exception(errorxml);
                }
            }
        }
コード例 #10
0
        public async Task GetDiagramTest()
        {
            var tasks = await workflowService.GetInboxTasks(vm);

            if (tasks.Data.Length == 0)
            {
                await this.SendToWorkflowTest();
            }

            tasks = await workflowService.GetInboxTasks(vm);

            var dr = new DiagramRequest();

            dr.processInstanceId = dr.processInstanceId = tasks.Data[0].ProcessInstanceId;

            var resp = await workflowService.GetDiagram(dr);


            // return await Task.FromResult(1);
        }
コード例 #11
0
ファイル: DiagramControllerTests.cs プロジェクト: tmcmil/cset
        public void PerformAnalysisTestRules()
        {
            DiagramController controller = new DiagramController();
            DiagramRequest    request    = new DiagramRequest();

            string[] testDiagrams = new string[]
            {
                "TestItems\\Rule2.txt",
                "TestItems\\Rule3.txt",
                "TestItems\\Rule4.xml",
                "TestItems\\Rule5.txt",
                "TestItems\\Rule6.xml"
            };
            foreach (string path in testDiagrams)
            {
                request.DiagramXml = File.ReadAllText(path);
                var test = controller.PerformAnalysis(request, 1);
                Assert.IsTrue(test.Count > 0, path);
                var jstring = Newtonsoft.Json.JsonConvert.SerializeObject(test);
                Trace.Write(jstring);
            }
        }
コード例 #12
0
        public virtual async Task <Result <byte[]> > GetDiagram(long processInstanceId)
        {
            try
            {
                var username = HttpContext.Current.Session["loggedInUsername"];
                if (username == null || string.IsNullOrEmpty(username.ToString()))
                {
                    throw new Exception("کاربر کنونی وارد نشده است");
                }

                var request = new DiagramRequest()
                {
                    Username          = username.ToString(),
                    processInstanceId = processInstanceId
                };
                var workflowService = InjectorSingleTon.Inject <IWorkflowService>();

                var diagram = await workflowService.GetDiagram(request);

                return(new Result <byte[]> {
                    Type = ResultType.Success, SingleRecord = diagram.Content
                });
            }
            catch (HttpRequestException e)
            {
                return(new Result <byte[]>
                {
                    Message = e.Message + e.InnerException?.Message + " سرور گردش کار فعال نیست خطا در اتصال ",
                    Type = ResultType.Fail
                });
            }
            catch (Exception e)
            {
                return(new Result <byte[]> {
                    Message = e.Message, Type = ResultType.Fail
                });
            }
        }
コード例 #13
0
        public List <IDiagramAnalysisNodeMessage> performAnalysis(DiagramRequest req, int assessmentId)
        {
            try
            {
                var messages = new List <IDiagramAnalysisNodeMessage>();
                if (!string.IsNullOrEmpty(req.DiagramXml))
                {
                    using (var db = new CSET_Context())
                    {
                        BusinessManagers.DiagramManager dm = new BusinessManagers.DiagramManager(db);
                        XmlDocument xDoc = new XmlDocument();
                        xDoc.LoadXml(req.DiagramXml);

                        DiagramAnalysis analysis = new DiagramAnalysis(db, assessmentId);
                        messages = analysis.PerformAnalysis(xDoc);
                    }
                }
                return(messages);
            }catch (Exception e)
            {
                throw e;
            }
        }
コード例 #14
0
ファイル: ImportManager.cs プロジェクト: vinhduong/cset
        public async Task ProcessCSETAssessmentImport(byte[] zipFileFromDatabase, int currentUserId)
        {
            using (CSET_Context context = new CSET_Context())
            {
                //* read from db and set as memory stream here.
                using (Stream fs = new MemoryStream(zipFileFromDatabase))
                {
                    ZipArchive   zip        = new ZipArchive(fs);
                    StreamReader r          = new StreamReader(zip.GetEntry("model.json").Open());
                    string       jsonObject = r.ReadToEnd();

                    // Apply any data updates to older versions
                    ImportUpgradeManager upgrader = new ImportUpgradeManager();
                    jsonObject = upgrader.Upgrade(jsonObject);

                    try
                    {
                        UploadAssessmentModel model = (UploadAssessmentModel)JsonConvert.DeserializeObject(jsonObject, new UploadAssessmentModel().GetType());

                        foreach (var doc in model.CustomStandardDocs)
                        {
                            var genFile = context.GEN_FILE.FirstOrDefault(s => s.File_Name == doc);
                            if (genFile == null)
                            {
                                StreamReader docReader = new StreamReader(zip.GetEntry(doc + ".json").Open());
                                var          docModel  = JsonConvert.DeserializeObject <ExternalDocument>(docReader.ReadToEnd());
                                genFile = docModel.ToGenFile();
                                var extension = Path.GetExtension(genFile.File_Name).Substring(1);
                                genFile.File_Type_ = context.FILE_TYPE.Where(s => s.File_Type1 == extension).FirstOrDefault();

                                try
                                {
                                    context.FILE_REF_KEYS.Add(new FILE_REF_KEYS {
                                        Doc_Num = genFile.Doc_Num
                                    });
                                    await context.SaveChangesAsync();
                                }
                                catch (Exception e)
                                {
                                    throw e;
                                }
                                context.GEN_FILE.Add(genFile);
                                context.SaveChanges();
                            }
                        }
                        foreach (var standard in model.CustomStandards)
                        {
                            var          sets            = context.SETS.Where(s => s.Set_Name.Contains(standard)).ToList();
                            SETS         set             = null;
                            StreamReader setReader       = new StreamReader(zip.GetEntry(standard + ".json").Open());
                            var          setJson         = setReader.ReadToEnd();
                            var          setModel        = JsonConvert.DeserializeObject <ExternalStandard>(setJson);
                            var          originalSetName = setModel.ShortName;
                            foreach (var testSet in sets)
                            {
                                setModel.ShortName = testSet.Short_Name;
                                var testSetJson = JsonConvert.SerializeObject(testSet.ToExternalStandard(), Newtonsoft.Json.Formatting.Indented);
                                if (testSetJson == setJson)
                                {
                                    set = testSet;
                                    break;
                                }
                                else
                                {
                                    setModel.ShortName = originalSetName;
                                }
                            }
                            if (set == null)
                            {
                                int incr = 1;
                                while (sets.Any(s => s.Short_Name == setModel.ShortName))
                                {
                                    setModel.ShortName = originalSetName + " " + incr;
                                    incr++;
                                }
                                var setResult = await setModel.ToSet();

                                if (setResult.IsSuccess)
                                {
                                    context.SETS.Add(setResult.Result);

                                    foreach (var question in setResult.Result.NEW_REQUIREMENT.SelectMany(s => s.NEW_QUESTIONs()).Where(s => s.Question_Id != 0).ToList())
                                    {
                                        context.Entry(question).State = EntityState.Unchanged;
                                    }
                                    try
                                    {
                                        await context.SaveChangesAsync();
                                    }
                                    catch (Exception e)
                                    {
                                        throw (e);
                                    }
                                    //Set the GUID at time of export so we are sure it's right!!!
                                    model.jANSWER = model.jANSWER.Where(s => s.Is_Requirement).GroupJoin(setResult.Result.NEW_REQUIREMENT, s => s.Custom_Question_Guid, req => new Guid(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(originalSetName + "|||" + req.Requirement_Title + "|||" + req.Requirement_Text))).ToString(), (erea, s) =>
                                    {
                                        var req = s.FirstOrDefault();
                                        if (req != null)
                                        {
                                            erea.Question_Or_Requirement_Id = req.Requirement_Id;
                                        }
                                        return(erea);
                                    }).Concat(model.jANSWER.Where(s => !s.Is_Requirement).GroupJoin(setResult.Result.NEW_QUESTION, s => s.Custom_Question_Guid, req => new Guid(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(req.Simple_Question))).ToString(), (erer, s) =>
                                    {
                                        var req = s.FirstOrDefault();
                                        if (req != null)
                                        {
                                            erer.Question_Or_Requirement_Id = req.Question_Id;
                                        }
                                        return(erer);
                                    })).ToList();
                                }
                            }
                            foreach (var availableStandard in model.jAVAILABLE_STANDARDS.Where(s => s.Set_Name == Regex.Replace(originalSetName, @"\W", "_") && s.Selected))
                            {
                                availableStandard.Set_Name = Regex.Replace(setModel.ShortName, @"\W", "_");
                            }
                        }

                        string email = context.USERS.Where(x => x.UserId == currentUserId).First().PrimaryEmail;



                        Importer import          = new Importer();
                        int      newAssessmentId = import.RunImportManualPortion(model, currentUserId, email, context);
                        import.RunImportAutomatic(newAssessmentId, jsonObject);



                        // Save the diagram
                        var assessment = context.ASSESSMENTS.Where(x => x.Assessment_Id == newAssessmentId).FirstOrDefault();
                        if (!string.IsNullOrEmpty(assessment.Diagram_Markup))
                        {
                            var diagramManager = new DiagramManager(context);
                            var diagReq        = new DiagramRequest()
                            {
                                DiagramXml     = assessment.Diagram_Markup,
                                AnalyzeDiagram = false,
                                revision       = false
                            };
                            var xDocDiagram = new XmlDocument();
                            xDocDiagram.LoadXml(assessment.Diagram_Markup);
                            diagramManager.SaveDiagram(newAssessmentId, xDocDiagram, diagReq);
                        }



                        // Clean up any imported standards that are unselected or deprecated
                        var unselectedStandards = context.AVAILABLE_STANDARDS.Where(x => x.Assessment_Id == newAssessmentId && !x.Selected).ToList();
                        context.AVAILABLE_STANDARDS.RemoveRange(unselectedStandards);
                        var deprecatedStandards = from av in context.AVAILABLE_STANDARDS
                                                  join set in context.SETS on av.Set_Name equals set.Set_Name
                                                  where set.Is_Deprecated
                                                  select av;
                        context.AVAILABLE_STANDARDS.RemoveRange(deprecatedStandards.ToList());
                        context.SaveChanges();


                        //NOTE THAT THIS ENTRY WILL ONLY COME FROM A OLD .cset file
                        //IMPORT
                        ZipArchiveEntry importLegacyDiagram = zip.GetEntry("Diagram.csetd");
                        if (importLegacyDiagram != null)
                        {
                            StreamReader   ldr    = new StreamReader(importLegacyDiagram.Open());
                            string         oldXml = ldr.ReadToEnd();
                            DiagramManager dm     = new DiagramManager(context);
                            dm.ImportOldCSETDFile(oldXml, newAssessmentId);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
        }
コード例 #15
0
ファイル: DiagramManager.cs プロジェクト: vcubefame/CSET
        /// <summary>
        /// Persists the diagram XML in the database.
        /// </summary>
        /// <param name="assessmentID"></param>
        /// <param name="diagramXML"></param>
        public void SaveDiagram(int assessmentID, XmlDocument xDoc, DiagramRequest req)
        {
            int    lastUsedComponentNumber = req.LastUsedComponentNumber;
            string diagramImage            = req.DiagramSvg;

            // the front end sometimes calls 'save' with an empty graph on open.
            // Need to prevent the javascript from doing that on open, but for now,
            // let's detect an empty graph and not save it.

            var cellCount   = xDoc.SelectNodes("//root/mxCell").Count;
            var objectCount = xDoc.SelectNodes("//root/object").Count;

            if (cellCount == 2 && objectCount == 0)
            {
                // Update 29-Aug-2019 RKW - we are no longer getting the save calls on open.
                // Allow all save calls with an empty graph.
                // return;
            }

            using (var db = new CSET_Context())
            {
                var assessmentRecord = db.ASSESSMENTS.Where(x => x.Assessment_Id == assessmentID).FirstOrDefault();
                if (assessmentRecord != null)
                {
                    try
                    {
                        HashSet <string> validGuid = new HashSet <string>();
                        XmlNodeList      cells     = xDoc.SelectNodes("//root/object[@ComponentGuid]");
                        foreach (XmlElement c in cells)
                        {
                            validGuid.Add(c.Attributes["ComponentGuid"].InnerText);
                        }

                        var list = db.ASSESSMENT_DIAGRAM_COMPONENTS.Where(x => x.Assessment_Id == assessmentID).ToList();
                        foreach (var i in list)
                        {
                            if (!validGuid.Contains(i.Component_Guid.ToString()))
                            {
                                db.ASSESSMENT_DIAGRAM_COMPONENTS.Remove(i);
                            }
                        }
                        db.SaveChanges();

                        DiagramDifferenceManager differenceManager = new DiagramDifferenceManager(db);
                        XmlDocument oldDoc = new XmlDocument();
                        if (!String.IsNullOrWhiteSpace(assessmentRecord.Diagram_Markup) && req.revision)
                        {
                            oldDoc.LoadXml(assessmentRecord.Diagram_Markup);
                        }
                        differenceManager.buildDiagramDictionaries(xDoc, oldDoc);
                        differenceManager.SaveDifferences(assessmentID);
                    }
                    catch (Exception e)
                    {
                    }
                    finally
                    {
                        assessmentRecord.LastUsedComponentNumber = lastUsedComponentNumber;
                        String diagramXML = xDoc.OuterXml;
                        if (!String.IsNullOrWhiteSpace(diagramXML))
                        {
                            assessmentRecord.Diagram_Markup = diagramXML;
                        }
                        assessmentRecord.Diagram_Image = diagramImage;
                        db.SaveChanges();
                    }
                }
                else
                {
                    //what the?? where is our assessment
                    throw new ApplicationException("Assessment record is missing for id" + assessmentID);
                }
            }
        }