void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format("Failed to Sign Pending Transaction, status: {0}", result.Receipt.Status), result); } }
void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format("Unable to create Consensus Topic, status: {0}", result.Receipt.Status), result); } }
void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format("Unable to Dissociate Token from Account, status: {0}", result.Receipt.Status), result); } }
static NetworkResult TestImages(NeuralNetwork network, IEnumerable <GrayscaleImage> images) { var count = images.Count(); var correct = 0; var costSum = 0d; foreach (var grayscaleImage in images) { var testResult = TestImage(network, grayscaleImage); costSum += testResult.Cost; if (testResult.IsCorrect) { correct++; } } costSum /= images.Count(); var result = new NetworkResult(count, correct, costSum); Console.WriteLine($" Tests: {result.Count}"); Console.WriteLine($" Correct: {result.Correct}"); Console.WriteLine($" Correct %: {result.CorrectPercent:0.###}%"); Console.WriteLine($" Cost: {costSum:0.########}"); Console.WriteLine($"#############################"); return(result); }
void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format("Submit Unsafe Transaction failed, status: {0}", result.Receipt.Status), result); } }
/// <summary> /// Load the Settings from the backend. /// </summary> /// <returns>Returns a JSON formated string.</returns> public async Task <string> LoadSettings() { try { Logger.Trace("LoadSettings"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(string.Format(Configuration.SettingsUri, Configuration.ApiKey)); HttpClient httpClient = new HttpClient(baseProtocolFilter); var responseMessage = await httpClient.SendRequestAsync(requestMessage); Logger.Trace("LoadSettings HTTPCode: {0}", responseMessage.StatusCode); LastCallResult = responseMessage.IsSuccessStatusCode ? NetworkResult.Success : NetworkResult.UnknownError; return(responseMessage?.Content.ToString()); } catch (Exception ex) { Logger.Error("LoadSettings Error", ex); LastCallResult = NetworkResult.NetworkError; return(null); } }
public Task <ResponseMessage> SendHistory(History history) { if (APIInvalid) { LastCallResult = NetworkResult.AuthenticationFailed; return(Task.FromResult(new ResponseMessage() { IsSuccess = false })); } if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; throw new IOException(); } if (UnknownError) { LastCallResult = NetworkResult.UnknownError; throw new Exception("ups"); } if (history != null) { HistoryEvents.AddRange(history.Events); HistoryActions.AddRange(history.Actions); } LastCallResult = NetworkResult.Success; return(Task.FromResult(new ResponseMessage() { IsSuccess = true })); }
void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format("Failed to submit suspend/freeze command, status: {0}", result.Receipt.Status), result); } }
/// <summary> /// Sends a layout request to server and returns the HTTP response, if any. /// </summary> /// <param name="apiId">optional api id, overrides the given id by SDKData.</param> /// <returns>A HttpResponseMessage containing the server response or null in case of an error.</returns> public async Task <ResponseMessage> RetrieveLayoutResponse(string apiId) { Logger.Trace("RetrieveLayoutResponse"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(Configuration.LayoutUri); HttpClient apiConnection = new HttpClient(baseProtocolFilter); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, string.IsNullOrEmpty(apiId) ? Configuration.ApiKey : apiId); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); string geoHash = await ServiceManager.LocationService.GetGeoHashedLocation(); if (!string.IsNullOrEmpty(geoHash)) { apiConnection.DefaultRequestHeaders.Add(Constants.Xgeo, geoHash); } apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(SdkData.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : SdkData.UserId); HttpResponseMessage responseMessage; try { responseMessage = await apiConnection.SendRequestAsync(requestMessage); } catch (Exception ex) { LastCallResult = NetworkResult.NetworkError; System.Diagnostics.Debug.WriteLine("LayoutManager.RetrieveLayoutResponseAsync(): Failed to send HTTP request: " + ex.Message); return(new ResponseMessage() { IsSuccess = false }); } Logger.Trace("RetrieveLayoutResponse HTTPCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return(new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }); } LastCallResult = NetworkResult.UnknownError; return(new ResponseMessage() { StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }); }
private async Task <NetworkResult> ExecuteTransactionAsync(INetworkTransaction transaction, Action <IContext>?configure, bool includeRecord, params Signatory?[] extraSignatories) { var result = new NetworkResult(); await using var context = CreateChildContext(configure); var gateway = context.Gateway; if (gateway is null) { throw new InvalidOperationException("The Network Gateway Node has not been configured. Please check that 'Gateway' is set in the Client context."); } var signatory = context.GatherSignatories(extraSignatories); var schedule = signatory.GetSchedule(); if (schedule is not null) { var scheduledTransactionBody = transaction.CreateSchedulableTransactionBody(); scheduledTransactionBody.TransactionFee = (ulong)context.FeeLimit; transaction = new ScheduleCreateTransactionBody { ScheduledTransactionBody = scheduledTransactionBody, AdminKey = schedule.Administrator is null ? null : new Key(schedule.Administrator), PayerAccountID = schedule.PendingPayer is null ? null : new AccountID(schedule.PendingPayer), Memo = schedule.Memo ?? "" }; } var transactionBody = transaction.CreateTransactionBody(); transactionBody.TransactionFee = (ulong)context.FeeLimit; transactionBody.NodeAccountID = new AccountID(gateway); transactionBody.TransactionID = result.TransactionID = context.GetOrCreateTransactionID(); transactionBody.TransactionValidDuration = new Duration(context.TransactionDuration); transactionBody.Memo = context.Memo ?? ""; var invoice = new Invoice(transactionBody); await signatory.SignAsync(invoice).ConfigureAwait(false); var signedTransaction = new Transaction { SignedTransactionBytes = invoice.GenerateSignedTransactionFromSignatures(context.SignaturePrefixTrimLimit).ToByteString() }; var precheck = await context.ExecuteSignedRequestWithRetryImplementationAsync(signedTransaction, transaction.InstantiateNetworkRequestMethod, getResponseCode).ConfigureAwait(false); if (precheck.NodeTransactionPrecheckCode != ResponseCodeEnum.Ok) { var responseCode = (ResponseCode)precheck.NodeTransactionPrecheckCode; throw new PrecheckException($"Transaction Failed Pre-Check: {responseCode}", result.TransactionID.AsTxId(), responseCode, precheck.Cost); } var receipt = result.Receipt = await context.GetReceiptAsync(result.TransactionID).ConfigureAwait(false); if (receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format(transaction.TransactionExceptionMessage, receipt.Status), result.TransactionID.AsTxId(), (ResponseCode)receipt.Status); } if (includeRecord) { result.Record = await GetTransactionRecordAsync(context, result.TransactionID).ConfigureAwait(false); } return(result);
/// <summary> /// Run forward part on given single device /// </summary> /// <param name="g">The computing graph for current device. It gets created and passed by the framework</param> /// <param name="srcSnts">A batch of input tokenized sentences in source side</param> /// <param name="tgtSnts">A batch of output tokenized sentences in target side. In training mode, it inputs target tokens, otherwise, it outputs target tokens generated by decoder</param> /// <param name="deviceIdIdx">The index of current device</param> /// <returns>The cost of forward part</returns> public override List <NetworkResult> RunForwardOnSingleDevice(IComputeGraph g, ISntPairBatch sntPairBatch, int deviceIdIdx, bool isTraining, DecodingOptions decodingOptions) { List <NetworkResult> nrs = new List <NetworkResult>(); var srcSnts = sntPairBatch.GetSrcTokens(0); var tgtSnts = sntPairBatch.GetTgtTokens(0); (IEncoder encoder, IWeightTensor srcEmbedding, IWeightTensor posEmbedding, FeedForwardLayer decoderFFLayer) = GetNetworksOnDeviceAt(deviceIdIdx); // Reset networks encoder.Reset(g.GetWeightFactory(), srcSnts.Count); var originalSrcLengths = BuildInTokens.PadSentences(srcSnts); var srcTokensList = m_modelMetaData.SrcVocab.GetWordIndex(srcSnts); BuildInTokens.PadSentences(tgtSnts); var tgtTokensLists = m_modelMetaData.ClsVocab.GetWordIndex(tgtSnts); int seqLen = srcSnts[0].Count; int batchSize = srcSnts.Count; // Encoding input source sentences IWeightTensor encOutput = Encoder.Run(g, sntPairBatch, encoder, m_modelMetaData, m_shuffleType, srcEmbedding, posEmbedding, null, srcTokensList, originalSrcLengths); IWeightTensor ffLayer = decoderFFLayer.Process(encOutput, batchSize, g); float cost = 0.0f; IWeightTensor probs = g.Softmax(ffLayer, inPlace: true); if (isTraining) { var tgtTokensTensor = g.CreateTokensTensor(tgtTokensLists); cost = g.CrossEntropyLoss(probs, tgtTokensTensor); } else { // Output "i"th target word using var targetIdxTensor = g.Argmax(probs, 1); float[] targetIdx = targetIdxTensor.ToWeightArray(); List <string> targetWords = m_modelMetaData.ClsVocab.ConvertIdsToString(targetIdx.ToList()); for (int k = 0; k < batchSize; k++) { tgtSnts[k] = targetWords.GetRange(k * seqLen, seqLen); } } NetworkResult nr = new NetworkResult { Cost = cost, Output = new List <List <List <string> > >() }; nr.Output.Add(tgtSnts); nrs.Add(nr); return(nrs); }
/// <summary> /// Internal implementation of the submit message call. /// </summary> private async Task <NetworkResult> SubmitUnsafeTransactionImplementationAsync(ReadOnlyMemory <byte> transaction, Action <IContext>?configure, bool includeRecord) { var result = new NetworkResult(); var innerTransactionId = result.TransactionID = idFromTransactionBytes(transaction); await using var context = CreateChildContext(configure); var gateway = context.Gateway; if (gateway is null) { throw new InvalidOperationException("The Network Gateway Node has not been configured. Please check that 'Gateway' is set in the Client context."); } var signatories = context.GatherSignatories(); var outerTransactionId = context.GetOrCreateTransactionID(); var uncheckedSubmitBody = new UncheckedSubmitBody(transaction); // Note: custom transaction body, does not carry a max fee since // the inner transaction is the transaction to process, it still // must be signed however. var transactionBody = new TransactionBody { TransactionID = outerTransactionId, NodeAccountID = new AccountID(gateway), TransactionValidDuration = new Proto.Duration(context.TransactionDuration), UncheckedSubmit = uncheckedSubmitBody }; var invoice = new Invoice(transactionBody, context.SignaturePrefixTrimLimit); await signatories.SignAsync(invoice).ConfigureAwait(false); var signedTransaction = new Transaction { SignedTransactionBytes = invoice.GenerateSignedTransactionFromSignatures().ToByteString() }; var precheck = await context.ExecuteSignedRequestWithRetryImplementationAsync(signedTransaction, (uncheckedSubmitBody as INetworkTransaction).InstantiateNetworkRequestMethod, getResponseCode).ConfigureAwait(false); if (precheck.NodeTransactionPrecheckCode != ResponseCodeEnum.Ok) { var responseCode = (ResponseCode)precheck.NodeTransactionPrecheckCode; throw new PrecheckException($"Transaction Failed Pre-Check: {responseCode}", transactionBody.TransactionID.AsTxId(), responseCode, precheck.Cost); } // NOTE: The outer transaction ID exists so that the administrative account has something to sign that // can be verified, however, the transaction never actually exists in the system so there will never be // a receipt for this submission, however, there will be an attempt to execute the submitted transaction // as this method bypasses PRECHECK validations. So, there will be a receipt for the inner transaction, // with success or a failure code. Therefore we return the receipt or record for the custom transaction. var receipt = result.Receipt = await context.GetReceiptAsync(innerTransactionId).ConfigureAwait(false); // Retain standard behavior of throwing an exception if the receipt has an error code. if (receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException($"Submit Unsafe Transaction failed, status: {receipt.Status}", new NetworkResult { TransactionID = innerTransactionId, Receipt = receipt }); } if (includeRecord) { result.Record = (await ExecuteQueryInContextAsync(new TransactionGetRecordQuery(innerTransactionId, false, false), context, 0).ConfigureAwait(false)).TransactionGetRecord.TransactionRecord; } return(result !);
private async void OnFetchApiKeyButtonClickedAsync(object sender, RoutedEventArgs e) { Model.IsValidatingOrFetchingApiKey = true; if (!string.IsNullOrEmpty(Model.Email) && !string.IsNullOrEmpty(Model.Password)) { ApiKeyHelper apiKeyHelper = new ApiKeyHelper(); NetworkResult result = await apiKeyHelper.FetchApiKeyAsync(Model.Email, Model.Password); if (result == NetworkResult.Success) { Model.ShowApiKeyErrorMessage = false; Model.Applications = apiKeyHelper.Applications; if (apiKeyHelper.Applications?.Count > 1) { Model.ShowApiKeySelection = apiKeyHelper.Applications.Count > 1; } else { // Model.ApiKey = apiKeyHelper.ApiKey; // Model.IsApiKeyValid = true; if (apiKeyHelper.Applications?.Count > 0) { Model.Application = apiKeyHelper.Applications[0]; } } } else { Model.IsApiKeyValid = false; string message = loader.GetString("unknownFetchApiKeyError"); switch (result) { case NetworkResult.NetworkError: message = loader.GetString("failedToFetchApiKeyDueToNetworkError"); break; case NetworkResult.AuthenticationFailed: message = loader.GetString("authenticationFailedForFetchingApiKey"); break; case NetworkResult.ParsingError: message = loader.GetString("failedToParseServerResponse"); break; case NetworkResult.NoWindowsCampains: message = loader.GetString("noWindowsCampaignsAvailable"); break; } Model.ApiKeyErrorMessage = message; Model.ShowApiKeyErrorMessage = true; } } Model.IsValidatingOrFetchingApiKey = false; }
public static Task DisplayNetworkError( this IDialogService dialogService, NetworkResult result) { var message = new StringBuilder(); message.Append("Status = ").Append(result.Status).AppendLine(); message.Append("Code = ").Append(result.StatusCode); return(dialogService.DisplayAlert("Network error", message.ToString(), "OK")); }
void INetworkTransaction.CheckReceipt(NetworkResult result) { if (result.Receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException(string.Format( FileID is not null ? "Unable to restore file, status: {0}" : "Unable to restore contract, status: {0}", result.Receipt.Status), result); } }
private async Task Send() { var result = await loadingService.WithExecuteAsync("Data send", async() => { NetworkResult ret = null; foreach (var entity in allEntities) { if (entity.IsChecked) { var pair = await inspectionService.QueryInspectionAsync(entity.StorageNo); var request = new StorageDetailsRequest { Renew = false, StorageNo = entity.StorageNo, UserId = session.UserId, Entries = pair.Entities.Select(x => new StorageDetailsRequestEntry { ItemCode = x.ItemCode, ItemName = x.ItemName, SalesPrice = x.SalesPrice, Qty = x.Qty }).ToArray() }; ret = await networkClient.Post( EndPoint.StorageDetails(settingService.GetEndPoint()), request, Definition.Timeout); if (!ret.Success) { return(ret); } } await inspectionService.DeleteInspectionLisAsynct(entity.StorageNo); } return(ret); }); if (result.Success) { await dialogService.DisplayInformation("Data send", "Send completed."); await Back(); } else { await dialogService.DisplayNetworkError(result); } }
public static NetworkResult guessHTTPService() { NetworkResult result = new NetworkResult("Unknown", 100.0f); NeuralNetwork.Network net = new NeuralNetwork.Network(); net.addInput("Windows"); net.addInput("Linux"); net.addInput("FreeBSD"); net.addInput("PHP"); net.addInput("ASP.NET"); net.addInput("Static"); net.addInput("Ruby/Node.js"); return(result); }
/// <summary> /// Sends a layout request to server and returns the HTTP response, if any. /// </summary> /// <param name="apiId">optional api id, overrides the given id by SDKData.</param> /// <returns>A HttpResponseMessage containing the server response or null in case of an error.</returns> public async Task<ResponseMessage> RetrieveLayoutResponse(string apiId) { Logger.Trace("RetrieveLayoutResponse"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(Configuration.LayoutUri); HttpClient apiConnection = new HttpClient(baseProtocolFilter); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, string.IsNullOrEmpty(apiId) ? Configuration.ApiKey : apiId); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); string geoHash = await ServiceManager.LocationService.GetGeoHashedLocation(); if (!string.IsNullOrEmpty(geoHash)) { apiConnection.DefaultRequestHeaders.Add(Constants.Xgeo, geoHash); } apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(SdkData.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : SdkData.UserId); HttpResponseMessage responseMessage; try { responseMessage = await apiConnection.SendRequestAsync(requestMessage); } catch (Exception ex) { LastCallResult = NetworkResult.NetworkError; System.Diagnostics.Debug.WriteLine("LayoutManager.RetrieveLayoutResponseAsync(): Failed to send HTTP request: " + ex.Message); return new ResponseMessage() {IsSuccess = false}; } Logger.Trace("RetrieveLayoutResponse HTTPCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }; } LastCallResult = NetworkResult.UnknownError; return new ResponseMessage() {StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode}; }
/// <summary> /// Check for reachability of resolver. /// </summary> public async Task <bool> CheckResolversReachable() { if (ServiceManager.ApiConnction == null) { return(false); } NetworkResult result = ServiceManager.ApiConnction.LastCallResult; if (result == NetworkResult.UnknownError) { await ServiceManager.ApiConnction.LoadSettings(); result = ServiceManager.ApiConnction.LastCallResult; } return(IsResolverReachable = result != NetworkResult.NetworkError && result != NetworkResult.UnknownError); }
/// <summary> /// Retrieves the receipt from the network matching the transaction /// id. Will wait for the disposition of the receipt to be known. /// </summary> /// <param name="transaction"> /// Transaction identifier of the receipt. /// </param> /// <param name="pending"> /// Flag indicating to return the pending or "scheduled" version of /// the transaction. If set to true, the network will look for /// the receipt of an executed pending transaction. The TxID is /// the ID of the tranaction that "created" the pending (scheduled) /// transaction. /// </param> /// <param name="configure"> /// Optional callback method providing an opportunity to modify /// the execution configuration for just this method call. /// It is executed prior to submitting the request to the network. /// </param> /// <returns> /// The receipt matching the transaction id, if found and marked /// sucessfull, otherwise a <see cref="TransactionException"/> is /// not found or returns an error status. /// </returns> /// <exception cref="TransactionException">If the network has no record of the transaction or request has invalid or had missing data.</exception> public async Task <TransactionReceipt> GetReceiptAsync(TxId transaction, Action <IContext>?configure = null) { await using var context = CreateChildContext(configure); var transactionId = new TransactionID(transaction); var receipt = await context.GetReceiptAsync(transactionId).ConfigureAwait(false); var result = new NetworkResult { TransactionID = transactionId, Receipt = receipt }; if (receipt.Status != ResponseCodeEnum.Success) { throw new TransactionException($"Unable to retreive receipt, status: {receipt.Status}", result); } return(result.ToReceipt()); }
/// <summary> /// Sends the given History object to the cloud. /// </summary> /// <param name="history">History object to send.</param> public async Task <ResponseMessage> SendHistory(History history) { try { Logger.Trace("SendHistory"); System.Net.Http.HttpClient apiConnection = new System.Net.Http.HttpClient(); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, Configuration.ApiKey); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(Configuration.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : Configuration.UserId); apiConnection.DefaultRequestHeaders.TryAddWithoutValidation(Constants.XUserAgent, UserAgentBuilder.BuildUserAgentJson()); string serializeObject = JsonConvert.SerializeObject(history); var content = new StringContent(serializeObject, Encoding.UTF8, "application/json"); System.Net.Http.HttpResponseMessage responseMessage = await apiConnection.PostAsync(new Uri(Configuration.LayoutUri), content); Logger.Trace("SendHistory HttpCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return(new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = Convert(responseMessage.StatusCode), IsSuccess = responseMessage.IsSuccessStatusCode }); } LastCallResult = NetworkResult.UnknownError; return(new ResponseMessage() { StatusCode = Convert(responseMessage.StatusCode), IsSuccess = responseMessage.IsSuccessStatusCode }); } catch (Exception ex) { Logger.Error("SendHistory Error", ex); LastCallResult = NetworkResult.NetworkError; return(new ResponseMessage() { IsSuccess = false }); } }
public async Task<ResponseMessage> RetrieveLayoutResponse(string apiId = null) { if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; } LastCallResult = NetworkResult.Success; if (!string.IsNullOrEmpty(ValidApiKey) && ValidApiKey != apiId && Configuration?.ApiKey != ValidApiKey) { return new ResponseMessage() {IsSuccess = true, Content = "", NetworResult = NetworkResult.Success, StatusCode = HttpStatusCode.Ok}; } return new ResponseMessage() { StatusCode = HttpStatusCode.Ok, Content = await Load(LayoutFile), Header = await Load("mock/layout_request_header.txt"), IsSuccess = true }; }
public async Task <string> LoadSettings() { if (APIInvalid) { LastCallResult = NetworkResult.AuthenticationFailed; return(string.Empty); } if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; throw new IOException(); } if (UnknownError) { LastCallResult = NetworkResult.UnknownError; throw new Exception("ups"); } LastCallResult = NetworkResult.Success; return(MockSettings); }
public async Task<string> LoadSettings() { if (APIInvalid) { LastCallResult = NetworkResult.AuthenticationFailed; return string.Empty; } if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; throw new IOException(); } if (UnknownError) { LastCallResult = NetworkResult.UnknownError; throw new Exception("ups"); } LastCallResult = NetworkResult.Success; return MockSettings; }
private static string NetworkLog(NetworkResult nr, ref string result) { switch (nr) { case NetworkResult.ClientSuccessfullyExited: Database.NetworkResult = result; Database.NetworkDone = true; return("Done!!!"); case NetworkResult.ClientCannotReceiveLastPackage: return("Client did not receive last package!"); case NetworkResult.ClientCannotReceiveNumberOfBytesOfLastPackage: return("Client did not receive the number of bytes of the last package!"); case NetworkResult.ClientCannotReceiveNumberOfPackages: return("Client did not receive the number of packages!"); case NetworkResult.ClientCannotReceivePackage: return("Client did not receive a package!"); case NetworkResult.ClientCannotReceiveResponse: return("Client did not receive a response from server!"); case NetworkResult.ClientCannotSendLastPackage: return("Client did not send the last package!"); case NetworkResult.ClientCannotSendNumberOfBytesOfLastPackage: return("Client did not send the number of bytes of the last package!"); case NetworkResult.ClientCannotSendNumberOfPackages: return("Client did not send the number of packages!"); case NetworkResult.ClientCannotSendPackage: return("Client did not send a package!"); case NetworkResult.ClientCannotSendResponse: return("Client did not send a response to the server!"); } return(""); }
public async Task <ResponseMessage> RetrieveLayoutResponse(string apiId = null) { if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; } LastCallResult = NetworkResult.Success; if (!string.IsNullOrEmpty(ValidApiKey) && ValidApiKey != apiId && Configuration?.ApiKey != ValidApiKey) { return(new ResponseMessage() { IsSuccess = true, Content = "", NetworResult = NetworkResult.Success, StatusCode = HttpStatusCode.Ok }); } return(new ResponseMessage() { StatusCode = HttpStatusCode.Ok, Content = await Load(LayoutFile), Header = await Load("mock/layout_request_header.txt"), IsSuccess = true }); }
/// <summary> /// Enum the share on the local machine /// </summary> private unsafe static NetworkShare[] EnumNetShares() { const uint MAX_PREFERRED_LENGTH = 0xFFFFFFFF; List <NetworkShare> networkShares = new List <NetworkShare>(); int entriesRead = 0, totalEntries = 0, resumeHandle = 0; int structSize = Marshal.SizeOf(typeof(NetworkShare)); StringBuilder server = new StringBuilder(Environment.MachineName); IntPtr bufPtr = IntPtr.Zero; NetworkResult result = (NetworkResult)NetShareEnum( server, 2, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesRead, ref totalEntries, ref resumeHandle ); if (result != NetworkResult.Success) { throw new Exception("Unable to enumerate share folders on local computer"); } for (int i = 0; i < entriesRead; i++) { networkShares.Add((NetworkShare)Marshal.PtrToStructure((IntPtr)((uint)bufPtr + structSize * i), typeof(NetworkShare))); } NetApiBufferFree(bufPtr); return(networkShares.ToArray()); }
/// <summary> /// Sends the given History object to the cloud. /// </summary> /// <param name="history">History object to send.</param> public async Task<ResponseMessage> SendHistory(History history) { try { Logger.Trace("SendHistory"); System.Net.Http.HttpClient apiConnection = new System.Net.Http.HttpClient(); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, Configuration.ApiKey); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(Configuration.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : Configuration.UserId); apiConnection.DefaultRequestHeaders.TryAddWithoutValidation(Constants.XUserAgent, UserAgentBuilder.BuildUserAgentJson()); string serializeObject = JsonConvert.SerializeObject(history); var content = new StringContent(serializeObject, Encoding.UTF8, "application/json"); System.Net.Http.HttpResponseMessage responseMessage = await apiConnection.PostAsync(new Uri(Configuration.LayoutUri), content); Logger.Trace("SendHistory HttpCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = Convert(responseMessage.StatusCode), IsSuccess = responseMessage.IsSuccessStatusCode }; } LastCallResult = NetworkResult.UnknownError; return new ResponseMessage() {StatusCode = Convert(responseMessage.StatusCode), IsSuccess = responseMessage.IsSuccessStatusCode}; } catch (Exception ex) { Logger.Error("SendHistory Error", ex); LastCallResult = NetworkResult.NetworkError; return new ResponseMessage() {IsSuccess = false}; } }
private static void _Client(ref Socket client, ref string text, out string result, out NetworkResult nr) { result = ""; nr = NetworkResult.ClientCannotSendNumberOfPackages; try { int NumberOfPackages = text.Length / 1024; if (client.Send(Utilities.IntToBytes(NumberOfPackages)) == 4) { byte[] Auxiliar = new byte[1]; nr = NetworkResult.ClientCannotReceiveResponse; if (client.Receive(Auxiliar) == 1) { int NumberOfBytesOfLastPackage = text.Length - (NumberOfPackages * 1024); nr = NetworkResult.ClientCannotSendNumberOfBytesOfLastPackage; if (client.Send(Utilities.IntToBytes(NumberOfBytesOfLastPackage)) == 4) { nr = NetworkResult.ClientCannotReceiveResponse; if (client.Receive(Auxiliar) == 1) { int PackageOffset = 0; byte[] Package = new byte[1024]; nr = NetworkResult.ClientCannotSendPackage; for (int PackageID = 0; PackageID < NumberOfPackages; PackageID++) { if (client.Send(Encoding.ASCII.GetBytes(text.Substring(PackageOffset, 1024))) == 1024) { nr = NetworkResult.ClientCannotReceiveResponse; if (client.Receive(Auxiliar) == 1) { nr = NetworkResult.ClientCannotSendPackage; PackageOffset += 1024; } else { return; } } else { return; } } nr = NetworkResult.ClientCannotSendLastPackage; if (client.Send(Encoding.ASCII.GetBytes(text.Substring(PackageOffset))) == NumberOfBytesOfLastPackage) { nr = NetworkResult.ClientCannotReceiveResponse; if (client.Receive(Auxiliar) == 1) { nr = NetworkResult.ClientCannotSendResponse; if (client.Send(Auxiliar) == 1) { nr = NetworkResult.ClientCannotReceiveNumberOfPackages; byte[] NumberOfPackets = new byte[4]; if (client.Receive(NumberOfPackets) == 4) { nr = NetworkResult.ClientCannotSendResponse; if (client.Send(Auxiliar) == 1) { nr = NetworkResult.ClientCannotReceiveNumberOfBytesOfLastPackage; NumberOfPackages = Utilities.BytesToInt(NumberOfPackets); if (client.Receive(NumberOfPackets) == 4) { nr = NetworkResult.ClientCannotSendResponse; if (client.Send(Auxiliar) == 1) { nr = NetworkResult.ClientCannotReceivePackage; Database.NetworkExpectedSize = NumberOfPackages + 1; for (int PackageID = 0; PackageID < NumberOfPackages; PackageID++) { if (client.Receive(Package) == 1024) { nr = NetworkResult.ClientCannotSendResponse; if (client.Send(Auxiliar) == 1) { nr = NetworkResult.ClientCannotReceivePackage; result += Encoding.ASCII.GetString(Package); Database.NetworkSize++; } else { return; } } else { return; } } nr = NetworkResult.ClientCannotReceiveLastPackage; int BytesOfLastPackage = Utilities.BytesToInt(NumberOfPackets); byte[] LastPackage = new byte[BytesOfLastPackage]; if (client.Receive(LastPackage) == BytesOfLastPackage) { result += Encoding.ASCII.GetString(LastPackage); nr = NetworkResult.ClientSuccessfullyExited; Database.NetworkSize++; } } } } } } } } } } } } } catch (SocketException) { } client.Shutdown(SocketShutdown.Both); client.Close(); }
/// <summary> /// Load the Settings from the backend. /// </summary> /// <returns>Returns a JSON formated string.</returns> public async Task<string> LoadSettings() { try { Logger.Trace("LoadSettings"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(string.Format(Configuration.SettingsUri, Configuration.ApiKey)); HttpClient httpClient = new HttpClient(baseProtocolFilter); var responseMessage = await httpClient.SendRequestAsync(requestMessage); Logger.Trace("LoadSettings HTTPCode: {0}", responseMessage.StatusCode); LastCallResult = responseMessage.IsSuccessStatusCode ? NetworkResult.Success : NetworkResult.UnknownError; return responseMessage?.Content.ToString(); } catch (Exception ex) { Logger.Error("LoadSettings Error", ex); LastCallResult = NetworkResult.NetworkError; return null; } }
/// <summary> /// Internal constructor for cases where a NetworkResult exists. /// </summary> internal TransactionException(string message, NetworkResult result) : base(message) { Receipt = result.ToReceipt(); }
/// <summary> /// Run forward part on given single device /// </summary> /// <param name="computeGraph">The computing graph for current device. It gets created and passed by the framework</param> /// <param name="srcSnts">A batch of input tokenized sentences in source side</param> /// <param name="tgtSnts">A batch of output tokenized sentences in target side</param> /// <param name="deviceIdIdx">The index of current device</param> /// <returns>The cost of forward part</returns> public override List <NetworkResult> RunForwardOnSingleDevice(IComputeGraph computeGraph, ISntPairBatch sntPairBatch, int deviceIdIdx, bool isTraining, DecodingOptions decodingOptions) { int batchSize = sntPairBatch.BatchSize; float cost = 0.0f; var nrs = new List <NetworkResult>(); var nr = new NetworkResult { Output = new List <List <List <string> > >() }; (IEncoder encoder, IWeightTensor srcEmbedding, IFeedForwardLayer encoderFFLayer, IWeightTensor posEmbedding, IWeightTensor segmentEmbedding) = GetNetworksOnDeviceAt(deviceIdIdx); IWeightTensor encOutput1; IWeightTensor encOutput2; if (!isTraining && (m_options.ProcessorType == ProcessorTypeEnums.CPU)) { //We only check cache at inference time string cacheKey1 = GenerateCacheKey(sntPairBatch.GetSrcTokens(0)); if (!m_memoryCache.TryGetValue(cacheKey1, out encOutput1)) { encOutput1 = Encoder.BuildTensorForSourceTokenGroupAt(computeGraph, sntPairBatch, m_shuffleType, encoder, m_modelMetaData, srcEmbedding, posEmbedding, segmentEmbedding, 0); // output shape: [batch_size, dim] var cacheEntryOptions = new MemoryCacheEntryOptions().SetSize(1); m_memoryCache.Set(cacheKey1, encOutput1.CopyWeightsRef($"cache_{encOutput1.Name}", false), cacheEntryOptions); } string cacheKey2 = GenerateCacheKey(sntPairBatch.GetSrcTokens(1)); if (!m_memoryCache.TryGetValue(cacheKey2, out encOutput2)) { encOutput2 = Encoder.BuildTensorForSourceTokenGroupAt(computeGraph, sntPairBatch, m_shuffleType, encoder, m_modelMetaData, srcEmbedding, posEmbedding, segmentEmbedding, 1); // output_shape: [batch_size, dim] var cacheEntryOptions = new MemoryCacheEntryOptions().SetSize(1); m_memoryCache.Set(cacheKey2, encOutput2.CopyWeightsRef($"cache_{encOutput2.Name}", false), cacheEntryOptions); } } else { //We always run encoder network during training time or using GPUs encOutput1 = Encoder.BuildTensorForSourceTokenGroupAt(computeGraph, sntPairBatch, m_shuffleType, encoder, m_modelMetaData, srcEmbedding, posEmbedding, segmentEmbedding, 0); // output shape: [batch_size, dim] encOutput2 = Encoder.BuildTensorForSourceTokenGroupAt(computeGraph, sntPairBatch, m_shuffleType, encoder, m_modelMetaData, srcEmbedding, posEmbedding, segmentEmbedding, 1); // output_shape: [batch_size, dim] } if (m_modelMetaData.SimilarityType.Equals("Continuous", StringComparison.InvariantCultureIgnoreCase)) { // Cosine similairy var w12 = computeGraph.EltMul(encOutput1, encOutput2); w12 = computeGraph.Sum(w12, 1); var w1 = computeGraph.EltMul(encOutput1, encOutput1); w1 = computeGraph.Sum(w1, 1); var w2 = computeGraph.EltMul(encOutput2, encOutput2); w2 = computeGraph.Sum(w2, 1); var n12 = computeGraph.EltMul(w1, w2); n12 = computeGraph.Rsqrt(n12); var probs = computeGraph.EltMul(w12, n12); if (isTraining) { var tgtSnts = sntPairBatch.GetTgtTokens(0); for (int k = 0; k < batchSize; k++) { float golden_score_k = float.Parse(tgtSnts[k][0]); // Get golden similiary score from target side float score_k = probs.GetWeightAt(new long[] { k, 0 }); probs.SetWeightAt(score_k - golden_score_k, new long[] { k, 0 }); cost += (float)Math.Abs(score_k - golden_score_k); } probs.CopyWeightsToGradients(probs); nr.Cost = cost / batchSize; } else { nr.Output.Add(new List <List <string> >()); for (int k = 0; k < batchSize; k++) { float score_k = probs.GetWeightAt(new long[] { k, 0 }); nr.Output[0].Add(new List <string>()); nr.Output[0][k].Add(score_k.ToString()); } } } else { IWeightTensor encOutput = computeGraph.EltMul(encOutput1, encOutput2); IWeightTensor ffLayer = encoderFFLayer.Process(encOutput, batchSize, computeGraph); using (IWeightTensor probs = computeGraph.Softmax(ffLayer, runGradients: false, inPlace: true)) { if (isTraining) { var tgtSnts = sntPairBatch.GetTgtTokens(0); for (int k = 0; k < batchSize; k++) { int ix_targets_k_j = m_modelMetaData.ClsVocab.GetWordIndex(tgtSnts[k][0]); float score_k = probs.GetWeightAt(new long[] { k, ix_targets_k_j }); cost += (float)-Math.Log(score_k); probs.SetWeightAt(score_k - 1, new long[] { k, ix_targets_k_j }); } ffLayer.CopyWeightsToGradients(probs); nr.Cost = cost / batchSize; } else { // Output "i"th target word using var targetIdxTensor = computeGraph.Argmax(probs, 1); float[] targetIdx = targetIdxTensor.ToWeightArray(); List <string> targetWords = m_modelMetaData.ClsVocab.ConvertIdsToString(targetIdx.ToList()); nr.Output.Add(new List <List <string> >()); for (int k = 0; k < batchSize; k++) { nr.Output[0].Add(new List <string>()); nr.Output[0][k].Add(targetWords[k]); } } } } nrs.Add(nr); return(nrs); }
public Task<ResponseMessage> SendHistory(History history) { if (APIInvalid) { LastCallResult = NetworkResult.AuthenticationFailed; return Task.FromResult(new ResponseMessage() { IsSuccess = false }); } if (FailNetwork) { LastCallResult = NetworkResult.NetworkError; throw new IOException(); } if (UnknownError) { LastCallResult = NetworkResult.UnknownError; throw new Exception("ups"); } if (history != null) { HistoryEvents.AddRange(history.Events); HistoryActions.AddRange(history.Actions); } LastCallResult = NetworkResult.Success; return Task.FromResult(new ResponseMessage() {IsSuccess = true}); }
private async Task Recieve() { var storageNos = Items .Where(x => x.IsSelected) .Select(x => x.Item.StorageNo) .ToList(); var exists = storageNos .Any(x => inspectionService.IsInspectionExists(x)); if (exists) { if (!await dialogService.DisplayConfirm("Data recieve", "Data already exists. delete it ?")) { return; } } var result = await loadingService.WithExecuteAsync("Data recieve", async() => { NetworkResult <StorageDetailsResponse> ret = null; foreach (var storageNo in storageNos) { ret = await networkClient.Get <StorageDetailsResponse>( EndPoint.StorageDetails(settingService.GetEndPoint(), storageNo), Definition.Timeout); if (!ret.Success) { return(ret); } var summary = ret.Result.Entries .Aggregate(new EntrySummaryView(), (s, e) => { s.DetailCount += 1; s.TotalPrice += e.SalesPrice *e.Qty; s.TotalQty += e.Qty; return(s); }); // MEMO DetailNo discards it as it will change again when sending await inspectionService.UpdateAsync( new InspectionStatusEntity { StorageNo = ret.Result.StorageNo, EntryUserId = ret.Result.EntryUserId, EntryAt = ret.Result.EntryAt, InspectionUserId = ret.Result.InspectionUserId, InspectionAt = ret.Result.InspectionAt, DetailCount = summary.DetailCount, TotalPrice = summary.TotalPrice, TotalQty = summary.TotalQty, IsChecked = false }, ret.Result.Entries.Select((x, i) => new InspectionEntity { ItemCode = x.ItemCode, ItemName = x.ItemName, SalesPrice = x.SalesPrice, Qty = x.Qty, OriginalQty = x.Qty, })); } return(ret); }); if (result.Success) { await dialogService.DisplayInformation("Data recieve", "Recieve completed."); await Back(); } else { await dialogService.DisplayNetworkError(result); } }
// Use this for initialization public NetworkResult Start() { var result = new NetworkResult(); double erroAtual = 0.0f; int cicloAtual = 0; int[] camadas = new int[this.qtdCamadas + 1]; camadas[0] = 1; for (int i = 1; i < this.qtdCamadas; i++) { camadas[i] = this.qtdNeuronios; } camadas[camadas.Length - 1] = 1; NeuralNetwork network = new NeuralNetwork(camadas, this.taxaAprendizagem); //intiilize network //inicializando amostras double x = this.min; double[,] entradas = new double[this.qtdAmostras, 1]; double[,] saidasEsperadas = new double[this.qtdAmostras, 1]; double[,] saidasEncontradas = new double[this.qtdAmostras, 1]; for (int i = 0; i < this.qtdAmostras; i++) { entradas[i, 0] = x; saidasEsperadas[i, 0] = this.funcao(x); x += 0.01f; } //treinando a rede do { for (int i = 0; i < this.qtdAmostras; i++) { double[] entrada = new double[1]; entrada[0] = entradas[i, 0]; double[] saida = new double[1]; saida = network.FeedForward(entrada); saidasEncontradas[i, 0] = saida[0]; double[] saidaEsperada = new double[1]; saidaEsperada[0] = saidasEsperadas[i, 0]; network.BackProp(saidaEsperada); } cicloAtual++; erroAtual = this.calculaErro(saidasEsperadas, saidasEncontradas); result.Erros.Add(erroAtual); Console.WriteLine(erroAtual); } while (this.usarErro ? (erroAtual >= this.erroAceitavel) : (cicloAtual < this.quantidadeCiclos)); double[,] novasEntradas = new double[(int)((this.max - this.min) / 0.01) + 1, 1]; int index = 0; for (var i = this.min; i < this.max; i += 0.01) { try { novasEntradas[index, 0] = i; result.Resultados.Add(this.funcao(i)); double[] e = new double[1]; e[0] = novasEntradas[index, 0]; result.ValoresEsperados.Add(Math.Tanh(network.FeedForward(e)[0])); index++; } catch { Console.WriteLine(index); Console.WriteLine(i); Console.WriteLine((this.max - this.min) / 0.01); throw; } } return(result); }
void INetworkTransaction.CheckReceipt(NetworkResult result) { throw new NotImplementedException(); }