Exemplo n.º 1
0
        public static WorkItemData getWorkItemAsync(WorkItemRequest wkitem, string token, IConfiguration configuration)
        {
            string hruri = configuration.GetSection("HumanReview:uri").Value + "workItems/";
            Uri    uri   = new Uri(hruri);
            HttpResponseMessage response;
            HttpClient          client;

            WorkItemData wrkData;

            using (client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();

                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                client.DefaultRequestHeaders.TryAddWithoutValidation("X-HumanReviewApi-Version", "1.0");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                var jsonText    = JsonConvert.SerializeObject(wkitem);
                var jsonContent = new StringContent(jsonText, UnicodeEncoding.UTF8, "application/json");
                ;
                response = client.PostAsync(uri, jsonContent).Result;
                response.EnsureSuccessStatusCode();
                var dataString = response.Content.ReadAsStringAsync().Result;

                wrkData = JsonConvert.DeserializeObject <WorkItemData>(dataString);
            }
            return(wrkData);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates WorkItem entry in Human Review API
        /// Used when Creating / Requesting new Human Review WorkItems
        /// Returns the structure containing Human Review Information of a created WorkItem
        /// </summary>
        /// <param name="wkitem"></param>
        /// <param name="token"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static WorkItemData GetHRWorkItem(WorkItemRequest wkitem, string token, IConfiguration configuration)
        {
            string hruri = configuration.GetSection("HumanReview:uri").Value + "workItems/";
            Uri    uri   = new Uri(hruri);
            HttpResponseMessage response;
            HttpClient          client;

            WorkItemData wrkData;

            using (client = new HttpClient())
            {
                var ReadyClient = InitializeHttpClient(client, token, true);
                //ReadyClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                var jsonText    = JsonConvert.SerializeObject(wkitem);
                var jsonContent = new StringContent(jsonText, UnicodeEncoding.UTF8, "application/json");
                ;
                response = ReadyClient.PostAsync(uri, jsonContent).Result; // Post Call To create a Human Review WorkItem
                response.EnsureSuccessStatusCode();
                var dataString = response.Content.ReadAsStringAsync().Result;

                wrkData = JsonConvert.DeserializeObject <WorkItemData>(dataString);

                ReadyClient.Dispose();
            }
            return(wrkData);
        }
Exemplo n.º 3
0
 public static string SerializeWorkItemRequest(WorkItemRequest data)
 {
     return(JsmlSerializer.Serialize(data, "data",
                                     new JsmlSerializer.SerializeOptions {
         Hook = _workItemRequestHook, DataContractTest = IsWorkItemRequestContract
     }));
 }
Exemplo n.º 4
0
        public void Updated_Minimal_None_NoneˆFails()
        {
            var payload = GetDataFileMatchingCallerName();

            var request = WorkItemRequest.Parse(payload);

            Assert.IsNotNull(request);
            Assert.IsFalse(request.IsValid);
            Assert.AreEqual("TFS Aggregator requires 'All' for 'Resource details to send'.", request.Error);
        }
Exemplo n.º 5
0
        /// <summary>
        ///
        /// This function returns a request structure to be sent to the Human Review for Creating and Updating WorkItems
        /// </summary>
        /// <param name="modulename"></param>
        /// <param name="QueueGuidString"></param>
        /// <param name="JsonData"></param>
        /// <param name="configuration"></param>
        /// <param name="workitemGuid"></param>
        /// <param name="hrRequestMode"></param>
        /// <returns></returns>
        public static object BuildHRWorkItemRequest(string modulename, string QueueGuidString, string JsonData,
                                                    IConfiguration configuration, string workitemGuid, HRRequestMode hrRequestMode)
        {
            string HRCreateRequestName        = "";
            string HRCreateRequestDescription = "";
            string HRStatusDetailTypeGuid     = "";
            string HRReviewTypeGuid           = "";
            bool   HREntryActive = true;
            Guid   QueueGuid     = Guid.Parse(QueueGuidString);

            if (hrRequestMode == HRRequestMode.Create)
            {
                HRCreateRequestName        = "Created Human Review WorkItem Entry for " + modulename + " Record";
                HRCreateRequestDescription = "Created Human Review WorkItem Entry for " + modulename + " Record";
                HRStatusDetailTypeGuid     = configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                HRReviewTypeGuid           = configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;

                WorkItemRequest HRCreateRequest = new WorkItemRequest
                {
                    Name                 = HRCreateRequestName,
                    Description          = HRCreateRequestDescription,
                    QueueGuid            = QueueGuid,
                    StatusDetailTypeGuid = HRStatusDetailTypeGuid,
                    ReviewTypeGuid       = HRReviewTypeGuid,
                    FormDefinitionJson   = JsonData,
                    IsActive             = HREntryActive
                };

                return(HRCreateRequest);
            }

            if (hrRequestMode == HRRequestMode.Update)
            {
                HRCreateRequestName        = "Updated Human Review WorkItem Entry for " + modulename + " Record";
                HRCreateRequestDescription = "Updated Human Review WorkItem Entry for " + modulename + " Record";
                HRStatusDetailTypeGuid     = configuration.GetSection("HumanReview:statusDetailTypeGuid_upd").Value;
                HRReviewTypeGuid           = configuration.GetSection("HumanReview:reviewTypeGuid_upd").Value;

                WorkItemPutRequest HRCreateRequest = new WorkItemPutRequest
                {
                    Name                 = HRCreateRequestName,
                    Description          = HRCreateRequestDescription,
                    QueueGuid            = QueueGuid,
                    StatusDetailTypeGuid = HRStatusDetailTypeGuid,
                    ReviewTypeGuid       = HRReviewTypeGuid,
                    FormDefinitionJson   = JsonData,
                    IsActive             = HREntryActive,
                    WorkitemGuid         = workitemGuid // Needed for Update calls
                };

                return(HRCreateRequest);
            }

            return(null);
        }
Exemplo n.º 6
0
        public void Updated_All_None_NoneˆSucceeds()
        {
            var payload = GetDataFileMatchingCallerName();

            var request = WorkItemRequest.Parse(payload);

            Assert.IsNotNull(request);
            Assert.IsTrue(request.IsValid);
            Assert.AreEqual(ChangeTypes.Change, request.ChangeType);
            Assert.AreEqual("1fe04a90-6116-437a-a208-f64a7711e8ff", request.CollectionId);
            Assert.AreEqual("https://giuliovaad.visualstudio.com/", request.TfsCollectionUri);
            Assert.AreEqual(12, request.WorkItemId);
            Assert.AreEqual("WorkItemTracking", request.TeamProject);
        }
Exemplo n.º 7
0
        public void Restored_All_None_NoneˆSucceeds()
        {
            var payload = GetDataFileMatchingCallerName();

            var request = WorkItemRequest.Parse(payload);

            Assert.IsNotNull(request);
            Assert.IsTrue(request.IsValid);
            Assert.AreEqual(ChangeTypes.Restore, request.ChangeType);
            Assert.AreEqual("fcb4f585-afdd-4dc8-bb1b-1d8d5d9d2ff2", request.CollectionId);
            Assert.AreEqual("https://win-ro13gv4kfhq/DefaultCollection/", request.TfsCollectionUri);
            Assert.AreEqual(2, request.WorkItemId);
            Assert.AreEqual("FirstProject", request.TeamProject);
        }
Exemplo n.º 8
0
        public void Restored_All_None_NoneˆSucceeds()
        {
            var payload = GetDataFileMatchingCallerName();

            var request = WorkItemRequest.Parse(payload);

            Assert.IsNotNull(request);
            Assert.IsTrue(request.IsValid);
            Assert.AreEqual(ChangeTypes.Restore, request.ChangeType);
            Assert.AreEqual("70b03e83-e51b-4ba1-8799-ee1ae0f863bb", request.CollectionId);
            Assert.AreEqual("https://win-vjnvouqjmam/DefaultCollection/", request.TfsCollectionUri);
            Assert.AreEqual(1, request.WorkItemId);
            Assert.AreEqual("prova1", request.TeamProject);
        }
Exemplo n.º 9
0
        public static string SerializeWorkItemRequest(WorkItemRequest data)
        {
            if (data == null)
            {
                return(null);
            }

            var sb = new StringBuilder();

            using (var sw = XmlWriter.Create(sb))
            {
                _workItemRequestSerializer.WriteObject(sw, data);
            }
            return(sb.ToString());
        }
        public InsertWorkItemCommand(WorkItemRequest request, WorkItemProgress progress, string studyInstanceUid, string seriesInstanceUid, string sopInstanceUid) : base("Insert a WorkItem")
        {
            _request               = request;
            _progress              = progress;
            _studyInstanceUid      = studyInstanceUid;
            ExpirationDelaySeconds = 60;

            WorkItemUid = new WorkItemUid
            {
                Complete          = false,
                FailureCount      = 0,
                SeriesInstanceUid = seriesInstanceUid,
                SopInstanceUid    = sopInstanceUid,
                Failed            = false
            };
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Post(WorkItemRequest request)
        {
            try
            {
                WorkItem workItem = _mapper.Map(request);

                workItem = await _repository.AddAsync(workItem);

                return(CreatedAtAction(nameof(GetById), new { id = workItem.Id }, _mapper.Map(workItem)));
            }

            catch (DataStoreException e)
            {
                _logger.LogError(e.Message, e, request);
                return(StatusCode(StatusCodes.Status500InternalServerError, e.Message));
            }
        }
Exemplo n.º 12
0
        public InsertWorkItemCommand(WorkItem item, string studyInstanceUid, string seriesInstanceUid, string sopInstanceUid)
            : base("Insert a WorkItem")
        {
            _request               = item.Request;
            _studyInstanceUid      = studyInstanceUid;
            ExpirationDelaySeconds = 60;

            WorkItem = item;

            WorkItemUid = new WorkItemUid
            {
                Complete          = false,
                FailureCount      = 0,
                WorkItemOid       = WorkItem.Oid,
                SeriesInstanceUid = seriesInstanceUid,
                SopInstanceUid    = sopInstanceUid,
                Failed            = false
            };
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Put(Guid id, WorkItemRequest request)
        {
            try
            {
                WorkItem workItem = await _repository.GetByIdAsync(id);

                if (workItem == null)
                {
                    return(NotFound());
                }

                _mapper.Map(workItem, request);

                await _repository.UpdateAsync(workItem);

                return(Ok());
            }

            catch (DataStoreException e)
            {
                _logger.LogError(e.Message, e, request);
                return(StatusCode(StatusCodes.Status500InternalServerError, e.Message));
            }
        }
Exemplo n.º 14
0
        public JsonResult GetInstructionsByEntity([FromBody] WorkItemPostData postData)
        {
            var Message = "";

            if (postData.ModuleTableEntryID == 0)
            {
                Message = "No BWQ Entity given";
                return(Json(Message));
            }
            if (postData.ProfileId == "")
            {
                Message = "No Profile given";
                return(Json(Message));
            }
            if (postData.token == "")
            {
                Message = "No token given";
                return(Json(Message));
            }

            var BwqEntities = _context.BWQEntities.Where(t => t.BWQEntitiesID == postData.ModuleTableEntryID);

            //var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJocmV2dXNlcjIiLCJzaWQiOiI4OTI4MjkyNzI4MjI4MjgyODcxMDIiLCJqdGkiOiJmYzliODk5Ny0wZTM4LTQwMjUtYTlmYy04OTY2OWY2MDhmMDkiLCJyb2wiOlt7ImlzYWRtIjp0cnVlLCJybmFtZSI6ImhyLWFkbWluIiwiZ3JwIjpbeyJnbmFtZSI6IkhSV0NPSk9CIn1dfV0sImRtbl9hZG0iOlt7ImRuYW1lIjoiYWRmNDgxOGItYzQxYy00ZjZhLTg1NjAtM2U0NjQxNWQyYzkzIn1dLCJpcHMiOlsiMTI3LjAuMC4xLzEyNy4wLjAuMSJdLCJleHAiOjE1MzkwODk3NjAsImlzcyI6Imh0dHA6Ly9odW1hbnJldmlldy5hcGkucmlzay5sZXhpc25leGlzLmNvbSIsImF1ZCI6Imh0dHA6Ly9odW1hbnJldmlldy5yaXNrLmxleGlzbmV4aXMuY29tIn0.D0JIe7CWT53Lmzfz3BsPzdSHWdDnK-cXxDj7TYdS3SI";
            var token = postData.token;


            var Modules   = _context.ApplicationModules;
            var QueueGuid = (from mods in Modules
                             where mods.ModuleName == "BWQ"
                             select mods.QueueGuid).FirstOrDefault();
            //Queue Guid "D673666A-C99A-4219-9378-032B15FD0C08"


            ReturnData retValue;
            int        WorkItemCount = 0;

            foreach (var ent in BwqEntities)
            {
                if (ent.WorkItemID == null)
                {
                    WorkItemCount += 1;

                    var BWQEntityInstructions = _context.BWQInstructions.Where(t => t.BWQEntitiesID == ent.BWQEntitiesID);
                    var JsonData = JsonConvert.SerializeObject(BWQEntityInstructions);

                    WorkItemRequest req = new WorkItemRequest();
                    req.name                 = "Work Item ID entry for " + postData.ModuleTableEntryID + " and Profile " + postData.ProfileId;
                    req.description          = "Work Item ID entry for BWQ Entity " + postData.ModuleTableEntryID + " and Profile " + postData.ProfileId;
                    req.queueGuid            = QueueGuid;
                    req.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_upd").Value;;
                    req.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_upd").Value;;
                    req.formDefinitionJson   = JsonData;
                    req.isActive             = true;

                    var returnGuid = postWorkItemForEntityAsync(req, token);
                    // workitem here
                    if (returnGuid.value.workItemGuid != null)
                    {
                        ent.WorkItemID = new Guid(returnGuid.value.workItemGuid);
                    }
                }
            }

            if (WorkItemCount > 0)
            {
                retValue = _context.SaveData();

                if (retValue.Message != "Success")
                {
                    return(Json(retValue));
                }                          // return error if workitemid was not updated for this bwq entity
            }

            var ret = from ins in _context.BWQInstructions
                      join ents in _context.BWQEntities on ins.BWQEntitiesID equals ents.BWQEntitiesID
                      join bwqs in _context.BWQ on ents.BWQID equals bwqs.BWQID
                      join bwqf in _context.BWQFieldSelect on ins.BWQFieldSelectID equals bwqf.BWQFieldSelectID
                      where ents.BWQEntitiesID == postData.ModuleTableEntryID
                      select new
            {
                BWQInstructionsID = ins.BWQInstructionsID,
                BWQDispositionsID = ins.BWQDispositionsID,
                BWQEntitiesID     = ins.BWQEntitiesID,
                BWQFieldSelectID  = ins.BWQFieldSelectID,
                BWQDispositions   = ins.BWQDispositions,
                //BWQEntities = ins.BWQEntities,
                //BWQFieldSelect = ins.BWQFieldSelect,
                Instructions   = ins.Instructions,
                CreatedBy      = ins.CreatedBy,
                DateCreatedUTC = ins.DateCreatedUTC,
                UpdatedBy      = ins.UpdatedBy,
                LastUpdatedUTC = ins.LastUpdatedUTC,
                BatchName      = bwqs.BatchName,
                WorkItemId     = ents.WorkItemID,
                Item           = bwqf.FieldDisplayName
            };

            if (ret.Count() < 1)
            {
                {
                    Message = "Instructions not found for BWQ Entity " + postData.ModuleTableEntryID;
                    return(Json(Message));
                }
            }

            return(Json(ret));
        }
Exemplo n.º 15
0
        [Authorize]                   // Require some form of authentication
        public HttpResponseMessage Post([FromBody] JObject payload)
        {
            var request = WorkItemRequest.Parse(payload);

            if (!request.IsValid)
            {
                Log(request.Error);
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = request.Error
                });
            }

            string policyFilePath = System.Configuration.ConfigurationManager.AppSettings["policyFilePath"];
            // macro expansion to permit multi-tenants
            string policyFile = policyFilePath.WithVar(request);

            // cache requires absolute path
            policyFile = System.Web.Hosting.HostingEnvironment.MapPath(policyFile);
            Debug.Assert(System.IO.File.Exists(policyFile));

            // need a logger to show errors in config file (Catch 22)
            var logger = new AspNetEventLogger(request.EventId, LogLevel.Normal);

            var context = new RequestContext(request.TfsCollectionUri, request.TeamProject);
            var runtime = RuntimeContext.GetContext(
                () => policyFile,
                context,
                logger,
                (runtimeContext) => new Core.Facade.WorkItemRepository(runtimeContext),
                (runtimeContext) => new Core.Script.ScriptLibrary(runtimeContext));

            if (runtime.HasErrors)
            {
                Log(runtime.Errors.Current);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    ReasonPhrase = runtime.Errors.Current
                });
            }

            try
            {
                using (EventProcessor eventProcessor = new EventProcessor(runtime))
                {
                    context.CurrentWorkItemId = request.WorkItemId;
                    context.CurrentChangeType = request.ChangeType;
                    var notification = context.Notification;

                    logger.StartingProcessing(context, notification);
                    var result = eventProcessor.ProcessEvent(context, notification);
                    logger.ProcessingCompleted(result);

                    if (result.StatusCode == 0)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                    else
                    {
                        return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                        {
                            ReasonPhrase = result.StatusMessage
                        });
                    }
                }//using
            }
            catch (Exception e)
            {
                logger.ProcessEventException(e);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    ReasonPhrase = e.Message
                });
            }//try
        }
Exemplo n.º 16
0
        public IActionResult Create([FromBody] AlertJobsQueueData newmodel)
        {
            if (!ModelState.IsValid)
            {
                { return(NotFound()); }
            }

            if (newmodel.HRToken.Trim() == "")
            {
                { return(NotFound("Invalid Token")); }
            }
            if (newmodel.AlertNames.Count() < 1)
            {
                return(BadRequest("No Alert Names found"));
            }
            if (newmodel.AlertJobsQueue == null)
            {
                return(BadRequest("No Alert Job found"));
            }

            // Check if HR is up
            var hruri      = _configuration.GetSection("HumanReview:uri").Value + "auth/token";
            var hrResponse = Common.ServerStatusBy(hruri);

            // We expect a 400 - Bad Request, anything else specifically 404 Not Found, return an error
            if (hrResponse.StatusCode == 404)
            {
                { return(NotFound("Error: Human Review Service unavailable")); }
            }

            AlertJobsQueue    alertJobQueue = newmodel.AlertJobsQueue;
            List <AlertNames> alertNames    = newmodel.AlertNames;
            ReturnData        retValue      = null;

            int alertJobsQueueID = 0;
            var identity         = alertJobQueue.CreatedBy;

            try
            {
                var returnObject = _context.AlertJobsQueue.Add(alertJobQueue);
                _context.SaveChanges();

                // check id of new Batch contained in alertJobQueue
                alertJobsQueueID = alertJobQueue.AlertJobsQueueID;
                var todayUtc = DateTime.UtcNow;

                foreach (var alertname in alertNames)
                {
                    var newAlertEntity = new AlertJobsQueueEntity();
                    newAlertEntity.AlertNameID      = alertname.AlertNameID;
                    newAlertEntity.AlertJobsQueueID = alertJobsQueueID; // created above
                    newAlertEntity.CreatedBy        = identity;
                    newAlertEntity.UpdatedBy        = identity;
                    newAlertEntity.DateCreatedUTC   = todayUtc;
                    newAlertEntity.LastUpdatedUTC   = todayUtc;
                    newAlertEntity.StatusID         = 26; // Newly Created, based in CollectionItem, CollectionID
                    //newAlertEntity.WorkItemID
                    _context.AlertJobsQueueEntity.Add(newAlertEntity);
                }
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                var loginfo = e.Message;
                ;
            }

            // Human Review
            #region Human Review Entries

            var AlertEntities = _context.AlertJobsQueueEntity.Where(t => t.AlertJobsQueueID == alertJobsQueueID);
            var Modules       = _context.ApplicationModules;
            var QueueGuid     = (from mods in Modules
                                 where mods.ModuleName == "Alerts"
                                 select mods.QueueGuid).FirstOrDefault();
            try
            {
                foreach (var alertentity in AlertEntities)
                {
                    var JsonData = JsonConvert.SerializeObject(alertentity);

                    WorkItemRequest HRCreateRequest = new WorkItemRequest();
                    HRCreateRequest.name                 = "Created WorkItem for Alert Entity " + alertentity.AlertJobsQueueEntityID;
                    HRCreateRequest.description          = "Created WorkItem for Alert Entity " + alertentity.AlertJobsQueueEntityID;
                    HRCreateRequest.queueGuid            = QueueGuid;
                    HRCreateRequest.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                    HRCreateRequest.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;
                    HRCreateRequest.formDefinitionJson   = JsonData;
                    HRCreateRequest.isActive             = true;

                    var returnGuid = Common.getWorkItemAsync(HRCreateRequest, newmodel.HRToken, _configuration);

                    if (returnGuid.value.workItemGuid == null)
                    {
                        var workitemnotcreated = new
                        {
                            Success = false,
                            Message = "WorkItem not created"
                        };



                        return(Json(workitemnotcreated));
                    }

                    alertentity.WorkItemID = new Guid(returnGuid.value.workItemGuid);
                }

                retValue = _context.SaveData();
                if (retValue.Message == "Success")
                {
                    return(Ok(retValue));
                }                        // return error if workitemid was not updated for this entity
            }
            catch (Exception e)
            {
                var loginfo    = e.Message;
                var iactdelete = Delete(alertJobsQueueID);
            }



            #endregion

            { return(BadRequest(retValue)); }
        }
