Ejemplo n.º 1
0
        public void CopyRequestDocument()
        {
            //This is a helper method to replicate an issue where two documents were uploaded for the same route
            Guid sourceDocumentID = new Guid("");

            using (var db = new DataContext())
            {
                var user     = db.Users.Where(u => u.UserName == "SystemAdministrator").Select(u => new { u.ID, u.UserName, Name = (u.FirstName + " " + u.LastName).Trim(), u.OrganizationID }).First();
                var identity = new Utilities.Security.ApiIdentity(user.ID, user.UserName, user.Name, user.OrganizationID);
                System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(identity, null);

                var sourceDocument = db.Documents.Single(d => d.ID == sourceDocumentID);

                var document = new Document
                {
                    Name         = sourceDocument.Name,
                    MimeType     = sourceDocument.MimeType,
                    FileName     = sourceDocument.FileName,
                    ItemID       = sourceDocument.ItemID,
                    Kind         = sourceDocument.Kind,
                    Length       = sourceDocument.Length,
                    UploadedByID = sourceDocument.UploadedByID,
                    Viewable     = sourceDocument.Viewable
                };
                document.RevisionSetID = document.ID;

                var sourceRequestDocument = db.RequestDocuments.First(rd => rd.RevisionSetID == sourceDocument.RevisionSetID);

                db.Documents.Add(document);
                db.RequestDocuments.Add(new RequestDocument {
                    RevisionSetID = document.RevisionSetID.Value, DocumentType = DTO.Enums.RequestDocumentType.Output, ResponseID = sourceRequestDocument.ResponseID
                });

                db.SaveChanges();

                document.CopyData(db, sourceDocumentID);
            }
        }
 /// <summary>
 /// Initializes a new DMC routing staus processor.
 /// </summary>
 /// <param name="dataContext"></param>
 /// <param name="identity"></param>
 public DMCRoutingStatusProcessor(DataContext dataContext, Utilities.Security.ApiIdentity identity)
 {
     DataContext = dataContext;
     Identity    = identity;
 }
Ejemplo n.º 3
0
        public AuditLog CreateLogItem(RequestUser requestUser, EntityState entityState, Utilities.Security.ApiIdentity identity, DataContext db, bool addToDbContext = true)
        {
            var orgUser  = db.Users.Where(u => u.ID == identity.ID).Select(u => new { u.UserName, u.Organization.Acronym }).FirstOrDefault();
            var assignee = db.Users.Where(u => u.ID == requestUser.UserID).Select(u => new { u.UserName, Organization = u.Organization.Acronym }).FirstOrDefault();

            var role = db.WorkflowRoles.Where(r => r.ID == requestUser.WorkflowRoleID).Select(r => r.Name).FirstOrDefault();

            string description = string.Format(@"{0} assigned as {1}\{2} by {3}\{4}", role, assignee.Organization, assignee.UserName, orgUser.Acronym, orgUser.UserName);

            if (entityState == EntityState.Deleted)
            {
                description = string.Format(@"{2}, {0}\{1}, has been un-assigned from a request by {3}\{4}", assignee.Organization, assignee.UserName, role, orgUser.Acronym, orgUser.UserName);
            }

            var log = new Audit.RequestAssignmentChangeLog {
                Description       = description,
                Reason            = entityState,
                UserID            = identity.ID,
                RequestID         = requestUser.RequestID,
                RequestUserUserID = requestUser.UserID,
                WorkflowRoleID    = requestUser.WorkflowRoleID
            };

            if (addToDbContext)
            {
                db.LogsRequestAssignmentChange.Add(log);
            }

            return(log);
        }
