Example #1
0
        public override void Resume(StateExitValue results)
        {
            Debug.Log("Resume FetchUserData");
            if (results != null)
            {
                if (results.sourceState == typeof(WaitingForDBLoad <ShipmentsData>))
                {
                    var resultData = results.data as WaitingForDBLoad <ShipmentsData> .Results;
                    if (resultData.wasSuccessful)
                    {
                        if (resultData.results != null)
                        {
                            // Got some results back!  Use this data.
                            //  CommonData.currentCategory = new DBStruct<ShipmentsData>(
                            //      CommonData.DBCategoryTablePath + categoryID, CommonData.app);
                            //  CommonData.currentCategory.Initialize(resultData.results);
                            //  Debug.Log("Fetched user " + CommonData.currentUser.data.name);
                        }
                        else
                        {
                            // Make a new user, using default credentials.
                            Debug.Log("Could not find category " + categoryName + " - Creating new profile.");
                            ShipmentsData temp = new ShipmentsData()
                            {
                                categoryID = this.categoryID, categoryName = this.categoryName
                            };

                            //  CommonData.currentCategory = new DBStruct<ShipmentsData>(
                            //    CommonData.DBCategoryTablePath + categoryID, CommonData.app);
                            //  CommonData.currentCategory.Initialize(temp);
                            //  CommonData.currentCategory.PushData();
                        }
                    }
                    else
                    {
                        // Can't fetch data.  Assume internet problems, stay offline.
                        CommonData.currentUser = null;
                    }
                }
            }
            // Whether we successfully fetched, or had to make a new user,
            // return control to the calling state.
            manager.PopState();
        }
        /// <summary>
        /// Manage the steps of parsing and creation of the various reports.
        /// </summary>
        /// <param name="filesToProcess">Files to parse</param>
        public static void DoTheMagic(string[] filesToProcess)
        {
            var             unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection("Unity");
            IUnityContainer container    = new UnityContainer();

            unitySection.Configure(container);

            IMaker  maker  = container.Resolve <IMaker>();
            IParser parser = container.Resolve <IParser>();
            ILogger logger = container.Resolve <ILogger>();

            byte[] outputFile = null;

            int correctCounter = 0;
            int failedCounter  = 0;

            FiltersSection section = ConfigurationManager.GetSection("Filters") as FiltersSection;

            foreach (var file in filesToProcess)
            {
                try
                {
                    logger.Info(string.Format("Inizio a processare il file {0}", Path.GetFileName(file)), 0, 0);

                    string path = Directory.GetParent(file).FullName;
                    string name = Path.GetFileNameWithoutExtension(file);

                    // Step #1: Parsing
                    ShipmentsData info = parser.Parse(File.ReadAllLines(file));
                    logger.Info(string.Format("===> Parsing completato correttamente. {0} corrieri trovati.", info.Shipments.Count), 0, 0);

                    List <ShipmentsData> filteredData = new List <ShipmentsData>();

                    int subReport = 1;

                    foreach (FiltersSettingsElement v in section.FiltersSettings)
                    {
                        string outputFileName = string.Format("{0}{1}.pdf", name, v.Suffix);

                        // Step #2: Filtering
                        Regex         currentRegex = new Regex(v.Pattern);
                        ShipmentsData currentData  = new ShipmentsData()
                        {
                            MetaInformation = info.MetaInformation,
                            Shipments       = info.Shipments.Where(x => currentRegex.IsMatch(x.Name)).ToList(),
                            Date            = info.Date
                        };

                        info.Shipments.RemoveAll(x => currentRegex.IsMatch(x.Name));

                        // Step #3: Making the final report
                        try
                        {
                            outputFile = maker.MakeFinalReport(currentData);
                            logger.Info(string.Format("===> [{1}/{2}] Report creato correttamente. {0} kB totali.", outputFile.Length / 1024, subReport, section.FiltersSettings.Count), 0, 0);

                            // Step #4: Writing the report
                            File.WriteAllBytes(Path.Combine(path, outputFileName), outputFile);
                            logger.Info(string.Format("===> [{2}/{3}] Report scritto correttamente: {0}. {1} Corrieri.", outputFileName, currentData.Shipments.Count, subReport, section.FiltersSettings.Count), 0, 0);
                        }
                        catch (Exception ex)
                        {
                            logger.Error(string.Format("Errore durante la creazione/scrittura del report {0}: {1}", outputFileName, ex.Message), 0, 0);
                        }
                        subReport++;
                    }

                    if (info.Shipments.Count > 0)
                    {
                        logger.Warning("**WARNING** Trovati corrieri spuri!", 0, 0);

                        outputFile = maker.MakeFinalReport(info);
                        logger.Info(string.Format("===> Report creato correttamente. {0} kB totali.", outputFile.Length / 1024), 0, 0);

                        string outputFileName = string.Format("{0}_Spurious.pdf", name);

                        File.WriteAllBytes(Path.Combine(path, outputFileName), outputFile);
                        logger.Info(string.Format("===> Report corrieri spuri scritto correttamente: {0}.", outputFileName), 0, 0);
                    }

                    correctCounter++;
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message, 0, 0);
                    failedCounter++;
                }
            }

            Console.WriteLine();
            Console.WriteLine(string.Format("Finito! {0} file totali, {1} processati correttamente, {2} file falliti!", filesToProcess.Length, correctCounter, failedCounter));
        }
