Beispiel #1
0
 /// <summary>
 /// Convert to service model
 /// </summary>
 /// <returns></returns>
 public static ApplicationDocument Clone(this ApplicationDocument model)
 {
     return(new ApplicationDocument {
         ID = model.ID,
         ApplicationState = model.ApplicationState,
         ApplicationId = model.ApplicationId,
         ApplicationUri = model.ApplicationUri,
         ApplicationName = model.ApplicationName,
         ApplicationType = model.ApplicationType,
         SiteId = model.SiteId,
         ApplicationNames = model.ApplicationNames?
                            .Select(n => new ApplicationDocument.LocalizedText {
             Locale = n.Locale,
             Name = n.Name
         })
                            .ToArray(),
         ProductUri = model.ProductUri,
         DiscoveryUrls = model.DiscoveryUrls?.ToArray(),
         ServerCapabilities = model.ServerCapabilities,
         GatewayServerUri = model.GatewayServerUri,
         DiscoveryProfileUri = model.DiscoveryProfileUri,
         UpdateTime = model.UpdateTime,
         NotSeenSince = model.NotSeenSince,
         CreateTime = model.CreateTime,
         ApproveTime = model.ApproveTime,
         UpdateAuthorityId = model.UpdateAuthorityId,
         DisableAuthorityId = model.DisableAuthorityId,
         CreateAuthorityId = model.CreateAuthorityId,
         ApproveAuthorityId = model.ApproveAuthorityId,
         ETag = model.ETag,
         ClassType = model.ClassType
     });
 }
Beispiel #2
0
        /// <summary>
        /// Convert to service model
        /// </summary>
        /// <returns></returns>
        public static ApplicationDocument ToDocumentModel(
            this ApplicationRegistrationRequestModel model, uint id)
        {
            var document = new ApplicationDocument {
                ID = id,
                ApplicationState = ApplicationState.New,
                CreateTime       = DateTime.UtcNow,
                SiteId           = model.SiteId,
                ApplicationId    = ApplicationInfoModelEx.CreateApplicationId(
                    model.SiteId, model.ApplicationUri, model.ApplicationType),
                ApplicationUri  = model.ApplicationUri,
                ApplicationName = model.ApplicationName ??
                                  model.LocalizedNames.FirstOrDefault().Value,
                ApplicationType  = model.ApplicationType ?? ApplicationType.ClientAndServer,
                ApplicationNames =
                    GetLocalizedText(model.LocalizedNames),
                ProductUri         = model.ProductUri,
                DiscoveryUrls      = model.DiscoveryUrls?.ToArray(),
                ServerCapabilities =
                    GetServerCapabilitiesAsString(model.Capabilities),
                GatewayServerUri    = model.GatewayServerUri,
                DiscoveryProfileUri = model.DiscoveryProfileUri,
            };

            document.Validate();
            return(document);
        }
 public void SaveApplicationDocument(ApplicationDocument applicationDocument)
 {
     if (applicationDocument.DocumentID == default(long) || applicationDocument.DocumentType == null)
     {
         throw new ArgumentException(nameof(applicationDocument));
     }
 }
        public async Task <ActionResult> Details(int?id)
        {
            #region USERVALIDATION
            token = (string)(Session["accessToken"]);
            string userID = (string)(Session["UserID"]);
            #endregion
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            List <ApplicationDocument> applicationDocument = new List <ApplicationDocument>();


            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseurl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                HttpResponseMessage Res = await client.GetAsync($"api/ApplicationDocuments/{id}");

                if (Res.IsSuccessStatusCode)
                {
                    var appDocResponse = Res.Content.ReadAsStringAsync().Result;
                    ApplicationDocument myapplicationdocument = JsonConvert.DeserializeObject <ApplicationDocument>(appDocResponse);
                    return(View(myapplicationdocument));
                }
                else
                {
                    this.AddNotification("Unable to display Application Documents information,please contact Administrator" + Res, NotificationType.ERROR);
                    return(View());
                }
            }
        }
        public async Task <ActionResult> Edit([Bind(Include = "ID,DocumentName,DocumentDescription,OrganizationID,ProgApplicationID,CreatedDate,isDeleted,TimeStamp")] ApplicationDocument applicationDocument)
        {
            if (ModelState.IsValid)
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseurl);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    HttpResponseMessage Res = await client.PutAsJsonAsync($"api/ApplicationDocuments/{applicationDocument.ID}", applicationDocument);

                    if (Res.IsSuccessStatusCode)
                    {
                        this.AddNotification("Application Document information modified successfully", NotificationType.SUCCESS);
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        this.AddNotification("Application Document information cannot be modified at this time. Please contact Administrator", NotificationType.ERROR);
                        return(View());
                    }
                }
            }
            ViewBag.OrganizationID = await OrganizationSelectListByModel(token, applicationDocument.OrganizationID);

            ViewBag.ProgApplicationID = await ProgApplicationSelectListByModel(token, applicationDocument.ProgApplicationID);

            return(View(applicationDocument));
        }
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            List <ApplicationDocument> applicationDocument   = new List <ApplicationDocument>();
            ApplicationDocument        myApplicationDocument = new ApplicationDocument();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseurl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                HttpResponseMessage Res = await client.GetAsync($"api/ApplicationDocuments/{id}");

                if (Res.IsSuccessStatusCode)
                {
                    var appDocResponse = Res.Content.ReadAsStringAsync().Result;
                    myApplicationDocument = JsonConvert.DeserializeObject <ApplicationDocument>(appDocResponse);
                }
                else
                {
                    this.AddNotification("Unable to display Activity document information,please contact Administrator" + Res, NotificationType.ERROR);
                    return(View());
                }
            }

            ViewBag.OrganizationID = await OrganizationSelectListByModel(token, myApplicationDocument.OrganizationID);

            ViewBag.ProgApplicationID = await ProgApplicationSelectListByModel(token, myApplicationDocument.ProgApplicationID);

            return(View(myApplicationDocument));
        }
