Example #1
0
        protected virtual Organization GetSubmitDocumentData(string transactionId, string docId)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Windsor.Node2008.WNOSDomain.Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                IHeaderDocument2Helper headerDocumentHelper;
                GetServiceImplementation(out headerDocumentHelper);

                // Deserialize the xml file whether or not it has an exchange header
                XmlElement loadElement = null;
                try
                {
                    AppendAuditLogEvent("Attempting to load document with Exchange Header");
                    headerDocumentHelper.Load(tempXmlFilePath);
                    string operation;
                    loadElement = headerDocumentHelper.GetFirstPayload(out operation);
                    if (loadElement == null)
                    {
                        throw new ArgumentException("The submitted document does not contain an ATTAINS payload");
                    }
                }
                catch (Exception)
                {
                    AppendAuditLogEvent("Document does not contain an Exchange Header");
                    // Assume, for now, that document does not have a header
                }

                AppendAuditLogEvent("Deserializing document data to ATTAINS data");
                Organization data = null;
                if (loadElement != null)
                {
                    data = _serializationHelper.Deserialize <Organization>(loadElement);
                }
                else
                {
                    data = _serializationHelper.Deserialize <Organization>(tempXmlFilePath);
                }

                return(data);
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }
Example #2
0
 public bool TryLoad(string serializeFilePath)
 {
     try
     {
         _hd = _serializationHelper.Deserialize <Docs.ExchangeNetworkDocument>(serializeFilePath);
         return(true);
     }
     catch (InvalidOperationException)
     {
         return(false);
     }
 }
        protected virtual CheckStatusInfo ValidateCheckStatusInfo()
        {
            Document existingDoc;

            try
            {
                existingDoc = _documentManager.GetDocumentByName(_transaction.Id, SUBMISSION_CHECK_STATUS_INFO_FILE_NAME, true);
            }
            catch (FileNotFoundException)
            {
                throw new FileNotFoundException(string.Format("The transaction is missing the required \"{0}\" attached document",
                                                              SUBMISSION_CHECK_STATUS_INFO_FILE_NAME));
            }
            CheckStatusInfo info = _serializationHelper.Deserialize <CheckStatusInfo>(existingDoc.Content);
            DateTime        now  = DateTime.Now;

            DateTime earliestSubmitTime = now.AddDays(-_checkStatusForNumDays);

            if (info.SubmitTime < earliestSubmitTime)
            {
                // Exceeded number of check days
                throw new ArgumentException("The remote transaction has not completed in the required amount of time.");
            }

            DateTime nextCheckTime = info.LastCheckStatusTime.AddMinutes(_checkStatusIntervalInMinutes);

            if (nextCheckTime > now)
            {
                // Not ready to check again yet
                return(null);
            }
            return(info);
        }
        protected AccountAuthorizationRequest GetAccountAuthorizationRequest(string transactionId, string docId)
        {
            byte[] content = _documentManager.GetUncompressedContent(transactionId, docId);

            ValidateAuthorizationRequestXml(content);

            AuthorizationRequest request;

            try
            {
                request = _serializationHelper.Deserialize <AuthorizationRequest>(content);
            }
            catch (Exception ex)
            {
                throw new InvalidDataException(string.Format("Could not deserialize authorization request document content for document id: \"{0}\"",
                                                             docId), ex);
            }
            if (_accountAuthorizationRequestManager.HasOpenRequestForUser(request.NaasUsername))
            {
                throw new ArgumentException(string.Format("There is already an open authorization request for the user: {0}", request.NaasUsername));
            }
            if ((request.GeneratedOn < DateTime.Now.AddYears(-2)) || (request.GeneratedOn > DateTime.Now.AddYears(1)))
            {
                throw new ArgumentException(string.Format("The request GeneratedOn date is invalid: {0}", request.GeneratedOn));
            }

            bool existsInNaas =
                _accountAuthorizationRequestManager.ValidateUserExistance(request.NaasUsername, request.AffiliatedNodeId,
                                                                          request.RequestedDataSourceNames);

            AccountAuthorizationRequest accountRequest = new AccountAuthorizationRequest();

            accountRequest.AffiliatedCounty        = request.AffiliatedCounty;
            accountRequest.AffiliatedNodeId        = request.AffiliatedNodeId;
            accountRequest.EmailAddress            = request.EmailAddress;
            accountRequest.FullName                = request.FullName;
            accountRequest.NaasAccount             = request.NaasUsername;
            accountRequest.OrganizationAffiliation = request.OrganizationAffiliation;
            accountRequest.PurposeDescription      = request.PurposeDescription;
            accountRequest.RequestedNodeIds        = request.RequestedNodeIds;
            accountRequest.RequestGeneratedOn      = request.GeneratedOn;
            accountRequest.TelephoneNumber         = request.TelephoneNumber;
            accountRequest.RequestType             = request.RequestType;
            if (!CollectionUtils.IsNullOrEmpty(request.RequestedDataSourceNames))
            {
                List <AccountAuthorizationRequestFlow> flowList =
                    new List <AccountAuthorizationRequestFlow>(request.RequestedDataSourceNames.Length);
                foreach (string flowName in request.RequestedDataSourceNames)
                {
                    flowList.Add(new AccountAuthorizationRequestFlow(flowName));
                }
                accountRequest.RequestedFlows = flowList;
            }
            accountRequest.TransactionId = transactionId;
            return(accountRequest);
        }
