Пример #1
0
        /// <summary>
        /// Fetch instance data and call member method to fetch and save document on file
        /// </summary>
        private void GetDocumentFromInstances()
        {
            InstanceResponseMessage responsMessage = null;
            string appId      = (string)GetOptionValue("appId");
            string org        = (string)GetOptionValue("org");
            int?   ownerId    = (int?)GetOptionValue("ownerId");
            Guid?  instanceId = (Guid?)GetOptionValue("instanceId");

            if (!string.IsNullOrEmpty(appId) || !string.IsNullOrEmpty(org))
            {
                responsMessage = _clientWrapper.GetInstanceMetaData(this.SelectableCliOptions);
            }
            else if (ownerId != null)
            {
                responsMessage = _clientWrapper.GetInstanceMetaData(ownerId, instanceId);
            }
            else
            {
                _logger.LogError($"No valid combination of command options, please use help to find available combintations");
                return;
            }

            if (responsMessage != null)
            {
                _logger.LogInformation($"Fetched {responsMessage.Instances.Length} instances. Count={responsMessage.Count}");

                Instance[] instances = responsMessage.Instances;
                FetchAndSaveData(instances, responsMessage.Next, _updateInstances);
            }
            else
            {
                _logger.LogInformation($"No data available for instance");
            }
        }
Пример #2
0
        public InstanceResponseMessage GetInstanceMetaData(Uri uri)
        {
            HttpClientWrapper          client   = new HttpClientWrapper(_logger);
            Task <HttpResponseMessage> response = client.GetWithUrl(uri);

            string responsMessage = response.Result.Content.ReadAsStringAsync().Result;

            InstanceResponseMessage instanceMessage = JsonConvert.DeserializeObject <InstanceResponseMessage>(responsMessage);

            return(instanceMessage);
        }
Пример #3
0
        /// <summary>
        ///  Fetch document from storage and save it to file. If the Next link is defined continue to read rest of instances and data
        /// </summary>
        /// <param name="instances">The instances for which the data shall be fetched</param>
        /// <param name="nextLink">The fetch of data elements is paged, the next link shall be used to fetch next page of instances</param>
        /// <param name="updateInstances"></param>
        private void FetchAndSaveData(Instance[] instances, Uri nextLink, string updateInstances)
        {
            foreach (Instance instance in instances)
            {
                int numberOfFiles = 0;
                foreach (DataElement data in instance.Data)
                {
                    string url          = data.SelfLinks.Platform;
                    Stream responseData = _clientWrapper.GetData(url, data.ContentType);

                    if (responseData != null)
                    {
                        string instanceGuidId = instance.Id.Split('/')[1];
                        string fileName       = $"{data.DataType.ToString()}_{((string.IsNullOrEmpty(data.Filename)) ? data.Id : data.Filename)}";

                        string fileFolder = $@"{instance.InstanceOwner.PartyId}\{instanceGuidId}";

                        if (CliFileWrapper.SaveToFile(fileFolder, fileName, responseData))
                        {
                            _logger.LogInformation($"File:{fileName} saved at {fileFolder}");
                        }
                        numberOfFiles++;
                    }
                }

                if (numberOfFiles == 0)
                {
                    _logger.LogInformation($"No files received for instance:{instance.Id}");
                }
            }

            if (nextLink != null)
            {
                InstanceResponseMessage responsMessage = _clientWrapper.GetInstanceMetaData(nextLink);
                _logger.LogInformation($"Fetched {responsMessage.Instances.Length} instances. Count={responsMessage.Count}");

                FetchAndSaveData(responsMessage.Instances, responsMessage.Next, updateInstances);
            }
        }