Beispiel #7
0
        /// <summary>
        /// Convert to document model
        /// </summary>
        /// <returns></returns>
        public static ApplicationDocument ToDocumentModel(
            this ApplicationInfoModel model, string etag = null)
        {
            var document = new ApplicationDocument {
                ID = 0,
                ApplicationState = model.State,
                ApplicationId    = model.ApplicationId,
                ApplicationUri   = model.ApplicationUri,
                ApplicationName  = model.ApplicationName ??
                                   model.LocalizedNames.FirstOrDefault().Value,
                ApplicationType  = model.ApplicationType,
                SiteId           = model.SiteId,
                ApplicationNames =
                    GetLocalizedText(model.LocalizedNames),
                ProductUri         = model.ProductUri,
                DiscoveryUrls      = model.DiscoveryUrls?.ToArray(),
                ServerCapabilities =
                    GetServerCapabilitiesAsString(model.Capabilities),
                GatewayServerUri    = model.GatewayServerUri,
                DiscoveryProfileUri = model.DiscoveryProfileUri,
                UpdateTime          = model.Updated?.Time,
                NotSeenSince        = model.NotSeenSince,
                CreateTime          = model.Created?.Time,
                ApproveTime         = model.Approved?.Time,
                UpdateAuthorityId   = model.Updated?.AuthorityId,
                CreateAuthorityId   = model.Created?.AuthorityId,
                ApproveAuthorityId  = model.Approved?.AuthorityId,
                ETag = etag
            };

            document.Validate();
            return(document);
        }
        public long AddThroughPut(ThroughPutObject throughPut)
        {
            try
            {
                if (throughPut == null)
                {
                    return(-2);
                }

                var documentEntity = ModelMapper.Map <DocumentObject, Document>(throughPut.DocumentObject);
                if (documentEntity == null || documentEntity.DocumentTypeId < 1)
                {
                    return(-2);
                }

                using (var db = new ImportPermitEntities())
                {
                    var throughPutEntities = (from th in db.ThroughPuts.Where(th => th.Id == throughPut.Id)
                                              join appItem in db.ApplicationItems on th.ApplicationItemId equals appItem.Id
                                              join app in db.Applications on appItem.ApplicationId equals app.Id
                                              select new { th, app }).ToList();

                    if (!throughPutEntities.Any())
                    {
                        return(-2);
                    }

                    var throughPutEntity = throughPutEntities[0].th;
                    var appEntity        = throughPutEntities[0].app;

                    var docEntity = db.Documents.Add(documentEntity);
                    db.SaveChanges();

                    var appDoc = new ApplicationDocument
                    {
                        DocumentId    = docEntity.DocumentId,
                        ApplicationId = appEntity.Id
                    };

                    db.ApplicationDocuments.Add(appDoc);
                    db.SaveChanges();


                    throughPutEntity.DocumentId      = docEntity.DocumentId;
                    throughPutEntity.Quantity        = throughPut.Quantity;
                    throughPutEntity.IPAddress       = throughPut.IPAddress;
                    db.Entry(throughPutEntity).State = EntityState.Modified;
                    db.SaveChanges();
                    return(throughPutEntity.Id);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(0);
            }
        }
        public long AddProductBankerDocument(DocumentObject document)
        {
            try
            {
                if (document == null)
                {
                    return(-2);
                }

                var documentEntity = ModelMapper.Map <DocumentObject, Document>(document);
                if (documentEntity == null || string.IsNullOrEmpty(documentEntity.DocumentPath))
                {
                    return(-2);
                }
                using (var db = new ImportPermitEntities())
                {
                    var productBankers = db.ProductBankers.Where(b => b.ApplicationItemId == document.ApplicationItemId && b.BankId == document.BankId).ToList();
                    if (!productBankers.Any())
                    {
                        return(-2);
                    }


                    var imApp = db.Documents.Add(documentEntity);
                    db.SaveChanges();

                    var bankerEntity = productBankers[0];
                    bankerEntity.DocumentId      = imApp.DocumentId;
                    db.Entry(bankerEntity).State = EntityState.Modified;
                    db.SaveChanges();

                    var app = new ApplicationDocument
                    {
                        DocumentId    = imApp.DocumentId,
                        ApplicationId = document.ApplicationId
                    };

                    var dx = db.ApplicationDocuments.Add(app);
                    db.SaveChanges();

                    if (dx.ApplicationDocumentId < 1)
                    {
                        db.Documents.Remove(imApp);
                        return(0);
                    }

                    return(imApp.DocumentId);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(0);
            }
        }
Beispiel #10
0
 /// <summary>
 /// Returns server capabilities as comma separated string.
 /// </summary>
 /// <param name="document">The application record.</param>
 public static string GetServerCapabilitiesAsString(this ApplicationDocument document)
 {
     if ((int)document.ApplicationType != (int)ApplicationType.Client)
     {
         if (string.IsNullOrEmpty(document.ServerCapabilities))
         {
             return("NA");
         }
     }
     return(GetServerCapabilitiesAsString(document.ServerCapabilities));
 }
        public async Task <ActionResult> Create([Bind(Include = "ID,DocumentName,DocumentDescription,LocalFilePath,FileName,OrganizationID,ProgApplicationID,CreatedDate,isDeleted,TimeStamp")] ApplicationDocument applicationDocument)
        {
            #region USERVALIDATION
            token = (string)(Session["accessToken"]);
            string userID = (string)(Session["UserID"]);
            #endregion

            if (ModelState.IsValid)
            {
                HttpPostedFileBase file          = Request.Files["file"];
                string             localfilepath = string.Empty;
                string             filename      = string.Empty;
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/DocumentManagement/ProjectActivityDocument"), fileName);
                    file.SaveAs(path);
                    localfilepath = clientpath + fileName;
                    filename      = fileName.ToString();
                }
                ;
                applicationDocument.CreatedDate   = DateTime.Now;
                applicationDocument.isDeleted     = false;
                applicationDocument.LocalFilePath = localfilepath;
                applicationDocument.FileName      = filename;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseurl);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                    HttpResponseMessage Res = await client.PostAsJsonAsync("api/ApplicationDocuments", applicationDocument);

                    if (Res.IsSuccessStatusCode)
                    {
                        this.AddNotification("Application Document created successfully", NotificationType.SUCCESS);
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        this.AddNotification("Application Document cannot be created at this time. Please contact Administrator" + Res, NotificationType.ERROR);
                        return(View());
                    }
                }
            }
            ViewBag.OrganizationID = await OrganizationSelectListByModel(token, applicationDocument.OrganizationID);

            ViewBag.ProgApplicationID = await ProgApplicationSelectListByModel(token, applicationDocument.ProgApplicationID);

            return(View(applicationDocument));
        }
        private ApplicationDocument Convert(DocumentValidationItemResponse document)
        {
            ApplicationDocument result = new ApplicationDocument();

            // result.ApplicationNumber = document.ApplicationNumber;
            result.DocumentKind         = document.DocumentKind;
            result.PartyId              = document.PartyId;
            result.DocumentContextKind  = document.DocumentContextKind;
            result.ArrangementRequestId = document.ArrangementRequestId;
            result.CollateralId         = document.CollateralId;
            result.Status = document.Status;

            return(result);
        }
