System.Threading.Tasks.Task.FromResult(System.Collections.Generic.List)

Here are the examples of the csharp api System.Threading.Tasks.Task.FromResult(System.Collections.Generic.List) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1206 Examples 7

19 View Source File : DbManagerTest.cs
License : MIT License
Project Creator : 0x1000000

Task<List<ColumnRawModel>> IDbStrategy.LoadColumns()
        {
            List<ColumnRawModel> columns = new List<ColumnRawModel>
            {
                new ColumnRawModel(new ColumnRef("dbo","TableZ", "Id"), 1, true, false, "int", "((0))", null, null, null),
                new ColumnRawModel(new ColumnRef("dbo","TableZ", "ValueA"), 2, false, false, "nvarchar", "(N'')", 255, null, null),
                new ColumnRawModel(new ColumnRef("dbo","TableZ", "Value_A"), 3, false, true, "decimal", null, null, 2, 6),
                new ColumnRawModel(new ColumnRef("dbo","TableA", "Id"), 4, true, false, "int", "((0))", null, null, null),
                new ColumnRawModel(new ColumnRef("dbo","TableA", "Value"), 5, false, false, "datetime", "(getutcdate())", null, null, null)
            };

            return Task.FromResult(columns);
        }

19 View Source File : MockDataStore.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public async Task<IEnumerable<Item>> GereplacedemsAsync(bool forceRefresh = false)
        {
            return await Task.FromResult(items);
        }

19 View Source File : ConfigurationManagerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "ConfigurationManagement")]
        public async Task ConfigureErrorOnMissingRunnerGroup()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                var expectedPools = new List<TaskAgentPool>() { new TaskAgentPool(_defaultRunnerGroupName) { Id = _defaultRunnerGroupId, IsInternal = true } };
                _runnerServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny<string>(), It.IsAny<TaskAgentPoolType>())).Returns(Task.FromResult(expectedPools));

                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);


                trace.Info("Preparing command line arguments");
                var command = new CommandSettings(
                    tc,
                    new[]
                    {
                       "configure",
                       "--url", _expectedServerUrl,
                       "--name", _expectedAgentName,
                       "--runnergroup", "notexists",
                       "--work", _expectedWorkFolder,
                       "--auth", _expectedAuthType,
                       "--token", _expectedToken,
                    });
                trace.Info("Constructed.");
                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                var ex = await replacedert.ThrowsAsync<TaskAgentPoolNotFoundException>(() => configManager.ConfigureAsync(command));

                replacedert.Contains("notexists", ex.Message);

                _runnerServer.Verify(x => x.GetAgentPoolsAsync(It.IsAny<string>(), It.Is<TaskAgentPoolType>(p => p == TaskAgentPoolType.Automation)), Times.Exactly(1));
            }
        }

19 View Source File : JobRunnerL0.cs
License : MIT License
Project Creator : actions

private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc = new Runner.Worker.ExecutionContext();
            _config = new Mock<IConfigurationStore>();
            _extensions = new Mock<IExtensionManager>();
            _jobExtension = new Mock<IJobExtension>();
            _jobServer = new Mock<IJobServer>();
            _jobServerQueue = new Mock<IJobServerQueue>();
            _stepRunner = new Mock<IStepsRunner>();
            _logger = new Mock<IPagingLogger>();
            _temp = new Mock<ITempDirectoryManager>();
            _diagnosticLogManager = new Mock<IDiagnosticLogManager>();

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();

            _jobRunner = new JobRunner();
            _jobRunner.Initialize(hc);

            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline = new Timeline(Guid.NewGuid());
            Guid jobId = Guid.NewGuid();
            _message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, testName, testName, null, null, null, new Dictionary<string, VariableValue>(), new List<MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List<Pipelines.ActionStep>(), null, null, null, null);
            _message.Variables[Constants.Variables.System.Culture] = "en-US";
            _message.Resources.Endpoints.Add(new ServiceEndpoint()
            {
                Name = WellKnownServiceEndpointNames.SystemVssConnection,
                Url = new Uri("https://pipelines.actions.githubusercontent.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme = "Test",
                    Parameters = {
                        {"AccessToken", "token"}
                    }
                },

            });

            _message.Resources.Repositories.Add(new Pipelines.RepositoryResource()
            {
                Alias = Pipelines.PipelineConstants.SelfAlias,
                Id = "github",
                Version = "sha1"
            });
            _message.ContextData.Add("github", new Pipelines.ContextData.DictionaryContextData());

            _initResult.Clear();

            _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<Pipelines.AgentJobRequestMessage>())).
                Returns(Task.FromResult(_initResult));

            var settings = new RunnerSettings
            {
                AgentId = 1,
                AgentName = "agent1",
                ServerUrl = "https://pipelines.actions.githubusercontent.com",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
                .Returns(settings);

            _logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>()));

            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServer.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_stepRunner.Object);
            hc.SetSingleton(_extensions.Object);
            hc.SetSingleton(_temp.Object);
            hc.SetSingleton(_diagnosticLogManager.Object);
            hc.EnqueueInstance<IExecutionContext>(_jobEc);
            hc.EnqueueInstance<IPagingLogger>(_logger.Object);
            hc.EnqueueInstance<IJobExtension>(_jobExtension.Object);
            return hc;
        }

19 View Source File : RabbitMqEventBusProvider.cs
License : MIT License
Project Creator : ad313

