Example #1
0
        /// <summary>
        /// Unzip a file and any zip files contained within it.
        /// </summary>
        /// <param name="zipFile">path of zipfile</param>
        /// <returns>true if file successfully unzipped, false if it failed</returns>
        private bool UnzipFile(string zipFile)
        {
            try
            {
                //Unzip the zip file
                string zipFileName = Path.GetFileName(zipFile);

                //DV NT Re-eng Phase 1 set as a public for use elsewhere
                _zipFileName = zipFileName;
                // create a public guid for the big zip file - not working as this is called for each little zip
                _guid = Guid.NewGuid().ToString();

                string zipFilePath   = zipFile.Replace(zipFileName, "");
                string zipFileSubDir = zipFilePath + zipFileName.Substring(0, zipFileName.Length - 4);
                Directory.CreateDirectory(zipFileSubDir);
                QuickZip.Unzip(zipFile, zipFileSubDir, new string[] { "*" });

                //Scan the unipped contents for input files
                ScanForInputFiles(zipFileSubDir);
                //DirectoryInfo dirInfo = new DirectoryInfo(zipFileSubDir);
                //dirInfo.Delete(true);
            }
            catch (Exception e)
            {
                NexdoxMessaging.SendMessage("Failed to unzip file: " + zipFile + " error message: " + e.Message, true, this);

                //_errorFiles.Add();
                return(false);
            }

            return(true);
        }
Example #2
0
        private void MoveFile(string from, string to)
        {
            NexdoxMessaging.SendMessage(string.Format("  Moving - {0} to {1}", from, to), false, this);

            if (File.Exists(to) && Statics.OverwriteDataFiles)
            {
                File.Delete(to);
            }

            File.Copy(from, to);
        }
Example #3
0
        public void Go()
        {
            NexdoxMessaging.StartEvent(this);
            Statics.Initialise(_engine, _appInfo);

            this.PerformIOC();

            _houseHoldingRunEngine.ProcessHouseHoldingRun();

            NexdoxMessaging.EndEvent(this);
        }
Example #4
0
        private void SaveDocumentToDatabase(ExtractedDocument extractedDocument, int docTypeId, int subDocTypeId, int manCoId, int gridRunId)
        {
            _documentService.AddDocument(
                extractedDocument.DocumentId,
                docTypeId,
                subDocTypeId,
                manCoId,
                gridRunId,
                extractedDocument.MailPrintFlag);

            NexdoxMessaging.SendMessage(string.Format("Document {0} saved to database", extractedDocument.DocumentId), true, this);
        }
Example #5
0
        private void CreateTriggerFileForTransfers(string triggerName)
        {
            NexdoxMessaging.SendMessage("    Creating Transfers Trigger File trigger.cnf", true, this);

            StreamWriter triggerFile = new StreamWriter(_transferFileDestinationDirectory + triggerName + ".cnf");

            foreach (string transferFile in _transferFiles)
            {
                triggerFile.WriteLine(transferFile);
            }

            triggerFile.Close();
            _transferFiles.Clear();
        }
Example #6
0
        private void CreateTriggerFilesForCwrCws(string triggerName)
        {
            NexdoxMessaging.SendMessage("    Creating Contract CWR+CWS Trigger File trigger.cnf", true, this);

            StreamWriter triggerFile = new StreamWriter(_contractCWRCWSFileDestinationDirectory + triggerName + ".cnf");

            foreach (string fileName in _contractCWRCWSFiles)
            {
                triggerFile.WriteLine(fileName);
            }

            triggerFile.Close();
            _contractCWRCWSFiles.Clear();
        }
Example #7
0
        private void ProcessXMLFile(string dataFile)
        {
            NexdoxMessaging.SendMessage(string.Format("Processing file {0}", dataFile), true, this);

            XmlDataExtractor xmlDataExtractor = new XmlDataExtractor();

            var grid = xmlDataExtractor.GetGrid(dataFile);

            var extractedDocuments = xmlDataExtractor.GetDocument(dataFile);

            string applicationCode = extractedDocuments.First().Application;

            _gridRunEngine.ProcessGridRun(
                string.Empty,
                applicationCode,
                string.Empty,
                grid,
                null,
                null,
                GridRunStatus.Undefined,
                null);

            var gridRun = _gridRunService.GetGridRun(applicationCode, grid);

            NexdoxMessaging.SendMessage(string.Format("Grid processed"), true, this);

            foreach (var document in extractedDocuments)
            {
                var subDocTypeData = this.GetSubDocTypeData(document.SubDocType);
                var manCoData      = this.GetManCoData(document.ManCoCode);

                var autoApproval = this._documentApprovalService.GetAutoApproval(manCoData.ManCoId, subDocTypeData.DocTypeId, subDocTypeData.SubDocTypeId);


                SaveDocumentToDatabase(document, subDocTypeData.DocTypeId, subDocTypeData.SubDocTypeId, manCoData.ManCoId, gridRun.Id);

                if (autoApproval != null)
                {
                    NexdoxMessaging.SendMessage(string.Format("Document {0} automatically approved", document.DocumentId), true, this);

                    _approvalEngine.AutoApproveDocument(document.DocumentId);
                }
                else
                {
                    NexdoxMessaging.SendMessage(string.Format("Document {0} requires manual approval approved", document.DocumentId), true, this);
                }
            }
        }