Beispiel #13
0
 /// <summary>
 /// Returns server capabilities as comma separated string.
 /// </summary>
 /// <param name="document">The application record.</param>
 public static string GetApplicationName(this ApplicationDocument document)
 {
     if (!string.IsNullOrEmpty(document.ApplicationName))
     {
         return(document.ApplicationName);
     }
     if (document.ApplicationNames != null &&
         document.ApplicationNames.Length != 0 &&
         !string.IsNullOrEmpty(document.ApplicationNames[0].Name))
     {
         return(document.ApplicationNames[0].Name);
     }
     return(null);
 }
        public static ApplicationDocumentView GetDocumentView(this ApplicationDocument document)
        {
            var    mapped      = Mapper.Map <ApplicationDocumentView>(document);
            string contextInfo = null;

            if (document.ArrangementRequest != null)
            {
                contextInfo = document.ArrangementRequest.ProductName;
            }
            if (document.Party != null)
            {
                contextInfo = (contextInfo != null) ? contextInfo + " - " + document.Party.CustomerName : document.Party.CustomerName;
            }
            mapped.DocumentContextInfo = contextInfo;
            return(mapped);
        }
Beispiel #15
0
 /// <summary>
 /// Patch document
 /// </summary>
 /// <param name="document"></param>
 /// <param name="request"></param>
 public static void Patch(this ApplicationDocument document,
                          ApplicationRegistrationUpdateModel request)
 {
     // Patch
     if (!string.IsNullOrEmpty(request.ApplicationName))
     {
         document.ApplicationName = request.ApplicationName;
     }
     if (request.Capabilities != null)
     {
         document.ServerCapabilities =
             GetServerCapabilitiesAsString(request.Capabilities);
     }
     if (!string.IsNullOrEmpty(request.DiscoveryProfileUri))
     {
         document.DiscoveryProfileUri = request.DiscoveryProfileUri;
     }
     if (!string.IsNullOrEmpty(request.GatewayServerUri))
     {
         document.GatewayServerUri = request.GatewayServerUri;
     }
     if (!string.IsNullOrEmpty(request.ProductUri))
     {
         document.ProductUri = request.ProductUri;
     }
     if (request.DiscoveryUrls != null)
     {
         document.DiscoveryUrls = request.DiscoveryUrls.ToArray();
     }
     if (request.LocalizedNames != null)
     {
         var table = GetLocalizedText(document.ApplicationNames);
         foreach (var item in request.LocalizedNames)
         {
             if (item.Value == null)
             {
                 table.Remove(item.Key);
             }
             else
             {
                 table.AddOrUpdate(item.Key, item.Value);
             }
         }
         document.ApplicationNames = GetLocalizedText(table);
     }
     document.Validate();
 }
        private void ResolveForParties()
        {
            var documents           = Application.Documents;
            var existingHandledDocs = new List <long>();

            foreach (var request in Application.ArrangementRequests)
            {
                if (request.ProductSnapshot?.RequiredDocumentation == null)
                {
                    continue;
                }
                var partyDocuments = request.ProductSnapshot.RequiredDocumentation.Where(d =>
                                                                                         d.DocumentContextKind.Equals(DocumentContextKind.PartyEnum) && Application.InvolvedParties.Count() > 0).ToList();
                foreach (var document in partyDocuments)
                {
                    foreach (var party in Application.InvolvedParties)
                    {
                        var appDocument = ApplicationDocument.FromProductDocument(document);
                        appDocument.ApplicationId = Application.ApplicationId;
                        appDocument.PartyId       = party.PartyId;
                        appDocument.Context       = "offer/" + Application.ApplicationNumber + "/involved-parties/" + party.PartyId;

                        if (PartyCorespondsToDocumentPartyRole(party, document))
                        {
                            if (documents.Contains(appDocument))
                            {
                                var existingDoc = documents.FirstOrDefault(d => d.Equals(appDocument));
                                existingHandledDocs.Add(existingDoc.DocumentId);
                            }
                            else
                            {
                                documents.Add(appDocument);
                            }
                        }
                    }
                }
            }
            var deleted = documents.Where(d => d.DocumentId != 0 && !existingHandledDocs.Contains(d.DocumentId) &&
                                          d.DocumentContextKind.Equals(DocumentContextKind.PartyEnum) && d.Origin.Equals(DocumentOrigin.Product))
                          .Select(d => d.DocumentId).ToList();

            _logger.LogInformation("There are {DeletedNumber} unused documents being deleted with party document context kind", deleted.Count());
            documents.RemoveAll(d => deleted.Contains(d.DocumentId));
            Existing.AddRange(existingHandledDocs);
            Deleted.AddRange(deleted);
        }
