public async Task PerformInplaceSqlCmdAction(Batch b) { try { switch (b.SqlCmdCommand.LexerTokenType) { case LexerTokenType.Connect: var qc = (b.SqlCmdCommand as ConnectSqlCmdCommand)?.Connect(); queryConnection = qc ?? queryConnection; break; case LexerTokenType.OnError: onErrorAction = (b.SqlCmdCommand as OnErrorSqlCmdCommand).Action; break; default: throw new SqlCmdException(string.Format(SR.SqlCmdUnsupportedToken, b.SqlCmdCommand.LexerTokenType)); } } catch (Exception ex) { b.HasError = true; await BatchMessageSent(new ResultMessage(ex.Message, true, null)); if (this.onErrorAction == OnErrorAction.Exit) { HasCancelled = true; CancelledBySqlCmd = true; cancellationSource.Cancel(); throw new SqlCmdException(SR.SqlCmdExitOnError); } } }
/// <summary> /// Method to deal with errors /// </summary> public override BatchParserAction OnError(Token token, OnErrorAction ea) { if (errorActionChangedDelegate != null) { errorActionChangedDelegate(ea); } return(BatchParserAction.Continue); }
public void CheckOnError() { var errorActionChanged = bpcmd.ErrorActionChanged; var action = new OnErrorAction(); var result = bpcmd.OnError(null, action); Assert.Equal(result, BatchParserAction.Continue); }
/// <summary> /// Called when [error string]. /// </summary> /// <param name="errorAction">The error action.</param> /// <returns>The on error action.</returns> private static string OnErrorString(OnErrorAction errorAction) { switch (errorAction) { case OnErrorAction.Continue: return "Continue"; case OnErrorAction.Return: default: return "Return"; } }
/// <summary> /// Called when [error string]. /// </summary> /// <param name="errorAction">The error action.</param> /// <returns>The on error action.</returns> private static string OnErrorString(OnErrorAction errorAction) { switch (errorAction) { case OnErrorAction.Continue: return("Continue"); case OnErrorAction.Return: default: return("Return"); } }
public static void BatchDataTableToList(DataTable dt, SPList list, OnErrorAction onError) { if (dt == null || dt.Rows.Count == 0) { return; } List <BatchDataMethod> methods = new List <BatchDataMethod>(); bool idColExists = dt.Columns.Contains("ID"); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; BatchDataMethod method = new BatchDataMethod() { ListId = list.ID }; if (idColExists && !Convert.IsDBNull(dr["ID"])) { method.Id = Convert.ToString(i) + ",Update"; method.Command = BatchDataCommandType.Update; method.ItemId = Convert.ToInt32(dr["ID"]); } else { method.Id = Convert.ToString(i) + ",Add"; method.Command = BatchDataCommandType.Add; } foreach (DataColumn col in dt.Columns) { if (col.ReadOnly || col.ColumnName == "ID") { continue; } method.ColumnsData.Add(new BatchDataColumn(col.ColumnName, dr[col.ColumnName])); } methods.Add(method); } string batchCommand = ProcessBatchDataHelper.GetBatch(methods, onError); string result; SPWeb web = list.ParentWeb; result = web.ProcessBatchData(batchCommand); }
/// <summary> /// Gets the batch. /// </summary> /// <param name="methods">The methods.</param> /// <param name="errorAction">The error action.</param> /// <returns></returns> public static string GetBatch(List<BatchDataMethod> methods, OnErrorAction errorAction) { XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes")); XElement batch = new XElement(XName.Get("Batch")); batch.Add(new XAttribute("OnError", OnErrorString(errorAction))); methods.ForEach(m => batch.Add(m.GetMethod())); xDoc.Add(batch); //return xDoc.ToString(SaveOptions.DisableFormatting); StringBuilder batchStr = new StringBuilder(); methods.ForEach(m => batchStr.Append(m.ToString())); return string.Format(BatchFormat, OnErrorString(errorAction), batchStr); }
BatchParserAction ICommandHandler.OnError(Token token, OnErrorAction action) { // Write error to console var error = new ModelValidationError( sourceName: Path.GetFileName(token.Filename), line: token.Begin.Line, column: token.Begin.Column, errorType: ModelErrorType.ParserError, severity: ModelErrorSeverity.Error, prefix: "SQL", errorCode: 9000001, // custom to this project, not a known MSBuild error code message: $": Parser error in {Path.GetFileName(token.Filename)}" ); Console.Error.WriteLine(error.ToString()); return(action == OnErrorAction.Ignore ? BatchParserAction.Continue : BatchParserAction.Abort); }
/// <summary> /// Gets the batch. /// </summary> /// <param name="methods">The methods.</param> /// <param name="errorAction">The error action.</param> /// <returns></returns> public static string GetBatch(List <BatchDataMethod> methods, OnErrorAction errorAction) { XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes")); XElement batch = new XElement(XName.Get("Batch")); batch.Add(new XAttribute("OnError", OnErrorString(errorAction))); methods.ForEach(m => batch.Add(m.GetMethod())); xDoc.Add(batch); //return xDoc.ToString(SaveOptions.DisableFormatting); StringBuilder batchStr = new StringBuilder(); methods.ForEach(m => batchStr.Append(m.ToString())); return(string.Format(BatchFormat, OnErrorString(errorAction), batchStr)); }
/// <summary> /// Add error to <see cref="Validator"/>. /// </summary> /// <param name="error">Error to add</param> public void Fail(Error error) { Assert.Argument(error, "error").NotNull(); var key = Key; if (Validator?.ErrorKeyPrefix != null) { key = key != null ? $"{Validator.ErrorKeyPrefix}.{key}" : Validator.ErrorKeyPrefix; } error.Key = key; OnErrorAction?.Invoke(error); if (Validator != null) { Validator.Add(error); } else { throw new ErrorException(error); } }
/// <summary> /// Convert value to specific T type /// </summary> public static object ConvertTo(this object Input, Type TargetType, OnErrorAction OnErrorAction = OnErrorAction.ThrowException) { if (Input == null || TargetType.IsAssignableFrom(Input.GetType())) { return(Input); } if (TargetType == typeof(string)) { try { return(Utility.GetConverter(Input.GetType()).ConvertTo(Input, TargetType)); } catch { return(Input.ToString()); } } if (!CanConvertTo(Input, TargetType)) { if (OnErrorAction == OnErrorAction.ThrowException) { throw new Exception("Can't convert type " + Input.GetType().Name + " to type " + TargetType.Name); } else if (OnErrorAction == OnErrorAction.ReturnNull) { return(Utility.GetDefault(TargetType)); } else { return(Input); } } try { if (TargetType.IsEnumType() && Input.GetType().IsEnumType()) { Input = Input + ""; } try { return(Utility.GetConverter(TargetType).ConvertFrom(Input)); } catch (Exception ex) { if (TargetType == typeof(string) && Input is IList) { return(Utility.SerializeArrayAsString(Input as IList)); } if (TargetType.IsList() && Input.GetType() == typeof(string)) { return(Utility.DeSerializeArrayFromString(TargetType, Input as string)); } throw ex; } } catch { try { return(Utility.GetConverter(Input.GetType()).ConvertTo(Input, TargetType)); } catch { if (OnErrorAction == OnErrorAction.ThrowException) { throw; } else if (OnErrorAction == OnErrorAction.ReturnNull) { return(Utility.GetDefault(TargetType)); } else { return(Input); } } } }
/// <summary> /// Initializes new instance of <see cref="ListenerErrorEventArgs"/> class. /// </summary> /// <param name="message">Error message.</param> /// <param name="nextAction">Action, that will be done after raising current error.</param> public ListenerErrorEventArgs(string message, OnErrorAction nextAction) : this(message, null, nextAction) { }
public BatchParserAction OnError(Token token, OnErrorAction action) { outputString.AppendFormat(CultureInfo.InvariantCulture, "*** PARSER: On error: {0}", action.ToString()); outputString.AppendLine(); return(BatchParserAction.Continue); }
/// <summary> /// Changed when parser changed the error action type /// </summary> /// <param name="ea"></param> private void OnErrorActionChanged(OnErrorAction ea) { errorAction = ea; }
/// <summary> /// Executes the script (on a separated thread) /// </summary> private void DoExecute(bool isBatchParser) { //we should not be in the middle of execution here if (executionState == ExecutionState.Executing || executionState == ExecutionState.ExecutingBatch) { throw new InvalidOperationException(SR.EE_ExecutionNotYetCompleteError); } executionState = ExecutionState.Initial; result = ScriptExecutionResult.Failure; currentBatchIndex = 0; currentBatch.ExecutionTimeout = executionTimeout; expectedShowPlan = ShowPlanType.None; if (!isLocalParse) { errorAction = conditions.IsHaltOnError ? OnErrorAction.Exit : OnErrorAction.Ignore; CreatePrePostConditionBatches(); } ConfigureBatchEventHandlers(currentBatch, batchEventHandlers, true); // do we have a cancel request already? lock (stateSyncLock) { if (executionState == ExecutionState.Cancelling) { RaiseScriptExecutionFinished(ScriptExecutionResult.Cancel); return; } Debug.Assert(executionState == ExecutionState.Initial); executionState = ExecutionState.Executing; } if ((result = ExecutePrePostConditionBatches(preConditionBatches)) == ScriptExecutionResult.Success) { DoScriptExecution(isBatchParser); } if (!CheckForDiscardedConnection()) { if (!isLocalParse) { if (conditions.IsTransactionWrapped && !conditions.IsParseOnly) { if (result == ScriptExecutionResult.Success) { postConditionBatches.Add(new Batch(ExecutionEngineConditions.CommitTransactionStatement, false, executionTimeout)); } else { postConditionBatches.Add(new Batch(ExecutionEngineConditions.RollbackTransactionStatement, false, executionTimeout)); } } // no need to update the result value as it has been updated by the DoScriptExecution() ExecutePrePostConditionBatches(postConditionBatches); } //fire an event that we're done with execution of all batches if (result == ScriptExecutionResult.Halted) //remap into failure { result = ScriptExecutionResult.Failure; } RaiseScriptExecutionFinished(result); } }
/// <summary> /// Initializes new instance of <see cref="ListenerErrorEventArgs"/> class. /// </summary> /// <param name="e">Thrown exception.</param> /// <param name="nextAction">Action, that will be done after raising current error.</param> public ListenerErrorEventArgs(Exception e, OnErrorAction nextAction) : this(null, e, nextAction) { }
/// <summary> /// Executes this query asynchronously and collects all result sets /// </summary> private async Task ExecuteInternal() { ReliableSqlConnection sqlConn = null; try { // check for cancellation token before actually making connection cancellationSource.Token.ThrowIfCancellationRequested(); // Mark that we've internally executed hasExecuteBeenCalled = true; // Don't actually execute if there aren't any batches to execute if (Batches.Length == 0) { if (BatchMessageSent != null) { await BatchMessageSent(new ResultMessage(SR.QueryServiceCompletedSuccessfully, false, null)); } if (QueryCompleted != null) { await QueryCompleted(this); } return; } // Locate and setup the connection queryConnection = await ConnectionService.Instance.GetOrOpenConnection(editorConnection.OwnerUri, ConnectionType.Query); onErrorAction = OnErrorAction.Ignore; sqlConn = queryConnection as ReliableSqlConnection; if (sqlConn != null) { // Subscribe to database informational messages sqlConn.GetUnderlyingConnection().FireInfoMessageEventOnUserErrors = true; sqlConn.GetUnderlyingConnection().InfoMessage += OnInfoMessage; } // Execute beforeBatches synchronously, before the user defined batches foreach (Batch b in BeforeBatches) { await b.Execute(queryConnection, cancellationSource.Token); } // We need these to execute synchronously, otherwise the user will be very unhappy foreach (Batch b in Batches) { // Add completion callbacks b.BatchStart += BatchStarted; b.BatchCompletion += BatchCompleted; b.BatchMessageSent += BatchMessageSent; b.ResultSetCompletion += ResultSetCompleted; b.ResultSetAvailable += ResultSetAvailable; b.ResultSetUpdated += ResultSetUpdated; await ExecuteBatch(b); } // Execute afterBatches synchronously, after the user defined batches foreach (Batch b in AfterBatches) { await b.Execute(queryConnection, cancellationSource.Token); } // Call the query execution callback if (QueryCompleted != null) { await QueryCompleted(this); } } catch (Exception e) { HasErrored = true; if (e is SqlCmdException || CancelledBySqlCmd) { await BatchMessageSent(new ResultMessage(SR.SqlCmdExitOnError, false, null)); } else if (e is OperationCanceledException) { await BatchMessageSent(new ResultMessage(SR.QueryServiceQueryCancelled, false, null)); } // Call the query failure callback if (QueryFailed != null) { await QueryFailed(this, e); } } finally { // Remove the message handler from the connection if (sqlConn != null) { // Subscribe to database informational messages sqlConn.GetUnderlyingConnection().InfoMessage -= OnInfoMessage; } // If any message notified us we had changed databases, then we must let the connection service know if (newDatabaseName != null) { ConnectionService.Instance.ChangeConnectionDatabaseContext(editorConnection.OwnerUri, newDatabaseName); } foreach (Batch b in Batches) { if (b.HasError) { ConnectionService.EnsureConnectionIsOpen(sqlConn); break; } } } }
/// <summary> /// Initializes new instance of <see cref="ListenerErrorEventArgs"/> class. /// </summary> /// <param name="message">Error message.</param> /// <param name="e">Thrown exception.</param> /// <param name="nextAction">Action, that will be done after raising current error.</param> public ListenerErrorEventArgs(string message, Exception e, OnErrorAction nextAction) { Message = message; Exception = e; NextAction = nextAction; }
public void OnError(string msg) { OnErrorAction?.Invoke(msg); ClearEvent(); }
/// <summary> /// Convert value to specific T type /// </summary> public static T ConvertTo <T>(this object Input, OnErrorAction OnErrorAction = OnErrorAction.ThrowException) { return((T)ConvertTo(Input, typeof(T), OnErrorAction)); }
public void OnError(YouTubePlayerErrorReason p0) { playerState = "ERROR (" + p0 + ")"; OnErrorAction?.Invoke(p0); }
private async Task DoExecute(DbConnection conn, CancellationToken cancellationToken, OnErrorAction onErrorAction = OnErrorAction.Ignore) { bool canContinue = true; int timesLoop = this.BatchExecutionCount; await SendMessageIfExecutingMultipleTimes(SR.EE_ExecutionInfo_InitializingLoop, false); executionStartTime = DateTime.Now; while (canContinue && timesLoop > 0) { try { await ExecuteOnce(conn, cancellationToken); } catch (DbException dbe) { HasError = true; if (onErrorAction == OnErrorAction.Exit) { throw new SqlCmdException(dbe.Message); } canContinue = await UnwrapDbException(dbe); if (canContinue) { // If it's a multi-batch, we notify the user that we're ignoring a single failure. await SendMessageIfExecutingMultipleTimes(SR.EE_BatchExecutionError_Ignoring, false); } } timesLoop--; } await SendMessageIfExecutingMultipleTimes(string.Format(CultureInfo.CurrentCulture, SR.EE_ExecutionInfo_FinalizingLoop, this.BatchExecutionCount), false); }
/// <summary> /// Executes this batch and captures any server messages that are returned. /// </summary> /// <param name="conn">The connection to use to execute the batch</param> /// <param name="cancellationToken">Token for cancelling the execution</param> /// <param name="onErrorAction">Continue (Ignore) or Exit on Error. This comes only in SQLCMD mode</param> public async Task Execute(DbConnection conn, CancellationToken cancellationToken, OnErrorAction onErrorAction = OnErrorAction.Ignore) { // Sanity check to make sure we haven't already run this batch if (HasExecuted) { throw new InvalidOperationException("Batch has already executed."); } // Notify that we've started execution if (BatchStart != null) { await BatchStart(this); } // Register the message Listener to *this instance* of the batch // Note: This is being done to associate messages with batches ReliableSqlConnection sqlConn = conn as ReliableSqlConnection; if (sqlConn != null) { sqlConn.GetUnderlyingConnection().InfoMessage += ServerMessageHandler; } try { await DoExecute(conn, cancellationToken, onErrorAction); } catch (TaskCanceledException) { // Cancellation isn't considered an error condition await SendMessage(SR.QueryServiceQueryCancelled, false); throw; } catch (Exception e) { HasError = true; await SendMessage(SR.QueryServiceQueryFailed(e.Message), true); throw; } finally { // Remove the message event handler from the connection if (sqlConn != null) { sqlConn.GetUnderlyingConnection().InfoMessage -= ServerMessageHandler; } // Mark that we have executed HasExecuted = true; executionEndTime = DateTime.Now; // Fire an event to signify that the batch has completed if (BatchCompletion != null) { await BatchCompletion(this); } } }
public virtual BatchParserAction OnError(Token token, OnErrorAction action) { throw new NotImplementedException("The method or operation is not implemented."); }
internal OnErrorSqlCmdCommand(OnErrorAction action) : base(LexerTokenType.OnError) { Action = action; }