Пример #4
0
        internal static InstanceResponseMessage CreateInstanceResponse(int numberOfInstances)
        {
            InstanceResponseMessage response = new InstanceResponseMessage();

            response.Instances = new Instance[numberOfInstances];

            DataElement dataElement = new DataElement()
            {
                DataType  = "Kvittering",
                SelfLinks = new ResourceLinks()
            };

            List <DataElement> dataElementList = new List <DataElement>();

            dataElementList.Add(dataElement);

            for (int i = 0; i < numberOfInstances; i++)
            {
                Instance instance = new Instance()
                {
                    Id            = $"100/2e130fad-c156-4424-8579-6537a1bf484f",
                    InstanceOwner = new InstanceOwner()
                    {
                        PartyId            = $"33445{i.ToString()}",
                        PersonNumber       = $"1234567890{i.ToString()}",
                        OrganisationNumber = $"9844566{i.ToString()}"
                    },
                    AppId = "AppId",
                    Org   = $"9844566{i.ToString()}",
                    Data  = dataElementList,
                };

                response.Instances[i] = instance;
            }

            return(response);
        }
Пример #5
0
        public void Storage_GetData_Data_For_Instance()
        {
            string expectedOrgOption      = "org";
            string expectedOrgDataType    = "string";
            string expectedOrgDescription = "org";
            string expectedOrgApiName     = "org";
            string expectedOrgValue       = "5533";

            string expectedFetchMessage = "Fetched 1 instances.";
            string expectedSaveMessage  = "File:Kvittering";
            int    expectedLogEntries   = 2;

            string environmentSetting         = "{\"UseLiveClient\": \"false\"}";
            NullLogger <OptionBuilder> logger = new NullLogger <OptionBuilder>();

            // Configure logger which is set on registered classes/objects
            TextWriter textWriter = new StringWriter();

            ConfigureLogging(textWriter);

            BuildEnvironment(environmentSetting);

            // Build command options
            OptionBuilder  builder           = OptionBuilder.Instance(logger);
            List <IOption> selectableOptions = new List <IOption>();

            selectableOptions.Add(TestDataBuilder.CreateOption(expectedOrgOption, expectedOrgDataType, expectedOrgDescription, expectedOrgApiName));
            Dictionary <string, string> cliOptions = new Dictionary <string, string>();

            cliOptions.Add(expectedOrgOption, expectedOrgValue);

            // Define which command and sub command that shall be registered in service provider
            List <Type> availableCommandTypes = new List <Type>();

            availableCommandTypes.Add(typeof(StorageCommand));

            List <Type> availableSubCommands = new List <Type>();

            availableSubCommands.Add(typeof(GetDataHandler));

            // Register commands and sub commands
            ServiceProvider serviceProvider = TestDataBuilder.BuildServiceProvider(availableCommandTypes, availableSubCommands, Log.Logger);

            // Set response from ClientWrapper
            InstanceResponseMessage response = TestDataBuilder.CreateInstanceResponse(1);

            StorageClientFileWrapper.InstanceResponse = response;
            StorageClientFileWrapper.DataContent      = new MemoryStream();

            // Fetch GetDataHandler subCommand
            var sssList = serviceProvider.GetServices <ISubCommandHandler>().ToList();
            ISubCommandHandler subCommandHandler = sssList.First(x => x.Name == "GetData");

            subCommandHandler.SelectableCliOptions = selectableOptions;
            subCommandHandler.DictOptions          = cliOptions;

            // Mock the file wrapper
            Mock <IFileWrapper> mockedWrapper = new Mock <IFileWrapper>();

            mockedWrapper.Setup(x => x.SaveToFile(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Stream>())).Returns(true);
            subCommandHandler.CliFileWrapper = mockedWrapper.Object;

            // Assign option values to the sub command
            builder.AssignValueToCliOptions(subCommandHandler);

            // Run the command
            subCommandHandler.Run();

            // Verify that the log contain expected result
            List <string> logEntries = GetLogEntries(textWriter);

            Assert.AreEqual(expectedLogEntries, logEntries.Count);

            string fetchMessage = logEntries.FirstOrDefault(x => x.Contains(expectedFetchMessage));

            Assert.IsFalse(string.IsNullOrEmpty(fetchMessage));

            string saveMessage = logEntries.FirstOrDefault(x => x.Contains(expectedSaveMessage));

            Assert.IsFalse(string.IsNullOrEmpty(saveMessage));

            textWriter.Dispose();
            builder.CfgCommands = null;
        }