Ejemplo n.º 4
0
        public async Task GetAllRequestTypesAvailable()
        {
            //going to know the datamart's involved in the request


            //get all the requesttypes the user can create, get the datamarts for the request that are included in the specified datamarts

            //get all the network requesttype mappings for the request types

            //only return requesttypes that have at least one mapping or one local datasource
            Guid IdentityID = new Guid("96DC0001-94F1-47CC-BFE6-A22201424AD0");
            var  Identity   = new Utilities.Security.ApiIdentity(IdentityID, "SystemAdministrator", "System Administrator");

            IEnumerable <Guid> cndsDatamartIDs = new[] { new Guid("efdb60d1-1501-4598-88ba-a6880096e838"),
                                                         new Guid("6b388358-31e1-4ea4-a6b9-a68a00b721c0"),
                                                         new Guid("adaffde9-2a7a-442d-951a-a70f00be7591"),
                                                         new Guid("47a822af-52b7-47e2-ae15-a79200ab9431"),
                                                         new Guid("410f8140-1d63-4b09-860c-a78600f08a31"),
                                                         new Guid("3ee787a1-56b5-46e5-82ac-a78600f49607"), //CNDS ID, for local
                                                         new Guid("5bb1a5df-8786-4b18-b7f3-a68a00b8602d"), //CNDS ID for local
                                                         new Guid("1ae5139d-7ac9-41c3-8552-a68300ae8381")  //CNDS ID, for local
            };



            using (var DataContext = new DataContext())
            {
                DataContext.Configuration.AutoDetectChangesEnabled = false;
                DataContext.Configuration.LazyLoadingEnabled       = false;
                //DataContext.Database.Log = (sql) => {
                //    Logger.Debug(sql);
                //};

                var externalDataSourceInformation = await CNDSApi.DataSources.ListExtended("$filter=" + string.Join(" or ", cndsDatamartIDs.Select(i => string.Format("ID eq {0}", i.ToString("D")))));

                var localNetwork = DataContext.Networks.Where(n => n.Name != "Aqueduct").Select(n => new { n.ID, n.Name }).FirstOrDefault();

                var networkResponse = await CNDSApi.Networks.LookupEntities(localNetwork.ID, cndsDatamartIDs);

                var content = await networkResponse.Content.ReadAsStringAsync();

                var localDataMartIdentifiers = Newtonsoft.Json.JsonConvert.DeserializeObject <Lpp.Utilities.BaseResponse <NetworkEntityIdentifier> >(content);
                var localDataMartIds         = localDataMartIdentifiers.results.Select(i => i.NetworkEntityID).ToArray();

                foreach (var dm in localDataMartIdentifiers.results)
                {
                    Logger.Debug(string.Format("CNDS ID: {1}        Local ID:{0}", dm.NetworkEntityID, dm.EntityID));
                }

                var projects = await(from p in DataContext.Secure <Project>(Identity, Lpp.Dns.DTO.Security.PermissionIdentifiers.Request.Edit)
                                     where p.Active && !p.Deleted && (!p.EndDate.HasValue || p.EndDate.Value > DateTime.UtcNow) && (p.StartDate <= DateTime.UtcNow)
                                     select p.ID).ToArrayAsync();

                var requestTypes = await(from rt in DataContext.ProjectRequestTypes
                                         join project in DataContext.Projects on rt.ProjectID equals project.ID
                                         let userID                         = IdentityID
                                                                  let netID = localNetwork.ID
                                                                              let netName                         = localNetwork.Name
                                                                                                        let wAcls = DataContext.ProjectRequestTypeWorkflowActivities
                                                                                                                    .Where(a => a.RequestTypeID == rt.RequestTypeID && a.WorkflowActivity.Start == true &&
                                                                                                                           a.SecurityGroup.Users.Any(sgu => sgu.UserID == userID) &&
                                                                                                                           a.ProjectID == project.ID &&
                                                                                                                           a.PermissionID == DTO.Security.PermissionIdentifiers.ProjectRequestTypeWorkflowActivities.EditTask.ID
                                                                                                                           )
                                                                                                                    where (rt.RequestType.WorkflowID.HasValue && wAcls.Any(a => a.Allowed) && wAcls.All(a => a.Allowed)) &&
                                                                                                                    projects.Contains(project.ID)
                                                                                                                    select new SourceRequestType
                {
                    ProjectID     = project.ID,
                    Project       = project.Name,
                    RequestTypeID = rt.RequestTypeID,
                    RequestType   = rt.RequestType.Name,
                    LocalRoutes   = (
                        from dm in project.DataMarts
                        let rtAcls = DataContext.ProjectRequestTypeAcls.Where(a => a.RequestTypeID == rt.RequestTypeID && a.ProjectID == dm.ProjectID && a.SecurityGroup.Users.Any(u => u.UserID == userID)).Select(a => a.Permission)
                                     .Concat(DataContext.DataMartRequestTypeAcls.Where(a => a.RequestTypeID == rt.RequestTypeID && a.DataMartID == dm.DataMartID && a.SecurityGroup.Users.Any(sgu => sgu.UserID == userID)).Select(a => a.Permission))
                                     .Concat(DataContext.ProjectDataMartRequestTypeAcls.Where(a => a.RequestTypeID == rt.RequestTypeID && a.ProjectID == dm.ProjectID && a.DataMartID == dm.DataMartID && a.SecurityGroup.Users.Any(sgu => sgu.UserID == userID)).Select(a => a.Permission))
                                     where localDataMartIds.Contains(dm.DataMartID) && (rtAcls.Any(a => a != DTO.Enums.RequestTypePermissions.Deny) && rtAcls.All(a => a != DTO.Enums.RequestTypePermissions.Deny))
                                     orderby dm.DataMart.Name
                                     select new Routing {
                        IsLocal = true,
                        NetworkID = netID,
                        Network = netName,
                        ProjectID = project.ID,
                        Project = project.Name,
                        RequestTypeID = rt.RequestTypeID,
                        RequestType = rt.RequestType.Name,
                        DataMartID = dm.DataMartID,
                        DataMart = dm.DataMart.Name
                    }
                        )
                }
                                         ).ToArrayAsync();



                var networkMappings = await CNDSApi.RequestTypeMapping.FindMappings(requestTypes.Select(rt => new Lpp.CNDS.DTO.NetworkProjectRequestTypeDataMartDTO {
                    NetworkID = localNetwork.ID, ProjectID = rt.ProjectID, RequestTypeID = rt.RequestTypeID
                }).ToArray());

                foreach (var item in requestTypes)
                {
                    var sourceMapping = networkMappings.Where(m => m.NetworkID == localNetwork.ID && m.ProjectID == item.ProjectID && m.RequestTypeID == item.RequestTypeID).FirstOrDefault();
                    if (sourceMapping != null)
                    {
                        item.ExternalRoutes = sourceMapping.Routes
                                              .Select(rt => new Routing
                        {
                            IsLocal       = rt.NetworkID == localNetwork.ID && rt.ProjectID == item.ProjectID,
                            NetworkID     = rt.NetworkID,
                            Network       = rt.Network,
                            ProjectID     = rt.ProjectID,
                            Project       = rt.Project,
                            RequestTypeID = rt.RequestTypeID,
                            RequestType   = rt.RequestType,
                            DataMartID    = rt.DataSourceID,
                            DataMart      = rt.DataSource
                        }).OrderBy(rt => rt.Network).ThenBy(rt => rt.Project).ThenBy(rt => rt.DataMart).ToArray();
                    }
                    else
                    {
                        item.ExternalRoutes = Array.Empty <Routing>();
                    }

                    item.InvalidRoutes = externalDataSourceInformation
                                         .Where(ds => !item.ExternalRoutes.Any(d => d.NetworkID == ds.NetworkID && ds.ID == d.DataMartID) &&
                                                !item.LocalRoutes.Any(d => d.NetworkID == localNetwork.ID && localDataMartIdentifiers.results.Any(i => i.EntityID == ds.ID && i.NetworkEntityID == d.DataMartID)))
                                         .Select(ds => new Routing {
                        NetworkID = ds.NetworkID, Network = ds.Network, DataMartID = ds.ID.Value, DataMart = ds.Name, IsLocal = false
                    })
                                         .Distinct().OrderBy(ds => ds.Network).ThenBy(ds => ds.DataMart);
                }

                //filter out any that do not have any local or external routes
                requestTypes = requestTypes.Where(rt => rt.LocalRoutes.Any() || rt.ExternalRoutes.Any()).ToArray();

                foreach (var requestType in requestTypes)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Project - RequestType: " + requestType.Project + " - " + requestType.RequestType);
                    sb.AppendLine("Local DataMarts:");
                    foreach (var dm in requestType.LocalRoutes)
                    {
                        sb.AppendLine("\tDataMart: " + dm.DataMart);
                    }
                    if (!requestType.LocalRoutes.Any())
                    {
                        sb.AppendLine("\tNo local datamarts.");
                    }
                    sb.AppendLine("External Routes:");
                    foreach (var dm in requestType.ExternalRoutes)
                    {
                        sb.AppendLine(string.Format("\tNetwork:{0}  Project:{1}  RequestType:{2}  Data Source:{3}", dm.Network, dm.Project, dm.RequestType, dm.DataMart));
                    }
                    if (!requestType.ExternalRoutes.Any())
                    {
                        sb.AppendLine("\tNo external routes.");
                    }

                    if (requestType.InvalidRoutes.Any())
                    {
                        sb.AppendLine("Invalid Data Sources:");
                        foreach (var ds in requestType.InvalidRoutes)
                        {
                            sb.AppendLine(string.Format("Network: {0}     Data Source:{1}", ds.Network, ds.DataMart));
                        }
                    }

                    Logger.Debug(sb.ToString());
                }
            }
        }