Example #3
0
        /// <summary>
        /// Used for creating the PDF output file
        /// </summary>
        /// <returns>Byte array containing the output PDF file</returns>
        public byte[] MakeFinalReport(ShipmentsData shipments)
        {
            Rectangle       page    = new Rectangle(PageSize.A4);
            PDFMakerSection section = ConfigurationManager.GetSection("PDFMaker") as PDFMakerSection;

            Dictionary <ShipmentElement, FinalReportSettingsElement> elementConfigurations =
                new Dictionary <ShipmentElement, FinalReportSettingsElement>();

            // Merge the configuration with the info retrieved
            foreach (FinalReportSettingsElement field in section.FinalReportSettings)
            {
                ShipmentElement element = shipments.MetaInformation.Single(x => x.Name == field.SourceFieldName);
                elementConfigurations[element] = field;
            }

            using (var stream = new MemoryStream())
                using (var document = new Document(page))
                    using (var writer = PdfWriter.GetInstance(document, stream))
                    {
                        // Initialization of PDF file
                        document.Open();
                        document.AddAuthor("Marco");
                        document.AddCreationDate();
                        document.AddLanguage("Italian");
                        document.AddTitle(string.Format("Report di spedizioni per il {0}", DateTime.Now.ToString("dd/M/yyyy")));

                        //Every iteration print information for a single courier
                        foreach (var currentCourier in shipments.Shipments)
                        {
                            Chunk idPhrase = new Chunk(currentCourier.ID.ToString() + "  ")
                            {
                                Font = FontFactory.GetFont(section.TitleFontName, section.IDFontSize, Font.BOLD, BaseColor.BLACK)
                            };

                            Chunk namePhrase = new Chunk(currentCourier.Name)
                            {
                                Font = FontFactory.GetFont(section.TitleFontName, section.NameFontSize, Font.BOLD, BaseColor.BLACK)
                            };

                            Chunk dateChunk = new Chunk(shipments.Date)
                            {
                                Font = FontFactory.GetFont(section.TitleFontName, section.DateFontSize, Font.BOLD, BaseColor.BLACK)
                            };

                            Paragraph title = new Paragraph()
                            {
                                Alignment = 1
                            };

                            title.Add(idPhrase);
                            title.Add(namePhrase);
                            title.Add(Chunk.NEWLINE);
                            title.Add(dateChunk);
                            title.Add(Chunk.NEWLINE);
                            title.Add(Chunk.NEWLINE);

                            PdfPTable table = new PdfPTable(elementConfigurations.Count)
                            {
                                TotalWidth  = 523,
                                LockedWidth = true
                            };

                            table.SetWidths(elementConfigurations.Select(x => x.Key.CharacterEnd - x.Key.CharacterStart).ToArray());

                            // Set the header
                            foreach (var item in elementConfigurations)
                            {
                                table.AddCell(new PdfPCell(new Phrase(new Chunk(item.Value.DestinationFieldName)
                                {
                                    Font = new Font(Font.FontFamily.COURIER, 9, Font.BOLD)
                                })));
                            }

                            // Every iteration add a line to the table
                            foreach (var currentShipment in currentCourier.Shipments)
                            {
                                // Handling shipments with empty "mitt" field
                                if (currentShipment.Single(x => x.Key.Name == "Mitt").Value.Length == 0)
                                {
                                    continue;
                                }

                                // Every iteration add a cell to a line
                                foreach (var currentShipmentElement in currentShipment)
                                {
                                    if (elementConfigurations.ContainsKey(currentShipmentElement.Key))
                                    {
                                        table.AddCell(new PdfPCell(new Phrase(new Chunk(currentShipmentElement.Value)
                                        {
                                            Font = new Font(Font.FontFamily.COURIER, 8)
                                        })));
                                    }
                                }

                                // Handle records that doesn't contain all the columns
                                table.CompleteRow();
                            }

                            // Used to effectively create the page(s) associated to a given courier
                            document.NewPage();
                            document.Add(title);

                            if (table.Rows.Count > 1)
                            {
                                document.Add(table);
                            }
                            else
                            {
                                Paragraph noShipment = new Paragraph()
                                {
                                    Alignment = 1
                                };

                                Chunk noShipmentMessage = new Chunk("Nessun ritiro.")
                                {
                                    Font = new Font(Font.FontFamily.COURIER, 12, Font.BOLD)
                                };

                                noShipment.Add(noShipmentMessage);
                                document.Add(noShipment);
                            }
                        }

                        return(stream.ToArray());
                    }
        }