Example #8
0
        private static void RegisterTypes(ContainerBuilder builder)
        {
            string ctor = Statics.UnitySQLServer;

            NexdoxMessaging.SendMessage(string.Format("Connection string : {0} ", ctor), false, null);

            var repositoryAssemblies = Assembly.Load("UnityRepository");

            builder.RegisterAssemblyTypes(repositoryAssemblies)
            .AsImplementedInterfaces()
            .WithParameter(new NamedParameter("connectionString", ctor));

            var serviceAssemblies = Assembly.Load("Services");

            builder.RegisterAssemblyTypes(serviceAssemblies).AsImplementedInterfaces();
        }
Example #9
0
        /// <summary>
        /// Initialise static variables.
        /// </summary>
        /// <param name="engine">Nexdox Engine created by NexdoxLaunch and passed to the program on declaration.</param>
        /// <param name="appInfo">Application Info created by NexdoxLaunch and passed to the program on declaration.</param>
        static public void Initialise(NexdoxEngine engine, ApplicationInfo appInfo)
        {
            OverwriteDataFiles     = bool.Parse(appInfo["OverwriteDataFiles"]);
            HugeFileSplitThreshold = Int32.Parse(appInfo["HugeFileSplitThreshold"]) * 1000;
            CntFilesRoutingMode    = appInfo["CntFilesRoutingMode"];
            SilentTest             = bool.Parse(appInfo["SilentTest"]);
            UnitySQLServer         = appInfo["UnitySQLServer"];
            //Resource Manager
            NexdoxResourceManager.Mode processingMode = NexdoxResourceManager.Mode.ProcessingNoDamConnection;
            switch (appInfo["DAMConnection"])
            {
            case "Compulsory":
                processingMode = NexdoxResourceManager.Mode.ProcessingCompulsoryDamConnection;
                break;

            case "Optional":
                processingMode = NexdoxResourceManager.Mode.ProcessingOptionalDamConnection;
                break;
            }

            string region = appInfo["Region"];

            NexdoxMessaging.SendMessage(string.Format("Setting up region: {0} resource manager", region), false, null);
            Resources = new NexdoxResourceManager(appInfo.ApplicationID, new DirectoryInfo(appInfo.ResourcePath), engine, processingMode, region);
            Resources.ResourceManagerAsset.GetLatestFromDam();
            CentralResources = Resources.ExternalApps[0];
            CentralResources.ResourceManagerAsset.GetLatestFromDam();

            //Read ManCoSettings from RMC
            ManagementCompanySettings = new ManCoSettingsCollection(CentralResources, NexdoxSettings.FontCollection, true);

            AppsToIgnore = new List <string>();

            //These applications will not be allocated data, the datafiles will be ignored
            FieldList ignoreApps = new FieldList(appInfo["AppsToIgnore"], ",", "\"", FieldList.SplitMethod.MicrosoftExcel);

            foreach (string app in ignoreApps)
            {
                AppsToIgnore.Add(app.ToUpper());
            }

            zipPackage = new ZipPackageCollection();

            //NTUtils.Statics.SharedFolderPath = appInfo["SharedResourceFolder"];
        }
Example #10
0
        public void Go()
        {
            // Start the nexdox messaging service
            NexdoxMessaging.StartEvent(this);

            // Initialise Statics
            Statics.Initialise(_engine, _appInfo);

            this.PerformIOC();

            // Allocation Stage
            Allocation allocationStage = new Allocation(
                _engine, _appInfo, _documentService, _documentApprovalService, _subDocTypeService, _gridRunEngine, _manCoService, _approvalEngine, _gridRunService);

            allocationStage.Process();

            // Stop the nexdox messaging service
            NexdoxMessaging.EndEvent(this);
        }
Example #11
0
        private void CreateTriggerFileForContractNotes(string triggerName)
        {
            NexdoxMessaging.SendMessage("    Creating Contract Trigger File(s) trigger_*.cnf", true, this);

            int contractCount = 0;

            foreach (string fileName in _contractFiles)
            {
                //need to generate a trigger file for each xml that is not SWS/SWR/CWS/CWR
                using (
                    StreamWriter triggerFile =
                        new StreamWriter(
                            string.Format("{0}{1}_{2}.cnf", _contractFileDestinationDirectory, triggerName, contractCount)))
                {
                    triggerFile.WriteLine(fileName);
                }

                contractCount++;
            }
            _contractFiles.Clear();
        }
Example #12
0
        private static void RegisterTypes(ContainerBuilder builder)
        {
            string ctor = Statics.UnitySQLServer;

            NexdoxMessaging.SendMessage(string.Format("Connection string : {0} ", ctor), false, null);

            var repositoryAssemblies = Assembly.Load("UnityRepository");

            builder.RegisterAssemblyTypes(repositoryAssemblies)
            .AsImplementedInterfaces()
            .WithParameter(new NamedParameter("connectionString", ctor));

            var abstractConfigurationManager = Assembly.Load("AbstractConfigurationManager");

            builder.RegisterAssemblyTypes(abstractConfigurationManager).AsImplementedInterfaces();

            var configurationManagerWrapperAssembly = Assembly.Load("ConfigurationManagerWrapper");

            builder.RegisterAssemblyTypes(configurationManagerWrapperAssembly).AsImplementedInterfaces();

            var logging = Assembly.Load("Logging");

            builder.RegisterAssemblyTypes(logging).AsImplementedInterfaces();

            var serviceAssemblies = Assembly.Load("Services");

            builder.RegisterAssemblyTypes(serviceAssemblies).AsImplementedInterfaces();

            var businessAssemblies = Assembly.Load("BusinessEngines");

            builder.RegisterAssemblyTypes(businessAssemblies).AsImplementedInterfaces();

            var commonContracts = Assembly.Load("Common.Contracts");

            builder.RegisterAssemblyTypes(commonContracts).AsImplementedInterfaces();

            builder.Register(c => new NLogLogger()).As <ILogger>().AsImplementedInterfaces();
        }