Ejemplo n.º 5
0
 public override Task <bool> CanUpdate(DataContext db, Utilities.Security.ApiIdentity identity, params Guid[] keys)
 {
     return(Task.Run(() => false));
 }
Ejemplo n.º 6
0
        public override IEnumerable <AuditLog> ProcessEvents(System.Data.Entity.Infrastructure.DbEntityEntry obj, DataContext db, Utilities.Security.ApiIdentity identity, bool read)
        {
            var requestUser = obj.Entity as RequestUser;

            if (requestUser == null)
            {
                throw new InvalidCastException("Invalid entity to log, expecting RequestUser.");
            }

            var logs = new List <AuditLog>();

            logs.Add(CreateLogItem(requestUser, obj.State, identity, db, true));

            return(logs);
        }
Ejemplo n.º 7
0
 public override IQueryable <Workflow> SecureList(DataContext db, IQueryable <Workflow> query, Utilities.Security.ApiIdentity identity, params DTO.Security.PermissionDefinition[] permissions)
 {
     return(query);
 }
Ejemplo n.º 8
0
 public override Task <bool> CanInsert(DataContext db, Utilities.Security.ApiIdentity identity, params Workflow[] objs)
 {
     return(Task.Run(() => false));
 }
Ejemplo n.º 9
0
 public override Task <bool> CanInsert(DataContext db, Utilities.Security.ApiIdentity identity, params Template[] objs)
 {
     return(HasPermissions(db, identity, PermissionIdentifiers.Portal.CreateTemplates));
 }
