/// <summary> /// Fetch the the NetworkSettings, and set the NetworkSettings variable, /// which is used for every subsequent request after the initial ones. /// </summary> /// <param name="initialPeer">Initial Peer <inheritdoc cref="PeerApi"/> from which the settings are fetched.</param> /// <returns>Instiate a <inheritdoc cref="PeerApi"/> based on the initial peer provided.</returns> private async Task SetNetworkSettings(PeerApi initialPeer) { // Request the NetworkSettings, Fees, and more peer address from the peers it connects to. var responseAutoConfigure = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, ArkStaticStrings.ArkApiPaths.Loader.GET_AUTO_CONFIGURE).ConfigureAwait(false); var responseFees = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, ArkStaticStrings.ArkApiPaths.Block.GET_FEES).ConfigureAwait(false); var responsePeer = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, string.Format(ArkStaticStrings.ArkApiPaths.Peer.GET, initialPeer.Ip, initialPeer.Port)).ConfigureAwait(false); // Auto-configures what has been fetched previously var autoConfig = JsonConvert.DeserializeObject <ArkLoaderNetworkResponse>(responseAutoConfigure); var fees = JsonConvert.DeserializeObject <Fees>(JObject.Parse(responseFees)["fees"].ToString()); var peer = JsonConvert.DeserializeObject <ArkPeerResponse>(responsePeer); // Fill the NetworkSettings with what has been fetched / auto-configured previously. NetworkApi.NetworkSettings = new ArkNetworkSettings() { Port = initialPeer.Port, BytePrefix = (byte)autoConfig.Network.Version, Version = peer.Peer.Version, NetHash = autoConfig.Network.NetHash, Fee = fees }; await NetworkApi.WarmUp(new PeerApi(NetworkApi, initialPeer.Ip, initialPeer.Port)).ConfigureAwait(false); }
public async Task Test_LoadAnswers_Makes_A_Request_To_The_Api() { var answers = new[] { new Answer() { Score = 5 }, new Answer() { Score = -1 } }; NetworkApi.QuestionAnswers((ids, site, order, sort, page, pagesize, filter) => Task.FromResult(new Response <Answer>() { Items = answers })); await Subject.LoadAnswers.Execute(); Assert.Collection(Subject.Answers, a => Assert.Equal("5", a.Score), a => Assert.Equal("-1", a.Score)); }
public async Task Test_Refresh_Clears_And_Loads_Questions() { Site = new SiteViewModel(new Site()); Subject.Questions.Add(new QuestionItemViewModel()); NetworkApi.Questions( (site, order, sort, page, pagesize, filter) => Task.FromResult(new Response <Question>() { Items = new[] { new Question() { Title = "Test", Owner = new ShallowUser() { ProfileImage = "https://example.com" } }, } })); await Subject.Refresh.Execute(); Assert.Collection(Subject.Questions, q => Assert.Equal("Test", q.Title)); }
public static async Task SyncBlock(Func<int, int> dispalyProgress = null) { //获取当前区块高度和远端区块高度 ApiResponse response = await NetworkApi.GetBlockChainInfo(); if (!response.HasError) { BlockChainInfo info = response.GetResult<BlockChainInfo>(); if (info.IsRunning) { if (info.RemoteLatestBlockHeight > info.LocalLastBlockHeight) { //开始同步 long localBlockHeight = info.LocalLastBlockHeight; long remoteBlockHeight = info.RemoteLatestBlockHeight; while (remoteBlockHeight > localBlockHeight) { dispalyProgress?.Invoke(Convert.ToInt32(((double)localBlockHeight / (double)remoteBlockHeight) * 100)); System.Threading.Thread.Sleep(3000); ApiResponse newResponse = await NetworkApi.GetBlockChainInfo(); if (!newResponse.HasError) { BlockChainInfo newBlockInfo = newResponse.GetResult<BlockChainInfo>(); localBlockHeight = newBlockInfo.LocalLastBlockHeight; remoteBlockHeight = newBlockInfo.RemoteLatestBlockHeight; if (remoteBlockHeight <= localBlockHeight) { dispalyProgress?.Invoke(100); } } } } } } }
async void Start() { inbound = await NetworkApi.AcceptInbound(this, 9080); inbound.Recieve.Add(OnInBoundRecieve); outbound = NetworkApi.OpenOutbound(9080, "127.0.0.1", this); outbound.Recieve.Add(OnOutboundRecieve); }
public async Task DisconnectNode() { ApiResponse response = await NetworkApi.DisconnectNode("123.123.123.123:4321"); Assert.IsFalse(response.HasError); bool result = response.GetResult <bool>(); Assert.IsNotNull(result); }
public async Task GetAddedNodeInfo() { ApiResponse response = await NetworkApi.GetAddedNodeInfo("192.168.1.177:4321"); Assert.IsFalse(response.HasError); AddNodeInfo result = response.GetResult <AddNodeInfo>(); Assert.IsNotNull(result); }
public async Task GetPeerInfo() { ApiResponse response = await NetworkApi.GetPeerInfo(); Assert.IsFalse(response.HasError); List <PeerInfo> result = response.GetResult <List <PeerInfo> >(); Assert.IsNotNull(result); }
public async Task GetConnectionCount() { ApiResponse response = await NetworkApi.GetConnectionCount(); Assert.IsFalse(response.HasError); long result = response.GetResult <long>(); Assert.IsNotNull(result); }
public async Task GetNetTotals() { ApiResponse response = await NetworkApi.GetNetTotals(); Assert.IsFalse(response.HasError); NetTotals result = response.GetResult <NetTotals>(); Assert.IsNotNull(result); }
public async Task GetBlockChainInfo() { ApiResponse response = await NetworkApi.GetBlockChainInfo(); Assert.IsFalse(response.HasError); BlockChainInfo result = response.GetResult <BlockChainInfo>(); Assert.IsNotNull(result); }
public async Task ListBanned() { ApiResponse response = await NetworkApi.ListBanned(); Assert.IsFalse(response.HasError); List <BannedInfo> result = response.GetResult <List <BannedInfo> >(); Assert.IsNotNull(result); }
private async Task LoadAssociatedAccountsImpl() { var accounts = await NetworkApi.UserAssociatedAccounts(Ids.Me); AssociatedAccounts.Clear(); AssociatedAccounts.AddRange(accounts.Items .Select(account => new NetworkUserViewModel(account)) .OrderByDescending(account => account.Reputation)); }
private async Task LoadSitesImpl() { if (!AvailableSites.Any()) { var sites = await NetworkApi.Sites(); AvailableSites.Clear(); AvailableSites.AddRange(sites.Items.Select(site => new SiteViewModel(site))); SelectedSite = AvailableSites.FirstOrDefault(); } }
/// <summary> /// Unmount a mapped drive. /// </summary> /// <param name="driveLetter"></param> public static void Unmount(string driveLetter) { driveLetter = ParseDriveLetter(driveLetter); // Unmount. var result = NetworkApi.WNetCancelConnection2(driveLetter, 0, true); if (result != 0) { throw new FilesMappedDriveException(String.Format(UnmountError, driveLetter, (SYSTEM_ERROR)result), result); } }
/// <summary> /// Find the full path to a mapped drive. /// </summary> /// <param name="drive"></param> /// <returns></returns> private static string GetDriveConnection(DriveInfo drive) { int bufferLength = 200; var driveName = new StringBuilder(bufferLength); var returnCode = NetworkApi.WNetGetConnection(drive.Name.Substring(0, 2), driveName, ref bufferLength); if (returnCode == 0) { return(driveName.ToString()); } return(null); }
public async Task Test_LoadQuestions_Does_Reload_If_The_Site_Is_Different_Than_The_Current_Questions() { Site = new SiteViewModel(new Site() { ApiSiteParameter = "stackoverflow" }); NetworkApi.Questions((site, order, sort, page, pagesize, filter) => { if (site == "stackoverflow") { return(Task.FromResult(new Response <Question>() { Items = new[] { new Question() { Title = "First" }, } })); } else { return(Task.FromResult(new Response <Question>() { Items = new[] { new Question() { Title = "Second" }, } })); } }); await Subject.LoadQuestions.Execute(); Assert.Collection(Subject.Questions, q => Assert.Equal("First", q.Title)); Site = new SiteViewModel(new Site() { ApiSiteParameter = "other" }); await Subject.LoadQuestions.Execute(); Assert.Collection(Subject.Questions, q => Assert.Equal("Second", q.Title)); }
public Task Test_LoadQuestions_Waits_For_LoadSites_To_Finish_Executing_If_No_Site_Is_Selected_But_Is_Already_Executing() { // TODO: Clean up test implementation? var loadSitesTask = new TaskCompletionSource <Unit>(); var testTask = new TaskCompletionSource <int>(); Site = null; LoadSites = ReactiveCommand.CreateFromTask(() => loadSitesTask.Task); NetworkApi.Questions( (site, order, sort, page, pagesize, filter) => Task.FromResult(new Response <Question>() { Items = new[] { new Question() { Owner = new ShallowUser() { DisplayName = "Test", ProfileImage = "http://example.com" } }, } })); // Act LoadSites.Execute().Subscribe(); var loadingObservable = Subject.LoadQuestions.Execute(); loadingObservable.Subscribe(u => { try { // Assert Assert.NotEmpty(Subject.Questions); testTask.SetResult(0); } catch (Exception ex) { testTask.SetException(ex); } }, ex => testTask.SetException(ex)); // Precondition Assert.Empty(Subject.Questions); Site = new SiteViewModel(); loadSitesTask.SetResult(Unit.Default); return(testTask.Task); }
public async Task Test_LoadQuestions_Executes_LoadSites_If_There_Is_No_Currently_Selected_Site() { Site = null; NetworkApi.Questions((site, order, sort, page, pagesize, filter) => Task.FromResult(new Response <Question>())); LoadSites = ReactiveCommand.Create(() => { Site = new SiteViewModel(); }); await Subject.LoadQuestions.Execute(); Assert.NotNull(Site); }
public static async Task<bool> IsNeedSyncBlock() { ApiResponse response = await NetworkApi.GetBlockChainInfo(); if (!response.HasError) { BlockChainInfo info = response.GetResult<BlockChainInfo>(); if (info.IsRunning) { if (info.RemoteLatestBlockHeight > info.LocalLastBlockHeight) { return true; } } } return false; }
public async Task Test_AnswersTitle_Pluralizes_The_Label_With_The_Number_Of_Answers_That_Are_Present(int numAnswers, string expected) { var answers = Enumerable.Range(0, numAnswers) .Select(i => new Answer() { Score = i }) .ToArray(); NetworkApi.QuestionAnswers((ids, site, order, sort, page, pagesize, filter) => Task.FromResult(new Response <Answer>() { Items = answers })); await Subject.LoadAnswers.Execute(); Assert.Equal(expected, Subject.AnswersTitle); }
public void StartNetworked(int port, string address, string playerSessionId, MonoBehaviour parent, DemoSettingsClient settings) { var spawnPoint = DemoSettings.GetSpawnPoint(); var playerConfig = DemoSettings.GetPlatformCharacterConfig(); var recieveByGuid = new Dictionary <string, MessageHandler>(); networkStream = NetworkApi.OpenOutbound(port, address, parent); networkStream.Recieve.Add((opCode, message) => { if (opCode == OpCode.PLAYER_ACCEPTED) { MessageHandler recieve = null; var acceptMsg = (PlayerAcceptMessage)message; var isSelf = acceptMsg.playerSessionId.Equals(playerSessionId); Debug.Log("client (" + playerSessionId + ")" + " accepts (" + acceptMsg.playerGuid + ") as self? " + isSelf); if (acceptMsg.playerSessionId.Equals(playerSessionId)) { var spawned = GameObject.Instantiate(settings.playerPrefab, spawnPoint, Quaternion.identity); var playerComp = spawned.GetComponent <PlayerCompClient>(); recieve = playerComp.RegisterNetwork(networkStream.Send, playerConfig, acceptMsg.PlayerGuid, acceptMsg.trustDistance); } else { var spawned = GameObject.Instantiate(settings.otherPlayerPrefab, spawnPoint, Quaternion.identity); var playerComp = spawned.GetComponent <OtherPlayerCompClient>(); recieve = playerComp.RegisterNetwork(playerConfig, settings.interpolation); } recieveByGuid[acceptMsg.PlayerGuid] = recieve; } else { MessageHandler reciever = null; var found = recieveByGuid.TryGetValue(PlayerGuidUtil.Get(message), out reciever); if (found) { reciever?.Invoke(opCode, message); } } return(1); }); var joinMessage = new PlayerJoinMessage(); joinMessage.playerSessionId = playerSessionId; networkStream.Send(OpCode.PLAYER_JOIN, joinMessage); }
public MainPage() { InitializeComponent(); NetworkApi api = RestService.For <NetworkApi>(AppConstants.BASE_URL); RegisterModel model = new RegisterModel(); model.email = "*****@*****.**"; model.password = "******"; model.confirm_password = "******"; model.first_name = "Dummy Name"; model.last_name = "Last Name"; model.gender = "M"; model.phone_no = 123; try { //CustBusinessLogin custBusinessLogin = new CustBusinessLogin(); CustService service = new CustService(); var DoIVal = service.GetCustomerName(); //var DoIVal = custBusinessLogin.GetCustName(); /*var regResponse = api.Register(model); * regResponse.ContinueWith(post => { * if (post.IsCompleted) * { * var demo = post.Result; * } * else if (post.IsFaulted) * { * Debug.WriteLine("Error occured ->" + post.Status); * } * else * { * Debug.WriteLine("Cancelled"); * } * }, TaskScheduler.FromCurrentSynchronizationContext()).ConfigureAwait(false);*/ } catch (Exception ex) { Debug.WriteLine("Error--->>" + ex.StackTrace); } }
public async Task Test_LoadQuestions_Loads_From_Currently_Selected_Site() { var called = false; Site = new SiteViewModel(new Site() { ApiSiteParameter = "stackoverflow" }); NetworkApi.Questions((site, order, sort, page, pagesize, filter) => { Assert.Equal("stackoverflow", site); called = true; return(Task.FromResult(new Response <Question>())); }); await Subject.LoadQuestions.Execute(); Assert.True(called); }
/// <summary> /// Create a mapped drive pointing to Azure files. /// </summary> /// <param name="driveLetter"></param> /// <param name="filesPath"></param> /// <param name="accountName"></param> /// <param name="accountKey"></param> /// <param name="force"></param> public static void Mount(string driveLetter, string filesPath, string accountName, string accountKey, bool force = true) { if (String.IsNullOrEmpty(filesPath)) { throw new ArgumentException("The filesPath is required.", "filesPath"); } if (String.IsNullOrEmpty(accountName)) { throw new ArgumentException("The accountName is required.", "accountName"); } if (String.IsNullOrEmpty(accountKey)) { throw new ArgumentException("The accountKey is required.", "accountKey"); } driveLetter = ParseDriveLetter(driveLetter); // Define the new resource. var resource = new NETRESOURCE { dwScope = (ResourceScope)2, dwType = (ResourceType)1, dwDisplayType = (ResourceDisplayType)3, dwUsage = (ResourceUsage)1, lpRemoteName = filesPath, lpLocalName = driveLetter }; // Close connection if it exists. if (force) { NetworkApi.WNetCancelConnection2(driveLetter, 0, true); } // Create the connection. var result = NetworkApi.WNetAddConnection2(resource, accountKey, accountName, 0); if (result != 0) { throw new FilesMappedDriveException(String.Format(MountError, driveLetter, filesPath, (SYSTEM_ERROR)result), result); } }
public Result SetNetworkActive(bool isActive) { ApiResponse response = NetworkApi.SetNetworkActive(isActive).Result; var result = GetResult(response); if (result.IsFail) { return(result); } if (isActive) { UpdateBlocksMonitor.Default.Reset(); UpdateBlocksMonitor.Default.Start(3000); } else { UpdateBlocksMonitor.Default.Stop(); } NodeMonitor.Default.Set_NetIsActive = isActive; return(result); }
/// <summary> /// Fetch the the NetworkSettings, and set the NetworkSettings variable, /// which is used for every subsequent request after the initial ones. /// </summary> /// <param name="initialPeer">Initial Peer <inheritdoc cref="PeerApi"/> from which the settings are fetched.</param> /// <returns>Instiate a <inheritdoc cref="PeerApi"/> based on the initial peer provided.</returns> private async Task SetNetworkSettings(PeerApi initialPeer) { try { // Request the NetworkSettings, Fees, and more peer address from the peers it connects to. var responseAutoConfigure = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, ArkStaticStrings.ArkApiPaths.Loader.GET_AUTO_CONFIGURE).ConfigureAwait(false); var responseFees = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, ArkStaticStrings.ArkApiPaths.Block.GET_FEES).ConfigureAwait(false); var responsePeer = await initialPeer.MakeRequest(ArkStaticStrings.ArkHttpMethods.GET, string.Format(ArkStaticStrings.ArkApiPaths.Peer.GET, initialPeer.Ip, initialPeer.Port)).ConfigureAwait(false); // Auto-configures what has been fetched previously var autoConfig = JsonConvert.DeserializeObject <ArkLoaderNetworkResponse>(responseAutoConfigure); var fees = JsonConvert.DeserializeObject <Fees>(JObject.Parse(responseFees)["fees"].ToString()); var peer = JsonConvert.DeserializeObject <ArkPeerResponse>(responsePeer); // Fill the NetworkSettings with what has been fetched / auto-configured previously. NetworkApi.NetworkSettings = new ArkNetworkSettings() { Port = initialPeer.Port, BytePrefix = (byte)autoConfig.Network.Version, Version = peer.Peer.Version, NetHash = autoConfig.Network.NetHash, Fee = fees, Token = autoConfig.Network.Token, Symbol = autoConfig.Network.Symbol, Explorer = autoConfig.Network.Explorer }; LoggingApi.Info(string.Format("Set network settings to <<{0}>>", JsonConvert.SerializeObject(NetworkApi.NetworkSettings))); await NetworkApi.WarmUp(new PeerApi(this, initialPeer.Ip, initialPeer.Port)).ConfigureAwait(false); } catch (Exception e) { LoggingApi.Error(e.ToString()); throw e; } }
private async Task LoadQuestionsImpl() { if (Search.SelectedSite == null) { if (!await Search.LoadSites.IsExecuting.FirstAsync()) { await Search.LoadSites.Execute(); } else { await Search.LoadSites.FirstAsync(); } } if (!Questions.Any() || Search.SelectedSite.ApiSiteParameter != LoadedSite) { LoadedSite = Search.SelectedSite.ApiSiteParameter; var response = await NetworkApi.Questions(LoadedSite); var questions = response.Items.Select(q => new QuestionItemViewModel(q)).ToArray(); Questions = new ReactiveList <QuestionItemViewModel>(questions); } }
public void Test_Refreshes_Questions_When_Site_Is_Changed_After_Activation() { NetworkApi.Questions((site, order, sort, page, pagesize, filter) => { Assert.Equal("othersite", site); return(Task.FromResult(new Response <Question>())); }); var api = new StubINetworkApi(); var search = new SearchViewModel(networkApi: api); Subject = new QuestionsViewModel(search: search, networkApi: NetworkApi); Subject.Questions.Add(new QuestionItemViewModel()); using (Subject.Activator.Activate()) { search.SelectedSite = new SiteViewModel(new Site() { ApiSiteParameter = "othersite" }); Assert.Empty(Subject.Questions); } }
public async Task Test_LoadQuestions_Makes_A_Request_To_The_Api() { var questions = new[] { new Question() { Score = 5 }, new Question() { Score = -1 } }; NetworkApi.Question((ids, site, filter) => Task.FromResult(new Response <Question>() { Items = questions })); await Subject.LoadQuestions.Execute(); Assert.Equal("5", Subject.Question.Score); }