Example #13
0
        /// <summary>
        /// Allocation Stage
        /// </summary>
        public void AllocationStage()
        {
            //Start the nexdox messaging service
            NexdoxMessaging.StartEvent(this);

            //Initialise Statics
            Statics.Initialise(_engine, _appInfo);

            this.PerformIOC();

            /* Nexdox.PDF.NexdoxPDFSettings.PdfOuputRenderState = Nexdox.PDF.NexdoxPDFSettings.PDFState.ForceRasterise;
             * Nexdox.PDF.NexdoxPDFSettings.JpgImageQuality = 85;
             * Nexdox.PDF.NexdoxPDFSettings.DefaultDPI = 450;
             * Nexdox.PDF.NexdoxPDFSettings.DefaultCompressionQuality = 125;*/

            //Allocation Stage
            Allocation allocationStage = new Allocation(
                _engine, _appInfo, _conFileService, _xmlFileService, _zipFileService, _docTypeService, _manCoService);

            allocationStage.Process();

            //Stop the nexdox messaging service
            NexdoxMessaging.EndEvent(this);
        }
Example #14
0
        public void SaveToDatabase(IXmlFileService xmlFileService,
                                   IZipFileService zipFileService, IConFileService conFileService, IDocTypeService docTypeService, IManCoService manCoService, ApplicationInfo appInfo)
        {
            try
            {
                NexdoxMessaging.SendMessage("    Adding Data to SQL Database", true, this);
                foreach (ZipPackage zp in Statics.zipPackage)
                {
                    switch (Path.GetExtension(zp.FileName).ToLower())
                    {
                    case ".xml":

                        DocType docType = docTypeService.GetDocType(zp.DocumentType);
                        if (docType == null)
                        {
                            throw new Exception(string.Format("Document type {0} not found in unity database", zp.DocumentType));
                        }

                        ManCo manCo = manCoService.GetManCo(zp.ManCoID);
                        if (manCo == null)
                        {
                            throw new Exception(string.Format("Man Co {0} not found in unity database", zp.ManCoID));
                        }

                        xmlFileService.CreateXmlFile(
                            Statics.zipPackage.DocumentSetID.ToString(),
                            zp.FileName,
                            zp.ParentZipFileName,
                            zp.Offshore,
                            docType.Id,
                            manCo.Id,
                            0,
                            string.Empty,
                            zp.FileName,
                            DateTime.Now,
                            appInfo.NexdoxGlobalRunID.ToString(),
                            File.GetLastWriteTime(appInfo.InputPath));
                        break;

                    case ".zip":
                        if (zp.IsBigZip)
                        {
                            zipFileService.CreateBigZipFile(Statics.zipPackage.DocumentSetID.ToString(), zp.FileName, File.GetLastWriteTime(appInfo.InputPath));
                        }
                        else
                        {
                            zipFileService.CreateLittleZipFile(Statics.zipPackage.DocumentSetID.ToString(), zp.FileName, zp.ParentZipFileName, File.GetLastWriteTime(appInfo.InputPath));
                        }
                        break;

                    case ".con":
                        conFileService.CreateConFile(Statics.zipPackage.DocumentSetID.ToString(), zp.FileName, zp.ParentZipFileName, File.GetLastWriteTime(appInfo.InputPath));
                        break;
                    }

                    /*SqlCommand sqlComm = new SqlCommand("sp_InsertInputFile", sqlConn);
                     * sqlComm.CommandType = CommandType.StoredProcedure;
                     *
                     * SqlParameter InputFileName = sqlComm.Parameters.Add("@INPUTFILENAME", SqlDbType.VarChar);
                     * InputFileName.Direction = ParameterDirection.Input;
                     * InputFileName.Value = zp.FileName;
                     *
                     * SqlParameter DocType = sqlComm.Parameters.Add("@DOCTYPE", SqlDbType.VarChar);
                     * DocType.Direction = ParameterDirection.Input;
                     * DocType.Value = zp.DocumentType;
                     *
                     * SqlParameter ParentDocFileName = sqlComm.Parameters.Add("@PARENTDOCFILENAME", SqlDbType.VarChar);
                     * ParentDocFileName.Direction = ParameterDirection.Input;
                     * ParentDocFileName.Value = zp.ParentZipFileName;
                     *
                     * SqlParameter BigZip = sqlComm.Parameters.Add("@BIGZIP", SqlDbType.Bit);
                     * BigZip.Direction = ParameterDirection.Input;
                     * BigZip.Value = zp.IsBigZip;
                     *
                     * SqlParameter LittleZip = sqlComm.Parameters.Add("@LITTLEZIP", SqlDbType.Bit);
                     * LittleZip.Direction = ParameterDirection.Input;
                     * LittleZip.Value = zp.IsLittleZip;
                     *
                     * SqlParameter DocumentSetID = sqlComm.Parameters.Add("@DOCUMENTSET_ID", SqlDbType.UniqueIdentifier);
                     * DocumentSetID.Direction = ParameterDirection.Input;
                     * DocumentSetID.Value = Statics.zipPackage.DocumentSetID;
                     *
                     * SqlParameter OffShore = sqlComm.Parameters.Add("@OFFSHORE", SqlDbType.Bit);
                     * OffShore.Direction = ParameterDirection.Input;
                     * OffShore.Value = zp.Offshore;
                     *
                     * SqlParameter ManCo = sqlComm.Parameters.Add("@MANCO", SqlDbType.VarChar);
                     * ManCo.Direction = ParameterDirection.Input;
                     * ManCo.Value = zp.ManCoID.ToString();
                     *
                     * SqlParameter Domicile = sqlComm.Parameters.Add("@DOMICILE", SqlDbType.VarChar);
                     * Domicile.Direction = ParameterDirection.Input;
                     * Domicile.Value = zp.Domicile;
                     *
                     * SqlParameter StatusID = sqlComm.Parameters.Add("@STATUS_ID", SqlDbType.Int);
                     * StatusID.Direction = ParameterDirection.Input;
                     * StatusID.Value = zp.StatusID;
                     *
                     * SqlParameter InputDateCreation = sqlComm.Parameters.Add("@INPUTCREATIONDATE", SqlDbType.DateTime);
                     * InputDateCreation.Direction = ParameterDirection.Input;
                     * InputDateCreation.Value = zp.InputCreationDate;
                     *
                     * SqlDataReader myReader = sqlComm.ExecuteReader();
                     * myReader.Close();*/
                }
            }
            catch (Exception e)
            {
                throw NexdoxMessaging.Exception(e.Message, this);
            }
        }
