public LoadingPage() { this.Loaded += (sender, e) => { //ProgressBar progress = new ProgressBar(); progress.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top; progress.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center; progress.IsIndeterminate = true; progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed; progress.Width = 400; ((Grid)this.Content).Children.Add(progress); //Error error = new Error(); error.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top; error.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right; error.Visibility = Windows.UI.Xaml.Visibility.Collapsed; error.Margin = new Thickness(0, 0, 30, 0); ((Grid)this.Content).Children.Add(error); //OfflineError offlineError = new OfflineError(); offlineError.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top; offlineError.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right; offlineError.Visibility = Windows.UI.Xaml.Visibility.Collapsed; offlineError.Margin = new Thickness(0, 0, 130, 0); ((Grid)this.Content).Children.Add(offlineError); }; }
void CompilePalLogger_OnError(string errorText, Error e) { Dispatcher.Invoke(() => { Hyperlink errorLink = new Hyperlink(); Run text = new Run(errorText); text.Foreground = e.ErrorColor; errorLink.Inlines.Add(text); errorLink.TargetName = e.ID.ToString(); errorLink.Click += errorLink_Click; if (CompileOutputTextbox.Document.Blocks.Any()) { var lastPara = (Paragraph)CompileOutputTextbox.Document.Blocks.LastBlock; lastPara.Inlines.Add(errorLink); } else { var newPara = new Paragraph(errorLink); CompileOutputTextbox.Document.Blocks.Add(newPara); } CompileOutputTextbox.ScrollToEnd(); }); }
public void CheckErrorForEquality() { var firstError = new Error(TestException); var secondError = new Error(TestException); Assert.AreEqual(firstError, secondError); Assert.AreEqual(firstError.GetHashCode(), secondError.GetHashCode()); }
public override string Log(Error error) { if (error == null) { throw new ArgumentNullException(nameof(error)); } var errorXml = ErrorXml.EncodeString(error); using (var scope = DataAccessScope.CreateReadCommitted()) { var dbElmahError = dataModel.ElmahErrors.Create(); dbElmahError.Application = ApplicationName; dbElmahError.Host = error.HostName; dbElmahError.Type = error.Type; dbElmahError.Source = error.Source; dbElmahError.Message = error.Message; dbElmahError.User = error.User; dbElmahError.StatusCode = error.StatusCode; dbElmahError.TimeUtc = error.Time; dbElmahError.AllXml = errorXml; scope.Complete(); return dbElmahError.Id.ToString(); } }
public ErrorLoggingEventArgs(Error error) { if (error == null) throw new ArgumentNullException("error"); _error = error; }
static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Program.Error = new Error(); Process instance = GetRunningInstance(); if (instance == null) { //GlobalVar.MainFrame = new MainFrame(); Application.Run(new MachineFrame()); //Application.Run(new TestForm()); } else { MessageBox.Show("程序已经打开!"); Application.Exit(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected override void Append(log4net.Core.LoggingEvent loggingEvent) { if (this._ErrorLog != null) { Error error; if (loggingEvent.ExceptionObject != null) { error = new Error(loggingEvent.ExceptionObject); } else { error = new Error(); } error.Time = DateTime.Now; if (loggingEvent.MessageObject != null) { error.Message = loggingEvent.MessageObject.ToString(); } error.Detail = base.RenderLoggingEvent(loggingEvent); error.HostName = this._HostName; error.User = loggingEvent.Identity; error.Type = "log4net - " + loggingEvent.Level; // maybe allow the type to be customized? this._ErrorLog.Log(error); } }
public static void ThrowError(Error err) { Console.WriteLine($"Unresolved error was thrown: {err}"); Console.WriteLine("Cancelling due to error..."); _wasCanceled = true; _builderThread.Abort(); }
/// <summary> /// Decodes an <see cref="Error"/> object from its XML representation. /// </summary> public static Error Decode(XmlReader reader) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.IsStartElement()) throw new ArgumentException("Reader is not positioned at the start of an element.", "reader"); // // Read out the attributes that contain the simple // typed state. // var error = new Error(); ReadXmlAttributes(reader, error); // // Move past the element. If it's not empty, then // read also the inner XML that contains complex // types like collections. // var isEmpty = reader.IsEmptyElement; reader.Read(); if (!isEmpty) { ReadInnerXml(reader, error); reader.ReadEndElement(); } return error; }
/// <summary>Gets the given request.</summary> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Get(Error request) { if (request != null && !String.IsNullOrEmpty(request.Id)) return new ErrorResponse(new Error { Id = "Test" }); return new ErrorCollectionResponse(new List<Error> { new Error { Id = "TestCollection" } }); }
/// <summary> /// Logs an error in log for the application. /// </summary> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); using (MySqlConnection cn = new MySqlConnection(ConnectionString)) { using (MySqlCommand cmd = new MySqlCommand("Elmah_LogError", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@pErrorId", id.ToString()); cmd.Parameters.AddWithValue("@pApplication", ApplicationName); cmd.Parameters.AddWithValue("@pHost", error.HostName); cmd.Parameters.AddWithValue("@pType", error.Type); cmd.Parameters.AddWithValue("@pSource", error.Source); cmd.Parameters.AddWithValue("@pMessage", error.Message); cmd.Parameters.AddWithValue("@pUser", error.User); cmd.Parameters.AddWithValue("@pStatusCode", error.StatusCode); cmd.Parameters.AddWithValue("@pTimeUtc", error.Time.ToUniversalTime()); cmd.Parameters.AddWithValue("@pAllXml", errorXml); cn.Open(); cmd.ExecuteNonQuery(); return id.ToString(); } } }
public IActionResult Clubs() { if (ModelState.IsValid) { ListModelResponse<Club> clubResponse = _context.GetUserClubs(_userManager.GetUserId(User)); if (clubResponse.DidError == true || clubResponse == null) { if (clubResponse == null) return View("Error"); Error er = new Error(clubResponse.ErrorMessage); return View("Error", er); } if(clubResponse.Model!=null) { ViewBag.ClubsByTitle = clubResponse.Model.OrderBy(p => p.Name); ViewBag.ClubsByLocation = clubResponse.Model.OrderBy(p => p.Location); } string sourceCookie = HttpContext.Request.Cookies["SourcePageClub"]; if (sourceCookie != null) { ViewBag.SourcePageClub = sourceCookie; } return View(clubResponse.Model); } else { return BadRequest(); } }
/// <summary> /// Encodes the default JSON representation of an <see cref="Error"/> /// object to a <see cref="TextWriter" />. /// </summary> /// <remarks> /// Only properties and collection entires with non-null /// and non-empty strings are emitted. /// </remarks> public static void Encode(Error error, TextWriter writer) { if (error == null) throw new ArgumentNullException("error"); if (writer == null) throw new ArgumentNullException("writer"); EncodeEnclosed(error, new JsonTextWriter(writer)); }
private static Error GenerateError(int nestingLevel = 0, int minimiumNestingLevel = 0) { var error = new Error(); error.Message = @"Generated exception message."; error.Type = TestConstants.ExceptionTypes.Random(); if (RandomHelper.GetBool()) error.Code = RandomHelper.GetRange(-234523453, 98690899).ToString(); for (int i = 0; i < RandomHelper.GetRange(minimiumNestingLevel, minimiumNestingLevel + 5); i++) { string key = RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 15)); while (error.Data.ContainsKey(key)) key = RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 15)); error.Data.Add(key, RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 25))); } var stack = new StackFrameCollection(); for (int i = 0; i < RandomHelper.GetRange(1, 10); i++) stack.Add(GenerateStackFrame()); error.StackTrace = stack; if (minimiumNestingLevel > 0 || (nestingLevel < 5 && RandomHelper.GetBool())) error.Inner = GenerateError(nestingLevel + 1); return error; }
void ITableEntity.ReadEntity(IDictionary<string, EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext) { // This can occasionally fail because someone didn't finish creating the entity yet. EntityProperty value; if (properties.TryGetValue("SerializedError", out value)) { Error = ErrorXml.DecodeString(value.StringValue); } else { Error = new Error { ApplicationName = "TableErrorLog", StatusCode = 999, HostName = Environment.MachineName, Time = DateTime.UtcNow, Type = typeof(Exception).FullName, Detail = "Error Log Entry is Corrupted/Missing in Table Store" }; return; } if (properties.TryGetValue("Detail", out value)) { Error.Detail = value.StringValue; } if (properties.TryGetValue("WebHostHtmlMessage", out value)) { Error.WebHostHtmlMessage = value.StringValue; } }
public void ErrorConstructor_Test2_non_Empty_error() { string error = "Test string"; Error target = new Error(error); Assert.AreEqual(target.Message, error); }
public void RepublishError(Error error, QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var model = connection.CreateModel()) { try { if (error.Exchange != string.Empty) { model.ExchangeDeclarePassive(error.Exchange); } var properties = model.CreateBasicProperties(); error.BasicProperties.CopyTo(properties); var body = Encoding.UTF8.GetBytes(error.Message); model.BasicPublish(error.Exchange, error.RoutingKey, properties, body); } catch (OperationInterruptedException) { Console.WriteLine("The exchange, '{0}', described in the error message does not exist on '{1}', '{2}'", error.Exchange, parameters.HostName, parameters.VHost); } } }
public void Issue308() { var error = new Error(); error.QueryString.Add(new NameValueCollection { { null, "foo" } }); var json = ErrorJson.EncodeString(error); Assert.NotNull(json); }
public void ErrorConstructor_Test1_Empty_error() { string error = string.Empty; Error target = new Error(error); Assert.AreEqual(target.Message, error); }
public static bool CheckSyntax(string expression, out Error[] errors) { var p = new CSharpParser(); p.ParseExpression(expression); errors = p.Errors.ToArray(); return !errors.Any(); }
public void LogExceptionNo(Exception exception, string no, string username) { // try-catch because database itself could be down or Request context is unknown. try { // ** Prototype pattern. the Error object has it default values initialized var error = new Error() { UserName = username, ErrorID = no, Exception = exception.GetType().FullName, Message = exception.Message, Everything = exception.ToString(), IpAddress = HttpContext.Current.Request.UserHostAddress, UserAgent = HttpContext.Current.Request.UserAgent, PathAndQuery = HttpContext.Current.Request.Url == null ? "" : HttpContext.Current.Request.Url.PathAndQuery, HttpReferer = HttpContext.Current.Request.UrlReferrer == null ? "" : HttpContext.Current.Request.UrlReferrer.PathAndQuery, CreatedOn = DateTime.Now, ChangedOn = DateTime.Now }; using (MyRealtyWebDBEntities context = new MyRealtyWebDBEntities()) { context.Errors.Add(error); context.SaveChanges(); } //DealSiteContext.Errors.Insert(error); } catch { /* do nothing, or send email to webmaster*/} }
public void WriteException(Exception ex) { var uh = new Error(ex); uh.ApplicationId = this.CurrentApplication.Id; IUnhandledErrorRepository rep = RepositoryFactory.Instance.CreateInstance<IUnhandledErrorRepository>(); uh = rep.Create(uh); var inner = ex.InnerException; while(inner != null) { var uhInner = new Error(inner); uhInner.ParentErrorId = uh.Id; uhInner.ApplicationId = this.CurrentApplication.Id; rep.Create(uhInner); inner = inner.InnerException; } var currentRequest = HttpContext.Current.Request; foreach (var cookieKey in currentRequest.Cookies.AllKeys) { Cookie sc = new Cookie(currentRequest.Cookies[cookieKey]); sc.ErrorId = uh.Id; IUnhandledCookieRepository crep = RepositoryFactory.Instance.CreateInstance<IUnhandledCookieRepository>(); crep.Create(sc); } }
protected virtual IActionResult InternalServerError(Error error) { if (error == null) throw new ArgumentNullException("error", "error is null"); foreach (var message in error.Messages) Logger.LogError(message); return new ObjectResult(error) { StatusCode = 500 }; }
/// <summary> /// Constructor /// </summary> /// <param name="status">The HTTP response status code</param> /// <param name="error">The Error object returned by the service</param> public KeyVaultClientException( HttpStatusCode status, Uri requestUri, Error error = null ) : base( GetExceptionMessage( error ) ) { Error = error; RequestUri = requestUri; Status = status; }
/// <summary> /// Конструктор /// </summary> /// <param name="aConnectionString">строка соединения</param> public WorkDB(string aConnectionString) { mCn = new OleDbConnection(aConnectionString); mErr = new Error(); mTxn = null; mIsInternalTransaction = false; }
/// <summary> /// Constructor /// </summary> public Error( Exception ex ) { Message = ex.Message; if( ex.InnerException != null ) InnerError = new Error( ex.InnerException ); }
private static string GetExceptionMessage( Error error ) { if ( error != null && !string.IsNullOrWhiteSpace( error.Message ) ) return error.Message; return "Service Error information was not available"; }
private static Error GenerateError(int maxErrorNestingLevel = 3, bool generateData = true, int currentNestingLevel = 0) { var error = new Error(); error.Message = @"Generated exception message."; error.Type = TestConstants.ExceptionTypes.Random(); if (RandomHelper.GetBool()) error.Code = RandomHelper.GetRange(-234523453, 98690899).ToString(); if (generateData) { for (int i = 0; i < RandomHelper.GetRange(1, 5); i++) { string key = RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 15)); while (error.Data.ContainsKey(key) || key == Event.KnownDataKeys.Error) key = RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 15)); error.Data.Add(key, RandomHelper.GetPronouncableString(RandomHelper.GetRange(5, 25))); } } var stack = new StackFrameCollection(); for (int i = 0; i < RandomHelper.GetRange(1, 10); i++) stack.Add(GenerateStackFrame()); error.StackTrace = stack; if (currentNestingLevel < maxErrorNestingLevel && RandomHelper.GetBool()) error.Inner = GenerateError(maxErrorNestingLevel, generateData, currentNestingLevel + 1); return error; }
public void Enqueue(Error error) { Manifest manifest = Manifest.FromError(error); manifest.LastAttempt = DateTime.MinValue; _data.Add(Tuple.Create(manifest, error)); while (_data.Count > MaxItems) _data.RemoveAt(0); }
public void Error(Exception exception) { var errorLog = new Error(exception); foreach (var logProvider in providers) logProvider.Log(errorLog); LastMessage = errorLog; }
/// <summary> /// Determines whether this instance equals a specified route. /// </summary> /// <param name="httpContext">The http context.</param> /// <param name="route">The route to compare.</param> /// <param name="routeKey">The name of the route key.</param> /// <param name="values">A list of parameter values.</param> /// <param name="routeDirection">The route direction.</param> /// <returns> /// True if this instance equals a specified route; otherwise, false. /// </returns> public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (httpContext == null) { throw Error.ArgumentNull("httpContext"); } if (values == null) { throw Error.ArgumentNull("values"); } if (routeDirection == RouteDirection.IncomingRequest) { object odataPathValue; if (!values.TryGetValue(ODataRouteConstants.ODataPath, out odataPathValue)) { return(false); } string odataPathString = odataPathValue as string; ODataPath odataPath; try { // Service root is the current RequestUri, less the query string and the ODataPath (always the // last portion of the absolute path). ODL expects an escaped service root and other service // root calculations are calculated using AbsoluteUri (also escaped). But routing exclusively // uses unescaped strings, determined using // address.GetComponents(UriComponents.Path, UriFormat.Unescaped) // // For example if the AbsoluteUri is // <http://localhost/odata/FunctionCall(p0='Chinese%E8%A5%BF%E9%9B%85%E5%9B%BEChars')>, the // oDataPathString will contain "FunctionCall(p0='Chinese西雅图Chars')". // // Due to this decoding and the possibility of unecessarily-escaped characters, there's no // reliable way to determine the original string from which oDataPathString was derived. // Therefore a straightforward string comparison won't always work. See RemoveODataPath() for // details of chosen approach. HttpRequest request = httpContext.Request; string serviceRoot = GetServiceRoot(request); // string requestLeftPart = request.Path..GetLeftPart(UriPartial.Path); //string serviceRoot = request.Path; /* * if (!String.IsNullOrEmpty(odataPathString)) * { * serviceRoot = RemoveODataPath(serviceRoot, odataPathString); * }*/ // As mentioned above, we also need escaped ODataPath. // The requestLeftPart and request.RequestUri.Query are both escaped. // The ODataPath for service documents is empty. string oDataPathAndQuery = String.Empty; if (!String.IsNullOrEmpty(odataPathString)) { oDataPathAndQuery = odataPathString; } if (request.QueryString.HasValue) { // Ensure path handler receives the query string as well as the path. oDataPathAndQuery += request.QueryString; } // Leave an escaped '/' out of the service route because DefaultODataPathHandler will add a // literal '/' to the end of this string if not already present. That would double the slash // in response links and potentially lead to later 404s. if (serviceRoot.EndsWith(_escapedSlash, StringComparison.OrdinalIgnoreCase)) { serviceRoot = serviceRoot.Substring(0, serviceRoot.Length - _escapedSlash.Length); } IODataPathHandler pathHandler = httpContext.RequestServices.GetRequiredService <IODataPathHandler>(); odataPath = pathHandler.Parse(_model, serviceRoot, oDataPathAndQuery); } catch (ODataException) { odataPath = null; } if (odataPath != null) { IODataFeature odataFeature = httpContext.ODataFeature(); odataFeature.Model = _model; odataFeature.IsValidODataRequest = true; odataFeature.Path = odataPath; odataFeature.RoutePrefix = _routePrefix; return(true); } else { IODataFeature odataFeature = httpContext.ODataFeature(); odataFeature.IsValidODataRequest = false; return(false); } } else { // This constraint only applies to incomming request. return(true); } }
private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevokedKeys, out UnprotectStatus status) { Debug.Assert(protectedData != null); try { // argument & state checking if (protectedData.Length < sizeof(uint) /* magic header */ + sizeof(Guid) /* key id */) { // payload must contain at least the magic header and key id throw Error.ProtectionProvider_BadMagicHeader(); } // Need to check that protectedData := { magicHeader || keyId || encryptorSpecificProtectedPayload } // Parse the payload version number and key id. uint magicHeaderFromPayload; Guid keyIdFromPayload; fixed(byte *pbInput = protectedData) { magicHeaderFromPayload = ReadBigEndian32BitInteger(pbInput); keyIdFromPayload = Read32bitAlignedGuid(&pbInput[sizeof(uint)]); } // Are the magic header and version information correct? int payloadVersion; if (!TryGetVersionFromMagicHeader(magicHeaderFromPayload, out payloadVersion)) { throw Error.ProtectionProvider_BadMagicHeader(); } else if (payloadVersion != 0) { throw Error.ProtectionProvider_BadVersion(); } if (_logger.IsDebugLevelEnabled()) { _logger.LogDebugF($"Performing unprotect operation to key {keyIdFromPayload:B} with purposes {JoinPurposesForLog(Purposes)}."); } // Find the correct encryptor in the keyring. bool keyWasRevoked; var currentKeyRing = _keyRingProvider.GetCurrentKeyRing(); var requestedEncryptor = currentKeyRing.GetAuthenticatedEncryptorByKeyId(keyIdFromPayload, out keyWasRevoked); if (requestedEncryptor == null) { if (_logger.IsDebugLevelEnabled()) { _logger.LogDebugF($"Key {keyIdFromPayload:B} was not found in the key ring. Unprotect operation cannot proceed."); } throw Error.Common_KeyNotFound(keyIdFromPayload); } // Do we need to notify the caller that he should reprotect the data? status = UnprotectStatus.Ok; if (keyIdFromPayload != currentKeyRing.DefaultKeyId) { status = UnprotectStatus.DefaultEncryptionKeyChanged; } // Do we need to notify the caller that this key was revoked? if (keyWasRevoked) { if (allowOperationsOnRevokedKeys) { if (_logger.IsVerboseLevelEnabled()) { _logger.LogVerboseF($"Key {keyIdFromPayload:B} was revoked. Caller requested unprotect operation proceed regardless."); } status = UnprotectStatus.DecryptionKeyWasRevoked; } else { if (_logger.IsVerboseLevelEnabled()) { _logger.LogVerboseF($"Key {keyIdFromPayload:B} was revoked. Unprotect operation cannot proceed."); } throw Error.Common_KeyRevoked(keyIdFromPayload); } } // Perform the decryption operation. ArraySegment <byte> ciphertext = new ArraySegment <byte>(protectedData, sizeof(uint) + sizeof(Guid), protectedData.Length - (sizeof(uint) + sizeof(Guid))); // chop off magic header + encryptor id ArraySegment <byte> additionalAuthenticatedData = new ArraySegment <byte>(_aadTemplate.GetAadForKey(keyIdFromPayload, isProtecting: false)); // At this point, cipherText := { encryptorSpecificPayload }, // so all that's left is to invoke the decryption routine directly. return(requestedEncryptor.Decrypt(ciphertext, additionalAuthenticatedData) ?? CryptoUtil.Fail <byte[]>("IAuthenticatedEncryptor.Decrypt returned null.")); } catch (Exception ex) when(ex.RequiresHomogenization()) { // homogenize all failures to CryptographicException throw Error.DecryptionFailed(ex); } }
private void EmitUnliftedBinaryOp(ExpressionType op, Type leftType, Type rightType) { Debug.Assert(!TypeUtils.IsNullableType(leftType)); Debug.Assert(!TypeUtils.IsNullableType(rightType)); if (op == ExpressionType.Equal || op == ExpressionType.NotEqual) { EmitUnliftedEquality(op, leftType); return; } if (!leftType.GetTypeInfo().IsPrimitive) { throw Error.OperatorNotImplementedForType(op, leftType); } switch (op) { case ExpressionType.Add: _ilg.Emit(OpCodes.Add); break; case ExpressionType.AddChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Add); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Add_Ovf_Un); } else { _ilg.Emit(OpCodes.Add_Ovf); } break; case ExpressionType.Subtract: _ilg.Emit(OpCodes.Sub); break; case ExpressionType.SubtractChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Sub); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Sub_Ovf_Un); } else { _ilg.Emit(OpCodes.Sub_Ovf); } break; case ExpressionType.Multiply: _ilg.Emit(OpCodes.Mul); break; case ExpressionType.MultiplyChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Mul); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Mul_Ovf_Un); } else { _ilg.Emit(OpCodes.Mul_Ovf); } break; case ExpressionType.Divide: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Div_Un); } else { _ilg.Emit(OpCodes.Div); } break; case ExpressionType.Modulo: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Rem_Un); } else { _ilg.Emit(OpCodes.Rem); } break; case ExpressionType.And: case ExpressionType.AndAlso: _ilg.Emit(OpCodes.And); break; case ExpressionType.Or: case ExpressionType.OrElse: _ilg.Emit(OpCodes.Or); break; case ExpressionType.LessThan: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Clt_Un); } else { _ilg.Emit(OpCodes.Clt); } break; case ExpressionType.LessThanOrEqual: { Label labFalse = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Ble_Un_S, labFalse); } else { _ilg.Emit(OpCodes.Ble_S, labFalse); } _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labFalse); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.MarkLabel(labEnd); } break; case ExpressionType.GreaterThan: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Cgt_Un); } else { _ilg.Emit(OpCodes.Cgt); } break; case ExpressionType.GreaterThanOrEqual: { Label labFalse = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Bge_Un_S, labFalse); } else { _ilg.Emit(OpCodes.Bge_S, labFalse); } _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labFalse); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.MarkLabel(labEnd); } break; case ExpressionType.ExclusiveOr: _ilg.Emit(OpCodes.Xor); break; case ExpressionType.LeftShift: if (rightType != typeof(int)) { throw ContractUtils.Unreachable; } EmitShiftMask(leftType); _ilg.Emit(OpCodes.Shl); break; case ExpressionType.RightShift: if (rightType != typeof(int)) { throw ContractUtils.Unreachable; } EmitShiftMask(leftType); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Shr_Un); } else { _ilg.Emit(OpCodes.Shr); } break; default: throw Error.UnhandledBinary(op); } }
/// <summary> /// Update products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <CatalogArrayInner> > UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IList <IDictionary <string, ProductInner> > productArrayOfDictionary = default(IList <IDictionary <string, ProductInner> >), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <CatalogArrayInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <CatalogArrayInner>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationResponse <ResourceCollection> > GetResourceCollectionWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse <ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject <ResourceCollection>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private void cmdDelete_Click(object sender, EventArgs e) { if (selectMode == enumSelectMode.Header) { if (gridHeader.SelectedCells.Count > 0) { DateTime _Tanggal = (DateTime)gridHeader.SelectedCells[0].OwningRow.Cells["hdrTglVoucher"].Value; if (GlobalVar.Gudang != "2808") { if (PeriodeClosing.IsKasirClosed(_Tanggal)) { MessageBox.Show("Sudah Closing!"); return; } } Guid rowID = (Guid)gridHeader.SelectedCells[0].OwningRow.Cells["hdrRowID"].Value; if ((int)dtDetail.Compute("count(Nomor)", "") > 0) { MessageBox.Show("Masih ada detail"); return; } if (MessageBox.Show("Data Ini Akan Dihapus?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { using (Database db = new Database(GlobalVar.DBName)) { VoucherJournal.DeleteVoucherJournal(db, rowID); } #region "Tambahan" int i = 0; int n = 0; i = gridHeader.SelectedCells[0].RowIndex; n = gridHeader.SelectedCells[0].ColumnIndex; DataRowView dv = (DataRowView)gridHeader.SelectedCells[0].OwningRow.DataBoundItem; DataRow dr = dv.Row; dr.Delete(); dtHeader.AcceptChanges(); gridHeader.Focus(); gridHeader.RefreshEdit(); if (gridHeader.RowCount > 0) { if (i == 0) { gridHeader.CurrentCell = gridHeader.Rows[0].Cells[n]; gridHeader.RefreshEdit(); } else { gridHeader.CurrentCell = gridHeader.Rows[i - 1].Cells[n]; gridHeader.RefreshEdit(); } } #endregion } catch (Exception ex) { Error.LogError(ex); } } } } else { if (gridDetail.SelectedCells.Count > 0) { DateTime _Tanggal = (DateTime)gridHeader.SelectedCells[0].OwningRow.Cells["hdrTglVoucher"].Value; if (GlobalVar.Gudang != "2808") { if (PeriodeClosing.IsKasirClosed(_Tanggal)) { MessageBox.Show("Sudah Closing!"); return; } } if (MessageBox.Show("Apakah giro ini tidak jadi dititipkan?", "", MessageBoxButtons.YesNo) == DialogResult.Yes) { Guid _GiroID = (Guid)gridDetail.SelectedCells[0].OwningRow.Cells["GiroID"].Value; Guid _RowID = (Guid)gridHeader.SelectedCells[0].OwningRow.Cells["hdrRowID"].Value; try { using (Database db = new Database(GlobalVar.DBName)) { db.Commands.Add(db.CreateCommand("usp_Giro_BatalTitip")); db.Commands[0].Parameters.Add(new Parameter("@GiroID", SqlDbType.UniqueIdentifier, _GiroID)); db.Commands[0].Parameters.Add(new Parameter("@LastUpdatedBy", SqlDbType.VarChar, SecurityManager.UserID)); db.Commands[0].ExecuteNonQuery(); } HeaderRowRefresh(_RowID); #region "Tambahan" int i = 0; int n = 0; i = gridDetail.SelectedCells[0].RowIndex; n = gridDetail.SelectedCells[0].ColumnIndex; DataRowView dv = (DataRowView)gridDetail.SelectedCells[0].OwningRow.DataBoundItem; DataRow dr = dv.Row; dr.Delete(); dtDetail.AcceptChanges(); gridDetail.Focus(); gridDetail.RefreshEdit(); if (gridDetail.RowCount > 0) { if (i == 0) { gridDetail.CurrentCell = gridDetail.Rows[0].Cells[n]; gridDetail.RefreshEdit(); } else { gridDetail.CurrentCell = gridDetail.Rows[i - 1].Cells[n]; gridDetail.RefreshEdit(); } } #endregion } catch (Exception ex) { Error.LogError(ex); } } } } }
protected virtual void OnError(ErrorEventArgs e) { Error?.Invoke(this, e); }
/// <summary> /// Logs the error to SQL /// If the rollup conditions are met, then the matching error will have a DuplicateCount += @DuplicateCount (usually 1, unless in retry) rather than a distinct new row for the error /// </summary> /// <param name="error">The error to log</param> protected override void LogError(Error error) { using (var c = GetConnection()) { if (RollupThreshold.HasValue && error.ErrorHash.HasValue) { if (isSqlServer) { var queryParams = new Serenity.Data.DynamicParameters(new { error.DuplicateCount, error.ErrorHash, ApplicationName = error.ApplicationName.Truncate(50), minDate = DateTime.UtcNow.Add(RollupThreshold.Value.Negate()) }); queryParams.Add("@newGUID", dbType: DbType.Guid, direction: ParameterDirection.Output); var count = c.Execute(@" Update Exceptions Set DuplicateCount = DuplicateCount + @DuplicateCount, @newGUID = GUID Where Id In (Select Top 1 Id From Exceptions Where ErrorHash = @ErrorHash And ApplicationName = @ApplicationName And DeletionDate Is Null And CreationDate >= @minDate)", queryParams); // if we found an error that's a duplicate, jump out if (count > 0) { error.GUID = queryParams.Get <Guid>("@newGUID"); return; } } else { var update = new SqlUpdate("Exceptions") .SetTo("DuplicateCount", "[DuplicateCount] + @DuplicateCount") .Where(new Criteria("[Id]").In(new Criteria("(" + new SqlQuery() .Dialect(c.GetDialect()) .Select("[Id]") .From("Exceptions") .Take(1) .Where(hashMatch))) + ")"); update.SetParam("@DuplicateCount", error.DuplicateCount); update.SetParam("@ErrorHash", error.ErrorHash); update.SetParam("@ApplicationName", error.ApplicationName.Truncate(50)); update.SetParam("@minDate", DateTime.UtcNow.Add(RollupThreshold.Value.Negate())); var count = update.Execute(c, ExpectedRows.Ignore); // if we found an exception that's a duplicate, jump out if (count > 0) { var q = new SqlQuery() .Dialect(c.GetDialect()) .From("Exceptions") .Select("GUID") .Take(1) .Where(hashMatch); q.SetParam("@ErrorHash", error.ErrorHash); q.SetParam("@ApplicationName", error.ApplicationName.Truncate(50)); q.SetParam("@minDate", DateTime.UtcNow.Add(RollupThreshold.Value.Negate())); error.GUID = c.Query <Guid>(q).First(); return; } } error.FullJson = error.ToJson(); c.Execute(@" Insert Into Exceptions ([GUID], [ApplicationName], [MachineName], [CreationDate], [Type], [IsProtected], [Host], [Url], [HTTPMethod], [IPAddress], [Source], [Message], [Detail], [StatusCode], [SQL], [FullJson], [ErrorHash], [DuplicateCount]) Values (@GUID, @ApplicationName, @MachineName, @CreationDate, @Type, @IsProtected, @Host, @Url, @HTTPMethod, @IPAddress, @Source, @Message, @Detail, @StatusCode, @SQL, @FullJson, @ErrorHash, @DuplicateCount)", new { error.GUID, ApplicationName = error.ApplicationName.Truncate(50), MachineName = error.MachineName.Truncate(50), error.CreationDate, Type = error.Type.Truncate(100), error.IsProtected, Host = error.Host.Truncate(100), Url = error.Url.Truncate(500), HTTPMethod = error.HTTPMethod.Truncate(10), // this feels silly, but you never know when someone will up and go crazy with HTTP 1.2! error.IPAddress, Source = error.Source.Truncate(100), Message = error.Message.Truncate(1000), error.Detail, error.StatusCode, error.SQL, error.FullJson, error.ErrorHash, error.DuplicateCount }); } } }
public IReadOnlyCollection <IKey> GetAllKeys() { var allElements = KeyRepository.GetAllElements(); // We aggregate all the information we read into three buckets Dictionary <Guid, KeyBase> keyIdToKeyMap = new Dictionary <Guid, KeyBase>(); HashSet <Guid> revokedKeyIds = null; DateTimeOffset? mostRecentMassRevocationDate = null; foreach (var element in allElements) { if (element.Name == KeyElementName) { // ProcessKeyElement can return null in the case of failure, and if this happens we'll move on. // Still need to throw if we see duplicate keys with the same id. var key = ProcessKeyElement(element); if (key != null) { if (keyIdToKeyMap.ContainsKey(key.KeyId)) { throw Error.XmlKeyManager_DuplicateKey(key.KeyId); } keyIdToKeyMap[key.KeyId] = key; } } else if (element.Name == RevocationElementName) { var revocationInfo = ProcessRevocationElement(element); if (revocationInfo is Guid) { // a single key was revoked if (revokedKeyIds == null) { revokedKeyIds = new HashSet <Guid>(); } revokedKeyIds.Add((Guid)revocationInfo); } else { // all keys as of a certain date were revoked DateTimeOffset thisMassRevocationDate = (DateTimeOffset)revocationInfo; if (!mostRecentMassRevocationDate.HasValue || mostRecentMassRevocationDate < thisMassRevocationDate) { mostRecentMassRevocationDate = thisMassRevocationDate; } } } else { // Skip unknown elements. _logger.UnknownElementWithNameFoundInKeyringSkipping(element.Name); } } // Apply individual revocations if (revokedKeyIds != null) { foreach (Guid revokedKeyId in revokedKeyIds) { KeyBase key; keyIdToKeyMap.TryGetValue(revokedKeyId, out key); if (key != null) { key.SetRevoked(); _logger.MarkedKeyAsRevokedInTheKeyring(revokedKeyId); } else { _logger.TriedToProcessRevocationOfKeyButNoSuchKeyWasFound(revokedKeyId); } } } // Apply mass revocations if (mostRecentMassRevocationDate.HasValue) { foreach (var key in keyIdToKeyMap.Values) { // The contract of IKeyManager.RevokeAllKeys is that keys created *strictly before* the // revocation date are revoked. The system clock isn't very granular, and if this were // a less-than-or-equal check we could end up with the weird case where a revocation // immediately followed by a key creation results in a newly-created revoked key (since // the clock hasn't yet stepped). if (key.CreationDate < mostRecentMassRevocationDate) { key.SetRevoked(); _logger.MarkedKeyAsRevokedInTheKeyring(key.KeyId); } } } // And we're finished! return(keyIdToKeyMap.Values.ToList().AsReadOnly()); }
// Find the substring of the given URI string before the given ODataPath. Tests rely on the following: // 1. ODataPath comes at the end of the processed Path // 2. Virtual path root, if any, comes at the beginning of the Path and a '/' separates it from the rest // 3. OData prefix, if any, comes between the virtual path root and the ODataPath and '/' characters separate // it from the rest // 4. Even in the case of Unicode character corrections, the only differences between the escaped Path and the // unescaped string used for routing are %-escape sequences which may be present in the Path // // Therefore, look for the '/' character at which to lop off the ODataPath. Can't just unescape the given // uriString because subsequent comparisons would only help to check wehther a match is _possible_, not where // to do the lopping. private static string RemoveODataPath(string uriString, string oDataPathString) { // Potential index of oDataPathString within uriString. int endIndex = uriString.Length - oDataPathString.Length - 1; if (endIndex <= 0) { // Bizarre: oDataPathString is longer than uriString. Likely the values collection passed to Match() // is corrupt. throw Error.InvalidOperation(SRResources.RequestUriTooShortForODataPath, uriString, oDataPathString); } string startString = uriString.Substring(0, endIndex + 1); // Potential return value. string endString = uriString.Substring(endIndex + 1); // Potential oDataPathString match. if (String.Equals(endString, oDataPathString, StringComparison.Ordinal)) { // Simple case, no escaping in the ODataPathString portion of the Path. In this case, don't do extra // work to look for trailing '/' in startString. return(startString); } while (true) { // Escaped '/' is a derivative case but certainly possible. int slashIndex = startString.LastIndexOf('/', endIndex - 1); int escapedSlashIndex = startString.LastIndexOf(_escapedSlash, endIndex - 1, StringComparison.OrdinalIgnoreCase); if (slashIndex > escapedSlashIndex) { endIndex = slashIndex; } else if (escapedSlashIndex >= 0) { // Include the escaped '/' (three characters) in the potential return value. endIndex = escapedSlashIndex + 2; } else { // Failure, unable to find the expected '/' or escaped '/' separator. throw Error.InvalidOperation(SRResources.ODataPathNotFound, uriString, oDataPathString); } startString = uriString.Substring(0, endIndex + 1); endString = uriString.Substring(endIndex + 1); // Compare unescaped strings to avoid both arbitrary escaping and use of lowercase 'a' through 'f' in // %-escape sequences. endString = Uri.UnescapeDataString(endString); if (String.Equals(endString, oDataPathString, StringComparison.Ordinal)) { return(startString); } if (endIndex == 0) { // Failure, could not match oDataPathString after an initial '/' or escaped '/'. throw Error.InvalidOperation(SRResources.ODataPathNotFound, uriString, oDataPathString); } } }
protected override string Validate(string value) { if (IsRequired && value == null) { Error.RequiredPropertyValidationError(PropertyName); } if (value != null) { if (StringPattern != null && StringPattern.Length > 0) { try { bool IsMatch = Regex.IsMatch( value, StringPattern, Pattern_Option, TimeSpan.FromMilliseconds(PaternTimeOut) ); if (!IsMatch) { Error.PatternMathcingFailed(PropertyName, value, StringPattern); } } catch (RegexMatchTimeoutException) { Error.PatternMathcingTimeOut(PropertyName, value, StringPattern, PaternTimeOut); } catch (Exception ex) { if (DefinedPattern == PreDefinedPatterns.None) { Error.PatternMatchingError(PropertyName, value, StringPattern, ex); } else { Error.PatternMatchingError(PropertyName, value, DefinedPattern.ToString()); } } } int Length = value.Length; if (AllowedMaxLength.HasValue && Length > AllowedMaxLength) { Error.MaxLengthPropertyValidationError(PropertyName, Length, AllowedMaxLength.Value); } if (AllowedMinLength.HasValue && Length < AllowedMinLength) { Error.MinLengthPropertyValidationError(PropertyName, Length, AllowedMinLength.Value); } if (AllowedValuesOnly != null && AllowedValuesOnly.Length > 0) { if (!Array.Exists <string>(AllowedValuesOnly, v => v.Equals(value))) { Error.ValueNotAllowedError(PropertyName, value, AllowedValuesOnly); } } if (AllowedValuesExcept != null && AllowedValuesExcept.Length > 0) { if (Array.Exists <string>(AllowedValuesExcept, v => v.Equals(value))) { Error.ValueNotAllowedError(PropertyName, value, AllowedValuesExcept); } } if (IsTrim) { value = value.Trim(); } else { if (IsLTrim) { value = value.TrimStart(); } if (IsRTrim) { value = value.TrimEnd(); } } } base.Validate(value); return(value); }
private async Async.Task <Error?> OnStateUpdate(Guid machineId, NodeStateUpdate ev) { var node = await _context.NodeOperations.GetByMachineId(machineId); if (node is null) { _log.Warning($"unable to process state update event. machine_id:{machineId} state event:{ev}"); return(null); } if (ev.State == NodeState.Free) { if (node.ReimageRequested || node.DeleteRequested) { _log.Info($"stopping free node with reset flags: {machineId}"); await _context.NodeOperations.Stop(node); return(null); } if (await _context.NodeOperations.CouldShrinkScaleset(node)) { _log.Info($"stopping free node to resize scaleset: {machineId}"); await _context.NodeOperations.SetHalt(node); return(null); } } if (ev.State == NodeState.Init) { if (node.DeleteRequested) { _log.Info($"stopping node (init and delete_requested): {machineId}"); await _context.NodeOperations.Stop(node); return(null); } // Don’t check reimage_requested, as nodes only send 'init' state once. If // they send 'init' with reimage_requested, it's because the node was reimaged // successfully. node = node with { ReimageRequested = false, InitializedAt = DateTimeOffset.UtcNow }; await _context.NodeOperations.SetState(node, ev.State); return(null); } _log.Info($"node state update: {machineId} from {node.State} to {ev.State}"); await _context.NodeOperations.SetState(node, ev.State); if (ev.State == NodeState.Free) { _log.Info($"node now available for work: {machineId}"); } else if (ev.State == NodeState.SettingUp) { if (ev.Data is NodeSettingUpEventData settingUpData) { if (!settingUpData.Tasks.Any()) { return(new Error(ErrorCode.INVALID_REQUEST, Errors: new string[] { $"setup without tasks. machine_id: {machineId}", })); } foreach (var taskId in settingUpData.Tasks) { var task = await _context.TaskOperations.GetByTaskId(taskId); if (task is null) { return(new Error( ErrorCode.INVALID_REQUEST, Errors: new string[] { $"unable to find task: {taskId}" })); } _log.Info($"node starting task. machine_id: {machineId} job_id: {task.JobId} task_id: {task.TaskId}"); // The task state may be `running` if it has `vm_count` > 1, and // another node is concurrently executing the task. If so, leave // the state as-is, to represent the max progress made. // // Other states we would want to preserve are excluded by the // outermost conditional check. if (task.State != TaskState.Running && task.State != TaskState.SettingUp) { await _context.TaskOperations.SetState(task, TaskState.SettingUp); } var nodeTask = new NodeTasks( MachineId: machineId, TaskId: task.TaskId, State: NodeTaskState.SettingUp); await _context.NodeTasksOperations.Replace(nodeTask); } } } else if (ev.State == NodeState.Done) { Error?error = null; if (ev.Data is NodeDoneEventData doneData) { if (doneData.Error is not null) { var errorText = EntityConverter.ToJsonString(doneData); error = new Error(ErrorCode.TASK_FAILED, Errors: new string[] { errorText }); _log.Error($"node 'done' with error: machine_id:{machineId}, data:{errorText}"); } } // if tasks are running on the node when it reports as Done // those are stopped early await _context.NodeOperations.MarkTasksStoppedEarly(node, error); await _context.NodeOperations.ToReimage(node, done : true); } return(null); }
public static Error ToAmqpError(Exception exception) { bool flag; if (exception == null) { return(null); } Error error = new Error() { Description = ExceptionHelper.GetExceptionMessage(exception, out flag) }; if (exception is AmqpException) { AmqpException amqpException = (AmqpException)exception; error.Condition = amqpException.Error.Condition; error.Info = amqpException.Error.Info; } else if (exception is UnauthorizedAccessException) { error.Condition = AmqpError.UnauthorizedAccess.Condition; } else if (exception is TransactionAbortedException) { error.Condition = AmqpError.TransactionRollback.Condition; } else if (exception is NotSupportedException) { error.Condition = AmqpError.NotImplemented.Condition; } else if (exception is MessagingEntityNotFoundException) { error.Condition = AmqpError.NotFound.Condition; } else if (exception is MessagingEntityAlreadyExistsException) { error.Condition = ClientConstants.EntityAlreadyExistsError; } else if (exception is AddressAlreadyInUseException) { error.Condition = ClientConstants.AddressAlreadyInUseError; } else if (exception is AuthorizationFailedException) { error.Condition = ClientConstants.AuthorizationFailedError; } else if (exception is MessageLockLostException) { error.Condition = ClientConstants.MessageLockLostError; } else if (exception is SessionLockLostException) { error.Condition = ClientConstants.SessionLockLostError; } else if (exception is Microsoft.ServiceBus.Messaging.QuotaExceededException || exception is System.ServiceModel.QuotaExceededException) { error.Condition = AmqpError.ResourceLimitExceeded.Condition; } else if (exception is TimeoutException) { error.Condition = ClientConstants.TimeoutError; } else if (exception is NoMatchingSubscriptionException) { error.Condition = ClientConstants.NoMatchingSubscriptionError; } else if (exception is ServerBusyException) { error.Condition = ClientConstants.ServerBusyError; } else if (exception is MessageStoreLockLostException) { error.Condition = ClientConstants.StoreLockLostError; } else if (exception is SessionCannotBeLockedException) { error.Condition = ClientConstants.SessionCannotBeLockedError; } else if (exception is PartitionNotOwnedException) { error.Condition = ClientConstants.PartitionNotOwnedError; } else if (exception is MessagingEntityDisabledException) { error.Condition = ClientConstants.EntityDisabledError; } else if (exception is OperationCanceledException) { error.Condition = ClientConstants.OperationCancelledError; } else if (exception is RelayNotFoundException) { error.Condition = ClientConstants.RelayNotFoundError; } else if (exception is MessageSizeExceededException) { error.Condition = AmqpError.MessageSizeExceeded.Condition; } else if (!(exception is ReceiverDisconnectedException)) { error.Condition = AmqpError.InternalError.Condition; if (flag) { if (exception is InvalidOperationException) { error.Condition = AmqpError.NotAllowed.Condition; } else if (exception is ArgumentOutOfRangeException) { error.Condition = ClientConstants.ArgumentOutOfRangeError; } else if (exception is ArgumentException) { error.Condition = ClientConstants.ArgumentError; } } error.Description = (ExceptionHelper.IncludeExceptionDetails || flag ? error.Description : SRClient.InternalServerError); } else { error.Condition = AmqpError.Stolen.Condition; } if (ExceptionHelper.IncludeExceptionDetails) { string stackTrace = exception.StackTrace; if (stackTrace != null) { if (stackTrace.Length > 32768) { stackTrace = stackTrace.Substring(0, 32768); } if (error.Info == null) { error.Info = new Fields(); } error.Info.Add(ClientConstants.StackTraceName, stackTrace); } } return(error); }
public string obtenerError() { Error error = errores[0]; return(error.mensaje); }
public override bool load() { if (File.Exists(myFilename) == false) { Warn.print("Cannot find file {0}", myFilename); myState = SourceState.FAILED; return(false); } using (FileStream waveFileStream = File.Open(myFilename, System.IO.FileMode.Open)) { BinaryReader reader = new BinaryReader(waveFileStream); int chunkID = reader.ReadInt32(); if (chunkID != 0x46464952) { Warn.print("{0} is not a RIFF formated file", myFilename); myState = SourceState.FAILED; return(false); } int fileSize = reader.ReadInt32(); int riffType = reader.ReadInt32(); if (riffType != 0x45564157) //"WAVE" in bytes { Warn.print("{0} is not a WAV", myFilename); myState = SourceState.FAILED; return(false); } int fmtID = reader.ReadInt32(); if (fmtID != 0x20746d66) //"fmt " in bytes { Warn.print("Cannot find valid fmt chunk in {0}", myFilename); myState = SourceState.FAILED; return(false); } int fmtSize = reader.ReadInt32(); if (fmtSize != 16) { Warn.print("{0} is not in 16 bit format", myFilename); myState = SourceState.FAILED; return(false); } int fmtCode = reader.ReadInt16(); if (fmtCode != 1) //PCM data { Warn.print("{0} is not in PCM format", myFilename); myState = SourceState.FAILED; return(false); } myNumChannels = reader.ReadInt16(); if (myIs3d == true && myNumChannels != 1) { Error.print("Unable to load stereo files for 3D capability"); myState = SourceState.FAILED; return(false); } mySampleRate = reader.ReadInt32(); int fmtAvgBPS = reader.ReadInt32(); int fmtBlockAlign = reader.ReadInt16(); int bitDepth = reader.ReadInt16(); if (fmtSize == 18) { // Read any extra values int fmtExtraSize = reader.ReadInt16(); reader.ReadBytes(fmtExtraSize); } int dataID = reader.ReadInt32(); if (dataID != 0x61746164) //"data" in bytes { Warn.print("Cannot find valid data chunk in file {0}", myFilename); myState = SourceState.FAILED; return(false); } int dataSize = reader.ReadInt32(); if (bitDepth != 16) { Warn.print("WAV files must be 16-bit PCM format"); myState = SourceState.FAILED; return(false); } //read the data byte[] data; data = reader.ReadBytes(dataSize); //convert to shorts short[] audioData = new short[dataSize / 2]; for (int i = 0; i < dataSize / 2; i++) { audioData[i] = BitConverter.ToInt16(data, i * 2); } AudioBuffer buffer = new AudioBuffer(myNumChannels == 1 ? AudioBuffer.AudioFormat.MONO16 : AudioBuffer.AudioFormat.STEREO16, mySampleRate); buffer.setData(audioData); //put it in the audio system buffer.buffer(); myBuffers.Add(buffer); } myState = Source.SourceState.LOADED; Info.print("Loaded audio file: {0}", myFilename); return(true); }
private void frmAntarGudangDownload_Load(object sender, EventArgs e) { if (File.Exists(GlobalVar.DbfDownload + "\\dbfmatch.zip")) { ExtractFile(GlobalVar.DbfDownload + "\\dbfmatch.zip"); } else { MessageBox.Show("File " + GlobalVar.DbfDownload + "\\dbfmatch.zip tidak ada"); return; } string fileNameH = "Hagtmp.dbf"; string fileNameD = "Dagtmp.dbf"; string fileNameS = "Stoktmp.dbf"; string fileNameSP = "Parttmp.DBF"; fileNameH = GlobalVar.DbfDownload + "\\" + fileNameH; fileNameD = GlobalVar.DbfDownload + "\\" + fileNameD; fileNameS = GlobalVar.DbfDownload + "\\" + fileNameS; fileNameSP = GlobalVar.DbfDownload + "\\" + fileNameSP; if (File.Exists(fileNameH)) { try { tblHeader = Foxpro.ReadFile(fileNameH); DataColumn newcol = new DataColumn("cUploaded"); newcol.DataType = Type.GetType("System.Boolean"); tblHeader.Columns.Add(newcol); dataGridView1.DataSource = tblHeader; lblDownloadStatus1.Text = "0/" + tblHeader.Rows.Count.ToString("#,##0"); progressBar1.Minimum = 0; progressBar1.Maximum = tblHeader.Rows.Count; this.Title = fileNameH; this.DialogResult = DialogResult.OK; } catch (Exception ex) { Error.LogError(ex); } } else { MessageBox.Show("File " + fileNameH + " tidak ada"); return; } if (File.Exists(fileNameD)) { try { tblDetail = Foxpro.ReadFile(fileNameD); DataColumn newcol = new DataColumn("cUploaded"); newcol.DataType = Type.GetType("System.Boolean"); tblDetail.Columns.Add(newcol); dataGridView3.DataSource = tblDetail; lblDownloadStatus2.Text = "0/" + tblDetail.Rows.Count.ToString("#,##0"); progressBar2.Minimum = 0; progressBar2.Maximum = tblDetail.Rows.Count; this.Title = fileNameD; this.DialogResult = DialogResult.OK; } catch (Exception ex) { Error.LogError(ex); } } else { MessageBox.Show("File " + fileNameD + " tidak ada"); return; } if (File.Exists(fileNameS)) { try { tblStok = Foxpro.ReadFile(fileNameS); DataColumn newcol = new DataColumn("cUploaded"); newcol.DataType = Type.GetType("System.Boolean"); tblStok.Columns.Add(newcol); this.DialogResult = DialogResult.OK; } catch (Exception ex) { Error.LogError(ex); } } else { MessageBox.Show("File " + fileNameS + " tidak ada"); return; } if (File.Exists(fileNameSP)) { try { tblStokPart = Foxpro.ReadFile(fileNameSP); DataColumn newcol = new DataColumn("cUploaded"); newcol.DataType = Type.GetType("System.Boolean"); tblStokPart.Columns.Add(newcol); this.DialogResult = DialogResult.OK; } catch (Exception ex) { Error.LogError(ex); } } else { MessageBox.Show("File " + fileNameSP + " tidak ada"); return; } }
public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } if (Request == null) { throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest); } object defaultValue = GetDefaultValueForType(type); // If content length is 0 then return default value for this type HttpContentHeaders contentHeaders = (content == null) ? null : content.Headers; if (contentHeaders == null || contentHeaders.ContentLength == 0) { return(Task.FromResult(defaultValue)); } try { Func <ODataDeserializerContext> getODataDeserializerContext = () => { return(new ODataDeserializerContext { Request = Request, }); }; Action <Exception> logErrorAction = (ex) => { if (formatterLogger == null) { throw ex; } formatterLogger.LogError(String.Empty, ex); }; ODataDeserializerProvider deserializerProvider = Request.GetRequestContainer() .GetRequiredService <ODataDeserializerProvider>(); return(Task.FromResult(ODataInputFormatterHelper.ReadFromStream( type, defaultValue, Request.GetModel(), ResultHelpers.GetODataResponseVersion(Request), GetBaseAddressInternal(Request), new WebApiRequestMessage(Request), () => ODataMessageWrapperHelper.Create(readStream, contentHeaders, Request.GetODataContentIdMapping(), Request.GetRequestContainer()), (objectType) => deserializerProvider.GetEdmTypeDeserializer(objectType), (objectType) => deserializerProvider.GetODataDeserializer(objectType, Request), getODataDeserializerContext, (disposable) => Request.RegisterForDispose(disposable), logErrorAction))); } catch (Exception ex) { return(TaskHelpers.FromError <object>(ex)); } }
public static Exception ToMessagingContract(Error error) { if (error == null) { return(new MessagingException("Unknown error.")); } string description = error.Description; if (error.Condition.Equals(ClientConstants.TimeoutError)) { return(new TimeoutException(description)); } if (error.Condition.Equals(AmqpError.NotFound.Condition)) { return(new MessagingEntityNotFoundException(description, null)); } if (error.Condition.Equals(AmqpError.NotImplemented.Condition)) { return(new NotSupportedException(description)); } if (error.Condition.Equals(ClientConstants.EntityAlreadyExistsError)) { return(new MessagingEntityAlreadyExistsException(description, null, null)); } if (error.Condition.Equals(ClientConstants.MessageLockLostError)) { return(new MessageLockLostException(description)); } if (error.Condition.Equals(ClientConstants.SessionLockLostError)) { return(new SessionLockLostException(description)); } if (error.Condition.Equals(AmqpError.ResourceLimitExceeded.Condition)) { return(new Microsoft.ServiceBus.Messaging.QuotaExceededException(description)); } if (error.Condition.Equals(ClientConstants.NoMatchingSubscriptionError)) { return(new NoMatchingSubscriptionException(description)); } if (error.Condition.Equals(AmqpError.NotAllowed.Condition)) { return(new InvalidOperationException(description)); } if (error.Condition.Equals(AmqpError.UnauthorizedAccess.Condition)) { return(new UnauthorizedAccessException(description)); } if (error.Condition.Equals(AmqpError.MessageSizeExceeded.Condition)) { return(new MessageSizeExceededException(description)); } if (error.Condition.Equals(ClientConstants.ServerBusyError)) { return(new ServerBusyException(description)); } if (error.Condition.Equals(ClientConstants.ArgumentError)) { return(new ArgumentException(description)); } if (error.Condition.Equals(ClientConstants.ArgumentOutOfRangeError)) { return(new ArgumentOutOfRangeException(description)); } if (error.Condition.Equals(ClientConstants.StoreLockLostError)) { return(new MessageStoreLockLostException(description)); } if (error.Condition.Equals(ClientConstants.SessionCannotBeLockedError)) { return(new SessionCannotBeLockedException(description)); } if (error.Condition.Equals(ClientConstants.PartitionNotOwnedError)) { return(new PartitionNotOwnedException(description)); } if (error.Condition.Equals(ClientConstants.EntityDisabledError)) { return(new MessagingEntityDisabledException(description, null)); } if (error.Condition.Equals(AmqpError.Stolen.Condition)) { return(new ReceiverDisconnectedException(description)); } return(new MessagingException(description)); }
private void cmdEDIT_Click(object sender, EventArgs e) { Guid _rowID; try { switch (selectedGrid) { case enumSelectedGrid.HeaderSelected: if (dataGridHeader.SelectedCells.Count == 0) { MessageBox.Show(Messages.Error.RowNotSelected); return; } if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "") { MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di edit...!!!"); return; } GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value; if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate) { throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate)); } _rowID = (Guid)dataGridHeader.SelectedCells[0].OwningRow.Cells["HeaderRowID"].Value; Penjualan.frmMPRUpdate ifrmChild = new Penjualan.frmMPRUpdate(this, _rowID); ifrmChild.ShowDialog(); break; case enumSelectedGrid.DetailSelected: //if (dataGridDetail.SelectedCells.Count == 0) //{ // MessageBox.Show(Messages.Error.RowNotSelected); // return; //} //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "") //{ // MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di edit...!!!"); // return; //} //string kodeRetur = dataGridDetail.SelectedCells[0].OwningRow.Cells["KodeRetur"].Value.ToString().Trim(); //if (kodeRetur == "1" ) //{ /* Note: * /* Bila jarak tgl terima dan tgl memo * belum 60 hari (!CekACCRetur()) * maka tidak diperlukan No ACC untuk prosess nota */ //if (!CekACCRetur()) //{ // MessageBox.Show("Tidak butuh ACC untuk proses nota retur"); // return; //} // } // //GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value; // //if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate) // //{ // // throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate)); // //} //_rowID = (Guid)dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailRowID"].Value; //Penjualan.frmMPRDetailUpdate ifrmChild2 = new Penjualan.frmMPRDetailUpdate(this, _rowID, frmMPRDetailUpdate.enumFormMode.Update); //ifrmChild2.ShowDialog(); break; default: break; } } catch (Exception ex) { Error.LogError(ex); } }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } if (Request == null) { throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest); } if (cancellationToken.IsCancellationRequested) { return(TaskHelpers.Canceled()); } try { if (typeof(Stream).IsAssignableFrom(type)) { // Ideally, it should go into the "ODataRawValueSerializer", // However, OData lib doesn't provide the method to overwrite/copyto stream // So, Here's the workaround Stream objStream = value as Stream; return(CopyStreamAsync(objStream, writeStream)); } HttpConfiguration configuration = Request.GetConfiguration(); if (configuration == null) { throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration); } HttpContentHeaders contentHeaders = (content == null) ? null : content.Headers; UrlHelper urlHelper = Request.GetUrlHelper() ?? new UrlHelper(Request); Func <ODataSerializerContext> getODataSerializerContext = () => { return(new ODataSerializerContext() { Request = Request, Url = urlHelper, }); }; ODataSerializerProvider serializerProvider = Request.GetRequestContainer() .GetRequiredService <ODataSerializerProvider>(); ODataOutputFormatterHelper.WriteToStream( type, value, Request.GetModel(), ResultHelpers.GetODataResponseVersion(Request), GetBaseAddressInternal(Request), contentHeaders == null ? null : contentHeaders.ContentType, new WebApiUrlHelper(urlHelper), new WebApiRequestMessage(Request), new WebApiRequestHeaders(Request.Headers), (services) => ODataMessageWrapperHelper.Create(writeStream, contentHeaders, services), (edmType) => serializerProvider.GetEdmTypeSerializer(edmType), (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, Request), getODataSerializerContext); return(TaskHelpers.Completed()); } catch (Exception ex) { return(TaskHelpers.FromError(ex)); } }
/// <summary> /// Initialises a new instance from the given error code. /// </summary> /// /// <param name="errorCode">The error code.</param> public GetPlayerDataAttachmentError(Error errorCode) { ErrorCode = errorCode; ErrorData = MultiTypeValue.Null; ErrorDescription = GetErrorDescription(ErrorCode); }
private void cmdDELETE_Click(object sender, EventArgs e) { try { DateTime tglmemo = ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value).Date; DateTime tglserver = GlobalVar.DateTimeOfServer.Date; switch (selectedGrid) { case enumSelectedGrid.HeaderSelected: if (dataGridHeader.SelectedCells.Count == 0) { MessageBox.Show(Messages.Error.RowNotSelected); } if (tipeLokasi == "G") { MessageBox.Show("Anda tidak punya wewenang hapus data"); return; } if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true) { MessageBox.Show("Tidak bisa hapus data sudah di audit"); return; } //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "") //{ // MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!"); // return; //} if (tglmemo != tglserver) { MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo"); return; } if (dataGridDetail.Rows.Count > 0) { MessageBox.Show("Hapus detail dulu...!"); return; } if (!SecurityManager.IsManager()) { MessageBox.Show("Hapus hanya dapat dilakukan oleh manager"); return; } //GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value; //if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate) //{ // throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate)); //} if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Guid rowID = (Guid)dataGridHeader.SelectedCells[0].OwningRow.Cells["HeaderRowID"].Value; try { this.Cursor = Cursors.WaitCursor; using (Database db = new Database()) { DataTable dt = new DataTable(); db.Commands.Add(db.CreateCommand("usp_ReturPenjualan_DELETE")); //cek heri db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID)); db.Commands[0].ExecuteNonQuery(); } MessageBox.Show("Record telah dihapus"); this.RefreshDataReturJual(); } catch (Exception ex) { Error.LogError(ex); } finally { this.Cursor = Cursors.Default; } } break; case enumSelectedGrid.DetailSelected: if (dataGridDetail.SelectedCells.Count == 0) { MessageBox.Show(Messages.Error.RowNotSelected); return; } if (tipeLokasi == "G") { MessageBox.Show("Anda tidak punya wewenang hapus data"); return; } if (bool.Parse(dataGridHeader.SelectedCells[0].OwningRow.Cells["isClosed"].Value.ToString()) == true) { MessageBox.Show("Tidak bisa hapus data sudah di audit"); return; } //if (dataGridHeader.SelectedCells[0].OwningRow.Cells["TglGudang"].Value.ToString() != "") //{ // MessageBox.Show("Sudah dibuat nota retur. Tidak bisa di hapus...!!!"); // return; //} bool link = (bool)(dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailSyncFlag"].Value); if (link) { MessageBox.Show("Sudah Link ke Piutang, tidak bisa dihapus"); return; } if (tglmemo != tglserver) { MessageBox.Show("Tidak bisa hapus record. Tanggal server beda dengan Tanggal Memo"); return; } if (!SecurityManager.IsManager()) { MessageBox.Show("Hapus hanya dapat dilakukan oleh manager"); return; } GlobalVar.LastClosingDate = (DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value; if ((DateTime)dataGridHeader.SelectedCells[0].OwningRow.Cells["TglMPR"].Value <= GlobalVar.LastClosingDate) { throw new Exception(String.Format(Messages.Error.AlreadyClosingPJT, GlobalVar.LastClosingDate)); } if (MessageBox.Show("Hapus record ini?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Guid rowID = (Guid)dataGridDetail.SelectedCells[0].OwningRow.Cells["DetailRowID"].Value; string kodeRetur = dataGridDetail.SelectedCells[0].OwningRow.Cells["KodeRetur"].Value.ToString(); string type_usp_DELETE; if (kodeRetur == "1") { type_usp_DELETE = "usp_ReturPenjualanDetail_DELETE"; //cek heri } else { type_usp_DELETE = "usp_ReturPenjualanTarikanDetail_DELETE"; //cek heri } try { this.Cursor = Cursors.WaitCursor; using (Database db = new Database()) { db.Commands.Add(db.CreateCommand(type_usp_DELETE)); db.Commands[0].Parameters.Add(new Parameter("@rowID", SqlDbType.UniqueIdentifier, rowID)); db.Commands[0].ExecuteNonQuery(); } MessageBox.Show("Record telah dihapus"); this.RefreshDataReturJualDetail(); } catch (Exception ex) { Error.LogError(ex); } finally { this.Cursor = Cursors.Default; } } break; } } catch (Exception ex) { Error.LogError(ex); } }
internal void OnInternalClosed(IAmqpObject sender, Error error) { Listener?.OnConnectionFailure(ExceptionSupport.GetException(error)); }
/// <summary> /// Initializes a new instance of the <see cref="ResponseExpression"/> class. /// </summary> /// <param name="source">The source of the response.</param> public ResponseExpression(SourceExpression source) { Source = source ?? throw Error.ArgumentNull(nameof(source)); }
static void PrintError(Error error) { Console.WriteLine("Error code " + error.StatusCode); Console.WriteLine(error.Description); }
/// <summary> /// Info for a specific pet /// </summary> /// <param name='petId'> /// The id of the pet to retrieve /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <Pet> > > ShowPetByIdWithHttpMessagesAsync(string petId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (petId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "petId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("petId", petId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ShowPetById", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets/{petId}").ToString(); _url = _url.Replace("{petId}", System.Uri.EscapeDataString(petId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <Pet> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <IList <Pet> >(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private static bool Insert(JObject root, string[] path, string value, bool throwOnError) { // to-do: verify consistent with new parsing, whether single value is in path or value Contract.Assert(root != null, "Root object can't be null"); JObject current = root; JObject parent = null; for (int i = 0; i < path.Length - 1; i++) { if (String.IsNullOrEmpty(path[i])) { if (throwOnError) { throw Error.Argument(Properties.Resources.InvalidArrayInsert, BuildPathString(path, i)); } return(false); } if (!((IDictionary <string, JToken>)current).ContainsKey(path[i])) { current[path[i]] = new JObject(); } else { // Since the loop goes up to the next-to-last item in the path, if we hit a null // or a primitive, then we have a mismatching node. if (current[path[i]] == null || current[path[i]] is JValue) { if (throwOnError) { throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, i)); } return(false); } } parent = current; current = current[path[i]] as JObject; } string lastKey = path[path.Length - 1]; if (String.IsNullOrEmpty(lastKey) && path.Length > 1) { if (!AddToArray(parent, path, value, throwOnError)) { return(false); } } else { if (current == null) { if (throwOnError) { throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, path.Length - 1)); } return(false); } if (!AddToObject(current, path, value, throwOnError)) { return(false); } } return(true); }
public NewMediumLevelRecordEditor(Plugin p, Record r, SubRecord sr, SubrecordStructure ss) { InitializeComponent(); Icon = Resources.tesv_ico; SuspendLayout(); this.sr = sr; this.ss = ss; this.p = p; this.r = r; // walk each element in standard fashion int panelOffset = 0; try { foreach (var elem in ss.elements) { Control c = null; if (elem.options != null && elem.options.Length > 1) { c = new OptionsElement(); } else if (elem.flags != null && elem.flags.Length > 1) { c = new FlagsElement(); } else { switch (elem.type) { case ElementValueType.LString: c = new LStringElement(); break; case ElementValueType.FormID: c = new FormIDElement(); break; case ElementValueType.Blob: c = new HexElement(); break; default: c = new TextElement(); break; } } if (c is IElementControl) { var ec = c as IElementControl; ec.formIDLookup = p.GetRecordByID; ec.formIDScan = p.EnumerateRecords; ec.strIDLookup = p.LookupFormStrings; ec.Element = elem; if (elem.repeat > 0) { var ge = new RepeatingElement(); c = ge; c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; ge.InnerControl = ec; ge.Element = elem; ec = ge; } else if (elem.optional) { var re = new OptionalElement(); c = re; c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; re.InnerControl = ec; re.Element = elem; ec = re; c = re; } else { c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; } c.MinimumSize = c.Size; controlMap.Add(elem, ec); fpanel1.Controls.Add(c); panelOffset = c.Bottom; } } foreach (Element elem in r.EnumerateElements(sr, true)) { var es = elem.Structure; IElementControl c; if (controlMap.TryGetValue(es, out c)) { if (c is IGroupedElementControl) { var gc = c as IGroupedElementControl; gc.Elements.Add(elem.Data); } else { c.Data = elem.Data; } } } } catch { strWarnOnSave = "The subrecord doesn't appear to conform to the expected structure.\nThe formatted information may be incorrect."; Error.SetError(bSave, strWarnOnSave); Error.SetIconAlignment(bSave, ErrorIconAlignment.MiddleLeft); AcceptButton = bCancel; // remove save as default button when exception occurs CancelButton = bCancel; UpdateDefaultButton(); } ResumeLayout(); }
public static Error IsCnpj(PropertyInfo property, object value, string errorCode = null) { if (ValidationHelper.IsValueNullOrEmpty(value)) { return(null); } var error = Error.Make($"Property '{property.Name}' is not a valid CNPJ", property.Name, errorCode); int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; var cnpj = Convert.ToString(value); cnpj = Regex.Replace(cnpj, "[^0-9]", ""); if (cnpj.Length != 14) { return(error); } string tempCnpj = cnpj.Substring(0, 12); int soma = 0; for (int i = 0; i < 12; i++) { soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i]; } int resto = (soma % 11); if (resto < 2) { resto = 0; } else { resto = 11 - resto; } string digito = resto.ToString(); tempCnpj = tempCnpj + digito; soma = 0; for (int i = 0; i < 13; i++) { soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i]; } resto = (soma % 11); if (resto < 2) { resto = 0; } else { resto = 11 - resto; } digito = digito + resto.ToString(); return(cnpj.EndsWith(digito) ? null : error); }
private static bool AddToObject(JObject obj, string[] path, string value, bool throwOnError) { Contract.Assert(obj != null, "JsonObject cannot be null"); int pathIndex = path.Length - 1; string key = path[pathIndex]; if (((IDictionary <string, JToken>)obj).ContainsKey(key)) { if (obj[key] == null || obj[key].Type == JTokenType.Null) { if (throwOnError) { throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, pathIndex)); } return(false); } bool isRoot = path.Length == 1; if (isRoot) { // jQuery 1.3 behavior, make it into an array(object) if primitive if (obj[key].Type == JTokenType.String) { string oldValue = obj[key].ToObject <string>(); JObject jo = new JObject(); jo.Add("0", oldValue); jo.Add("1", value); obj[key] = jo; } else if (obj[key] is JObject) { // if it was already an object, simply add the value JObject jo = obj[key] as JObject; string index = GetIndex(jo, throwOnError); if (index == null) { return(false); } jo.Add(index, value); } } else { if (throwOnError) { throw Error.Argument(Properties.Resources.JQuery13CompatModeNotSupportNestedJson, BuildPathString(path, pathIndex)); } return(false); } } else { // if the object didn't contain the key, simply add it now // the null check here is necessary because otherwise the created JValue type will be implictly cast as a string JValue if (value == null) { obj[key] = null; } else { obj[key] = value; } } return(true); }