Ejemplo n.º 10
0
 public override Task <bool> CanUpdate(DataContext db, Utilities.Security.ApiIdentity identity, params Guid[] keys)
 {
     return(HasPermissions(db, identity, keys, PermissionIdentifiers.Templates.Edit));
 }
Ejemplo n.º 11
0
        public override IQueryable <Template> SecureList(DataContext db, IQueryable <Template> query, Utilities.Security.ApiIdentity identity, params DTO.Security.PermissionDefinition[] permissions)
        {
            return(query);

            //Must allow all templates to be viewed because this is used throughout to get template information.

            //if (permissions == null || permissions.Length == 0)
            //{
            //    permissions = new PermissionDefinition[] { PermissionIdentifiers.Portal.ListTemplates, PermissionIdentifiers.Templates.View };
            //}
            //return db.Filter(query, identity, permissions);
        }
Ejemplo n.º 12
0
        public TestDMCController()
        {
            var user = DataContext.Users.Select(u => new { u.ID, u.UserName, u.FirstName, u.LastName, u.OrganizationID }).Single(u => u.UserName == TestUserName);

            _apiIdentity = new ApiIdentity(user.ID, user.UserName, (user.FirstName + " " + user.LastName).Trim(), user.OrganizationID);
        }
        public void OnSubmitSchedulerRequest(Guid userID, Guid requestID)
        {
            //Ensure the request exists and is not deleted, otherwise clear the schedule
            if (DataContext.Requests.Any(p => p.ID == requestID) == false || DataContext.Requests.Any(p => p.ID == requestID && p.Deleted == true))
            {
                DeleteRequestSchedules(requestID);
                return;
            }

            var user = (from u in DataContext.Users where u.ID == userID select u).AsNoTracking().FirstOrDefault();

            Lpp.Utilities.Security.ApiIdentity identity = new Utilities.Security.ApiIdentity(user.ID, user.UserName, user.FullName, user.OrganizationID);

            try
            {
                if (!DataContext.Requests.Any(p => p.ID == requestID))
                {
                    throw new Exception("Cannot find scheduled request ID = " + requestID.ToString());
                }

                var request = DataContext.Requests
                              .Include("Activity")
                              .Include("Activity.ParentActivity")
                              .Include("Activity.ParentActivity.ParentActivity")
                              .Include("SourceActivity")
                              .Include("SourceActivityProject")
                              .Include("SourceTaskOrder")
                              .Include("Organization")
                              .Include("Project")
                              .Include("RequestType")
                              .Include("RequesterCenter")
                              .Include("WorkplanType")
                              .Include("CreatedBy")
                              .Include("UpdatedBy")
                              .Include("SubmittedBy")
                              .Include("DataMarts")
                              .Include("Folders")
                              .Include("SearchTerms")
                              //.AsNoTracking()
                              .SingleOrDefault(r => r.ID == requestID);

                if (request == null)
                {
                    throw new Exception("Cannot find scheduled request ID = " + requestID.ToString());
                }

                var newRequest = CopyRequest(request, identity);
                //db.Entry(ctx.Request).Reload();
                DataContext.Entry(request).Reload();
                DataContext.Entry(newRequest).Reload();

                // Suffix the request name by its recurrence type and instance count.
                XmlSerializer        serializer    = new XmlSerializer(typeof(DTO.Schedule.RequestScheduleModel));
                RequestScheduleModel scheduleModel = serializer.Deserialize(new StringReader(request.Schedule ?? "")) as RequestScheduleModel;

                string schedName = string.IsNullOrEmpty(request.Name) ? "" : request.Name.Substring(0, (request.Name.Length > 100) ? 100 : request.Name.Length);
                schedName = schedName + " (" + scheduleModel.RecurrenceType + " " + (++request.ScheduleCount) + ")";

                newRequest.Name = schedName;
                // If there is a request due date and there is a schedule start date and request due date > schedule start date,
                // then slide the due date forward by the same amount from the current date.
                if (request.DueDate != null && scheduleModel.StartDate != null)
                {
                    DateTime newDueDate = DateTime.Now.Add(((DateTime)request.DueDate).Subtract(scheduleModel.StartDate.DateTime));
                    TimeSpan delta      = newDueDate.Subtract((DateTime)request.DueDate);
                    newRequest.DueDate = newDueDate;
                    //RequestService.TimeShift(newCtx, delta);
                }

                //var res = RequestService.TimeShift(newCtx, newCtx.Request.CreatedOn - ctx.Request.CreatedOn);
                DataContext.SaveChanges();
                if (!SubmitRequest(newRequest.ID, identity))
                {
                    throw new Exception("Failed to submit request.");
                }
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                throw;
            }
        }