Example #15
0
        /// <summary>
        /// Process the XML input files
        /// </summary>
        private void ProcessXMLFile(string dataFile)
        {
            ZipPackage zp = new ZipPackage();

            zp.FileName = Path.GetFileName(dataFile);

            string[] parts = dataFile.Split('.');
            string   documentIdentifier = parts[3] + parts[4];

            NexdoxMessaging.SendMessage("    Processing xml file " + Path.GetFileName(dataFile) + "...", true, this);

            if (!File.Exists(dataFile.ToUpper().Replace(".XML", ".job")))
            {
                OutputErrorRecord(Path.GetFileName(dataFile), "Corresponding .job file does not exist");
                return;
            }

            StreamReader      jobInputFileStream = new StreamReader(dataFile.ToUpper().Replace(".XML", ".job"));
            XmlReaderSettings jobSettings        = new XmlReaderSettings();

            jobSettings.XmlResolver = null;
            XmlReader jobData = XmlReader.Create(jobInputFileStream, jobSettings);

            string domicile    = string.Empty;
            string batchNumber = string.Empty;

            jobData.ReadToFollowing("Domicile");
            domicile    = jobData.ReadElementContentAsString().ToUpper();
            zp.Domicile = domicile;

            string managerIdString = string.Empty;

            try
            {
                jobData.ReadToFollowing("Manager_ID");
            }
            catch (Exception e)
            {
                OutputErrorRecord(Path.GetFileName(dataFile), e.Message + "\",\"" + e.StackTrace);
                jobData.Close();
                jobInputFileStream.Close();
                return;
            }

            if (jobData.EOF)
            {
                OutputErrorRecord(Path.GetFileName(dataFile), "The job file is does not contain Manager_ID");
                jobData.Close();
                jobInputFileStream.Close();
                return;
            }
            else
            {
                managerIdString = jobData.ReadElementContentAsString();
                int managerId;
                if (!int.TryParse(managerIdString, out managerId))
                {
                    OutputErrorRecord(Path.GetFileName(dataFile), "Unknown Manager ID: " + managerIdString);
                }
                zp.ManCoID = managerIdString;

                if (Statics.ManagementCompanySettings.Exists(delegate(NTGEN00.ManCoSettings manCoSettings){ return(manCoSettings.ManagementCompanyID == managerId); }))
                {
                    NTGEN00.ManCoSettings manCoSettings = Statics.ManagementCompanySettings[managerId];

                    Statics.zipPackage.Add(zp);

                    //Open data file as xml
                    StreamReader      inputFileStream = new StreamReader(dataFile);
                    XmlReaderSettings settings        = new XmlReaderSettings();
                    settings.XmlResolver = null;
                    XmlReader xmlData = XmlReader.Create(inputFileStream, settings);

                    //Get file name minus extension
                    string fileNameNoExtension = new FileInfo(dataFile).Name;
                    fileNameNoExtension = fileNameNoExtension.Substring(0, fileNameNoExtension.Length - 4);

                    //Can we tell what application it's supposed to go to by doc type
                    string destinationDirectory = string.Empty;
                    string appName    = string.Empty;
                    string docType    = string.Empty;
                    string subDocType = string.Empty;


                    //Get document type
                    xmlData.ReadToFollowing("Doc_Type");

                    if (xmlData.EOF)
                    {
                        destinationDirectory = _appInfo.OutputPath + "InvalidFiles";
                        OutputErrorRecord(Path.GetFileName(dataFile), "No Doc_Type in data file");
                        return;
                    }
                    else
                    {
                        docType         = xmlData.ReadElementContentAsString().ToUpper();
                        zp.DocumentType = docType;
                        xmlData.ReadToFollowing("Doc_Sub_Type");
                        subDocType = xmlData.EOF ? "N/A" : xmlData.ReadElementContentAsString();

                        jobData.Close();
                        jobInputFileStream.Close();

                        string subDocAndDocType = docType + subDocType;
                        if (Statics.Resources.Lookups[LookupEnums.MonitorDirectory].Lookup.Contains(subDocAndDocType))
                        {
                            appName = Statics.Resources.Lookups[LookupEnums.AppName].Lookup.Find(subDocAndDocType);
                            destinationDirectory =
                                Statics.Resources.Lookups[LookupEnums.MonitorDirectory].Lookup.Find(subDocAndDocType);
                        }
                        else
                        {
                            destinationDirectory = _appInfo.OutputPath + "InvalidFiles";
                            OutputErrorRecord(
                                Path.GetFileName(dataFile),
                                string.Format("Doc_Type ({0}) and Sub_Doc_Type ({1}) unknown", docType, subDocType));
                            return;
                        }
                    }



                    if (string.Compare(appName, "ntgen03", true) == 0)
                    {
                        if (manCoSettings.IsEMEA(appName) || manCoSettings.Offshore)
                        {
                            appName = "ntgen23";
                            destinationDirectory = @"\\127.0.0.1\nexdox\ntgen23\monitor";
                        }
                    }
                    else if (string.Compare(appName, "ntgen01", true) == 0)
                    {
                        switch (Statics.CntFilesRoutingMode)
                        {
                        case "PremierSeparately":
                            if (!manCoSettings.Offshore)
                            {
                                appName = (manCoSettings.ManagementCompanyID == 14) || (manCoSettings.ManagementCompanyID == 17)
                              ? "ntprm01"
                              : "ntgen01";
                            }
                            else
                            {
                                appName = "ntgen51";
                            }
                            break;

                        case "PremierAsOnshore":
                            appName = manCoSettings.Offshore ? "ntgen51" : "ntgen01";
                            break;

                        default:
                            break;
                        }

                        destinationDirectory = string.Format(@"\\127.0.0.1\nexdox\{0}\monitor", appName);
                    }

                    if (!manCoSettings.ApplicationsSwitchedOff.Contains(appName))
                    {
                        //Make sure destination directory string ends in a \
                        if (!destinationDirectory.EndsWith("\\"))
                        {
                            destinationDirectory += "\\";
                        }

                        //Move job file to application input directory
                        NexdoxMessaging.SendMessage(
                            string.Format("  Allocating '{0}' files to '{1}' directory.", fileNameNoExtension, destinationDirectory),
                            false,
                            this);

                        if (!File.Exists(string.Format("{0}.job", dataFile.Substring(0, dataFile.Length - 4))))
                        {
                            OutputErrorRecord(Path.GetFileName(dataFile), "No job file supplied with xml file");
                            return;
                        }
                        else if (!Statics.AppsToIgnore.Contains(appName.ToUpper()))
                        {
                            if (!Directory.Exists(destinationDirectory))
                            {
                                Directory.CreateDirectory(destinationDirectory);
                            }

                            //Move data file to application input directory
                            MoveFile(
                                string.Format("{0}.job", dataFile.Substring(0, dataFile.Length - 4)),
                                string.Format("{0}{1}.job", destinationDirectory, fileNameNoExtension));
                            MoveFile(
                                string.Format("{0}.xml", dataFile.Substring(0, dataFile.Length - 4)),
                                string.Format("{0}{1}.xml", destinationDirectory, fileNameNoExtension));

                            _allocatedFiles.Add("\"" + Path.GetFileName(dataFile) + "\",\"" + appName + "\"");


                            zp.Offshore = manCoSettings.Offshore ? true : false;
                            zp.StatusID = 1;


                            if (string.Compare(docType, "CNF", true) == 0)
                            {
                                //All input for NXNOR07 should be processed together
                                _transferFiles.Add(fileNameNoExtension);
                                _transferFileDestinationDirectory = destinationDirectory;
                            }
                            else if (string.Compare(docType, "CNT", true) == 0)
                            {
                                if (string.Compare(subDocType, "SWS", true) == 0 || string.Compare(subDocType, "SWR", true) == 0)
                                {
                                    _contractSWRSWSFiles.Add(fileNameNoExtension);
                                    _contractSWRSWSFileDestinationDirectory = destinationDirectory;
                                }
                                else if (string.Compare(subDocType, "CWR", true) == 0 || string.Compare(subDocType, "CWS", true) == 0)
                                {
                                    _contractCWRCWSFiles.Add(fileNameNoExtension);
                                    _contractCWRCWSFileDestinationDirectory = destinationDirectory;
                                }
                                else
                                {
                                    _contractFiles.Add(fileNameNoExtension);
                                    _contractFileDestinationDirectory = destinationDirectory;
                                }
                            }
                        }
                        else
                        {
                            //ignore these files
                            _ignoreFiles.Add("\"" + Path.GetFileName(dataFile) + "\",\"" + appName + "\"");
                        }
                    }
                    else
                    {
                        OutputErrorRecord(
                            Path.GetFileName(dataFile), "Application: " + appName + " switched off for ManCo ID: " + managerIdString);
                        return;
                    }
                }
                else
                {
                    OutputErrorRecord(Path.GetFileName(dataFile), "Unknown ManCo ID: " + managerIdString);
                    return;
                }
            }
        }