Beispiel #17
0
        public long AddDocument(DocumentObject document)
        {
            try
            {
                if (document == null)
                {
                    return(-2);
                }

                var documentEntity = ModelMapper.Map <DocumentObject, Document>(document);
                if (documentEntity == null || string.IsNullOrEmpty(documentEntity.DocumentPath))
                {
                    return(-2);
                }
                using (var db = new ImportPermitEntities())
                {
                    var imApp = db.Documents.Add(documentEntity);
                    db.SaveChanges();


                    var app = new ApplicationDocument
                    {
                        DocumentId    = imApp.DocumentId,
                        ApplicationId = document.ApplicationId
                    };

                    var dx = db.ApplicationDocuments.Add(app);
                    db.SaveChanges();

                    if (dx.ApplicationDocumentId < 1)
                    {
                        db.Documents.Remove(imApp);
                        return(0);
                    }

                    return(imApp.DocumentId);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                return(0);
            }
        }
Beispiel #18
0
        private async Task SaveApplicationDocumentsAsync(long applicationID, ApplicationXmlInfo applInfo, Stream xml)
        {
            var packageDocumentData = await DocumentService.SaveDocumentAsync(new DocumentCreateRequest()
            {
                Filename    = "ApplicationXml",
                ContentType = "application/xml",
                Content     = xml
            });

            var packageDocument = new ApplicationDocument()
            {
                ApplicationID = applicationID,
                DocumentType  = 1, // main package
                DocumentID    = packageDocumentData.DocumentDataID
            };

            List <ApplicationDocument> applicationDocuments = new List <ApplicationDocument>();

            applicationDocuments.Add(packageDocument);

            if (applInfo.AttachedDocumentIDs != null && applInfo.AttachedDocumentIDs.Any())
            {
                var attachedDocs = await DocumentService.GetDocumentsAsync(applInfo.AttachedDocumentIDs.ToList());

                applicationDocuments.AddRange(attachedDocs.Select(d => new ApplicationDocument()
                {
                    ApplicationID = applicationID,
                    DocumentID    = d.DocID.Value,
                    DocumentType  = 2 // attachment
                }));
            }

            foreach (var applDoc in applicationDocuments)
            {
                ApplicationDocumentRepository.Create(applDoc);
            }
        }
Beispiel #19
0
 /// <summary>
 /// Create model
 /// </summary>
 /// <param name="document"></param>
 public static ApplicationInfoModel ToServiceModel(
     this ApplicationDocument document)
 {
     return(new ApplicationInfoModel {
         ApplicationId = document.ApplicationId,
         State = document.ApplicationState,
         ApplicationUri = document.ApplicationUri,
         ApplicationName = document.GetApplicationName(),
         ApplicationType = document.ApplicationType,
         LocalizedNames = GetLocalizedText(document.ApplicationNames),
         ProductUri = document.ProductUri,
         DiscoveryUrls = document.DiscoveryUrls.ToHashSetSafe(),
         Capabilities = GetServerCapabilities(document.ServerCapabilities),
         GatewayServerUri = document.GatewayServerUri,
         DiscoveryProfileUri = document.DiscoveryProfileUri,
         NotSeenSince = document.NotSeenSince,
         Approved = ToServiceModel(
             document.ApproveTime, document.ApproveAuthorityId),
         Created = ToServiceModel(
             document.CreateTime, document.CreateAuthorityId),
         Updated = ToServiceModel(
             document.UpdateTime, document.UpdateAuthorityId),
     });
 }
        private void ResolveForCollaterals()
        {
            var documents           = Application.Documents;
            var existingHandledDocs = new List <long>();
            var collateralCodes     = _configurationService.GetEffective <ClassificationSchema>("collateral/classification-schemes/collateral-code").Result;

            foreach (var request in Application.ArrangementRequests)
            {
                if (request is FinanceServiceArrangementRequest financeRequest)
                {
                    if (request.ProductSnapshot?.RequiredDocumentation == null)
                    {
                        _logger.LogInformation("Required documentation on product snapshot is null. Passing to the next request...");
                        continue;
                    }
                    var collateralDocuments = request.ProductSnapshot.RequiredDocumentation.Where(d =>
                                                                                                  d.DocumentContextKind.Equals(DocumentContextKind.CollateralEnum) && financeRequest.CollateralRequirements != null).ToList();
                    _logger.LogInformation("Found {NumberOfDocuments} documents related to collaterals", collateralDocuments.Count());
                    foreach (var document in collateralDocuments)
                    {
                        foreach (var collateralRequirement in financeRequest.CollateralRequirements)
                        {
                            var hasCollateralKind = collateralCodes.Values
                                                    .Exists(v => v.AdditionalFields.GetValueOrDefault("collateral-arrangement-code", "").Equals(collateralRequirement.CollateralArrangementCode) &&
                                                            v.AdditionalFields.GetValueOrDefault("collateral-kind", "").Equals(document.CollateralKind));
                            if (hasCollateralKind)
                            {
                                collateralRequirement.SecuredDealLinks = collateralRequirement.SecuredDealLinks ?? new List <SecuredDealLink>();
                                foreach (var deal in collateralRequirement.SecuredDealLinks)
                                {
                                    var appDocument = ApplicationDocument.FromProductDocument(document);
                                    appDocument.ApplicationId        = Application.ApplicationId;
                                    appDocument.ArrangementRequestId = request.ArrangementRequestId;
                                    appDocument.CollateralId         = "" + collateralRequirement.CollateralRequirementId + "-" + deal.ArrangementNumber;
                                    appDocument.Context = "offer/" + Application.ApplicationNumber + "/arrangement-requests/" +
                                                          request.ArrangementRequestId + "/collateral-arrangements/" + deal.ArrangementNumber;

                                    if (documents.Contains(appDocument))
                                    {
                                        _logger.LogDebug("Found existing application document related to collateral.");
                                        var existingDoc = documents.FirstOrDefault(d => d.Equals(appDocument));
                                        existingHandledDocs.Add(existingDoc.DocumentId);
                                    }
                                    else
                                    {
                                        _logger.LogDebug("Adding new application document related to collateral");
                                        documents.Add(appDocument);
                                    }
                                }
                            }
                            else
                            {
                                _logger.LogInformation("Collateral kind {CollateralKind} not found for collateral arrangement code {CollateralArrangementCode}",
                                                       document.CollateralKind, collateralRequirement.CollateralArrangementCode);
                            }
                        }
                    }
                }
            }
            var deleted = documents.Where(d => d.DocumentId != 0 && !existingHandledDocs.Contains(d.DocumentId) &&
                                          d.DocumentContextKind.Equals(DocumentContextKind.CollateralEnum) && d.Origin.Equals(DocumentOrigin.Product))
                          .Select(d => d.DocumentId).ToList();

            _logger.LogInformation("There are {DeletedNumber} unused documents being deleted with collateral document context kind", deleted.Count());
            _logger.LogInformation("There are {ExistingNumber} existing documents with collateral document context kind", existingHandledDocs.Count());
            documents.RemoveAll(d => deleted.Contains(d.DocumentId));
            Existing.AddRange(existingHandledDocs);
            Deleted.AddRange(deleted);
        }
Beispiel #21
0
        /// <summary>
        /// Validates all fields in an application record to be consistent with
        /// the OPC UA specification.
        /// </summary>
        /// <param name="document">The application</param>
        public static void Validate(this ApplicationDocument document)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (document.ApplicationUri == null)
            {
                throw new ArgumentNullException(nameof(document.ApplicationUri));
            }

            if (!Uri.IsWellFormedUriString(document.ApplicationUri, UriKind.Absolute))
            {
                throw new ArgumentException(document.ApplicationUri +
                                            " is not a valid URI.", nameof(document.ApplicationUri));
            }

            if ((document.ApplicationType < ApplicationType.Server) ||
                (document.ApplicationType > ApplicationType.DiscoveryServer))
            {
                throw new ArgumentException(document.ApplicationType.ToString() +
                                            " is not a valid ApplicationType.", nameof(document.ApplicationType));
            }

            if (string.IsNullOrEmpty(document.GetApplicationName()))
            {
                throw new ArgumentException(
                          "At least one ApplicationName must be provided.",
                          nameof(document.ApplicationNames));
            }

            if (string.IsNullOrEmpty(document.ProductUri))
            {
                throw new ArgumentException(
                          "A ProductUri must be provided.", nameof(document.ProductUri));
            }

            if (!Uri.IsWellFormedUriString(document.ProductUri, UriKind.Absolute))
            {
                throw new ArgumentException(document.ProductUri +
                                            " is not a valid URI.", nameof(document.ProductUri));
            }

            if (document.DiscoveryUrls != null)
            {
                foreach (var discoveryUrl in document.DiscoveryUrls)
                {
                    if (string.IsNullOrEmpty(discoveryUrl))
                    {
                        continue;
                    }

                    if (!Uri.IsWellFormedUriString(discoveryUrl, UriKind.Absolute))
                    {
                        throw new ArgumentException(discoveryUrl + " is not a valid URL.",
                                                    nameof(document.DiscoveryUrls));
                    }

                    // TODO: check for https:/hostname:62541, typo is not detected here
                }
            }

            if ((int)document.ApplicationType != (int)Opc.Ua.ApplicationType.Client)
            {
                if (document.DiscoveryUrls == null || document.DiscoveryUrls.Length == 0)
                {
                    throw new ArgumentException(
                              "At least one DiscoveryUrl must be provided.",
                              nameof(document.DiscoveryUrls));
                }

                if (string.IsNullOrEmpty(document.ServerCapabilities))
                {
                    throw new ArgumentException(
                              "At least one Server Capability must be provided.",
                              nameof(document.ServerCapabilities));
                }

                // TODO: check for valid servercapabilities
            }
            else
            {
                if (document.DiscoveryUrls != null && document.DiscoveryUrls.Length > 0)
                {
                    throw new ArgumentException(
                              "DiscoveryUrls must not be specified for clients.",
                              nameof(document.DiscoveryUrls));
                }
            }
        }