Ejemplo n.º 14
0
        public async Task <HttpResponseMessage> Register(CNDSRegisterRequestDTO dto)
        {
            await ConfirmProxyUser(dto);

            var requestTypeDetails = await DataContext.RequestTypes.Where(rt => rt.ID == dto.RequestTypeID)
                                     .Select(rt => new
            {
                rt.ID,
                rt.WorkflowID,
                StartActivityID     = rt.Workflow.RequestReviewWorkflowActivityID ?? DataContext.WorkflowActivityCompletionMaps.Where(wa => wa.WorkflowID == rt.WorkflowID && wa.SourceWorkflowActivity.Start == true).Select(wa => wa.SourceWorkflowActivityID).FirstOrDefault(),
                SubmittedActivityID = rt.Workflow.CompleteDistributionWorkflowActivityID,
                WorkflowRoleID      = rt.Workflow.Roles.Where(wr => wr.IsRequestCreator == true).Select(wr => wr.ID).FirstOrDefault()
            }
                                             ).FirstOrDefaultAsync();

            DTO.RequestDTO sourceRequest = Newtonsoft.Json.JsonConvert.DeserializeObject <DTO.RequestDTO>(dto.RequestDetails);

            //register the request, routes, responses, documents
            var request = DataContext.Requests.Add(new Data.Request
            {
                ID                 = dto.ParticipantID,
                ProjectID          = dto.ProjectID,
                RequestTypeID      = dto.RequestTypeID,
                WorkflowID         = requestTypeDetails.WorkflowID,
                WorkFlowActivityID = requestTypeDetails.StartActivityID,
                CreatedByID        = dto.SourceNetworkID,
                UpdatedByID        = dto.SourceNetworkID,
                SubmittedOn        = DateTime.UtcNow,
                SubmittedByID      = dto.SourceNetworkID,
                Description        = sourceRequest.Description,
                //TODO: figure out the naming format of the request
                Name                  = sourceRequest.Project + ": " + sourceRequest.Name,
                OrganizationID        = Requests.RequestsController.CNDSOrganizationRouteProxyID,
                Priority              = sourceRequest.Priority,
                Query                 = sourceRequest.Query,
                DataMarts             = new List <RequestDataMart>(),
                AdapterPackageVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(this.GetType().Assembly.Location).FileVersion,
                RejectedByID          = null,
                RejectedOn            = null,
                Private               = false
            });

            if (sourceRequest.DueDate.HasValue)
            {
                request.DueDate = sourceRequest.DueDate.Value.DateTime;
            }

            request.Users.Add(new RequestUser
            {
                RequestID      = request.ID,
                UserID         = dto.SourceNetworkID,
                WorkflowRoleID = requestTypeDetails.WorkflowRoleID
            });

            var workflowTask = DataContext.Actions.Add(PmnTask.CreateForWorkflowActivity(request.ID, request.WorkFlowActivityID.Value, request.WorkflowID.Value, DataContext));

            //register the documents
            List <Document> documents = new List <Document>();

            foreach (var doc in dto.Documents)
            {
                var document = DataContext.Documents.Add(new Document
                {
                    ID            = doc.DocumentID,
                    RevisionSetID = doc.RevisionSetID,
                    ItemID        = workflowTask.ID,
                    Name          = doc.Name,
                    FileName      = doc.FileName,
                    Kind          = doc.Kind,
                    Length        = doc.Length,
                    Description   = doc.Description,
                    MimeType      = doc.MimeType,
                    UploadedByID  = dto.SourceNetworkID
                });

                DataContext.ActionReferences.Add(new TaskReference {
                    TaskID = workflowTask.ID, ItemID = document.ID, Type = DTO.Enums.TaskItemTypes.ActivityDataDocument
                });
                documents.Add(document);
            }

            foreach (var datamart in dto.Routes)
            {
                var route = new RequestDataMart
                {
                    ID          = datamart.RouteID,
                    DataMartID  = datamart.DataMartID,
                    DueDate     = datamart.DueDate,
                    Priority    = datamart.Priority,
                    RequestID   = request.ID,
                    RoutingType = DTO.Enums.RoutingType.ExternalCNDS,
                    //default status is awaiting request approval, if the proxy user has permission to skip will be updated and notification sent to source request
                    Status    = DTO.Enums.RoutingStatus.AwaitingRequestApproval,
                    Responses = new HashSet <Response>()
                };

                var response = route.AddResponse(request.CreatedByID);
                response.ID = datamart.ResponseID;

                var responseDocuments = datamart.DocumentIDs.Select(docID => {
                    var dd = documents.First(d => d.ID == docID);
                    return(new RequestDocument {
                        DocumentType = DTO.Enums.RequestDocumentType.Input, ResponseID = response.ID, RevisionSetID = dd.RevisionSetID.Value
                    });
                });

                DataContext.RequestDocuments.AddRange(responseDocuments);

                request.DataMarts.Add(DataContext.RequestDataMarts.Add(route));
            }

            //Parse the query and fix the document references in the fileupload and modular program terms
            DTO.QueryComposer.QueryComposerRequestDTO queryDTO = Newtonsoft.Json.JsonConvert.DeserializeObject <DTO.QueryComposer.QueryComposerRequestDTO>(request.Query);
            var fileUploadTerms = queryDTO.Where.Criteria.SelectMany(c => c.Terms.Where(t => t.Type == Lpp.QueryComposer.ModelTermsFactory.FileUploadID || t.Type == QueryComposer.ModelTermsFactory.ModularProgramID)).ToArray();

            if (fileUploadTerms.Length > 0)
            {
                foreach (var term in fileUploadTerms)
                {
                    var termValue = Newtonsoft.Json.JsonConvert.DeserializeObject <FileUploadValues>(term.Values["Values"].ToString());
                    foreach (var termDoc in termValue.Documents)
                    {
                        var docDTO = dto.Documents.Where(d => d.SourceRevisionSetID == termDoc.RevisionSetID).FirstOrDefault();
                        if (docDTO != null)
                        {
                            termDoc.RevisionSetID = docDTO.RevisionSetID;
                        }
                    }

                    term.Values["Values"] = termValue;
                }

                request.Query = Newtonsoft.Json.JsonConvert.SerializeObject(queryDTO);
            }

            try
            {
                await DataContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Logger.Error("Error saving request: " + request.ID, ex);
                System.Diagnostics.Debugger.Break();
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }

            if (documents.Count > 0)
            {
                //var tasks = dto.Documents.Select(async doc => await GetDocumentContent(doc.DocumentID));
                //await Task.WhenAll(tasks);

                foreach (var doc in documents)
                {
                    await GetDocumentContent(doc.ID);
                }
            }

            //Submit the request if the proxy user has permission to skip request approval
            var permissionFilter = new ExtendedQuery
            {
                Projects             = (a) => a.ProjectID == request.ProjectID,
                ProjectOrganizations = (a) => a.ProjectID == request.ProjectID && a.OrganizationID == request.OrganizationID,
                Organizations        = (a) => a.OrganizationID == request.OrganizationID,
                Users = (a) => a.UserID == request.CreatedByID
            };

            var apiIdentity = new Utilities.Security.ApiIdentity(dto.SourceNetworkID, dto.SourceNetworkName.Replace(" ", "_"), dto.SourceNetworkName, Requests.RequestsController.CNDSOrganizationRouteProxyID);
            var permissions = await DataContext.HasGrantedPermissions <Request>(apiIdentity, request.ID, permissionFilter, Dns.DTO.Security.PermissionIdentifiers.Request.SkipSubmissionApproval);

            if (permissions.Contains(DTO.Security.PermissionIdentifiers.Request.SkipSubmissionApproval))
            {
                await DataContext.Entry(request).ReloadAsync();

                await DataContext.Entry(request).Collection(r => r.DataMarts).LoadAsync();

                var responses = (await DataContext.RequestDataMarts.Where(rdm => rdm.RequestID == request.ID && rdm.Status == DTO.Enums.RoutingStatus.AwaitingRequestApproval).SelectMany(rdm => rdm.Responses.Where(rsp => rsp.Count == rdm.Responses.Max(rr => rr.Count))).ToArrayAsync()).ToDictionary(r => r.RequestDataMartID);

                //update the routings to Submitted
                foreach (var dm in request.DataMarts)
                {
                    await DataContext.Entry(dm).ReloadAsync();

                    Response response = null;
                    if (responses.TryGetValue(dm.ID, out response))
                    {
                        response.SubmittedByID = dto.SourceNetworkID;
                        response.SubmittedOn   = DateTime.UtcNow;
                    }

                    dm.Status = DTO.Enums.RoutingStatus.Submitted;
                }
                try
                {
                    await DataContext.SaveChangesAsync();
                }
                catch (Exception ex) {
                    Logger.Error(ex.Message, ex);
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
                }

                //update the request to submitted
                //manually override the request status using sql direct, EF does not allow update of computed
                await DataContext.Database.ExecuteSqlCommandAsync("UPDATE Requests SET Status = @status WHERE ID = @ID", new System.Data.SqlClient.SqlParameter("@status", (int)DTO.Enums.RequestStatuses.Submitted), new System.Data.SqlClient.SqlParameter("@ID", request.ID));

                await DataContext.Entry(request).ReloadAsync();

                //close the review task
                workflowTask.Status          = DTO.Enums.TaskStatuses.Complete;
                workflowTask.EndOn           = DateTime.UtcNow;
                workflowTask.PercentComplete = 100d;

                //create a new task for the next activity, and set the activity on the request
                request.WorkFlowActivityID = requestTypeDetails.SubmittedActivityID;
                var submitTask = DataContext.Actions.Add(PmnTask.CreateForWorkflowActivity(request.ID, request.WorkFlowActivityID.Value, request.WorkflowID.Value, DataContext));
                try
                {
                    await DataContext.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
                }

                //notify CNDS of request status change, which will in turn notify the source network to update the status of the route
                System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
                {
                    using (var helper = new Lpp.CNDS.ApiClient.NetworkRequestDispatcher())
                    {
                        foreach (var responseID in dto.Routes.Select(rt => rt.ResponseID))
                        {
                            await helper.UpdateSourceRoutingStatus(new[] { new DTO.CNDSUpdateRoutingStatusDTO {
                                                                               ResponseID = responseID, Message = string.Empty, RoutingStatus = DTO.Enums.RoutingStatus.Submitted
                                                                           } });
                        }
                    }
                });
            }


            return(Request.CreateResponse(HttpStatusCode.OK));;
        }