Example #16
0
        /////// <summary>
        /////// Checks to see if any of the XML files are over the size threshold and attempts to splirt them into smaller files
        /////// </summary>
        ////private void SplitHugeDataFiles()
        ////{
        ////  int hugeFileSplitThreshold = Int32.Parse(_appInfo["HugeFileSplitThreshold"]) * 1000;

        ////  foreach (string inputFile in Directory.GetFiles(_appInfo.OutputPath, _appInfo["XmlFileMask"]))
        ////  {
        ////    FileInfo fi = new FileInfo(inputFile);

        ////    if (fi.Length < hugeFileSplitThreshold)
        ////      continue;

        ////    var documents = XElement.Load(inputFile).Elements("Document_Data");

        ////    string docSubType = documents.First().Element("Doc").Element("Doc_Sub_Type").Value;

        ////    if (!(new[] { "PER", "AGT" }).Contains(docSubType))
        ////      continue;

        ////    int splitCount = (int)(fi.Length / hugeFileSplitThreshold) + 1;

        ////    var consolidatedDocuments = documents.GroupBy(d => d.Element("Addressee").Element("Id").Value).OrderBy(g => g.Count()).Reverse();

        ////    int documentsPerChunk = (int)(documents.Count() / splitCount);

        ////    int counter = 0;

        ////    string mainPartOfInitialFileNames = Path.ChangeExtension(inputFile, null);

        ////    XElement initialJobFile = XElement.Load(mainPartOfInitialFileNames + ".job");

        ////    List<XElement> tempDocuments = new List<XElement>();

        ////    foreach (var documentsForOneAddressee in consolidatedDocuments)
        ////    {
        ////      if (tempDocuments.Count + documentsForOneAddressee.Count() < documentsPerChunk)
        ////      {
        ////        tempDocuments.AddRange(documentsForOneAddressee);
        ////      }
        ////      else
        ////      {
        ////        if (tempDocuments.Count() == 0) // Is still too large, but we had no possibility to change this
        ////        {
        ////          tempDocuments = documentsForOneAddressee.ToList();
        ////          // Process tempDocuments and clear tempDocuments
        ////          SaveSmallerXMLChunks(tempDocuments, initialJobFile, mainPartOfInitialFileNames, counter);
        ////          tempDocuments.Clear();
        ////        }
        ////        else
        ////        {
        ////          // Process tempDocuments, and tail should be saved
        ////          SaveSmallerXMLChunks(tempDocuments, initialJobFile, mainPartOfInitialFileNames, counter);
        ////          tempDocuments = documentsForOneAddressee.ToList();
        ////        }

        ////        counter++;
        ////      }
        ////    }

        ////    SaveSmallerXMLChunks(tempDocuments, initialJobFile, mainPartOfInitialFileNames, counter);

        ////    File.Move(mainPartOfInitialFileNames + ".xml", mainPartOfInitialFileNames + ".xml.huge");
        ////    File.Move(mainPartOfInitialFileNames + ".job", mainPartOfInitialFileNames + ".job.huge");
        ////  }
        ////}

        /////// <summary>
        /////// saves chunks of xml as smaller input files
        /////// </summary>
        /////// <param name="documents">List of documents that makeup our new file</param>
        /////// <param name="initialJobFile">The initial XML file</param>
        /////// <param name="mainPartOfInitialFileNames">Filename</param>
        /////// <param name="counter">Current File Chunk Number</param>
        ////private void SaveSmallerXMLChunks(List<XElement> documents, XElement initialJobFile, string mainPartOfInitialFileNames, int counter)
        ////{
        ////  string newMainpartOfName = string.Format("{0}.{1:d3}", mainPartOfInitialFileNames, counter);

        ////  XElement newDocumentSet = new XElement("Document_Pack", documents);

        ////  initialJobFile.Element("Rec_Total").Element("count").Value = documents.Count().ToString();

        ////  newDocumentSet.Save(newMainpartOfName + ".xml");
        ////  initialJobFile.Save(newMainpartOfName + ".job");
        ////}

        /// <summary>
        /// Updates any new PDFs supplied into the shared resources folder
        /// </summary>
        private void ProcessInserts(string pdfFile)
        {
            //Get filename of the insert
            string pdfFileName = Path.GetFileName(pdfFile);

            string path = pdfFile.Replace(pdfFileName, "");

            NexdoxMessaging.SendMessage("    Processing pdf file " + pdfFileName + "...", true, this);

            try
            {
                string pdfInsert = pdfFile;
                string epsInsert = pdfInsert.Substring(0, pdfInsert.LastIndexOf("."));

                System.Diagnostics.Process process;
                ProcessStartInfo           processInfo = new ProcessStartInfo(
                    _appInfo["PDFConversionAppPath"] + @"\pdf2vec.exe", "\"" + pdfInsert + "\" \"" + epsInsert + ".eps\"");
                processInfo.CreateNoWindow         = true;
                processInfo.UseShellExecute        = false;
                processInfo.RedirectStandardOutput = true;
                process = System.Diagnostics.Process.Start(processInfo);
                process.WaitForExit(10000); //10 seconds?

                using (StreamWriter writer = new StreamWriter(_appInfo.OutputPath + "test.txt"))
                {
                    string line;

                    while ((line = process.StandardOutput.ReadLine()) != null)
                    {
                        writer.WriteLine(line);
                    }
                }

                int exitCode = process.ExitCode;
                process.Close();
            }
            catch (Exception e)
            {
                NexdoxMessaging.SendMessage("ERROR - When converting eps file - " + e.Message, false, null);
            }

            //Ok, now we need to make sure that there is no showpage. Otherwise our output will create
            //an additional page. blast!

            NexdoxResourceManager.ImageList allImages =
                Statics.CentralResources.Images.FindAllMatchingNames(Path.GetFileNameWithoutExtension(pdfFile));
            NexdoxResourceManager.ImageList updatedImages = new NexdoxResourceManager.ImageList();

            foreach (string file in Directory.GetFiles(path, Path.GetFileNameWithoutExtension(pdfFile) + "*.eps"))
            {
                string fileNameWithoutExtension    = Path.GetFileNameWithoutExtension(file);
                string newFileNameWithoutExtension = fileNameWithoutExtension.Replace("-", "_").Replace(" ", "_");
                File.Move(path + fileNameWithoutExtension + ".eps", path + newFileNameWithoutExtension + ".temp");
                using (StreamWriter writer = new StreamWriter(path + newFileNameWithoutExtension + ".eps", false))
                {
                    using (StreamReader reader = new StreamReader(path + newFileNameWithoutExtension + ".temp"))
                    {
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line.Contains("showpage") || line.Contains("verydoc"))
                            {
                                continue;
                            }

                            writer.WriteLine(line);
                        }
                    }
                }

                NexdoxResourceManager.ImageList images =
                    Statics.CentralResources.Images.FindAllMatchingNames(newFileNameWithoutExtension);

                if (images.Count > 1)
                {
                    bool imageUploaded = false;
                    foreach (NexdoxResourceManager.ImageResource image in images)
                    {
                        if (string.Compare(image.BaseName, newFileNameWithoutExtension, true) == 0)
                        {
                            UpdateImageInDAM(path, updatedImages, newFileNameWithoutExtension, image);
                            imageUploaded = true;
                        }
                    }

                    if (!imageUploaded)
                    {
                        AddNewImageToDAM(path, updatedImages, newFileNameWithoutExtension);
                    }
                }
                else if (images.Count == 0)
                {
                    AddNewImageToDAM(path, updatedImages, newFileNameWithoutExtension);
                }
                else
                {
                    UpdateImageInDAM(path, updatedImages, newFileNameWithoutExtension, images[0]);
                }

                File.Delete(newFileNameWithoutExtension + ".temp");
            }

            string errMsg = String.Empty;

            // DV - I'm not sure why this bit is here, it looks to duplicate what happens above, seemingly just
            // here to catch any issues

            //chekout RMC
            foreach (NexdoxResourceManager.ImageResource image in allImages)
            {
                if (!updatedImages.Contains(image))
                {
                    NexdoxResourceManager.CheckOutResult result = image.ParentResourceManager.ResourceManagerAsset.CheckOut();
                    if (result != NexdoxResourceManager.CheckOutResult.Success)
                    {
                        throw NexdoxMessaging.Exception(
                                  "Error checking out parent resource: " + image.ParentResourceManager.ResourceManagerAsset.Name + ". "
                                  + result.ToString(),
                                  this);
                    }

                    result = image.CheckOut();

                    if (result != NexdoxResourceManager.CheckOutResult.Success)
                    {
                        throw NexdoxMessaging.Exception(
                                  "Error checking out image resource: " + image.Name + ". " + result.ToString(), this);
                    }

                    image.Deleted = true;
                    image.Save("", false);
                    image.CheckIn();
                    image.ParentResourceManager.ResourceManagerAsset.Save("", false);
                    image.ParentResourceManager.ResourceManagerAsset.CheckIn();
                    if (string.Compare(_appInfo["Region"], "Live", true) == 0)
                    {
                        image.SetCurrentRegionVersion("Live", image.VersionNo);
                        image.SetCurrentRegionVersion("Test", image.VersionNo);
                        image.ParentResourceManager.ResourceManagerAsset.SetCurrentRegionVersion(
                            "Live", image.ParentResourceManager.ResourceManagerAsset.VersionNo);
                        image.ParentResourceManager.ResourceManagerAsset.SetCurrentRegionVersion(
                            "Test", image.ParentResourceManager.ResourceManagerAsset.VersionNo);
                    }
                    else if (string.Compare(_appInfo["Region"], "Test", true) == 0)
                    {
                        image.SetCurrentRegionVersion("Test", image.VersionNo);
                        image.ParentResourceManager.ResourceManagerAsset.SetCurrentRegionVersion(
                            "Test", image.ParentResourceManager.ResourceManagerAsset.VersionNo);
                    }
                    //Always into Dev
                    image.SetCurrentRegionVersion("Dev", image.VersionNo);
                    image.ParentResourceManager.ResourceManagerAsset.SetCurrentRegionVersion(
                        "Dev", image.ParentResourceManager.ResourceManagerAsset.VersionNo);
                }
            }
        }