public async Task<List<T>> GetQueueItemsAsync<T>(string key, int length)
        {
            using (await GetLockObject(key).LockAsync())
            {
                var queueName = GetChannelQueueKey(key);
                return await Task.FromResult(GetQueueItemsMethod<T>(queueName, length));
            }
        }

19 View Source File : RabbitMqEventBusProvider.cs
License : MIT License
Project Creator : ad313

public async Task<List<T>> GetErrorQueueItemsAsync<T>(string key, int length)
        {
            using (await GetLockObject(key).LockAsync())
            {
                var queueName = GetChannelErrorQueueKey(key);
                return await Task.FromResult(GetErrorQueueItems<T>(queueName, length));
            }
        }

19 View Source File : MemoryEventBusProvider.cs
License : MIT License
Project Creator : ad313

public async Task<List<T>> GetQueueItemsAsync<T>(string key, int length)
        {
            return await Task.FromResult(GetQueueItems<T>(key, length));
        }

19 View Source File : InMemoryDatabase.cs
License : MIT License
Project Creator : AElfProject

public Task<List<byte[]>> GetAllAsync(IList<string> keys)
        {
            if (keys.Count == 0)
                return null;

            var result = new List<byte[]>();
            
            foreach (var key in keys)
            {
                Check.NotNullOrWhiteSpace(key, nameof(key));
                _dictionary.TryGetValue(key, out var value);
                result.Add(value);
            }

            return result.Any() ? Task.FromResult(result) : Task.FromResult<List<byte[]>>(null);
        }

19 View Source File : TransactionListProvider.cs
License : MIT License
Project Creator : AElfProject

public Task<List<Transaction>> GetTransactionListAsync()
        {
            var list = _transactionList;
            return Task.FromResult(list);
        }

19 View Source File : TestTokenBalanceTransactionGenerator.cs
License : MIT License
Project Creator : AElfProject

public Task<List<Transaction>> GenerateTransactionsAsync(Address @from, long preBlockHeight, Hash preBlockHash)
        {
            var res = new List<Transaction>();
            if (GenerateTransactionFunc == null)
            {
                return Task.FromResult(res);
            }

            res.Add(GenerateTransactionFunc(from, preBlockHeight, preBlockHash));
            return Task.FromResult(res);
        }

19 View Source File : TransactionPoolTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            services.AddSingleton<TransactionExecutionValidationProvider>();
            services.AddSingleton<TransactionMethodValidationProvider>();
            services.AddSingleton<TransactionMockExecutionHelper>();

            services.AddSingleton(provider =>
            {
                var mockService = new Mock<IPlainTransactionExecutingService>();

                mockService.Setup(m =>
                        m.ExecuteAsync(It.IsAny<TransactionExecutingDto>(), It.IsAny<CancellationToken>()))
                    .Returns<TransactionExecutingDto, CancellationToken>((transactionExecutingDto, cancellationToken) =>
                    {
                        var transactionMockExecutionHelper =
                            context.Services.GetRequiredServiceLazy<TransactionMockExecutionHelper>().Value;
                        return Task.FromResult(new List<ExecutionReturnSet>
                        {
                            new ExecutionReturnSet
                            {
                                Status = transactionMockExecutionHelper.GetTransactionResultStatus()
                            }
                        });
                    });

                return mockService.Object;
            });
            
            services.AddSingleton(provider =>
            {
                var mockService = new Mock<ITransactionReadOnlyExecutionService>();

                mockService.Setup(m =>
                        m.IsViewTransactionAsync(It.IsAny<IChainContext>(), It.IsAny<Transaction>()))
                    .Returns<IChainContext, Transaction>((chainContext, transaction) => Task.FromResult(transaction.MethodName == "View"));

                return mockService.Object;
            });
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public Task<List<Transaction>> GetTransactionsAsync(IEnumerable<Hash> transactionHashes)
        {
            return Task.FromResult(_data.Where(d => transactionHashes.Contains(d.GetHash())).ToList());
        }

19 View Source File : KernelTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            var transactionList = new List<Transaction>
            {
                new Transaction
                {
                    From = SampleAddress.AddressList[0],
                    To = SampleAddress.AddressList[1],
                    MethodName = "GenerateConsensusTransactions"
                }
            };
            services.AddTransient(o =>
            {
                var mockService = new Mock<ISystemTransactionGenerator>();
                mockService.Setup(m =>
                    m.GenerateTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()));

                return mockService.Object;
            });

            services.AddTransient(o =>
            {
                var mockService = new Mock<ISystemTransactionGenerationService>();
                mockService.Setup(m =>
                        m.GenerateSystemTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()))
                    .Returns(Task.FromResult(transactionList));

                return mockService.Object;
            });

            services.AddTransient<IBlockExecutingService, TestBlockExecutingService>();


            //For BlockExtraDataService testing.
            services.AddTransient(
                builder =>
                {
                    var dataProvider = new Mock<IBlockExtraDataProvider>();

                    ByteString bs = ByteString.CopyFrom(BitConverter.GetBytes(long.MaxValue - 1));

                    dataProvider.Setup(m => m.GetBlockHeaderExtraDataAsync(It.IsAny<BlockHeader>()))
                        .Returns(Task.FromResult(bs));

                    dataProvider.Setup(d => d.BlockHeaderExtraDataKey).Returns("TestExtraDataKey");

                    return dataProvider.Object;
                });
            services.AddTransient(provider =>
            {
                var mockService = new Mock<ISmartContractAddressService>();
                return mockService.Object;
            });

            services.AddTransient<BlockValidationProvider>();
        }

19 View Source File : KernelCoreTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            
            //For system transaction generator testing
            services.AddTransient(provider =>
            {
                var transactionList = new List<Transaction>
                {
                    new Transaction() {From = SampleAddress.AddressList[0], To = SampleAddress.AddressList[2], MethodName = "InValue"},
                    new Transaction() {From = SampleAddress.AddressList[1], To = SampleAddress.AddressList[3], MethodName = "OutValue"},
                };
                var consensusTransactionGenerator = new Mock<ISystemTransactionGenerator>();
                consensusTransactionGenerator
                    .Setup(m => m.GenerateTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()))
                    .Returns(Task.FromResult(transactionList));
                    
                return consensusTransactionGenerator.Object;
            });
            
            //For BlockExtraDataService testing.
            services.AddTransient(
                builder =>
                {
                    var  dataProvider = new Mock<IBlockExtraDataProvider>();
                    dataProvider.Setup( m=>m.GetBlockHeaderExtraDataAsync(It.Is<BlockHeader>(o=>o.Height != 100)))
                        .Returns(Task.FromResult(ByteString.CopyFromUtf8("not null")));

                    ByteString bs = null;
                    dataProvider.Setup( m=>m.GetBlockHeaderExtraDataAsync(It.Is<BlockHeader>(o => o.Height == 100)))
                        .Returns(Task.FromResult(bs));
                    
                    dataProvider.Setup(m => m.BlockHeaderExtraDataKey).Returns(nameof(IBlockExtraDataProvider));
                    return dataProvider.Object;
                });
        }

19 View Source File : SmartContractExecutionExecutingTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            services.AddTransient(p =>
            {
                var mockService = new Mock<ITransactionExecutingService>();
                mockService.Setup(m => m.ExecuteAsync(It.IsAny<TransactionExecutingDto>(),
                        It.IsAny<CancellationToken>()))
                    .Returns<TransactionExecutingDto, CancellationToken>(
                        (transactionExecutingDto, cancellationToken) =>
                        {
                            var returnSets = new List<ExecutionReturnSet>();

                            var count = 0;
                            foreach (var tx in transactionExecutingDto.Transactions)
                            {
                                if (cancellationToken.IsCancellationRequested && count >= 3)
                                {
                                    break;
                                }

                                var returnSet = new ExecutionReturnSet
                                {
                                    TransactionId = tx.GetHash()
                                };
                                returnSet.StateChanges.Add(tx.GetHash().ToHex(), tx.ToByteString());
                                returnSets.Add(returnSet);
                                count++;
                            }

                            return Task.FromResult(returnSets);
                        });

                return mockService.Object;
            });
            services.AddTransient(p =>
            {
                var mockService = new Mock<IBlockExecutingService>();
                mockService.Setup(m =>
                        m.ExecuteBlockAsync(It.IsAny<BlockHeader>(), It.IsAny<List<Transaction>>()))
                    .Returns<BlockHeader, IEnumerable<Transaction>>((blockHeader, transactions) =>
                    {
                        var block = new Block
                        {
                            Header = blockHeader,
                            Body = new BlockBody()
                        };
                        block.Body.AddTransactions(transactions.Select(x => x.GetHash()));
                        return Task.FromResult(new BlockExecutedSet(){Block = block});
                    });
                return mockService.Object;
            });
        }

19 View Source File : NetworkServiceTestModule.cs
License : MIT License
Project Creator : AElfProject

public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var peerPool = context.ServiceProvider.GetRequiredService<IPeerPool>();
            var osTestHelper = context.ServiceProvider.GetRequiredService<OSTestHelper>();

            {
                var normalPeer = new Mock<IPeer>();
                normalPeer.Setup(m => m.RemoteEndpoint).Returns(new DnsEndPoint("192.168.100.200", 5000));
                var blockWithTransactions = osTestHelper.GenerateBlockWithTransactions(Hash.Empty, 10);
                normalPeer.Setup(p => p.Info).Returns(new PeerConnectionInfo
                    {Pubkey = "NormalPeer", ConnectionTime = TimestampHelper.GetUtcNow()});
                normalPeer.Setup(p => p.GetBlocksAsync(It.IsAny<Hash>(), It.IsAny<int>()))
                    .Returns<Hash, int>((h, cnt) => Task.FromResult(new List<BlockWithTransactions>()));
                normalPeer.Setup(p => p.IsReady).Returns(true);
                normalPeer.Setup(p => p.GetBlockByHashAsync(It.Is<Hash>(h => h == HashHelper.ComputeFrom("bHash1"))))
                    .Returns<Hash>(h => Task.FromResult(blockWithTransactions));
                normalPeer.Setup(m => m.GetNodesAsync(It.IsAny<int>()))
                    .Returns(Task.FromResult(new NodeList
                    {
                        Nodes =
                        {
                            new NodeInfo
                            {
                                Endpoint = "http://192.168.100.88:8000",
                                Pubkey = ByteString.CopyFromUtf8("p2")
                            }
                        }
                    }));
                
                peerPool.TryAddPeer(normalPeer.Object);
            }

            {
                var failedPeerPeer = new Mock<IPeer>();
                failedPeerPeer.Setup(p => p.RemoteEndpoint).Returns(new DnsEndPoint("192.168.100.400", 80));
                failedPeerPeer.Setup(p => p.Info).Returns(new PeerConnectionInfo
                    {Pubkey = "FailedPeer", ConnectionTime = TimestampHelper.GetUtcNow()});
                failedPeerPeer.Setup(p => p.IsInvalid).Returns(true);
                failedPeerPeer.Setup(p => p.GetBlockByHashAsync(It.IsAny<Hash>())).Throws(new NetworkException());
                failedPeerPeer.Setup(p => p.GetBlocksAsync(It.IsAny<Hash>(), It.IsAny<int>())).Throws(new NetworkException());
                peerPool.TryAddPeer(failedPeerPeer.Object);
            }
        }

19 View Source File : OSCoreWithChainTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddTransient<ISystemTransactionGenerationService>(o =>
            {
                var mockService = new Mock<ISystemTransactionGenerationService>();
                mockService.Setup(s =>
                        s.GenerateSystemTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()))
                    .Returns(Task.FromResult(new List<Transaction>()));
                return mockService.Object;
            });

            context.Services.AddTransient<IBlockExtraDataService>(o =>
            {
                var mockService = new Mock<IBlockExtraDataService>();
                mockService.Setup(s =>
                    s.FillBlockExtraDataAsync(It.IsAny<BlockHeader>())).Returns(Task.CompletedTask);
                return mockService.Object;
            });

            context.Services.AddTransient<IBlockValidationService>(o =>
            {
                var mockService = new Mock<IBlockValidationService>();
                mockService.Setup(s =>
                    s.ValidateBlockBeforeAttachAsync(It.IsAny<IBlock>())).Returns(Task.FromResult(true));
                mockService.Setup(s =>
                    s.ValidateBlockBeforeExecuteAsync(It.IsAny<IBlock>())).Returns(Task.FromResult(true));
                mockService.Setup(s =>
                    s.ValidateBlockAfterExecuteAsync(It.IsAny<IBlock>())).Returns(Task.FromResult(true));
                return mockService.Object;
            });

            context.Services.AddSingleton<IAElfNetworkServer>(o => Mock.Of<IAElfNetworkServer>());
            context.Services.AddSingleton<ITxHub, MockTxHub>();

            context.Services.AddSingleton<ISmartContractRunner, UnitTestCSharpSmartContractRunner>(provider =>
            {
                var option = provider.GetService<IOptions<RunnerOptions>>();
                return new UnitTestCSharpSmartContractRunner(
                    option.Value.SdkDir);
            });
            context.Services.AddSingleton<IDefaultContractZeroCodeProvider, Kernel.UnitTestContractZeroCodeProvider>();
            context.Services.AddSingleton<ISmartContractAddressService, UnitTestSmartContractAddressService>();
            context.Services
                .AddSingleton<ISmartContractAddressNameProvider, ParliamentSmartContractAddressNameProvider>();
        }

19 View Source File : OSTestAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            Configure<ChainOptions>(o => { o.ChainId = ChainHelper.ConvertBase58ToChainId("AELF"); });

            var ecKeyPair = CryptoHelper.GenerateKeyPair();
            var nodeAccount = Address.FromPublicKey(ecKeyPair.PublicKey).ToBase58();
            var nodeAccountPreplacedword = "123";

            Configure<AccountOptions>(o =>
            {
                o.NodeAccount = nodeAccount;
                o.NodeAccountPreplacedword = nodeAccountPreplacedword;
            });

            context.Services.AddSingleton<IKeyStore>(o =>
            {
                var keyStore = new Mock<IKeyStore>();
                ECKeyPair keyPair = null;

                keyStore.Setup(k => k.GetAccountKeyPair(It.IsAny<string>())).Returns(() => keyPair);
                
                keyStore.Setup(k => k.GetAccountsAsync()).Returns(Task.FromResult(new List<string>()));
                
                keyStore.Setup(k => k.CreateAccountKeyPairAsync(It.IsAny<string>()))
                    .Returns(Task.FromResult(CryptoHelper.FromPrivateKey(ByteArrayHelper.HexStringToByteArray("5945c176c4269dc2aa7daf7078bc63b952832e880da66e5f2237cdf79bc59c5f"))));

                keyStore.Setup(k => k.UnlockAccountAsync(It.IsAny<string>(), It.IsAny<string>())).Returns(() =>
                {
                    keyPair = ecKeyPair;
                    return Task.FromResult(AccountError.None);
                });

                return keyStore.Object;
            });

            context.Services.AddTransient<AccountService>();
            
            Configure<AbpBackgroundWorkerOptions>(o => { o.IsEnabled = false; });
        }

19 View Source File : Typeahead.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

public static async Task<List<T>> SearchEnum<T>(string searchText) 
        {
            var list = new List<T>((T[])Enum.GetValues(typeof(T)));
            return await Task.FromResult(list.Where(x => x.ToString().ToLower().Contains(searchText.ToLower())).ToList());
        }

19 View Source File : DummyHttpService.cs
License : MIT License
Project Creator : aliencube

public async Task<List<DummyResponseModel>> GetDummies()
        {
            var result = new List<DummyResponseModel>()
            {
                new DummyResponseModel(),
            };

            return await Task.FromResult(result).ConfigureAwait(false);
        }

19 View Source File : MainPageViewModel.cs
License : MIT License
Project Creator : Altevir

Task<List<Store>> Search(string text)
        {
            List<Store> stores = new List<Store>();
            IsVisibleBtnClose = false;

            if (string.IsNullOrEmpty(text))
            {
                foreach (var item in Stores)
                    stores.Add(item);
            }
            else
            {
                var result = Stores.Where(p => p.name.ToLower().Contains(text.ToLower()));
                IsVisibleBtnClose = !result.Any();

                if (result.Any())
                    foreach (var item in result)
                        stores.Add(item);
            }

            return Task.FromResult(stores);
        }

19 View Source File : SigningKeysRetrieverStub.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<ICollection<SecurityKey>> GetSigningKeys(string url)
        {
            List<SecurityKey> signingKeys = new List<SecurityKey>();

            X509Certificate2 cert = new X509Certificate2("JWTValidationCert.cer");
            SecurityKey key = new X509SecurityKey(cert);

            signingKeys.Add(key);

            return await Task.FromResult(signingKeys);
        }

19 View Source File : IAltinnApp.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

virtual async Task<List<string>> GetPageOrder(string org, string app, int instanceOwnerId, Guid instanceGuid, string layoutSetId, string currentPage, string dataTypeId, object formData)
        {
            return await Task.FromResult(new List<string>());
        }

19 View Source File : ValidationMockSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<ValidationIssue>> ValidateAndUpdateProcess(Instance instance, string taskId)
        {
            return Task.FromResult(new List<ValidationIssue>());
        }

19 View Source File : ValidationMockSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<ValidationIssue>> ValidateDataElement(Instance instance, DataType dataType, DataElement dataElement)
        {
            return Task.FromResult(new List<ValidationIssue>());
        }

19 View Source File : InstanceEventAppSIMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<InstanceEvent>> GetInstanceEvents(string instanceId, string instanceOwnerId, string org, string app, string[] eventTypes, string from, string to)
        {
            return Task.FromResult(new List<InstanceEvent>());
        }

19 View Source File : PepWithPDPAuthorizationMockSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static Task<List<Role>> GetDecisionPointRolesForUser(int coveredByUserId, int offeredByPartyId)
        {
            string rolesPath = GetRolesPath(coveredByUserId, offeredByPartyId);

            List<Role> roles = new List<Role>();

            if (File.Exists(rolesPath))
            {
                string content = System.IO.File.ReadAllText(rolesPath);
                roles = (List<Role>)JsonConvert.DeserializeObject(content, typeof(List<Role>));
            }

            return Task.FromResult(roles);
        }

public async Task<List<X509Certificate2>> GetCertificates()
        {
            X509Certificate2 cert = new X509Certificate2(_certificateSettings.CertificatePath, _certificateSettings.CertificatePwd);

            List<X509Certificate2> certificates = new List<X509Certificate2> { cert };

            return await Task.FromResult(certificates);
        }

19 View Source File : ConfigurationManagerStub.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private async Task<ICollection<SecurityKey>> GetSigningKeys()
        {
            List<SecurityKey> signingKeys = new List<SecurityKey>();

            X509Certificate2 cert = new X509Certificate2("JWTValidationCert.cer");
            SecurityKey key = new X509SecurityKey(cert);

            signingKeys.Add(key);

            return await Task.FromResult(signingKeys);
        }

19 View Source File : SubscriptionRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<Subscription>> GetSubscriptionsByConsumer(string consumer)
        {
            string subscriptionsPath = Path.Combine(GetSubscriptionPath(), "1.json");
            List<Subscription> subscriptions = null;
            if (File.Exists(subscriptionsPath))
            {
                string content = File.ReadAllText(subscriptionsPath);
                subscriptions = JsonConvert.DeserializeObject<List<Subscription>>(content);
            }
            else
            {
                subscriptions = new List<Subscription>();
            }

            return Task.FromResult(subscriptions.Where(s => s.Consumer.StartsWith("/org/")).ToList());
        }

19 View Source File : SubscriptionRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<Subscription>> GetSubscriptionsExcludeOrg(string source, string subject, string type)
        {
            string subscriptionsPath = Path.Combine(GetSubscriptionPath(), "1.json");
            List<Subscription> subscriptions = null;
            if (File.Exists(subscriptionsPath))
            {
                string content = File.ReadAllText(subscriptionsPath);
                subscriptions = JsonConvert.DeserializeObject<List<Subscription>>(content);
            }
            else
            {
                subscriptions = new List<Subscription>();
            }

            return Task.FromResult(subscriptions.Where(s =>
                                !s.Consumer.StartsWith("/org/") &&
                                s.SourceFilter.Equals(source) &&
                                subject.Equals(subject) &&
                                (string.IsNullOrEmpty(s.TypeFilter) || type.Equals(s.TypeFilter))).ToList());
        }

19 View Source File : ConfigurationManagerStub.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private async Task<ICollection<SecurityKey>> GetSigningKeys()
        {
            List<SecurityKey> signingKeys = new List<SecurityKey>();

            X509Certificate2 cert = new X509Certificate2("selfSignedTestCertificatePublic.cer");
            SecurityKey key = new X509SecurityKey(cert);

            signingKeys.Add(key);

            return await Task.FromResult(signingKeys);
        }

19 View Source File : DataRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<List<DataElement>> ReadAll(Guid instanceGuid)
        {
            List<DataElement> dataElements = new List<DataElement>();
            string dataElementsPath = GetDataElementsPath();

            string[] dataElementPaths = Directory.GetFiles(dataElementsPath);
            foreach (string elementPath in dataElementPaths)
            {
                string content = File.ReadAllText(elementPath);
                DataElement dataElement = (DataElement)JsonConvert.DeserializeObject(content, typeof(DataElement));
                if (dataElement.InstanceGuid.Contains(instanceGuid.ToString()))
                {
                    dataElements.Add(dataElement);
                }
            }

            return await Task.FromResult(dataElements);
        }