Example #5
0
        private List <T> RetrieveStoredContents <T>()
        {
            EnsureFileExistence();
            var contents = File.ReadAllText(_storageFilePath);
            var serVals  = _serializationHelper.Deserialize <Dictionary <Type, List <object> > >(contents) ?? new Dictionary <Type, List <object> >();

            if (!serVals.ContainsKey(typeof(T)))
            {
                return(new List <T>());
            }

            var stringVal = serVals[typeof(T)];
            var listVal   = stringVal.Select(x => (T)x)
                            .ToList();

            return(listVal);
        }
        public string ImportSettings(byte[] settingsFileBytes, ImportExportSettings settingsToImport,
                                     ImportSettingsAction importAction, NodeVisit visit)
        {
            ValidateByRole(visit, SystemRoleType.Admin);

            if (settingsToImport == ImportExportSettings.None)
            {
                return(null);
            }
            if (_compressionHelper.IsCompressed(settingsFileBytes))
            {
                try
                {
                    settingsFileBytes = _compressionHelper.UncompressDeep(settingsFileBytes);
                }
                catch (Exception e)
                {
                    throw new ArgException("Failed to uncompress zip file content: " + e.Message);
                }
            }
            NodeSettings nodeSettings;

            try
            {
                nodeSettings = _serializationHelper.Deserialize <NodeSettings>(settingsFileBytes);
            }
            catch (Exception e)
            {
                throw new ArgException("Failed to deserialize node settings content: " + e.Message);
            }
            string   errorMessage = null;
            DateTime modifiedOn   = DateTime.Now;
            string   modifiedById = visit.Account.Id;

            if (EnumUtils.IsFlagSet(settingsToImport, ImportExportSettings.GlobalArguments))
            {
                IList <ConfigItem> list =
                    NodeSettings.GetGlobalArguments(nodeSettings.GlobalArguments, modifiedById,
                                                    modifiedOn);
                ConfigManager.Import(list, importAction);
            }
            return(errorMessage);
        }
Example #7
0
        protected virtual void DoImport()
        {
            try
            {
                AppendAuditLogEvent("Deserializing AQS XML from file \"{0}\" ...", _xmlFilePath);
                AirQualitySubmissionType data = _serializationHelper.Deserialize <AirQualitySubmissionType>(_xmlFilePath);

                AppendAuditLogEvent("Importing AQS data into database ...");

                AQSPersistDataToDatabase dataPersister = new AQSPersistDataToDatabase(_baseDao, _clearMetadata);
                dataPersister.UpsertAirQualityData(data, this);

                AppendAuditLogEvent("Successfully imported AQS XML into database.");
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to import AQS XML into database with error: {0}",
                                    ExceptionUtils.GetDeepExceptionMessage(e));
                throw;
            }
        }
        protected virtual bool DoProcessResponseDocuments(string localTransactionId, IList <string> documentNames, out Windsor.Node2008.WNOSDomain.Document zipResponseFile)
        {
            AppendAuditLogEvent("Attempting to process response documents for ICIS submission with transaction id \"{0}\"", _submissionTrackingDataType.SubmissionTransactionId);

            string responseZipFileName = FindResponseZipFileName(documentNames);

            AppendAuditLogEvent("Extracting response document content ...");

            zipResponseFile = _documentManager.GetDocumentByName(localTransactionId, responseZipFileName, true);

            string tempFolder = _settingsProvider.CreateNewTempFolderPath();

            _compressionHelper.UncompressDirectory(zipResponseFile.Content, tempFolder);

            string[] responseFiles = Directory.GetFiles(tempFolder);

            string responseAcceptedFilePath = FindResponseAcceptedFilePath(responseFiles);
            string responseRejectedFilePath = FindResponseRejectedFilePath(responseFiles);

            AppendAuditLogEvent("Loading response document content ...");

            AppendAuditLogEvent("Transforming accepted response file ...");
            string responseAcceptedTransformedFilePath = TransformResponseFile50(responseAcceptedFilePath);
            SubmissionResultList acceptedList          = _serializationHelper.Deserialize <SubmissionResultList>(responseAcceptedTransformedFilePath);

#if INCLUDE_TEST_SUBMIT_PROCESSOR
            if (DebugUtils.IsDebugging)
            {
                foreach (var submissionResultsDataType in acceptedList.SubmissionResult)
                {
                    if (string.IsNullOrEmpty(submissionResultsDataType.SubmissionTransactionId))
                    {
                        throw new ArgException("submissionResultsDataType.SubmissionTransactionId is null");
                    }
                }
            }
#endif // INCLUDE_TEST_SUBMIT_PROCESSOR

            AppendAuditLogEvent("Transforming rejected response file ...");
            string responseRejectedTransformedFilePath = TransformResponseFile50(responseRejectedFilePath);
            SubmissionResultList rejectedList          = _serializationHelper.Deserialize <SubmissionResultList>(responseRejectedTransformedFilePath);
#if INCLUDE_TEST_SUBMIT_PROCESSOR
            if (DebugUtils.IsDebugging)
            {
                foreach (var submissionResultsDataType in rejectedList.SubmissionResult)
                {
                    if (string.IsNullOrEmpty(submissionResultsDataType.SubmissionTransactionId))
                    {
                        throw new ArgException("submissionResultsDataType.SubmissionTransactionId is null");
                    }
                }
            }
#endif // INCLUDE_TEST_SUBMIT_PROCESSOR

            List <SubmissionResultsDataType> saveList = new List <SubmissionResultsDataType>(CollectionUtils.Count(acceptedList.SubmissionResult) +
                                                                                             CollectionUtils.Count(rejectedList.SubmissionResult));

            DateTime now = DateTime.Now;
            CollectionUtils.ForEach(acceptedList.SubmissionResult, delegate(SubmissionResultsDataType result)
            {
                //DebugUtils.AssertDebuggerBreak(result.SubmissionTransactionId == _submissionTrackingDataType.SubmissionTransactionId);
                result.CreatedDateTime = now;
                saveList.Add(result);
            });
            CollectionUtils.ForEach(rejectedList.SubmissionResult, delegate(SubmissionResultsDataType result)
            {
                //DebugUtils.AssertDebuggerBreak(result.SubmissionTransactionId == _submissionTrackingDataType.SubmissionTransactionId);
                result.CreatedDateTime = now;
                saveList.Add(result);
            });


            _baseDao.TransactionTemplate.Execute(delegate(Spring.Transaction.ITransactionStatus status)
            {
                try
                {
                    AppendAuditLogEvent("Saving response data to database ...");
                    Type mappingAttributesType = typeof(Windsor.Node2008.WNOSPlugin.ICISNPDES_50.MappingAttributes);

                    Dictionary <string, int> tableRowCounts = _objectsToDatabase.SaveToDatabase(saveList, _baseDao, false, mappingAttributesType);

                    AppendAuditLogEvent("Response data saved to database with the following insert row counts: {0}", CreateTableRowCountsString(tableRowCounts));
                }
                catch (Exception ex1)
                {
                    AppendAuditLogEvent("Failed to save response data to database, rolling back transaction: {0}", ExceptionUtils.GetDeepExceptionMessage(ex1));
                    throw;
                }

                ExecuteStoredProc();

                return(null);
            });

            return(true);
        }
Example #9
0
        protected virtual CommonTransactionStatusCode ProcessSubmitDocument(string transactionId, string docId, out string statusDetail)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Windsor.Node2008.WNOSDomain.Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (_compressionHelper.IsCompressed(document.Content))
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                if (_validateXml)
                {
                    ValidateXmlFileAndAttachErrorsAndFileToTransaction(tempXmlFilePath, "xml_schema.xml_schema.zip",
                                                                       null, transactionId);
                }

                AppendAuditLogEvent("Deserializing document data to ICIS data");
                XmlReader reader = new NamespaceSpecifiedXmlTextReader("http://www.exchangenetwork.net/schema/icis/4", tempXmlFilePath);
                Windsor.Node2008.WNOSPlugin.ICISAIR_54.Document data =
                    _serializationHelper.Deserialize <Windsor.Node2008.WNOSPlugin.ICISAIR_54.Document>(reader);

                //Windsor.Node2008.WNOSPlugin.ICISAIR_54.Document data =
                //    _serializationHelper.Deserialize<Windsor.Node2008.WNOSPlugin.ICISAIR_54.Document>(tempXmlFilePath);

                if (CollectionUtils.IsNullOrEmpty(data.Payload))
                {
                    statusDetail = "Deserialized ICIS does not contain any payload elements, exiting processing thread.";
                    AppendAuditLogEvent(statusDetail);
                    return(CommonTransactionStatusCode.Completed);
                }
                AppendAuditLogEvent("ICIS data contains {0} payloads", data.Payload.Length.ToString());

                Type mappingAttributesType = typeof(Windsor.Node2008.WNOSPlugin.ICISAIR_54.MappingAttributes);

                _baseDao.TransactionTemplate.Execute(delegate
                {
                    if (_deleteExistingDataBeforeInsert)
                    {
                        AppendAuditLogEvent("Deleting all existing ICIS payload data from the data store");

                        int numRowsDeleted = _objectsToDatabase.DeleteAllFromDatabase(typeof(Windsor.Node2008.WNOSPlugin.ICISAIR_54.Payload),
                                                                                      _baseDao, mappingAttributesType);
                        if (numRowsDeleted > 0)
                        {
                            AppendAuditLogEvent("Deleted {0} existing ICIS payload data rows from the data store",
                                                numRowsDeleted.ToString());
                        }
                        else
                        {
                            AppendAuditLogEvent("Did not find any existing ICIS payload data to delete from the data store");
                        }
                    }

                    AppendAuditLogEvent("Storing ICIS payload data into database");

                    foreach (Windsor.Node2008.WNOSPlugin.ICISAIR_54.Payload payload in data.Payload)
                    {
                        Dictionary <string, int> tableRowCounts = _objectsToDatabase.SaveToDatabase(payload, _baseDao, mappingAttributesType);

                        AppendAuditLogEvent("Stored ICIS payload data for operation \"{0}\" into data store with the following table row counts: {1}",
                                            payload.Operation.ToString(), CreateTableRowCountsString(tableRowCounts));
                    }

                    return(null);
                });

                AttachSubmissionResponseToTransaction(transactionId);

                statusDetail = "Successfully processed the submitted ICIS document.";
                return(CommonTransactionStatusCode.Completed);
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to process document with id \"{0}\" with error: {1}",
                                    docId.ToString(), ExceptionUtils.GetDeepExceptionMessage(e));
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }
Example #10
0
        protected void ProcessSubmitDocument(string transactionId, string docId)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Windsor.Node2008.WNOSDomain.Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                AppendAuditLogEvent("Deserializing document data to BEACHES data");
                Windsor.Node2008.WNOSPlugin.BEACHES_24.BeachDataSubmissionDataType data =
                    _serializationHelper.Deserialize <Windsor.Node2008.WNOSPlugin.BEACHES_24.BeachDataSubmissionDataType>(tempXmlFilePath);
                data.BeforeSaveToDatabase();

                AppendAuditLogEvent("Storing BEACHES data into database");

                AppendAuditLogEvent("BEACHES data contains {0} Organization Details, {0} Beach Details, and {0} Beach Procedure Details",
                                    CollectionUtils.Count(data.OrganizationDetail).ToString(),
                                    CollectionUtils.Count(data.BeachDetail).ToString(),
                                    CollectionUtils.Count(data.BeachProcedureDetail).ToString());

                AppendAuditLogEvent("Deleting existing BEACHES data from the data store ...");

                int numRowsDeleted = 0;
                Dictionary <string, int> tableRowCounts = null;

                _baseDao.TransactionTemplate.Execute(delegate
                {
                    _baseDao.AdoTemplate.ExecuteNonQuery(CommandType.Text, "DELETE FROM NOTIF_YEARCOMPLETION");
                    _baseDao.AdoTemplate.ExecuteNonQuery(CommandType.Text, "DELETE FROM NOTIF_PROCEDURE");
                    _baseDao.AdoTemplate.ExecuteNonQuery(CommandType.Text, "DELETE FROM NOTIF_BEACH");
                    _baseDao.AdoTemplate.ExecuteNonQuery(CommandType.Text, "DELETE FROM NOTIF_ORGANIZATION");

                    CollectionUtils.ForEach(data.OrganizationDetail, delegate(Windsor.Node2008.WNOSPlugin.BEACHES_24.OrganizationDetailDataType organizationDetailDataType)
                    {
                        Dictionary <string, int> tableRowCountsTemp = _objectsToDatabase.SaveToDatabase(organizationDetailDataType, _baseDao);
                        tableRowCounts = AddTableRowCounts(tableRowCountsTemp, tableRowCounts);
                    });
                    CollectionUtils.ForEach(data.BeachDetail, delegate(Windsor.Node2008.WNOSPlugin.BEACHES_24.BeachDetailDataType beachDetail)
                    {
                        Dictionary <string, int> tableRowCountsTemp = _objectsToDatabase.SaveToDatabase(beachDetail, _baseDao);
                        tableRowCounts = AddTableRowCounts(tableRowCountsTemp, tableRowCounts);
                    });
                    CollectionUtils.ForEach(data.BeachProcedureDetail, delegate(Windsor.Node2008.WNOSPlugin.BEACHES_24.BeachProcedureDetailDataType beachProcedureDetail)
                    {
                        Dictionary <string, int> tableRowCountsTemp = _objectsToDatabase.SaveToDatabase(beachProcedureDetail, _baseDao);
                        tableRowCounts = AddTableRowCounts(tableRowCountsTemp, tableRowCounts);
                    });
                    if (data.YearCompletionIndicators != null)
                    {
                        Dictionary <string, int> tableRowCountsTemp = _objectsToDatabase.SaveToDatabase(data.YearCompletionIndicators, _baseDao);
                        tableRowCounts = AddTableRowCounts(tableRowCountsTemp, tableRowCounts);
                    }

                    return(null);
                });

                if (numRowsDeleted > 0)
                {
                    AppendAuditLogEvent("Deleted {0} existing BEACHES data rows from the data store",
                                        numRowsDeleted.ToString());
                }
                else
                {
                    AppendAuditLogEvent("Did not find any existing BEACHES data to delete from the data store");
                }
                AppendAuditLogEvent("Stored BEACHES data content into the data store with the following table row counts: {0}",
                                    CreateTableRowCountsString(tableRowCounts));
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to process document with id \"{0}.\"  EXCEPTION: {1}",
                                    docId.ToString(), ExceptionUtils.ToShortString(e));
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }
        protected void ProcessSubmitDocument(string transactionId, string docId)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                IHeaderDocumentHelper headerDocumentHelper;
                GetServiceImplementation(out headerDocumentHelper);

                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                XmlElement loadElement = null;
                try
                {
                    AppendAuditLogEvent("Attempting to load document with Exchange Header");
                    headerDocumentHelper.Load(tempXmlFilePath);
                    string operation;
                    loadElement = headerDocumentHelper.GetFirstPayload(out operation);
                    if (loadElement == null)
                    {
                        throw new ArgumentException("The submitted document does not contain a payload");
                    }
                }
                catch (Exception)
                {
                    AppendAuditLogEvent("Document does not contain an Exchange Header");
                    // Assume, for now, that document does not have a header
                }

                AppendAuditLogEvent("Deserializing document data to TRI data");
                XmlReader reader;

                if (loadElement != null)
                {
                    reader = new NamespaceSpecifiedXmlNodeReader(TRI_XML_NAMESPACE, loadElement);
                }
                else
                {
                    reader = new NamespaceSpecifiedXmlTextReader(TRI_XML_NAMESPACE, tempXmlFilePath);
                }
                TRIDataType data = _serializationHelper.Deserialize <TRIDataType>(reader);

                AppendAuditLogEvent("Setting TRI transaction id to \"{0}\"", transactionId);
                data.TransactionID = transactionId;

                try
                {
                    AppendAuditLogEvent("Storing TRI data into database");

                    TRIData triDataLoader = new TRIData();
                    triDataLoader.Load(data, _baseDao, _deleteExistingDataBeforeInsert);

                    AppendAuditLogEvent("Stored TRI data into database");
                }
                catch (Exception ex)
                {
                    AppendAuditLogEvent("Failed to store TRI data into database: {0}",
                                        ExceptionUtils.GetDeepExceptionMessage(ex));
                    throw;
                }

                if (!string.IsNullOrEmpty(_postProcessingStoredProcName))
                {
                    try
                    {
                        AppendAuditLogEvent("Calling TRI post processing stored proc: \"{0}\"", _postProcessingStoredProcName);

                        _baseDao.DoStoredProc(_postProcessingStoredProcName);

                        AppendAuditLogEvent("Successfully called TRI post processing stored proc");
                    }
                    catch (Exception ex)
                    {
                        AppendAuditLogEvent("Failed to call TRI post processing stored proc: {0}",
                                            ExceptionUtils.GetDeepExceptionMessage(ex));
                        throw;
                    }
                }
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to process document with id \"{0}.\"  EXCEPTION: {1}",
                                    docId.ToString(), ExceptionUtils.ToShortString(e));
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }
Example #12
0
        protected virtual WQXDataType GetWQXData(string transactionId, string docId,
                                                 out Windsor.Node2008.WNOSPlugin.WQX1XsdOrm.WQXDataType data1,
                                                 out WQXDeleteDataType deleteData, out string attachmentsFolderPath)
        {
            WQXDataType data = null;

            data1      = null;
            deleteData = null;
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            attachmentsFolderPath = null;
            string tempFolder = null;

            try
            {
                IHeaderDocumentHelper headerDocumentHelper;
                GetServiceImplementation(out headerDocumentHelper);

                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    tempFolder = _settingsProvider.CreateNewTempFolderPath();
                    AppendAuditLogEvent("Decompressing document to temporary folder");
                    _compressionHelper.UncompressDirectory(document.Content, tempFolder);
                    string[] xmlFiles = Directory.GetFiles(tempFolder, "*.xml");
                    if (xmlFiles.Length == 0)
                    {
                        throw new ArgException("Failed to locate a WQX xml file in the WQX data");
                    }
                    else if (xmlFiles.Length > 1)
                    {
                        throw new ArgException("More than one xml file was found in the WQX data");
                    }
                    tempXmlFilePath = xmlFiles[0];
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                XmlElement loadElement = null;
                try
                {
                    AppendAuditLogEvent("Attempting to load document with Exchange Header");
                    headerDocumentHelper.Load(tempXmlFilePath);
                    loadElement = headerDocumentHelper.GetPayload("Update-Insert");
                    if (loadElement == null)
                    {
                        loadElement = headerDocumentHelper.GetPayload("Delete");
                        if (loadElement == null)
                        {
                            throw new ArgumentException("The submitted document does not contain an \"Update-Insert\" or \"Delete\" payload");
                        }
                    }
                }
                catch (Exception)
                {
                    AppendAuditLogEvent("Document does not contain an Exchange Header");
                    // Assume, for now, that document does not have a header
                }

                AppendAuditLogEvent("Deserializing document data to WQX data");
                if (loadElement != null)
                {
                    try
                    {
                        data = _serializationHelper.Deserialize <WQXDataType>(loadElement);
                        attachmentsFolderPath = tempFolder;
                    }
                    catch (Exception)
                    {
                        AppendAuditLogEvent("Failed to deserialize WQX v2, trying WQX v1 ...");
                        try
                        {
                            data1 = _serializationHelper.Deserialize <Windsor.Node2008.WNOSPlugin.WQX1XsdOrm.WQXDataType>(loadElement);
                        }
                        catch (Exception)
                        {
                            AppendAuditLogEvent("Failed to deserialize WQX v1, trying WQX v2 Delete data ...");
                            deleteData = _serializationHelper.Deserialize <WQXDeleteDataType>(loadElement);
                        }
                    }
                }
                else
                {
                    try
                    {
                        data = _serializationHelper.Deserialize <WQXDataType>(tempXmlFilePath);
                        attachmentsFolderPath = tempFolder;
                    }
                    catch (Exception)
                    {
                        AppendAuditLogEvent("Failed to deserialize WQX v2, trying WQX v1 ...");
                        try
                        {
                            data1 = _serializationHelper.Deserialize <Windsor.Node2008.WNOSPlugin.WQX1XsdOrm.WQXDataType>(tempXmlFilePath);
                        }
                        catch (Exception)
                        {
                            AppendAuditLogEvent("Failed to deserialize WQX v1, trying WQX v2 Delete data ...");
                            deleteData = _serializationHelper.Deserialize <WQXDeleteDataType>(tempXmlFilePath);
                        }
                    }
                }
            }
            catch (Exception)
            {
                FileUtils.SafeDeleteAllFilesAndFoldersInFolder(tempFolder);
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
            return(data);
        }
        protected void ProcessSubmitDocument(string transactionId, string docId)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Windsor.Node2008.WNOSDomain.Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                IHeaderDocumentHelper headerDocumentHelper;
                GetServiceImplementation(out headerDocumentHelper);

                XmlElement loadElement    = null;
                Type       submissionType = null;
                try
                {
                    AppendAuditLogEvent("Attempting to load document with Exchange Header");
                    headerDocumentHelper.Load(tempXmlFilePath);
                    string operation;
                    loadElement = headerDocumentHelper.GetFirstPayload(out operation);
                    if (loadElement == null)
                    {
                        throw new ArgumentException("The submitted document does not contain a payload");
                    }
                    submissionType = GetSubmissionDataTypeFromHeaderOperation(operation);
                }
                catch (Exception)
                {
                    AppendAuditLogEvent("Document does not contain an Exchange Header");
                    // Assume, for now, that document does not have a header
                }

                if (typeof(T) == typeof(object))
                {
                    if (submissionType == null)
                    {
                        throw new ArgumentException("The RCRA submission data type cannot be determined from the Exchange Header");
                    }
                }
                else if (submissionType != null)
                {
                    if (submissionType != typeof(T))
                    {
                        throw new ArgumentException(string.Format("The RCRA submission data type ({0}) does not match the expected data type ({1})",
                                                                  submissionType.Name, typeof(T).Name));
                    }
                }
                AppendAuditLogEvent("Deserializing document data to RCRA data");
                T data = null;
                if (loadElement != null)
                {
                    if ((typeof(T) == typeof(object)))
                    {
                        data = (T)_serializationHelper.Deserialize(loadElement, submissionType);
                    }
                    else
                    {
                        data = _serializationHelper.Deserialize <T>(loadElement);
                    }
                }
                else
                {
                    data = _serializationHelper.Deserialize <T>(tempXmlFilePath);
                }

                AppendAuditLogEvent("Submitted document is of type {0}", data.GetType().Name);

                Dictionary <string, int> tableRowCounts = null;

                string deleteMessage = null;
                _baseDao.TransactionTemplate.Execute(delegate
                {
                    if (_deleteExistingDataBeforeInsert)
                    {
                        deleteMessage = DeleteBeforeInsert(data);
                    }

                    tableRowCounts = Insert(data);

                    return(null);
                });

                if (!string.IsNullOrEmpty(deleteMessage))
                {
                    AppendAuditLogEvent(deleteMessage);
                }
                AppendAuditLogEvent("Inserted RCRA content into the data store with the following table row counts: {0}",
                                    CreateTableRowCountsString(tableRowCounts));
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to process document with id \"{0}.\"  EXCEPTION: {1}",
                                    docId.ToString(), ExceptionUtils.ToShortString(e));
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }
        public static WQXDataType GenerateWqxObjectsFromSubmissionFile(IAppendAuditLogEvent appendAuditLogEvent, string submissionFilePath,
                                                                       string sysTempFolderPath, Assembly xmlSchemaZippedResourceAssembly,
                                                                       string xmlSchemaZippedQualifiedResourceName, string xmlSchemaRootFileName,
                                                                       ISerializationHelper serializationHelper, ICompressionHelper compressionHelper,
                                                                       out string attachmentsFolderPath, out string validationErrorsFile)
        {
            WQXDataType data = null;

            attachmentsFolderPath = null;
            string wqxFilePath = null;

            validationErrorsFile = null;

            try
            {
                attachmentsFolderPath = Path.Combine(sysTempFolderPath, Guid.NewGuid().ToString());
                Directory.CreateDirectory(attachmentsFolderPath);

                appendAuditLogEvent.AppendAuditLogEvent("Decompressing the WQX data to a temporary folder ...");
                try
                {
                    compressionHelper.UncompressDirectory(submissionFilePath, attachmentsFolderPath);
                }
                catch (Exception ex)
                {
                    throw new ArgException("An error occurred decompressing the WQX data: {0}", ExceptionUtils.GetDeepExceptionMessage(ex));
                }
                string[] xmlFiles = Directory.GetFiles(attachmentsFolderPath, "*.xml");
                if (xmlFiles.Length == 0)
                {
                    throw new ArgException("Failed to locate an WQX xml file in the WQX data");
                }
                else if (xmlFiles.Length > 1)
                {
                    throw new ArgException("More than one xml file was found in the WQX data");
                }
                wqxFilePath = xmlFiles[0];

                if (!string.IsNullOrEmpty(xmlSchemaZippedQualifiedResourceName))
                {
                    validationErrorsFile =
                        BaseWNOSPlugin.ValidateXmlFile(wqxFilePath, xmlSchemaZippedResourceAssembly, xmlSchemaZippedQualifiedResourceName,
                                                       xmlSchemaRootFileName, sysTempFolderPath, appendAuditLogEvent, compressionHelper);

                    if (validationErrorsFile != null)
                    {
                        FileUtils.SafeDeleteDirectory(attachmentsFolderPath);
                        return(null);
                    }
                }

                //Remove header
                wqxFilePath = RemoveHeaderFile(wqxFilePath, sysTempFolderPath, serializationHelper);

                appendAuditLogEvent.AppendAuditLogEvent("Deserializing the WQX data xml file ...");
                try
                {
                    data = serializationHelper.Deserialize <WQXDataType>(wqxFilePath);
                }
                catch (Exception ex)
                {
                    appendAuditLogEvent.AppendAuditLogEvent("Failed to deserialize the WQX data xml file: {0}", ExceptionUtils.GetDeepExceptionMessage(ex));
                    throw;
                }
                if (data == null)
                {
                    appendAuditLogEvent.AppendAuditLogEvent("The WQX data does not contain any organizations, so no elements will be stored in the database.");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                FileUtils.SafeDeleteDirectory(attachmentsFolderPath);
                throw ex;
            }
            finally
            {
                FileUtils.SafeDeleteFile(wqxFilePath);
            }

            return(data);
        }
Example #15
0
        protected void ProcessSubmitDocument(string transactionId, string docId)
        {
            string tempXmlFilePath = _settingsProvider.NewTempFilePath();

            try
            {
                AppendAuditLogEvent("Getting data for document with id \"{0}\"", docId);
                Windsor.Node2008.WNOSDomain.Document document = _documentManager.GetDocument(transactionId, docId, true);
                if (document.IsZipFile)
                {
                    AppendAuditLogEvent("Decompressing document to temporary file");
                    _compressionHelper.UncompressDeep(document.Content, tempXmlFilePath);
                }
                else
                {
                    AppendAuditLogEvent("Writing document data to temporary file");
                    File.WriteAllBytes(tempXmlFilePath, document.Content);
                }

                IHeaderDocumentHelper headerDocumentHelper;
                GetServiceImplementation(out headerDocumentHelper);

                XmlElement loadElement = null;
                try
                {
                    AppendAuditLogEvent("Attempting to load document with Exchange Header");
                    headerDocumentHelper.Load(tempXmlFilePath);
                    string operation;
                    loadElement = headerDocumentHelper.GetFirstPayload(out operation);
                    if (loadElement == null)
                    {
                        throw new ArgumentException("The submitted document does not contain a payload");
                    }
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("Document does not contain an Exchange Header", ex);
                }
                if (string.IsNullOrEmpty(headerDocumentHelper.Organization))
                {
                    throw new ArgumentException("Document does not contain an Organization element in the Exchange Header");
                }
                if (headerDocumentHelper.Organization.Length < 4)
                {
                    throw new ArgumentException("Document does not contain an valid Organization element in the Exchange Header");
                }
                string orgId = headerDocumentHelper.Organization.Substring(0, 4);
                AppendAuditLogEvent("Submitted document contains data for data organization \"{0}\"",
                                    orgId);

                AppendAuditLogEvent("Deserializing document data to UIC data");
                UICDataType data = null;
                if (loadElement != null)
                {
                    data = _serializationHelper.Deserialize <UICDataType>(loadElement);
                }
                else
                {
                    data = _serializationHelper.Deserialize <UICDataType>(tempXmlFilePath);
                }
                data.OrgId = orgId;

                int numRowsDeleted = 0;
                Dictionary <string, int> tableRowCounts = null;

                _baseDao.TransactionTemplate.Execute(delegate
                {
                    if (_deleteExistingDataBeforeInsert)
                    {
                        AppendAuditLogEvent("Deleting existing UIC data from the data store for organization \"{0}\" ...", data.OrgId);
                        numRowsDeleted = _baseDao.DoSimpleDelete("UIC_ORG", "ORG_ID", data.OrgId);
                    }

                    tableRowCounts = _objectsToDatabase.SaveToDatabase(data, _baseDao);

                    return(null);
                });

                if (_deleteExistingDataBeforeInsert)
                {
                    if (numRowsDeleted > 0)
                    {
                        AppendAuditLogEvent("Deleted {0} existing WQX data rows from the data store for organization \"{1}\"",
                                            numRowsDeleted.ToString(), data.OrgId);
                    }
                    else
                    {
                        AppendAuditLogEvent("Did not find any existing UIC data to delete from the data store for data organization \"{0}\"",
                                            data.OrgId);
                    }
                }
                AppendAuditLogEvent("Stored UIC data content with data organization \"{0}\" into data store with the following table row counts: {1}",
                                    data.OrgId, CreateTableRowCountsString(tableRowCounts));
            }
            catch (Exception e)
            {
                AppendAuditLogEvent("Failed to process document with id \"{0}.\"  EXCEPTION: {1}",
                                    docId.ToString(), ExceptionUtils.ToShortString(e));
                throw;
            }
            finally
            {
                FileUtils.SafeDeleteFile(tempXmlFilePath);
            }
        }