Exemplo n.º 17
0
        public JsonResult CheckWorkItemID([FromBody] WorkItemPostData postData)
        {
            if (!ModelState.IsValid)
            {
                var badrequest = new
                {
                    Success = false,
                    Message = "Error in Input"
                };
                return(Json(badrequest));
            }

            // Check if HR is up
            var hruri      = _configuration.GetSection("HumanReview:uri").Value + "auth/token";
            var hrResponse = Common.ServerStatusBy(hruri);

            // We expect a 400 - Bad Request, anything else specifically 404 Not Found, return an error
            if (hrResponse.StatusCode == 404)
            {
                { return(Json("Error: Human Review Service unavailable")); }
            }

            var Message = "";

            if (postData.ModuleTableEntryID == 0)
            {
                Message = "No News Entry given";
                return(Json(Message));
            }

            if (postData.token == "")
            {
                Message = "No token given";
                return(Json(Message));
            }

            var token = postData.token;


            // check if News Entry exists
            var NewsEntry = _NewsDBcontext.FeedItemQueue.Where(t => t.id == postData.ModuleTableEntryID).FirstOrDefault();

            if (NewsEntry == null)
            {
                Message = "News Entry does not exist";
                return(Json(Message));
            }
            // check for WorkItemID
            var MappingEntry = _context.HRWorkItemDataMap.Where(t => t.ModuleTableEntryID == postData.ModuleTableEntryID).FirstOrDefault();

            //check if there is an existing WorkItem previously defined
            var DefinedWorkItemGuid = "";

            if (MappingEntry != null)
            {
                DefinedWorkItemGuid = MappingEntry.WorkItemID.ToString();
            }

            ReturnData retValue;

            Guid GuidToSet;

            if (DefinedWorkItemGuid != "")
            {
                GuidToSet = new Guid(DefinedWorkItemGuid.ToString());
            }
            else
            {
                var Modules   = _context.ApplicationModules;
                var QueueGuid = (from mods in Modules
                                 where mods.ModuleName == "News Queue"
                                 select mods.QueueGuid).FirstOrDefault();

                var JsonData = JsonConvert.SerializeObject(NewsEntry);

                WorkItemRequest req = new WorkItemRequest();
                req.name                 = "Work Item ID entry for News Entry " + postData.ModuleTableEntryID;
                req.description          = "Work Item ID entry for News Entry " + postData.ModuleTableEntryID;
                req.queueGuid            = QueueGuid;
                req.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                req.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;
                req.formDefinitionJson   = JsonData;
                req.isActive             = true;

                var returnGuid = Common.getWorkItemAsync(req, token, _configuration);

                if (returnGuid.value.workItemGuid == null)
                {
                    var workitemnotcreated = new
                    {
                        Success = false,
                        Message = "WorkItem not created"
                    };
                    return(Json(workitemnotcreated));
                    // TODO: LOG THIS ERROR
                }

                GuidToSet = new Guid(returnGuid.value.workItemGuid);
            }

            if (MappingEntry == null) // No Entry in HR WorkItemGuid table, insert one
            {
                var newDataMap = new HRWorkItemDataMap();
                newDataMap.WorkUnitTypeID = 5; // Module type

                /*
                 * 3	Investigation
                 * 4	Alerts
                 * 5	News Queue
                 * 6	BWQ
                 */
                // Row ID in Module table, in this case id column of NewsFeed..FeedItemQueue
                newDataMap.ModuleTableEntryID = postData.ModuleTableEntryID;

                newDataMap.WorkItemID = GuidToSet; //HR WorkItem GUID

                newDataMap.UpdatedBy      = postData.appuserid.ToString();
                newDataMap.CreatedBy      = postData.appuserid.ToString();
                newDataMap.DateCreatedUTC = DateTime.UtcNow;
                newDataMap.LastUpdatedUTC = DateTime.UtcNow;

                _context.HRWorkItemDataMap.Add(newDataMap);

                retValue = _context.SaveData();

                if (retValue.Message != "Success")
                {
                    return(Json(retValue));
                }
            }



            return(Json(new { WorkItemGuid = GuidToSet }));
        }