19 View Source File : TextRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<List<TextResource>> Get(List<string> appIds, string language)
        {
            List<TextResource> result = new List<TextResource>();
            foreach (string appId in appIds)
            {
                string org = appId.Split("/")[0];
                string app = appId.Split("/")[1];

                TextResource resource = Get(org, app, language).Result;
                if (resource != null)
                {
                    result.Add(resource);
                }
            }

            return await Task.FromResult(result);
        }

19 View Source File : PepWithPDPAuthorizationMockSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<Role>> GetDecisionPointRolesForUser(int coveredByUserId, int offeredByPartyId)
        {
            string rolesPath = GetRolesPath(coveredByUserId, offeredByPartyId);

            List<Role> roles = new List<Role>();

            if (File.Exists(rolesPath))
            {
                string content = File.ReadAllText(rolesPath);
                roles = (List<Role>)JsonConvert.DeserializeObject(content, typeof(List<Role>));
            }

            return Task.FromResult(roles);
        }

public Task<List<DelegationChange>> GetAllDelegationChanges(string altinnAppId, int offeredByPartyId, int? coveredByPartyId, int? coveredByUserId)
        {
            return Task.FromResult(new List<DelegationChange>());
        }

19 View Source File : RolesMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<Role>> GetDecisionPointRolesForUser(int coveredByUserId, int offeredByPartyId)
        {
            List<Role> roles = new List<Role>();
            string rolesPath = GetRolesPath(coveredByUserId, offeredByPartyId);
            if (File.Exists(rolesPath))
            {
                string content = File.ReadAllText(rolesPath);
                roles = (List<Role>)JsonSerializer.Deserialize(content, typeof(List<Role>), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });               
            }

            return Task.FromResult(roles);
        }

19 View Source File : CloudEventRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<CloudEvent>> Get(string after, DateTime? from, DateTime? to, string subject, List<string> source, List<string> type, int size)
        {
            string eventsPath = Path.Combine(GetEventsPath(), [email protected]"{_eventsCollection}.json");

            if (File.Exists(eventsPath))
            {
                string content = File.ReadAllText(eventsPath);
                List<EventsTableEntry> tableEntries = JsonConvert.DeserializeObject<List<EventsTableEntry>>(content);

                // logic for filtering on source and type not implemented.
                IEnumerable<EventsTableEntry> filter = tableEntries;

                if (!string.IsNullOrEmpty(after))
                {
                    int sequenceNo = filter.Where(te => te.Id.Equals(after)).Select(te => te.SequenceNo).FirstOrDefault();
                    filter = filter.Where(te => te.SequenceNo > sequenceNo);
                }

                if (from.HasValue)
                {
                    filter = filter.Where(te => te.Time >= from);
                }

                if (to.HasValue)
                {
                    filter = filter.Where(te => te.Time <= to);
                }

                if (!string.IsNullOrEmpty(subject))
                {
                    filter = filter.Where(te => te.Subject.Equals(subject));
                }

                if (source != null && source.Count > 0)
                {
                    // requires more logic to match all fancy cases.
                    filter = filter.Where(te => source.Contains(te.Source.ToString()));
                }

                if (type != null && type.Count > 0)
                {
                    // requires more logic to match all fancy cases.
                    filter = filter.Where(te => type.Contains(te.Type.ToString()));
                }

                List<CloudEvent> result = filter.Select(t => t.CloudEvent)
                    .Take(size)
                    .ToList();

                result.ForEach(ce => ce.Time = ce.Time.Value.ToUniversalTime());
                return Task.FromResult(result);
            }

            return null;
        }

19 View Source File : EventsServiceMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<CloudEvent>> Get(string after, DateTime? from, DateTime? to, int partyId, List<string> source, List<string> type, int size)
        {
            string eventsPath = Path.Combine(GetEventsPath(), [email protected]"{_eventsCollection}.json");

            if (File.Exists(eventsPath))
            {
                string content = File.ReadAllText(eventsPath);
                List<EventsTableEntry> tableEntries = JsonConvert.DeserializeObject<List<EventsTableEntry>>(content);

                // logic for filtering on source and type not implemented.
                IEnumerable<EventsTableEntry> filter = tableEntries;

                if (!string.IsNullOrEmpty(after))
                {
                    int sequenceNo = filter.Where(te => te.Id.Equals(after)).Select(te => te.SequenceNo).FirstOrDefault();
                    filter = filter.Where(te => te.SequenceNo > sequenceNo);
                }

                if (from.HasValue)
                {
                    filter = filter.Where(te => te.Time >= from);
                }

                if (to.HasValue)
                {
                    filter = filter.Where(te => te.Time <= to);
                }

                if (partyId > 0)
                {
                    string subject = $"/party/{partyId}";
                    filter = filter.Where(te => te.Subject.Equals(subject));
                }

                List<CloudEvent> result = filter.Select(t => t.CloudEvent)
                    .Take(size)
                    .ToList();

                result.ForEach(ce => ce.Time = ce.Time.Value.ToUniversalTime());
                return Task.FromResult(result);
            }

            return null;
        }

19 View Source File : ConfigurationManagerStub.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private async Task<ICollection<SecurityKey>> GetSigningKeys(string _)
        {
            X509Certificate2 cert = new X509Certificate2("JWTValidationCert.cer");
            SecurityKey key = new X509SecurityKey(cert);

            List<SecurityKey> signingKeys = new () { key };

            return await Task.FromResult(signingKeys);
        }

19 View Source File : InstanceEventRepositoryMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<List<InstanceEvent>> ListInstanceEvents(string instanceId, string[] eventTypes, DateTime? fromDateTime, DateTime? toDateTime)
        {
            List<InstanceEvent> events = new List<InstanceEvent>();

            lock (TestDataUtil.DataLock)
            {
                string eventsPath = GetInstanceEventsPath(instanceId.Split("/")[1], instanceId.Split("/")[0]);
                if (Directory.Exists(eventsPath))
                {
                    string[] instanceEventPath = Directory.GetFiles(eventsPath);
                    foreach (string path in instanceEventPath)
                    {
                        string content = File.ReadAllText(path);
                        InstanceEvent instance = (InstanceEvent)JsonConvert.DeserializeObject(content, typeof(InstanceEvent));
                        events.Add(instance);
                    }
                }
            }

            return await Task.FromResult(events);
        }

19 View Source File : ConfigurationManagerStub.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static async Task<ICollection<SecurityKey>> GetSigningKeys()
        {
            List<SecurityKey> signingKeys = new List<SecurityKey>();

            X509Certificate2 cert = new X509Certificate2("selfSignedTestCertificatePublic.cer");
            SecurityKey key = new X509SecurityKey(cert);

            signingKeys.Add(key);

            return await Task.FromResult(signingKeys);
        }

19 View Source File : PartiesService.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<Party>> GetParties(int userId)
        {
            string path = GetPartyListPath(userId);
            
            if (File.Exists(path))
            {
                string content = System.IO.File.ReadAllText(path);
                List<Party> instance = (List<Party>)JsonConvert.DeserializeObject(content, typeof(List<Party>));
                return Task.FromResult(instance);
            }

            return null;
        }

19 View Source File : RolesWrapper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<List<Role>> GetDecisionPointRolesForUser(int coveredByUserId, int offeredByPartyId)
        {
            string rolesPath = GetRolesPath(coveredByUserId, offeredByPartyId);

            List<Role> roles = new List<Role>();

            if (File.Exists(rolesPath))
            {
                string content = System.IO.File.ReadAllText(rolesPath);
                roles = (List<Role>)JsonConvert.DeserializeObject(content, typeof(List<Role>));
            }

            return await Task.FromResult(roles);
        }

19 View Source File : IGiteaMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public Task<List<FileSystemObject>> GetDirectoryAsync(string org, string app, string directoryPath, string shortCommitId)
        {
            List<FileSystemObject> fileSystemObjects = new List<FileSystemObject>();

            string path = Path.Combine(_unitTestFolder, [email protected]"..\..\..\_TestData\FileSystemObjects\{org}\{app}\{directoryPath.Replace('/', '\\')}{shortCommitId}\directoryList.json");

            if (File.Exists(path))
            {
                string content = File.ReadAllText(path);

                fileSystemObjects = System.Text.Json.JsonSerializer.Deserialize<List<FileSystemObject>>(content);
            }

            return Task.FromResult(fileSystemObjects);
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : ansel86castro

public static Task<List<T>> ToListAsync<T>(this IQueryable<T> query)
        {
            if (IAsyncQueryExecutioner.Executioner == null)
                return Task.FromResult(query.ToList());

            return IAsyncQueryExecutioner.Executioner.ToListAsync(query);
        }

19 View Source File : EmployeeControllerTest.cs
License : MIT License
Project Creator : appsonsf

[TestMethod]
        public async Task Test_GetById_GetByUserId()
        {
            var dep0 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq",
            };
            var dep1 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq-jt",
                ParentId = dep0.Id,
            };
            var dep2 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq-gs",
                ParentId = dep0.Id,
            };
            var pos1 = new PositionListOutput
            {
                Id = Guid.NewGuid(),
                Name = "pos1",
                DepartmentId = dep1.Id,
            };
            var pos2 = new PositionListOutput
            {
                Id = Guid.NewGuid(),
                Name = "pos2",
                DepartmentId = dep2.Id,
            };
            var emp0 = new EmployeeOutput
            {
                Id = Guid.NewGuid(),
                UserId = Guid.NewGuid(),
                Name = "aaa",
                PrimaryDepartmentId = dep1.Id,
                PrimaryPositionId = pos1.Id,
                ParttimePositionIds = new List<Guid> { pos2.Id },
            };

            var departmentAppService = Subsreplacedute.For<IDepartmentAppService>();
            departmentAppService.GetAllListAsync()
                .Returns(Task.FromResult((new[] { dep0, dep1, dep2 }).ToList()));

            var positionAppService = Subsreplacedute.For<IPositionAppService>();
            positionAppService.GetAllListAsync()
                .Returns(Task.FromResult((new[] { pos1, pos2 }).ToList()));

            var employeeAppService = Subsreplacedute.For<IEmployeeAppService>();
            employeeAppService.GetByIdAsync(emp0.Id)
                .Returns(Task.FromResult(emp0));
            employeeAppService.GetByUserIdAsync(emp0.UserId.Value)
                .Returns(Task.FromResult(emp0));

            var groupAppService = Subsreplacedute.For<IGroupAppService>();
            groupAppService.CheckSameWhiteListGroupAsync(User_EmployeeMdmId, emp0.Id)
                .Returns(Task.FromResult(true));

            var userFavoriteAppService = Subsreplacedute.For<IUserFavoriteAppService>();
            userFavoriteAppService.IsFavoritedAsync(User_Id, emp0.Id)
                .Returns(Task.FromResult(true));

            var userSettingAppService = Subsreplacedute.For<IUserSettingAppService>();
            userSettingAppService.GetInfoVisibilityAsync(emp0.UserId.Value)
                .Returns(Task.FromResult(new InfoVisibility { Mobile = false }));

            var target = new EmployeeController(
                CreateMemoryCache(),
                CreateMapper(),
                departmentAppService,
                positionAppService,
                employeeAppService,
                groupAppService,
                _ => userFavoriteAppService,
                _ => userSettingAppService
                );
            target.ControllerContext = CreateMockContext();

            var result = await target.GetById(emp0.Id);
            var data = result.Value;
            data.SameWhiteListGroup.Should().BeTrue();
            data.IsFavorited.Should().BeTrue();
            data.Name.Should().Be(emp0.Name);
            data.Mobile.Should().Be("***");
            data.PositionName.Should().Be(pos1.Name);

            data.DepartmentNames.Count.Should().Be(2);
            data.DepartmentNames[0].Should().Be(dep1.Name);

            data.ParttimeJobs.Count.Should().Be(1);
            data.ParttimeJobs[0].PositionName.Should().Be(pos2.Name);
            data.ParttimeJobs[0].DepartmentNames.Count.Should().Be(2);
            data.ParttimeJobs[0].DepartmentNames[0].Should().Be(dep2.Name);

            result = await target.GetByUserId(emp0.UserId.Value);
            data = result.Value;
            data.Should().NotBeNull();
        }