Ejemplo n.º 15
0
        public async Task <HttpResponseMessage> UpdateRoutingStatus(IEnumerable <CNDSUpdateRoutingStatusDTO> dtos)
        {
            var responseIDs = dtos.Select(r => r.ResponseID).Distinct();
            var responses   = (await DataContext.Responses.Include(rsp => rsp.RequestDataMart).Where(rsp => responseIDs.Contains(rsp.ID)).ToArrayAsync()).ToDictionary(k => k.ID);

            if (responses.Count < responseIDs.Count())
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "One or more of the specified responses were not found."));
            }

            foreach (var dto in dtos)
            {
                Response response;
                if (!responses.TryGetValue(dto.ResponseID, out response))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The specified response was not found."));
                }

                await ConfirmProxyUser(dto.NetworkID, dto.Network);

                var routing = response.RequestDataMart;
                await DataContext.Entry(routing).Reference(r => r.Request).LoadAsync();

                var originalRequestStatus = routing.Request.Status;
                var originalStatus        = routing.Status;

                if (originalStatus == DTO.Enums.RoutingStatus.Completed)
                {
                    routing.Status = DTO.Enums.RoutingStatus.ResultsModified;
                }

                if (originalStatus != DTO.Enums.RoutingStatus.Completed && originalStatus != DTO.Enums.RoutingStatus.ResultsModified)
                {
                    routing.Status = dto.RoutingStatus;
                }

                routing.UpdatedOn = DateTime.UtcNow;

                response.ResponseMessage = dto.Message;

                //only set the response time and ID if the response is completed
                var completeStatuses = new[] {
                    Lpp.Dns.DTO.Enums.RoutingStatus.Completed,
                    Lpp.Dns.DTO.Enums.RoutingStatus.ResultsModified,
                    Lpp.Dns.DTO.Enums.RoutingStatus.RequestRejected,
                    Lpp.Dns.DTO.Enums.RoutingStatus.ResponseRejectedBeforeUpload,
                    Lpp.Dns.DTO.Enums.RoutingStatus.ResponseRejectedAfterUpload,
                    Lpp.Dns.DTO.Enums.RoutingStatus.AwaitingResponseApproval
                };

                if (completeStatuses.Contains(routing.Status))
                {
                    response.ResponseTime  = DateTime.UtcNow;
                    response.RespondedByID = dto.NetworkID;
                }
                Logger.Error("Updating status to : " + dto.RoutingStatus + " from " + originalStatus);

                await DataContext.SaveChangesAsync();

                if (completeStatuses.Contains(routing.Status))
                {
                    await DataContext.Entry(routing.Request).ReloadAsync();

                    if (routing.Request.Status == DTO.Enums.RequestStatuses.Complete)
                    {
                        var apiIdentity = new Utilities.Security.ApiIdentity(dto.NetworkID, dto.Network.Replace(" ", "_"), dto.Network, Requests.RequestsController.CNDSOrganizationRouteProxyID);

                        //send the request status complete notification
                        var request = routing.Request;

                        var      requestStatusLogger = new Dns.Data.RequestLogConfiguration();
                        string[] emailText           = await requestStatusLogger.GenerateRequestStatusChangedEmailContent(DataContext, request.ID, apiIdentity.ID, originalRequestStatus, request.Status);

                        var logItems = requestStatusLogger.GenerateRequestStatusEvents(DataContext, apiIdentity, false, originalRequestStatus, request.Status, request.ID, emailText[1], emailText[0], "Request Status Changed");

                        try
                        {
                            await DataContext.SaveChangesAsync();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.Message, ex);
                            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
                        }

                        await Task.Run(() =>
                        {
                            List <Utilities.Logging.Notification> notifications = new List <Utilities.Logging.Notification>();

                            foreach (Lpp.Dns.Data.Audit.RequestStatusChangedLog logitem in logItems)
                            {
                                var items = requestStatusLogger.CreateNotifications(logitem, DataContext, true);
                                if (items != null && items.Any())
                                {
                                    notifications.AddRange(items);
                                }
                            }

                            if (notifications.Any())
                            {
                                requestStatusLogger.SendNotification(notifications);
                            }
                        });
                    }
                }
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }