public static void SendError(ZoneClient client, ServerError error) { using (Packet pack = new Packet(SH3Type.Error)) { pack.WriteShort((byte)error); client.SendPacket(pack); } }
public void Execute(ServerError error) { var msg = string.Format( @"{0} Document: {1} Index: {2} When: {3}", error.Error, error.Document, error.Index, error.Timestamp); Clipboard.SetText(msg); }
public static bool TryParseServerError(this JToken jToken, JsonSerializer serializer, out ServerError error) { error = null; if (jToken == null) { return(false); } var errorProperty = jToken.Children <JProperty>().FirstOrDefault(c => c.Name == "error"); var rootCauseProperty = jToken.Children <JProperty>().FirstOrDefault(c => c.Name == "root_cause"); if (errorProperty == null && rootCauseProperty == null) { return(false); } var j = jToken; if (rootCauseProperty != null) { var o = new JObject { { "error", jToken } }; j = o; } using (var sw = new StringWriter()) using (var localWriter = new JsonTextWriter(sw)) { serializer.Serialize(localWriter, j); using (var ms = new MemoryStream(sw.ToString().Utf8Bytes())) error = ServerError.Create(ms); } return(true); }
public ActionResult Update([DataSourceRequest] DataSourceRequest request, VmTrailer trailer) { var isEditable = CurrentUser.IsAdmin; if (!isEditable) { ModelState.AddModelError("Update", "Current user does not have permission to update trailers."); } if (ModelState.IsValid) { var dbTrailer = Db.Trailers.Find(trailer.TrailerId); if (dbTrailer != null) { dbTrailer.IsActive = trailer.IsActive; dbTrailer.TrailerDescription = trailer.TrailerDescription; dbTrailer.AxlesDescription = trailer.AxlesDescription; dbTrailer.CapacityKg = trailer.CapacityKg; dbTrailer.TrailerTypeId = trailer.TrailerTypeId; dbTrailer.UnitOfMeasureId = trailer.UnitOfMeasureId; dbTrailer.Volume = trailer.Volume; try { Db.SaveChanges(); } catch (Exception e) { ModelState.AddModelError("Update trailer", ServerError.GetErrorFromException(e).ExceptionMsg); } } } return(Json(new[] { trailer }.ToDataSourceResult(request, ModelState))); }
private static void SendFailedLogin(LoginClient pClient, ServerError pError) { using (Packet pack = new Packet(SH3Type.Error)) { pack.WriteUShort((ushort)pError); pClient.SendPacket(pack); } }
public LoginReturn() { error = new ServerError(); AuthToken = ""; }
/// <summary> /// Initializes a new instance of the <see cref="ServerException"/> class. /// </summary> /// <param name="error">The error.</param> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public ServerException(ServerError error, string message, Exception inner) : base(message, inner) { this.error = error; }
public ActionResult SaveEditedLoad(VmKoLoad load) { try { if (CurrentUser.UserLevel < (int)Enums.AccessLevel.Dispatcher) { throw new ServerException($"Save Load: User does not have permission to save load {load.LoadId}"); } var dbLoad = Db.Loads.Find(load.LoadId); if (dbLoad == null) { throw new ServerException($"SaveEditedLoad: Cannot find load {load.LoadId}"); } dbLoad.DriverId = load.DriverId; dbLoad.TruckId = load.TruckId; dbLoad.LoadStatusId = load.LoadStatusId; dbLoad.LoadDate = load.LoadDate; var isChangeTrailer = dbLoad.TrailerId != load.TrailerId; var isReOrderItems = false; if (load.NewOrderSequence != null) { var currentOrderSequence = dbLoad.Orders.OrderBy(r => r.LoadSort).Select(o => o.OrderId).ToArray(); isReOrderItems = !currentOrderSequence.SequenceEqual(load.NewOrderSequence); } if (isReOrderItems) { var position = 1; foreach (var orderId in load.NewOrderSequence) { var dbOrder = dbLoad.Orders.FirstOrDefault(o => o.OrderId == orderId); if (dbOrder != null) { dbOrder.LoadSort = position; position++; } } } if (isChangeTrailer) { int?unitOfMeasure = null; var dbTrailer = Db.Trailers.Find(load.TrailerId); if (dbTrailer != null) { unitOfMeasure = dbTrailer.UnitOfMeasureId; } dbLoad.UnitOfMeasureId = unitOfMeasure; } dbLoad.TrailerId = load.TrailerId; dbLoad.ModifiedByUserLoginId = CurrentUser.UserLoginId; dbLoad.ModifiedDate = DateTime.Now; Db.SaveChanges(); } catch (Exception e) { return(ReturnLoad(load, ServerError.GetErrorFromException(e).ExceptionMsg)); } return(ReturnLoad(load, $"Load {load.LoadId} has been saved")); }
public ActionResult SaveOrder(VmKoOrder order) { try { if (CurrentUser.UserLevel < (int)Enums.AccessLevel.Entry) { throw new ServerException("Save Order: User does not have permission to save an order"); } var dbOrder = Db.Orders.FirstOrDefault(o => o.OrderId == order.OrderId); if (dbOrder != null) { var isOnLoad = dbOrder.LoadId != null; if (isOnLoad) { var dbLoad = Db.Loads.Find(dbOrder.LoadId); if (dbLoad != null) { dbLoad.ModifiedDate = DateTime.Now; dbLoad.ModifiedByUserLoginId = CurrentUser.UserLoginId; } } dbOrder.CustAddress = order.CustomerAddress; dbOrder.CustomerName = order.CustomerName; dbOrder.OrderNumber = order.OrderNumber; dbOrder.DeliveryDate = order.DeliveryDate; dbOrder.PickupDate = order.PickupDate; dbOrder.Destination = order.Destination; dbOrder.WarehouseId = order.WarehouseId; dbOrder.IsDangerousGoods = order.IsDangerousGoods; dbOrder.IsCustomerPickup = order.IsCustomerPickup; dbOrder.Notes = order.Notes; dbOrder.Volume = order.Volume; dbOrder.UnitOfMeasureId = order.UnitOfMeasureId; dbOrder.WeightKg = order.WeightKg; dbOrder.ModifiedDate = DateTime.Now; dbOrder.ModifiedByUserLoginId = CurrentUser.UserLoginId; Db.SaveChanges(); } else {// add it;) var newOrder = new Order() { OrderNumber = order.OrderNumber, CreatedDate = DateTime.Now, CreatedByUserLoginId = CurrentUser.UserLoginId }; Db.Orders.Add(newOrder); Db.SaveChanges(); order.OrderId = newOrder.OrderId; order.LastChangeDate = newOrder.CreatedDate; order.UserName = CurrentUser.DisplayName; } } catch (Exception e) { return(ReturnOrder(order, ServerError.GetErrorFromException(e).ExceptionMsg)); } return(ReturnOrder(order, $"Order# {order.OrderNumber} has been saved")); }
public void onServerError(Packet packet) { ServerError serverError = new ServerError(packet); connectionManager.onServerError(serverError); }
public static ElasticsearchResponse <T> SetServerError <T>(this ElasticsearchResponse <T> response, ServerError error) where T : ResponseBase { return(response.SetProperty("ServerError", error)); }
public ThenServerError(ServerError error, string message) { _error = error; _message = message; }
internal static void InvokeServerError(ServerErrorArgs args) { ServerError?.Invoke(null, args); }
public bool CanExecute(ServerError error) { return error != null; }
/// <summary> Try to parse an Elasticsearch <see cref="ServerError"/> </summary> public static bool TryGetElasticsearchServerError(this BytesResponse response, out ServerError serverError) { serverError = null; if (response.Body == null || response.Body.Length == 0 || response.ResponseMimeType != RequestData.MimeType) { return(false); } var settings = response.ApiCall.ConnectionConfiguration; using var stream = settings.MemoryStreamFactory.Create(response.Body); return(ServerError.TryCreate(stream, out serverError)); }
/// <summary> /// Occurs when the server returns an error code of 500 or higher. /// </summary> /// <param name="e">Arguments for the event.</param> protected virtual void OnServerError(RetryEventArgs e) { ServerError?.Invoke(this, e); }
public ElasticSearchException(string message, Exception ex, ServerError serverError) : base(message, ex) { ServerError = serverError; }
protected void BroadcastError(ServerError error) { OnError?.Invoke(error); }
private void OnServerError(ServerError serverError) { OnAppBuildFailedRecieved(new AppBuildFailed(serverError.Error)); }
public ActionResult DropOrder(long orderId, long loadId) { var result = new VmDragDropResult() { LoadId = loadId, OrderId = orderId }; try { if (CurrentUser.UserLevel < (int)Enums.AccessLevel.Dispatcher) { throw new ServerException("Drop Order: User does not have permission to move orders."); } var dbOrder = Db.Orders.FirstOrDefault(o => o.OrderId == orderId); if (dbOrder != null) { var isFromOrderList = dbOrder.LoadId == null; var isMovedFromAnotherLoad = !isFromOrderList && dbOrder.LoadId != loadId; if (isMovedFromAnotherLoad) { var previousLoad = Db.Loads.Find(dbOrder.LoadId); if (previousLoad != null) { previousLoad.ModifiedDate = DateTime.Now; previousLoad.ModifiedByUserLoginId = CurrentUser.UserLoginId; } } if (isFromOrderList || isMovedFromAnotherLoad) { var dbLoad = Db.Loads.Find(loadId); if (dbLoad != null) { if (dbLoad.LoadStatusId == 1) { dbOrder.LoadId = loadId; dbLoad.ModifiedDate = DateTime.Now; dbLoad.ModifiedByUserLoginId = CurrentUser.UserLoginId; var maxLoadSortNum = Db.Orders.Where(o => o.LoadId == dbOrder.LoadId).Max(o => o.LoadSort) ?? 0; dbOrder.LoadSort = maxLoadSortNum + 1; } } } Db.SaveChanges(); } } catch (Exception e) { result.Message = ServerError.GetErrorFromException(e).ExceptionMsg; return(Json(result.ToJsonString(), JsonRequestBehavior.AllowGet)); } result.Message = $"OrderId {orderId} has been moved to loadId {loadId}"; return(Json(result.ToJsonString(), JsonRequestBehavior.AllowGet)); }
protected virtual void OnServerError(ServerStartErrorEventArgs e) { ServerError?.Invoke(this, e); }
/// <summary> /// Initializes a new instance of the <see cref="ServerException"/> class. /// </summary> /// <param name="error">The error.</param> /// <param name="message">The message.</param> public ServerException(ServerError error, string message) : base(message) { this.error = error; }
public static ReadOnlySequence <byte> NewSendError(long producerId, long sequenceId, ServerError error, string errorMsg) { var sendError = new CommandSendError { ProducerId = (ulong)producerId, SequenceId = (ulong)sequenceId, Error = error, Message = errorMsg }; return(Serializer.Serialize(sendError.ToBaseCommand())); }
public IHttpActionResult RegisterSubscriber() { try { NameValueCollection f = HttpContext.Current.Request.Form; string username = f["username"]; string password = f["password"]; string address = f["address"]; string phone = f["phone"]; string friendlyname = f["friendlyname"]; string foodprefs = f["preferences"]; string passwordq = f["passwordq"]; string passworda = f["passworda"]; byte emailoffers = Convert.ToByte(f["emailoffers"]); byte mailinglist = Convert.ToByte(f["mailinglist"]); byte textoffers = Convert.ToByte(f["textoffers"]); lastcallEntities db = new lastcallEntities(); subscriber s = (from x in db.subscribers where x.email == username select x).FirstOrDefault(); if (s != null) { return(Json(new ServerError(ServerErrorNumber.UsernameInUse))); } // The new subscriber record s = new subscriber() { deliveryaddress = address, email = username, emailoffers = emailoffers, friendlyname = friendlyname, onmailinglist = mailinglist, password = password, //TODO: Need to encrypt phone = phone, textoffers = textoffers, }; // The chosen preferences are returned as a semi-colon separated string of preference IDs if (!String.IsNullOrEmpty(foodprefs)) { string[] userprefs = foodprefs.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); // The subscriber's food preferences foodpreference[] preferences = new foodpreference[userprefs.Length]; for (int i = 0; i < userprefs.Length; i++) { preferences[i] = new foodpreference() { subscriberid = s.id, preferenceid = Int32.Parse(userprefs[i]) }; } // Entity Framework goodness. The associated foodpreferences records will be created as the subscriber record is saved. s.foodpreferences = preferences; } // Save the new subscriber record and associated food preferences db.subscribers.Add(s); db.SaveChanges(); db.Dispose(); } catch (Exception X) { ServerError err = new ServerError(ServerErrorNumber.ThrewException); err.ErrorDetails = X.Message; return(Json(err, Global.JSONSettings())); } return(Json(new ServerError(), Global.JSONSettings())); }
public ServerResponse(ServerError serverError) { this.Error = serverError; }
public MealOfferReturn() { error = new ServerError(); // mealoffers remains a null array until the number of entries can be determined }
public ServerResponse(ServerError serverError, T payload) { this.Error = serverError; this.Payload = payload; }
/// <summary> /// Read messages from the device /// </summary> /// <param name="ar">Async Result</param> private void ReadCallback(IAsyncResult ar) { int bytesRead = 0; bool noRead = false; ReadObject readObject = (ReadObject)ar.AsyncState; try { bytesRead = readObject.client.EndReceive(ar); } catch (Exception ex) { ServerError?.Invoke(ex); return; } if (bytesRead > 0) { if (readObject.isFirstMessage) { string derPublicKey = keyGeneration.GetDerPublicKey(); SendString(readObject.client, derPublicKey); Form1.WriteLine("Public Key Sent"); readObject.isFirstMessage = false; } else { byte[] dataReceived = new byte[bytesRead]; Array.Copy(readObject.buffer, dataReceived, bytesRead); string textData = Encoding.UTF8.GetString(dataReceived); if (textData.StartsWith("set-session-key")) { Form1.WriteLine("Got set session key"); string encryptedSessionKey = textData.Substring(15); string sessionKey = Encoding.UTF8.GetString(keyGeneration.DecryptData(Convert.FromBase64String(encryptedSessionKey))); readObject.session.SetSessionKey(sessionKey); } else { Form1.WriteLine("Got session message"); byte[] sessionData = readObject.session.DecryptData(textData); string sessionTextData = Encoding.UTF8.GetString(sessionData); Form1.WriteLine($"Session Data: {sessionTextData}"); if (sessionTextData.StartsWith("res-")) { Form1.WriteLine("Got request setter"); readObject.requestString = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); Form1.WriteLine($"Request string set to: {readObject.requestString}"); SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes("no-data")))); Form1.WriteLine("Continue message sent to client"); } else if (sessionTextData.StartsWith("no-")) { Form1.WriteLine($"Couldn't find credentials on the device: {sessionTextData}"); string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); if (parameter == "setup") { LockStateChanged?.Invoke(LockState.Failed); } else if (parameter == "fp") { Form1.WriteLine("User failed to authenticate with fingerprint!"); if (readObject.requestString == "getkname-windowsLogon") { WindowsLocking.CancelRegistration(); } else if (readObject.requestString.StartsWith("pw-")) { Form1.WriteLine("Password get failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(3), JavascriptServer.CredentialTransferState.Failed); } } else if (readObject.requestString.StartsWith("storpw-")) { Form1.WriteLine("Password storage failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(7), JavascriptServer.CredentialTransferState.Failed); } } else if (readObject.requestString.StartsWith("getkname-")) { Form1.WriteLine("Get key failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(10), JavascriptServer.CredentialTransferState.Failed); } } } noRead = true; } else if (sessionTextData == "getuser") { if (jsSrv == null) { throw new InvalidOperationException("Can't store password while javascript server is down"); } object[] data = jsSrv.storePasswordQueue.GetQueueData(readObject.requestString.Substring(7)); if (data == null || data.Length != 2) { throw new NullReferenceException("Can't find credentials for the specified web site hash"); } readObject.credentials.username = (string)data[0]; readObject.credentials.password = (string)data[1]; SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(readObject.credentials.username)))); } else if (sessionTextData == "getpass") { SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(readObject.credentials.password)))); if (jsSrv != null) { jsSrv.storePasswordQueue.UpdateState(readObject.requestString.Substring(7), JavascriptServer.CredentialTransferState.Success); } DismissIfOpen?.Invoke(); noRead = true; } else if (sessionTextData.StartsWith("usresp-")) { string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); readObject.credentials.username = parameter; Form1.WriteLine($"Got credentials: usr: {readObject.credentials.username} ; pwd: {readObject.credentials.password}"); if (jsSrv == null) { throw new NullReferenceException("Javascript Server was down when trying to get credentials data"); } jsSrv.getPasswordQueue.UpdateExtraData(readObject.requestString.Substring(3), readObject.credentials.username, readObject.credentials.password); jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(3), JavascriptServer.CredentialTransferState.Success); noRead = true; } else if (sessionTextData.StartsWith("pushkey-")) { string key = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); if (readObject.requestString == "win") { if (WindowsLocking.IsLogonValid(key)) { LockStateChanged?.Invoke(LockState.Unlocked); } else { LockStateChanged?.Invoke(LockState.Failed); } } else if (readObject.requestString == "lock") { if (WindowsLocking.IsLogonValid(key)) { LockStateChanged?.Invoke(LockState.Locked); } else { LockStateChanged?.Invoke(LockState.Failed); } } else { if (jsSrv == null) { throw new NullReferenceException("Javascript server is down when trying to forward 2fa key"); } jsSrv.getKeyQueue.UpdateExtraData(readObject.requestString.Substring(10), key); jsSrv.getKeyQueue.UpdateState(readObject.requestString.Substring(10), JavascriptServer.CredentialTransferState.Success); } noRead = true; } else if (sessionTextData.StartsWith("pwresp-")) { string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); readObject.credentials.password = parameter; DismissIfOpen?.Invoke(); } else if (sessionTextData == "getkvalue") { string parameter = readObject.requestString.Substring(readObject.requestString.IndexOf('-') + 1); string pushKey; if (parameter == "windowsLogon") //Windows Lock Authentication { string lockingKey = WindowsLocking.RegisterLogon(); pushKey = lockingKey; } else { if (jsSrv == null) { throw new NullReferenceException("Javascript server was down when trying to send key to android device"); } if (jsSrv.storeKeyQueue.Contains(readObject.requestString.Substring(9))) { pushKey = (string)jsSrv.storeKeyQueue.GetQueueData(readObject.requestString.Substring(9))[0]; } else { pushKey = "fail"; } } if (pushKey == null) { pushKey = "fail"; } SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(pushKey)))); if (pushKey == "fail") { Form1.WriteLine("PushKey set to fail!"); jsSrv.storeKeyQueue.UpdateState(readObject.requestString.Substring(9), JavascriptServer.CredentialTransferState.Failed); } else { jsSrv.storeKeyQueue.UpdateState(readObject.requestString.Substring(9), JavascriptServer.CredentialTransferState.Success); } noRead = true; } } } } Array.Clear(readObject.buffer, 0, readObject.buffer.Length); if (!noRead) { readObject.client.BeginReceive(readObject.buffer, 0, readObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), readObject); } }
public ApiCallDetailsOverride(IApiCallDetails original, ServerError error) { _original = original; _error = error; _isValid = false; }
/// <summary> Try to parse an Elasticsearch <see cref="ServerError"/> </summary> public static bool TryGetElasticsearchServerError(this StringResponse response, out ServerError serverError) { serverError = null; if (string.IsNullOrEmpty(response.Body) || response.ResponseMimeType != RequestData.MimeType) { return(false); } var settings = response.ApiCall.ConnectionConfiguration; using var stream = settings.MemoryStreamFactory.Create(Encoding.UTF8.GetBytes(response.Body)); return(ServerError.TryCreate(stream, out serverError)); }
private static void RegisterError(ISpan span, IApiCallDetails response) { if (response.Success) { return; } var exception = response.OriginalException ?? response.AuditTrail.FirstOrDefault(a => a.Exception != null)?.Exception; var f = PipelineFailure.Unexpected; // report inner exception stack traces for these directly if possible if (exception is ElasticsearchClientException es) { f = es.FailureReason ?? f; exception = es.InnerException ?? es; } if (exception is UnexpectedElasticsearchClientException un) { f = un.FailureReason ?? f; exception = un.InnerException ?? un; } var culprit = "Client Error"; var message = $"{f.GetStringValue()} {exception?.Message}"; var stackFrames = exception == null ? null : new StackTrace(exception, true).GetFrames(); if (stackFrames == null || stackFrames.Length == 0) { stackFrames = new StackTrace(true).GetFrames(); } var causeOnServer = false; if (response.ResponseBodyInBytes != null) { using var memoryStream = new MemoryStream(response.ResponseBodyInBytes); if (ServerError.TryCreate(memoryStream, out var serverError) && serverError != null) { causeOnServer = true; culprit = $"Elasticsearch Server Error: {serverError.Error.Type}"; message = $"The server returned a ({response.HttpStatusCode}) and indicated: " + ( serverError.Error?.CausedBy?.Reason ?? serverError.Error?.CausedBy?.Type ?? serverError.Error?.RootCause.FirstOrDefault()?.Reason ?? serverError.Error?.Reason ?? "Response did not indicate a server error, usually means no json was with an error key was returned."); } } if (exception == null && !causeOnServer) { return; } if (causeOnServer && string.IsNullOrEmpty(message)) { return; } if (causeOnServer) { span.CaptureError(message, culprit, stackFrames); } else { span.CaptureException(exception); } }
/// <summary> /// Try to parse an Elasticsearch <see cref="ServerError"/>, this only works if /// <see cref="ITransportConfigurationValues.DisableDirectStreaming"/> gives us access to <see cref="IApiCallDetails.RequestBodyInBytes"/> /// </summary> public static bool TryGetElasticsearchServerError(this ITransportResponse response, out ServerError serverError) { serverError = null; var bytes = response.ApiCall.ResponseBodyInBytes; if (bytes == null || response.ApiCall.ResponseMimeType != RequestData.MimeType) { return(false); } var settings = response.ApiCall.ConnectionConfiguration; using var stream = settings.MemoryStreamFactory.Create(bytes); return(ServerError.TryCreate(stream, out serverError)); }
private void ProcessAndLogServerError(ServerError serverError) { Error = serverError.ToString(); LogAndShowError(); }
private static void Throw(ServerError error, string message) => throw (error switch
/// <summary> /// Initalizes a new instance of a <see cref="ClientErrorException"/> /// with the specified message and <see cref="ServerError"/>. /// </summary> public ServerErrorException(string message, ServerError error) : base(message) { Error = error; }