예제 #1
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Create a new Syndication Feed.
            SyndicationFeed        feed  = new SyndicationFeed("EWA Files Receive Log", "A WCF Syndication Feed", null);
            List <SyndicationItem> items = new List <SyndicationItem>();

            items.Count();

            // Category and Description
            feed.Categories.Add(new SyndicationCategory("Validated"));

            feed.Description = new TextSyndicationContent("RSS feed for files received through EWA");



            // Put all file names in root directory into array.
            string[] SDMXFiles = Directory.GetFiles(ConfigurationManager.AppSettings["EWAPath"], "*.xml");

            // Loop thru files
            foreach (string SDMXFile in SDMXFiles)
            {
                string SDMXFileName   = SDMXFile.Substring(SDMXFile.LastIndexOf('\\') + 1);
                string SDMXFolderName = SDMXFile.Substring(0, SDMXFile.LastIndexOf('\\') - 1);

                XDocument xDoc = XDocument.Load(SDMXFile);



                // Get all namespaces in SDMX doc
                var nspaces = xDoc.Root.Attributes().
                              Where(a => a.IsNamespaceDeclaration).
                              GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
                                      a => XNamespace.Get(a.Value)).
                              ToDictionary(g => g.Key,
                                           g => g.First());

                XNamespace xNs_Header = null, xNs_Data = null;

                // Loop thru namespaces, get the ones we need for Header and Data
                foreach (var ns in nspaces)
                {
                    if (ns.Value.ToString().Contains("/message"))
                    {
                        xNs_Header = ns.Value;
                    }
                    if (ns.Value.ToString().Contains("KeyFamily"))
                    {
                        xNs_Data = ns.Value;
                    }
                }

                //1.	Prepared date in SDMX header
                //2.	Table code: In SDMX header DataSetID
                //3.	Frequency: first series attribute FREQ
                //4.	Country ISO: First series attribute REF_AREA
                //5.	Validated or not: Look for _VALID_ in file name
                //7.    Sender message notes: Include link to EWA interface
                //8.    Folder name where the file was saved to

                // Put header information into variables
                var headerLines = from header in xDoc.Descendants(xNs_Header + "Header")
                                  select new
                {
                    Prepared   = header.Element(xNs_Header + "Prepared").Value,
                    SenderCode = header.Element(xNs_Header + "Sender").Attribute("id").Value,
                    ID         = header.Element(xNs_Header + "DataSetID").Value
                };

                // Get frequency from first series attribute
                bool Validated = SDMXFileName.ToLower().Contains("_valid_");

                // Get frequency from first series attribute
                string Freq = xDoc.Descendants(xNs_Data + "DataSet").Descendants(xNs_Data + "Series").First().Attribute("FREQ").Value;

                // Get frequency from first series attribute
                string Country = xDoc.Descendants(xNs_Data + "DataSet").Descendants(xNs_Data + "Series").First().Attribute("REF_AREA").Value;

                // Get table code from header ID
                string[] ID_Bits = headerLines.First().ID.Split('_');
                string   TableCode;
                if (ID_Bits.Count() > 1)
                {
                    TableCode = ID_Bits[1].ToString().Trim();
                }
                else
                {
                    TableCode = headerLines.First().ID;
                }

                // Format the prepared date/time
                string PreparedDate = headerLines.First().Prepared.ToString().Replace('T', ' ').Trim();
                if (PreparedDate.Contains("+"))
                {
                    PreparedDate = PreparedDate.Substring(0, PreparedDate.IndexOf('+'));
                }

                // Build content string
                string Content =
                    "  <b>TableCode:</b>" + TableCode
                    + " \t <b>Frequency:</b>" + Freq
                    + " \t <b>Country:</b>" + Country
                    + " \t <b>Validated:</b>" + Validated
                    + " \t <b>SenderCode:</b>" + headerLines.First().SenderCode;

                Uri fileUri = new Uri("file://" + SDMXFile);

                DateTimeOffset PublishDate = DateTime.MinValue;
                try
                {
                    PublishDate = DateTime.ParseExact(PreparedDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                }
                catch (Exception ex)
                {
                    Content += " \t <b>Wrong format prepared date:</b>" + PreparedDate;
                }

                //// Put all info into a new RSS item and add it to the feed
                //item = new SyndicationItem(
                //    "File:" + SDMXFileName
                //    , Content
                //    , file
                //);

                SyndicationItem item = new SyndicationItem();
                if (PublishDate != DateTime.MinValue)
                {
                    item.PublishDate = PublishDate;
                }
                item.Content = new TextSyndicationContent(Content);
                item.Title   = new TextSyndicationContent("File:" + SDMXFileName);
                item.Links.Add(new SyndicationLink(fileUri));

                items.Add(item);

                //break;
            }

            feed.Items = items;

            // Return ATOM or RSS based on query string
            // rss -> http://localhost:8732/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
            // atom -> http://localhost:8732/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/?format=atom
            string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];

            SyndicationFeedFormatter formatter = null;

            //if (query == "atom")
            //{
            //    formatter = new Atom10FeedFormatter(feed);
            //}
            //else
            //{
            formatter = new Rss20FeedFormatter(feed);
            //}

            return(formatter);
        }