19 View Source File : WorkbenchControllerInitDataTest.cs
License : MIT License
Project Creator : appsonsf

[TestMethod]
        public async Task TestGetAppEntrancesAsync()
        {
            var workbenchAppService = Subsreplacedute.For<IWorkbenchAppService>();
            workbenchAppService.GetAppEntrancesRawByClientIdAsync(Client.DefaultId)
              .Returns(Task.FromResult(new List<AppEntrance>(){
                  new AppEntrance { Id = new Guid("0459738c0233483cabb53295e3bae783") }
              }
              ));

            var target = new WorkbenchController(
                workbenchAppService,
                Subsreplacedute.For<IClientAppService>(),
                Subsreplacedute.For<IBizSystemAppService>(),
                Subsreplacedute.For<IBadgeApiClient>(),
                Subsreplacedute.For<IMobileCodeSender>(),
                _ => Subsreplacedute.For<IUserSettingAppService>());
            target.ControllerContext = CreateMockContext();

            var result = await target.GetAppEntrancesAsync();
            var lst = result.Value.As<List<AppEntrance>>();
            lst.Should().NotBeNullOrEmpty();
            lst[0].Id.Should().Be(new Guid("0459738c0233483cabb53295e3bae783"));
        }

19 View Source File : WorkbenchControllerInitDataTest.cs
License : MIT License
Project Creator : appsonsf

[TestMethod]
        public async Task TestGetTodoCenterBizSystemsAsync()
        {
            var model = new List<TodoCenterBizSystem>
            {
               new TodoCenterBizSystem
               {
                   Id="aaa"
               }
            };
            var todoCenterAppService = Subsreplacedute.For<IBizSystemAppService>();
            todoCenterAppService.GetAllForTodoCenterAsync()
                .Returns(Task.FromResult(model));

            var target = new WorkbenchController(
                Subsreplacedute.For<IWorkbenchAppService>(),
                Subsreplacedute.For<IClientAppService>(),
                todoCenterAppService,
                Subsreplacedute.For<IBadgeApiClient>(),
                Subsreplacedute.For<IMobileCodeSender>(),
                _ => Subsreplacedute.For<IUserSettingAppService>());
            target.ControllerContext = CreateMockContext();

            var result = await target.GetTodoCenterBizSystemsAsync();
            var lst = result.Value.As<List<TodoCenterBizSystem>>();
            lst.Should().NotBeNullOrEmpty();
            lst[0].Id.Should().Be("aaa");
        }

19 View Source File : WorkbenchControllerTest.cs
License : MIT License
Project Creator : appsonsf

[TestMethod]
        public async Task GetAll()
        {
            var workbenchAppService = Subsreplacedute.For<IWorkbenchAppService>();
            workbenchAppService.GetAppEntrancesAsync(Arg.Is<GetAppEntrancesInput>(o =>
                o.ClientId == Client.DefaultId && o.ClientPlatform == ClientPlatform.Android))
            .Returns(Task.FromResult(new List<AppEntranceDto>
            {
                new AppEntranceDto
                {
                    Id=Guid.NewGuid(),
                    AppId="aaa",
                },
                new AppEntranceDto
                {
                    Id=Guid.NewGuid(),
                    AppId="bbb"
                }
            }));

            var target = new WorkbenchController(
                workbenchAppService,
                Subsreplacedute.For<IClientAppService>(),
                Subsreplacedute.For<IBizSystemAppService>(),
                Subsreplacedute.For<IBadgeApiClient>(),
                Subsreplacedute.For<IMobileCodeSender>(),
                _ => Subsreplacedute.For<IUserSettingAppService>());
            target.ControllerContext = CreateMockContext();

            var result = await target.GetAll(ClientPlatform.Android);
            result.Value.Should().NotBeNull();
            result.Value.Count.Should().Be(2);
        }

See More Examples