Exemplo n.º 18
0
        public IActionResult Create([FromBody] NewBatchObject newbatch)
        {
            if (!ModelState.IsValid)
            {
                { return(NotFound()); }
            }
            if (newbatch.HRToken.Trim() == "")
            {
                { return(NotFound("Invalid Token")); }
            }
            if (newbatch.Instructions.Count() < 1)
            {
                return(BadRequest("No Instructions found"));
            }
            if (newbatch.Ent_IDs.Count < 1)
            {
                return(BadRequest("No Entities found"));
            }

            // Check if HR is up
            var hruri      = _configuration.GetSection("HumanReview:uri").Value + "auth/token";
            var hrResponse = Common.ServerStatusBy(hruri);

            // We expect a 400 - Bad Request, anything else specifically 404 Not Found, return an error
            if (hrResponse.StatusCode == 404)
            {
                { return(NotFound("Error: Human Review Service unavailable")); }
            }

            int        BatchIdOutput = 0;
            string     ReturnMessage = "";
            ReturnData retValue;

            var InstructionList = new InstructionsCollection();

            foreach (var ins in newbatch.Instructions)
            {
                InstructionList.Add(ins);
            }
            var EntitiesList = new EntitiesCollection();

            foreach (var ent in newbatch.Ent_IDs)
            {
                EntitiesList.Add(ent);
            }


            #region  Save Editorial Data
            try
            {
                using (var sqlCmd = _context.Database.GetDbConnection().CreateCommand())
                {
                    string sp = "usp_CreateBatch_ins";

                    sqlCmd.CommandText = sp;
                    sqlCmd.CommandType = CommandType.StoredProcedure;

                    sqlCmd.Parameters.Add(new SqlParameter("@BatchName", SqlDbType.VarChar, 500)
                    {
                        Value = newbatch.BatchName
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@Description", SqlDbType.VarChar, 1000)
                    {
                        Value = newbatch.Description
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.Date)
                    {
                        Value = newbatch.StartDate
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@DueDate", SqlDbType.Date)
                    {
                        Value = newbatch.DueDate
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@PriorityCollectionItemID", SqlDbType.Int)
                    {
                        Value = newbatch.PriorityCollectionItemID
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@StatusCollectionItemID", SqlDbType.Int)
                    {
                        Value = newbatch.StatusCollectionItemID
                    });

                    sqlCmd.Parameters.Add(new SqlParameter("@Instructions", SqlDbType.Structured)
                    {
                        Value = InstructionList
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@Ent_IDs", SqlDbType.Structured)
                    {
                        Value = EntitiesList
                    });

                    sqlCmd.Parameters.Add(new SqlParameter("@Username", SqlDbType.VarChar, 50)
                    {
                        Value = newbatch.Username
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@OriginalCount", SqlDbType.Int)
                    {
                        Value = newbatch.OriginalCount
                    });
                    sqlCmd.Parameters.Add(new SqlParameter("@Operation", SqlDbType.VarChar, 500)
                    {
                        Value = newbatch.Operation
                    });

                    // output params
                    SqlParameter Results  = new SqlParameter("@Results", SqlDbType.VarChar, 500);
                    SqlParameter NewBWQID = new SqlParameter("@NewBWQID", SqlDbType.Int);
                    Results.Direction  = ParameterDirection.Output;
                    NewBWQID.Direction = ParameterDirection.Output;

                    sqlCmd.Parameters.Add(Results);
                    sqlCmd.Parameters.Add(NewBWQID);

                    if (sqlCmd.Connection.State != ConnectionState.Open)
                    {
                        sqlCmd.Connection.Open();
                    }

                    var execResult = sqlCmd.ExecuteNonQuery();
                    ReturnMessage = Results.Value.ToString();

                    if (NewBWQID.Value.ToString() == "") // no records created
                    {
                        return(BadRequest(new { batch = BatchIdOutput, message = ReturnMessage }));
                    }

                    BatchIdOutput = Convert.ToInt32(NewBWQID.Value);
                }
            }
            catch (Exception e)
            {
                // TODO: log
                return(BadRequest(new { batch = BatchIdOutput, message = ReturnMessage + " " + e.Message }));
            }
            #endregion

            //Human Review Entries
            #region Create Human Review Entries
            try
            {
                var BWQEntities = _context.BWQEntities.Where(t => t.BWQID == BatchIdOutput);
                var Modules     = _context.ApplicationModules;
                var QueueGuid   = (from mods in Modules
                                   where mods.ModuleName == "BWQ"
                                   select mods.QueueGuid).FirstOrDefault();

                foreach (var bwqent in BWQEntities)
                {
                    var BWQEntityInstructionsObject = _context.BWQInstructions
                                                      .Where(t => t.BWQEntitiesID == bwqent.BWQEntitiesID);

                    var thisInstruction = BWQEntityInstructionsObject
                                          .Select(x => new
                    {
                        BWQInstructionsID = x.BWQInstructionsID,
                        BWQEntitiesID     = x.BWQEntitiesID,
                        BWQDispositionsID = x.BWQDispositionsID,
                        BWQFieldSelectID  = x.BWQFieldSelectID,
                        Instructions      = x.Instructions,
                        CreatedBy         = x.CreatedBy,
                        DateCreatedUTC    = x.DateCreatedUTC,
                        UpdatedBy         = x.UpdatedBy,
                        LastUpdatedUTC    = x.LastUpdatedUTC,
                        BWQEntities       = "",
                        BWQDispositions   = "",
                        BWQFieldSelect    = ""
                    });


                    var JsonData = JsonConvert.SerializeObject(thisInstruction);

                    WorkItemRequest HRCreateRequest = new WorkItemRequest();
                    HRCreateRequest.name                 = "Instruction Entries for BWQ Entity " + bwqent.BWQEntitiesID + " and Profile ID " + bwqent.MMMEntityID;
                    HRCreateRequest.description          = "Instruction Entries for BWQ Entity " + bwqent.BWQEntitiesID + " and Profile " + bwqent.MMMEntityID;
                    HRCreateRequest.queueGuid            = QueueGuid;
                    HRCreateRequest.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                    HRCreateRequest.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;
                    HRCreateRequest.formDefinitionJson   = JsonData;
                    HRCreateRequest.isActive             = true;

                    //var returnGuid = getWorkItemForEntityAsync(HRCreateRequest, newbatch.HRToken);

                    var returnGuid = Common.getWorkItemAsync(HRCreateRequest, newbatch.HRToken, _configuration);

                    /*
                     * if (returnGuid.value.workItemGuid == null)
                     * {
                     *  var workitemnotcreated = new
                     *  {
                     *      Success = false,
                     *      Message = "WorkItem not created"
                     *  };
                     *  return BadRequest(workitemnotcreated);
                     *  // TODO: LOG THIS ERROR
                     * }
                     */

                    if (returnGuid.value.workItemGuid == null)
                    {
                        var workitemnotcreated = new
                        {
                            Success = false,
                            Message = "WorkItem not created"
                        };

                        // delete the BWQ entry created above if WorkItemGuid is not created
                        using (var sqlCmd = _context.Database.GetDbConnection().CreateCommand())
                        {
                            string sp = "usp_DeleteBatch_del";

                            sqlCmd.CommandText = sp;
                            sqlCmd.CommandType = CommandType.StoredProcedure;
                            sqlCmd.Parameters.Add(new SqlParameter("@BWQID", SqlDbType.VarChar, 10)
                            {
                                Value = BatchIdOutput.ToString()
                            });
                            // output params
                            SqlParameter Results = new SqlParameter("@Results", SqlDbType.VarChar, 500);
                            Results.Direction = ParameterDirection.Output;
                            sqlCmd.Parameters.Add(Results);


                            if (sqlCmd.Connection.State != ConnectionState.Open)
                            {
                                sqlCmd.Connection.Open();
                            }

                            var execResult = sqlCmd.ExecuteNonQuery();
                            ReturnMessage = Results.Value.ToString();
                        }

                        return(Json(workitemnotcreated + " - " + ReturnMessage));
                    }

                    bwqent.WorkItemID = new Guid(returnGuid.value.workItemGuid);
                }
                ;

                retValue = _context.SaveData();

                if (retValue.Message != "Success")
                {
                    return(Json(retValue));
                }                          // return error if workitemid was not updated for this bwq entity
            }
            catch (Exception e)
            {
                return(BadRequest(new { batch = BatchIdOutput, message = e.Message }));
            }
            #endregion

            return(Ok(new { batch = BatchIdOutput, message = ReturnMessage }));
            //return Ok();
        }
Exemplo n.º 19
0
        public JsonResult CheckWorkItemIDForEntity([FromBody] WorkItemPostData postData)
        {
            if (!ModelState.IsValid)
            {
                var badrequest = new
                {
                    Success = false,
                    Message = "Error in Input"
                };
                return(Json(badrequest));
            }

            var Message = "";

            if (postData.ModuleTableEntryID == 0)
            {
                Message = "No BWQ Entity given";
                return(Json(Message));
            }
            if (postData.ProfileId == "")
            {
                Message = "No Profile given";
                return(Json(Message));
            }
            if (postData.token == "")
            {
                Message = "No token given";
                return(Json(Message));
            }
            // Check if HR is up
            var hruri      = _configuration.GetSection("HumanReview:uri").Value + "auth/token";
            var hrResponse = Common.ServerStatusBy(hruri);

            // We expect a 400 - Bad Request, anything else specifically 404 Not Found, return an error
            if (hrResponse.StatusCode == 404)
            {
                { return(Json("Error: Human Review Service unavailable")); }
            }


            var token = postData.token;

            // check for WorkItemID
            var BwqEntity = _context.BWQEntities.Where(t => t.BWQEntitiesID == postData.ModuleTableEntryID);

            //check if there is an existing WorkItem previously defined
            var DefinedWorkItemGuid = (from bwqents in BwqEntity
                                       where bwqents.WorkItemID != null
                                       select bwqents.WorkItemID).FirstOrDefault().ToString();



            // Get the Entity Detail from MMM, return if not found
            var EntityDetails = _mmmcontext.Entities.Where(t => t.Ent_ID == Convert.ToInt32(postData.ProfileId)).FirstOrDefault();

            if (EntityDetails == null)
            {
                var notfound = new
                {
                    Success = false,
                    Message = "Profile not found in Profile Database"
                };
                return(Json(notfound));
            }

            int        WorkItemCount = 0;
            ReturnData retValue;

            Guid GuidToSet;

            if (DefinedWorkItemGuid != "")
            {
                GuidToSet = new Guid(DefinedWorkItemGuid.ToString());
            }
            else
            {
                var Modules   = _context.ApplicationModules;
                var QueueGuid = (from mods in Modules
                                 where mods.ModuleName == "BWQ"
                                 select mods.QueueGuid).FirstOrDefault();

                var BWQEntityInstructions = _context.BWQInstructions.Where(t => t.BWQEntitiesID == postData.ModuleTableEntryID);
                var JsonData = JsonConvert.SerializeObject(BWQEntityInstructions);

                WorkItemRequest req = new WorkItemRequest();
                req.name                 = "Work Item ID entry for BWQ Entity " + postData.ModuleTableEntryID + " and Profile " + postData.ProfileId;
                req.description          = "Work Item ID entry for BWQ Entity " + postData.ModuleTableEntryID + " and Profile " + postData.ProfileId;
                req.queueGuid            = QueueGuid;
                req.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                req.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;
                req.formDefinitionJson   = JsonData;
                req.isActive             = true;

                var returnGuid = Common.getWorkItemAsync(req, token, _configuration);

                // workitem here

                if (returnGuid.value.workItemGuid == null)
                {
                    var workitemnotcreated = new
                    {
                        Success = false,
                        Message = "WorkItem not created"
                    };
                    return(Json(workitemnotcreated));
                    // TODO: LOG THIS ERROR
                }

                GuidToSet = new Guid(returnGuid.value.workItemGuid);
            }

            foreach (var ent in BwqEntity)
            {
                if (ent.WorkItemID == null)
                {
                    WorkItemCount += 1;

                    // Set workitemGuid
                    ent.WorkItemID = GuidToSet;
                }
            }

            if (WorkItemCount > 0)
            {
                retValue = _context.SaveData();

                if (retValue.Message != "Success")
                {
                    return(Json(retValue));
                }                          // return error if workitemid was not updated for this bwq entity
            }

            return(Json(new { WorkItemGuid = GuidToSet }));
        }
Exemplo n.º 20
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="item">The WorkItem to create a proxy for.</param>
 public WorkItemStatusProxy(WorkItem item)
 {
     Item     = item;
     Progress = item.Progress;
     Request  = item.Request;
 }
        public JsonResult CheckWorkItemIDForEntity([FromBody] WorkItemPostData postData)
        {
            if (!ModelState.IsValid)
            {
                var badrequest = new
                {
                    Success = false,
                    Message = "Error in Input"
                };
                return(Json(badrequest));
            }

            // Check if HR is up
            var hruri      = _configuration.GetSection("HumanReview:uri").Value + "auth/token";
            var hrResponse = Common.ServerStatusBy(hruri);

            // We expect a 400 - Bad Request, anything else specifically 404 Not Found, return an error
            if (hrResponse.StatusCode == 404)
            {
                { return(Json("Error: Human Review Service unavailable")); }
            }

            var Message = "";

            if (postData.ModuleTableEntryID == 0)
            {
                Message = "No Alert Entry given";
                return(Json(Message));
            }

            if (postData.token == "")
            {
                Message = "No token given";
                return(Json(Message));
            }

            var token = postData.token;

            // check for WorkItemID
            var AlertEntityEntry = _context.AlertJobsQueueEntity
                                   .Where(t => t.AlertJobsQueueEntityID == postData.ModuleTableEntryID);

            //check if there is an existing WorkItem previously defined
            var DefinedWorkItemGuid = (from alertentityentry in AlertEntityEntry
                                       where alertentityentry.WorkItemID != null
                                       select alertentityentry.WorkItemID).FirstOrDefault().ToString();

            int        WorkItemCount = 0;
            ReturnData retValue;

            Guid GuidToSet;

            if (DefinedWorkItemGuid != "")
            {
                GuidToSet = new Guid(DefinedWorkItemGuid.ToString());
            }
            else
            {
                var Modules   = _context.ApplicationModules;
                var QueueGuid = (from mods in Modules
                                 where mods.ModuleName == "Alerts"
                                 select mods.QueueGuid).FirstOrDefault();

                var JsonData = JsonConvert.SerializeObject(AlertEntityEntry);

                WorkItemRequest req = new WorkItemRequest();
                req.name                 = "Created WorkItem for Alert Entity " + postData.ModuleTableEntryID;
                req.description          = "Created WorkItem for Alert Entity " + postData.ModuleTableEntryID;
                req.queueGuid            = QueueGuid;
                req.statusDetailTypeGuid = _configuration.GetSection("HumanReview:statusDetailTypeGuid_ins").Value;
                req.reviewTypeGuid       = _configuration.GetSection("HumanReview:reviewTypeGuid_ins").Value;
                req.formDefinitionJson   = JsonData;
                req.isActive             = true;

                var returnGuid = Common.getWorkItemAsync(req, token, _configuration);
                // workitem here

                if (returnGuid.value.workItemGuid == null)
                {
                    var workitemnotcreated = new
                    {
                        Success = false,
                        Message = "WorkItem not created"
                    };
                    return(Json(workitemnotcreated));
                    // TODO: LOG THIS ERROR
                }

                GuidToSet = new Guid(returnGuid.value.workItemGuid);
            }

            foreach (var alertentityentry in AlertEntityEntry)
            {
                if (alertentityentry.WorkItemID == null)
                {
                    WorkItemCount += 1;

                    alertentityentry.WorkItemID = GuidToSet;
                }
            }

            if (WorkItemCount > 0)
            {
                retValue = _context.SaveData();

                if (retValue.Message != "Success")
                {
                    return(Json(retValue));
                }
            }


            return(Json(new { WorkItemGuid = GuidToSet }));
        }