예제 #2
0
        /// <summary>
        /// Sample 1 - Import 3 indicator definitions exported from IMR in order of increasing complexity: simple count, percent, disaggregation
        /// </summary>
        /// <param name="args">None</param>
        static void Main(string[] args)
        {
            try
            {
                #region Initialise

                //  Create new DOM Object to work with
                SDMXDom dom = new SDMXDom();
                dom.OnDOMValidationError += new EventHandler <DOMValidationEventArgs>(dom_OnDOMValidationError);

                //  Create an sdmxFile object to read / write files
                SDMXFile sdmxFile = new SDMXFile();

                const string zipFileLocation = @"../../../../SDMX_Sample_Export.zip";

                #endregion

                #region Load the DOM

                //  Load + Unzip the IMR test data into the sdmFile object.
                //  This object is used to manage all interaction with the phyical disk.
                sdmxFile.LoadFromZip(zipFileLocation);

                //  Load the DOM + Validate using all files in the SDMXFilesContainer
                dom.Load(sdmxFile.Files, true);

                #endregion

                #region DSD Processing

                //  Process the CodeLists
                Console.WriteLine("The CodeLists from the DSD are being processed \r\n");

                foreach (CodeList codeList in dom.CodeListsDSD)
                {
                    Console.WriteLine("[{0}] :", codeList.Identifier);

                    if (codeList.Codes != null)
                    {
                        foreach (Code code in codeList.Codes)
                        {
                            Console.WriteLine("\t{0}", code);
                        }
                    }
                }

                WriteColorMessage("\r\nPress any key to process the HierarchicalCodeList...", ConsoleColor.Green);
                Console.ReadKey();

                //  Process the HierarchicalCodeList
                foreach (HierarchicalCodeList hierarchicalCodeList in dom.HierarchicalCodeLists)
                {
                    Console.WriteLine("HierarchicalCodeList {0}, is being processed", hierarchicalCodeList.Identifier);

                    foreach (Hierarchy hierarchy in hierarchicalCodeList.Hierarchies)
                    {
                        Console.WriteLine("\tHierarchy {0}, is being processed", hierarchy.ID);
                    }
                }

                WriteColorMessage("\r\nPress any key to process the DSD Concepts...", ConsoleColor.Green);
                Console.ReadKey();

                //  Process the Concepts
                Console.WriteLine("The Concepts from the DSD are being processed \r\n");

                foreach (ConceptScheme conceptScheme in dom.ConceptSchemesDSD)
                {
                    Console.WriteLine("[{0}]", conceptScheme.Identifier);

                    foreach (Concept Concept in conceptScheme.Concepts)
                    {
                        Console.WriteLine("\t{0} : {1}", Concept.Identifier, Concept.Name);
                    }
                }


                WriteColorMessage("\r\nPress any key to process the Observation Data...", ConsoleColor.Green);
                Console.ReadKey();

                //  Process the Observation Data
                Console.WriteLine("The Observation Data are being processed \r\n");

                if (dom.DataSet == null)
                {
                    Console.WriteLine("No observation data found");
                }
                else
                {
                    foreach (Series serie in dom.DataSet.Series)
                    {
                        Console.WriteLine("The Indicator : {0}, is being processed", serie.Indicator.Description.EnglishOrFirst());

                        if (serie.Observations != null && serie.Observations.Count == 0)
                        {
                            Console.WriteLine("The Indicator : {0}, has no data", serie.Indicator.Description);
                        }
                        else
                        {
                            foreach (Observation obs in serie.Observations)
                            {
                                Console.WriteLine("The Indicator : {0}, has an observed data value of {1} for the time period {2}",
                                                  serie.Indicator.Description, obs.Value, obs.TimePeriod);
                            }
                        }
                    }
                }

                WriteColorMessage("\r\nPress any key to process the MSD CodeLists...", ConsoleColor.Green);
                Console.ReadKey();

                #endregion

                #region MSD Processing

                //  Process the CodeLists
                Console.WriteLine("The CodeLists from the MSD are being processed \r\n");

                foreach (CodeList codeList in dom.CodeListsMSD)
                {
                    Console.WriteLine("[{0}] :", codeList.Identifier);

                    if (codeList.Codes != null)
                    {
                        foreach (Code code in codeList.Codes)
                        {
                            Console.WriteLine("\t{0}", code);
                        }
                    }
                }

                WriteColorMessage("\r\nPress any key to process the MSD Concepts", ConsoleColor.Green);
                Console.ReadKey();

                //  Process the MSD Concepts
                Console.WriteLine("The Concepts from the MSD are being processed \r\n");

                foreach (ConceptScheme conceptScheme in dom.ConceptSchemesMSD)
                {
                    Console.WriteLine("[{0}]", conceptScheme.Identifier);

                    foreach (Concept Concept in conceptScheme.Concepts)
                    {
                        Console.WriteLine("\t{0} : {1}", Concept.Identifier, Concept.Name);
                    }
                }


                WriteColorMessage("\r\nPress any key to process the MetadataStructures", ConsoleColor.Green);
                Console.ReadKey();

                //  Read the metadata associtated with each code-list
                Console.WriteLine("The MetadataStructures are being processed \r\n");

                foreach (MetadataStructure mds in dom.MetadataStructures)
                {
                    //  Get metadatas for TargetIdentifier FTI
                    FullTargetIdentifier fullTargetIdentifier = mds.FullTargetIdentifiers["FTI_WHO"];

                    //  FIRST EXAMPLE : GET METADATA FOR A SINGLE IDENTIFIER COMPONENT
                    //  (i.e. Indicator Properties)

                    if (fullTargetIdentifier != null)
                    {
                        //  Get metadata for each identifier components
                        foreach (IdentifierComponent ic in fullTargetIdentifier.IdentifierComponents)
                        {
                            //  Get all AttributeValueSet corresponding to the current IdentifierComponent
                            IEnumerable <AttributeValueSet> metadatas = ic.GetMetadata(fullTargetIdentifier, dom);

                            if (metadatas == null)
                            {
                                Console.WriteLine("No metadata exists for the IdentifierComponent {0}", ic.ID);
                            }
                            else
                            {
                                //  If there is metadata for the current IdentifierCompoment, loop on each attribute value set.
                                //  Here we can identifiy to which Code(s) the metadata correspond (i.e. Indicator 6)

                                foreach (AttributeValueSet attributeValueSet in metadatas)
                                {
                                    //  Idenfiy the metadata Code
                                    ComponentValue targetValue = attributeValueSet.TargetValues.First();
                                    Console.WriteLine("Metadatas for {0} {1}", ic.ID, targetValue.Value.Value);

                                    foreach (ReportedAttribute reportedAttribute in attributeValueSet.ReportedAttributes)
                                    {
                                        //  Reported attribute value can be either localized or not (String or LocalizedString)
                                        //  Therefore, we must check the value type before processing it.

                                        if (reportedAttribute.StringValue != null)
                                        {
                                            //  Print the string value
                                            Console.WriteLine("\t{0} : {1}", reportedAttribute.Concept.Name, reportedAttribute.StringValue);
                                        }

                                        if (reportedAttribute.LocalizedStringValue != null)
                                        {
                                            //  Print the string value for each language
                                            foreach (KeyValuePair <string, string> item in reportedAttribute.LocalizedStringValue)
                                            {
                                                Console.WriteLine("\t{0} [{1}] : {2}", reportedAttribute.Concept.Name, item.Key, item.Value);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //  SECOND EXAMPLE : GET METADATA FOR MULTIPLE IDENTIFIER COMPONENTS
                    //  i.e. Indicator > IndicatorSet

                    //  Note : In our sdmx-hd file sample, there is not such metadatas so the result will be null.
                    if (fullTargetIdentifier != null)
                    {
                        List <IdentifierComponent> idenfierComponents = new List <IdentifierComponent>()
                        {
                            fullTargetIdentifier.IdentifierComponents["IC_ISET"],
                            fullTargetIdentifier.IdentifierComponents["IC_ISET"],
                            fullTargetIdentifier.IdentifierComponents["IC_INDICATOR"]
                        };
                        IEnumerable <AttributeValueSet> multipleIdenfierComponentsMetadatas = idenfierComponents.GetMetadata(fullTargetIdentifier, dom);
                    }
                }
                #endregion
            }
            catch (SDMXException sdmxex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(sdmxex.Message);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
            }

            WriteColorMessage("\r\nPress any key to close the program...", ConsoleColor.Blue);
            Console.ReadKey();
        }