Example #17
0
        public void Process()
        {
            NexdoxMessaging.SendMessage("Allocation Stage...", true, this);

            //Todo: Do some kind of sequence checking... there may be a better place to do this than here.

            //Make sure Xceed libraries are enabled
            Xceed.Zip.Licenser.LicenseKey = "ZIN37-T1W1B-SW87P-N8AA";

            string grid = _appInfo.NexdoxGlobalRunID.ToString();

            //Get the input files
            ScanForInputFiles(_appInfo.InputPath);

            //Now add each level of Zip structure to the class
            NexdoxMessaging.SendMessage("Deconstructing Zip Package....", true, this);

            //Top Level first (Big Zip)
            foreach (string zipFile in Directory.GetFiles(_appInfo.InputPath, "*", SearchOption.TopDirectoryOnly))
            {
                ZipPackage zpBig = new ZipPackage()
                {
                    FileName          = Path.GetFileName(zipFile),
                    ParentZipFileName = "",
                    IsBigZip          = true,
                    InputCreationDate = new FileInfo(zipFile).LastWriteTime,
                    StatusID          = 0,
                };

                Statics.zipPackage.Add(zpBig);

                string pathLittleZip = _appInfo.InputPath + Path.ChangeExtension(zpBig.FileName, "");

                //Next Level. (Little Zip)
                foreach (string littlezipFile in Directory.GetFiles(pathLittleZip, "*", SearchOption.TopDirectoryOnly))
                {
                    ZipPackage zpLittle = new ZipPackage()
                    {
                        FileName          = Path.GetFileName(littlezipFile.ToUpper()),
                        ParentZipFileName = zpBig.FileName,
                        IsLittleZip       = true,
                        InputCreationDate = new FileInfo(littlezipFile).LastWriteTime,
                        StatusID          = 0,
                    };
                    Statics.zipPackage.Add(zpLittle);

                    string pathDataFiles = pathLittleZip + "\\" + Path.ChangeExtension(zpLittle.FileName, "");

                    //Now the Data Files
                    foreach (string dataFile in Directory.GetFiles(pathDataFiles, "*", SearchOption.TopDirectoryOnly))
                    {
                        if (Path.GetExtension(dataFile) == ".XML")
                        {
                            foreach (ZipPackage zp in Statics.zipPackage)
                            {
                                if (zp.FileName == Path.GetFileName(dataFile))
                                {
                                    zp.ParentZipFileName = zpLittle.FileName;
                                    zp.InputCreationDate = new FileInfo(littlezipFile).LastWriteTime;
                                }
                            }
                        }
                        else //.CON File
                        {
                            ZipPackage zpData = new ZipPackage()
                            {
                                FileName          = Path.GetFileName(dataFile),
                                ParentZipFileName = zpLittle.FileName,
                                InputCreationDate = new FileInfo(littlezipFile).LastWriteTime,
                                StatusID          = 0,
                            };
                            Statics.zipPackage.Add(zpData);
                        }
                    }
                }
            }

            Statics.zipPackage.SaveToDatabase(_xmlFileService, _zipFileService, _conFileService, _docTypeService, _manCoService, _appInfo);
            Statics.zipPackage.SaveToOutputDir(_appInfo.OutputPath, grid);

            if (_extractedFiles.Count > 0)
            {
                using (
                    StreamWriter extractedFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-ExtractedXML.csv")))
                {
                    extractedFile.WriteLine("\"FileName\"");

                    foreach (string file in _extractedFiles)
                    {
                        extractedFile.WriteLine(file);
                    }
                }
            }

            if (_allocatedFiles.Count > 0)
            {
                using (
                    StreamWriter allocatedFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-AllocatedXML.csv")))
                {
                    allocatedFile.WriteLine("\"FileName\",\"Application\"");

                    foreach (string file in _allocatedFiles)
                    {
                        allocatedFile.WriteLine(file);
                    }
                }
            }

            if (_zipErrorFiles.Count > 0)
            {
                using (
                    StreamWriter zipErrorFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-FailedZIP.csv")))
                {
                    zipErrorFile.WriteLine("\"FileName\",\"Error\"");

                    foreach (string error in _zipErrorFiles)
                    {
                        zipErrorFile.WriteLine(error);
                    }
                }
            }

            if (_pdfErrorFiles.Count > 0)
            {
                using (
                    StreamWriter pdfErrorFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-FailedPDF.csv")))
                {
                    pdfErrorFile.WriteLine("\"FileName\",\"Error\"");

                    foreach (string error in _pdfErrorFiles)
                    {
                        pdfErrorFile.WriteLine(error);
                    }
                }
            }

            if (_xmlErrorFiles.Count > 0)
            {
                using (
                    StreamWriter xmlErrorFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-FailedXML.csv")))
                {
                    xmlErrorFile.WriteLine("\"FileName\",\"Error\"");

                    foreach (string error in _xmlErrorFiles)
                    {
                        xmlErrorFile.WriteLine(error);
                    }
                }
            }

            if (_ignoreFiles.Count > 0)
            {
                using (
                    StreamWriter ignoredFile =
                        new StreamWriter(File.Create(_appInfo.OutputPath + "[" + grid + "]" + "-ignoredXML.csv")))
                {
                    ignoredFile.WriteLine("\"FileName\",\"Application\"");

                    foreach (string ignore in _ignoreFiles)
                    {
                        ignoredFile.WriteLine(ignore);
                    }
                }
            }

            NexdoxMessaging.SendMessage("Finished Allocation Stage.", true, this);
        }